repo_name
stringlengths
5
108
path
stringlengths
6
333
size
stringlengths
1
6
content
stringlengths
4
977k
license
stringclasses
15 values
julianhyde/calcite
core/src/main/java/org/apache/calcite/sql/util/IdPair.java
1904
/* * 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.util; import java.util.List; import java.util.Map; import java.util.Objects; /** Similar to {@link org.apache.calcite.util.Pair} but identity is based * on identity of values. * * <p>Also, uses {@code hashCode} algorithm of {@link List}, * not {@link Map.Entry#hashCode()}. * * @param <L> Left type * @param <R> Right type */ public class IdPair<L, R> { final L left; final R right; /** Creates an IdPair. */ public static <L, R> IdPair<L, R> of(L left, R right) { return new IdPair<>(left, right); } protected IdPair(L left, R right) { this.left = Objects.requireNonNull(left); this.right = Objects.requireNonNull(right); } @Override public String toString() { return left + "=" + right; } @Override public boolean equals(Object obj) { return obj == this || obj instanceof IdPair && left == ((IdPair) obj).left && right == ((IdPair) obj).right; } @Override public int hashCode() { return (31 + System.identityHashCode(left)) * 31 + System.identityHashCode(right); } }
apache-2.0
vikkyrk/incubator-beam
sdks/java/core/src/main/java/org/apache/beam/sdk/coders/BigEndianIntegerCoder.java
3325
/* * 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.beam.sdk.coders; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.EOFException; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.UTFDataFormatException; import org.apache.beam.sdk.values.TypeDescriptor; /** * A {@link BigEndianIntegerCoder} encodes {@link Integer Integers} in 4 bytes, big-endian. */ public class BigEndianIntegerCoder extends CustomCoder<Integer> { public static BigEndianIntegerCoder of() { return INSTANCE; } ///////////////////////////////////////////////////////////////////////////// private static final BigEndianIntegerCoder INSTANCE = new BigEndianIntegerCoder(); private static final TypeDescriptor<Integer> TYPE_DESCRIPTOR = new TypeDescriptor<Integer>() {}; private BigEndianIntegerCoder() {} @Override public void encode(Integer value, OutputStream outStream, Context context) throws IOException, CoderException { if (value == null) { throw new CoderException("cannot encode a null Integer"); } new DataOutputStream(outStream).writeInt(value); } @Override public Integer decode(InputStream inStream, Context context) throws IOException, CoderException { try { return new DataInputStream(inStream).readInt(); } catch (EOFException | UTFDataFormatException exn) { // These exceptions correspond to decoding problems, so change // what kind of exception they're branded as. throw new CoderException(exn); } } @Override public void verifyDeterministic() {} /** * {@inheritDoc} * * @return {@code true}. This coder is injective. */ @Override public boolean consistentWithEquals() { return true; } @Override public String getEncodingId() { return ""; } /** * {@inheritDoc} * * @return {@code true}, because {@link #getEncodedElementByteSize} runs in constant time. */ @Override public boolean isRegisterByteSizeObserverCheap(Integer value, Context context) { return true; } @Override public TypeDescriptor<Integer> getEncodedTypeDescriptor() { return TYPE_DESCRIPTOR; } /** * {@inheritDoc} * * @return {@code 4}, the size in bytes of an integer's big endian encoding. */ @Override protected long getEncodedElementByteSize(Integer value, Context context) throws Exception { if (value == null) { throw new CoderException("cannot encode a null Integer"); } return 4; } }
apache-2.0
nebula-plugins/java-source-refactor
rewrite-core/src/main/java/org/openrewrite/internal/lang/NonNull.java
1707
/* * Copyright 2020 the original 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.openrewrite.internal.lang; import javax.annotation.Nonnull; import javax.annotation.meta.TypeQualifierNickname; import java.lang.annotation.*; /** * A common annotation to declare that annotated elements cannot be {@code null}. * Leverages JSR 305 meta-annotations to indicate nullability in Java to common tools with * JSR 305 support and used by Kotlin to infer nullability of the API. * <p>Should be used at parameter, return value, and field level. Method overrides should * repeat parent {@code @NonNull} annotations unless they behave differently. * <p>Use {@code @NonNullApi} (scope = parameters + return values) and/or {@code @NonNullFields} * (scope = fields) to set the default behavior to non-nullable in order to avoid annotating * your whole codebase with {@code @NonNull}. * * @see NonNullApi * @see NonNullFields * @see Nullable */ @Target({ElementType.METHOD, ElementType.PARAMETER, ElementType.FIELD, ElementType.TYPE, ElementType.TYPE_PARAMETER}) @Retention(RetentionPolicy.RUNTIME) @Documented @Nonnull @TypeQualifierNickname public @interface NonNull { }
apache-2.0
mkloeckner/version-range-maven-plugin
src/main/java/org/kloeckner/maven/plugin/util/VersionRangeUtils.java
11735
package org.kloeckner.maven.plugin.util; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.Reader; import java.io.Writer; import java.nio.file.Paths; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Properties; import org.apache.maven.artifact.ArtifactUtils; import org.apache.maven.model.Model; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.project.MavenProject; import org.codehaus.plexus.interpolation.InterpolationException; import org.codehaus.plexus.interpolation.MapBasedValueSource; import org.codehaus.plexus.interpolation.ObjectBasedValueSource; import org.codehaus.plexus.interpolation.PrefixAwareRecursionInterceptor; import org.codehaus.plexus.interpolation.PrefixedObjectValueSource; import org.codehaus.plexus.interpolation.StringSearchInterpolator; import org.codehaus.plexus.util.IOUtil; import org.codehaus.plexus.util.ReaderFactory; import org.codehaus.plexus.util.WriterFactory; import org.jdom.CDATA; import org.jdom.Comment; import org.jdom.Document; import org.jdom.Element; import org.jdom.Namespace; import org.jdom.Text; import org.jdom.filter.ContentFilter; import org.jdom.filter.ElementFilter; import org.jdom.output.Format; import org.jdom.output.XMLOutputter; /** */ public class VersionRangeUtils { public static final String POMv4 = "pom.xml"; // private static final String FS = File.separator; private static String ls = VersionRangeUtils.LS; /** * The line separator to use. */ public static final String LS = System.getProperty("line.separator"); private VersionRangeUtils() { // private } public static MavenProject getRootProject(List<MavenProject> reactorProjects) { MavenProject project = reactorProjects.get(0); for (MavenProject currentProject : reactorProjects) { if (currentProject.isExecutionRoot()) { project = currentProject; break; } } return project; } public static String interpolate(String value, Model model) throws MojoExecutionException { if (value != null && value.contains("${")) { StringSearchInterpolator interpolator = new StringSearchInterpolator(); List<String> pomPrefixes = Arrays.asList("pom.", "project."); interpolator.addValueSource(new PrefixedObjectValueSource(pomPrefixes, model, false)); interpolator.addValueSource(new MapBasedValueSource(model.getProperties())); interpolator.addValueSource(new ObjectBasedValueSource(model)); try { value = interpolator.interpolate(value, new PrefixAwareRecursionInterceptor(pomPrefixes)); } catch (InterpolationException e) { throw new MojoExecutionException("Failed to interpolate " + value + " for project " + model.getId(), e); } } return value; } public static String rewriteParent(MavenProject project, Element rootElement, Namespace namespace, Map<String, String> mappedVersions, Map<String, String> originalVersions) throws MojoExecutionException { String parentVersion = null; if (project.hasParent()) { Element parentElement = rootElement.getChild("parent", namespace); Element versionElement = parentElement.getChild("version", namespace); MavenProject parent = project.getParent(); String key = ArtifactUtils.versionlessKey(parent.getGroupId(), parent.getArtifactId()); parentVersion = mappedVersions.get(key); // if (parentVersion == null) { // //MRELEASE-317 // parentVersion = getResolvedSnapshotVersion(key, resolvedSnapshotDependencies); // } if (parentVersion == null) { if (parent.getVersion().equals(originalVersions.get(key))) { throw new MojoExecutionException("Version for parent '" + parent.getName() + "' was not mapped"); } } else { rewriteValue(versionElement, parentVersion); } } return parentVersion; } public static void rewriteValue(Element element, String value) { Text text = null; if (element.getContent() != null) { for (Iterator<?> it = element.getContent().iterator(); it.hasNext();) { Object content = it.next(); if ((content instanceof Text) && ((Text) content).getTextTrim().length() > 0) { text = (Text) content; while (it.hasNext()) { content = it.next(); if (content instanceof Text) { text.append((Text) content); it.remove(); } else { break; } } break; } } } if (text == null) { element.addContent(value); } else { String chars = text.getText(); String trimmed = text.getTextTrim(); int idx = chars.indexOf(trimmed); String leadingWhitespace = chars.substring(0, idx); String trailingWhitespace = chars.substring(idx + trimmed.length()); text.setText(leadingWhitespace + value + trailingWhitespace); } } public static void rewriteVersion(Element rootElement, Namespace namespace, Map<String, String> mappedVersions, String projectId, MavenProject project, String parentVersion) throws MojoExecutionException { Element versionElement = rootElement.getChild("version", namespace); String version = mappedVersions.get(projectId); if (version == null) { throw new MojoExecutionException("Version for '" + project.getName() + "' was not mapped"); } if (versionElement == null) { if (!version.equals(parentVersion)) { // we will add this after artifactId, since it was missing but different from the inherited version Element artifactIdElement = rootElement.getChild("artifactId", namespace); int index = rootElement.indexOf(artifactIdElement); versionElement = new Element("version", namespace); versionElement.setText(version); rootElement.addContent(index + 1, new Text("\n ")); rootElement.addContent(index + 2, versionElement); } } else { rewriteValue(versionElement, version); } } public static File getStandardPom(MavenProject project) { if (project == null) { return null; } File pom = project.getFile(); if (pom == null) { return null; } return pom; } public static List<Element> getChildren(Element root, String... names) { Element parent = root; for (int i = 0; i < names.length - 1 && parent != null; i++) { parent = parent.getChild(names[i], parent.getNamespace()); } if (parent == null) { return Collections.emptyList(); } return parent.getChildren(names[names.length - 1], parent.getNamespace()); } /** * Gets the string contents of the specified XML file. Note: In contrast to an XML processor, the line separators in * the returned string will be normalized to use the platform's native line separator. This is basically to save * another normalization step when writing the string contents back to an XML file. * * @param file The path to the XML file to read in, must not be <code>null</code>. * @return The string contents of the XML file. * @throws IOException If the file could not be opened/read. */ public static String readXmlFile(File file) throws IOException { return readXmlFile(file, LS); } public static String readXmlFile(File file, String ls) throws IOException { Reader reader = null; try { reader = ReaderFactory.newXmlReader(file); return normalizeLineEndings(IOUtil.toString(reader), ls); } finally { IOUtil.close(reader); } } /** * Normalizes the line separators in the specified string. * * @param text The string to normalize, may be <code>null</code>. * @param separator The line separator to use for normalization, typically "\n" or "\r\n", must not be * <code>null</code>. * @return The input string with normalized line separators or <code>null</code> if the string was <code>null</code> * . */ public static String normalizeLineEndings(String text, String separator) { String norm = text; if (text != null) { norm = text.replaceAll("(\r\n)|(\n)|(\r)", separator); } return norm; } public static void writePom(File pomFile, Document document, String modelVersion, String intro, String outtro) throws MojoExecutionException { Element rootElement = document.getRootElement(); Namespace pomNamespace = Namespace.getNamespace("", "http://maven.apache.org/POM/" + modelVersion); rootElement.setNamespace(pomNamespace); Namespace xsiNamespace = Namespace.getNamespace("xsi", "http://www.w3.org/2001/XMLSchema-instance"); rootElement.addNamespaceDeclaration(xsiNamespace); if (rootElement.getAttribute("schemaLocation", xsiNamespace) == null) { rootElement.setAttribute("schemaLocation", "http://maven.apache.org/POM/" + modelVersion + " http://maven.apache.org/maven-v" + modelVersion.replace('.', '_') + ".xsd", xsiNamespace); } // the empty namespace is considered equal to the POM namespace, so match them up to avoid extra xmlns="" ElementFilter elementFilter = new ElementFilter(Namespace.getNamespace("")); for (Iterator<?> i = rootElement.getDescendants(elementFilter); i.hasNext();) { Element e = (Element) i.next(); e.setNamespace(pomNamespace); } Writer writer = null; try { writer = WriterFactory.newXmlWriter(pomFile); if (intro != null) { writer.write(intro); } Format format = Format.getRawFormat(); format.setLineSeparator(ls); XMLOutputter out = new XMLOutputter(format); out.output(document.getRootElement(), writer); if (outtro != null) { writer.write(outtro); } } catch (IOException e) { throw new MojoExecutionException("Error writing POM: " + e.getMessage(), e); } finally { IOUtil.close(writer); } } public static void normaliseLineEndings(Document document) { for (Iterator<?> i = document.getDescendants(new ContentFilter(ContentFilter.COMMENT)); i.hasNext();) { Comment c = (Comment) i.next(); c.setText(VersionRangeUtils.normalizeLineEndings(c.getText(), ls)); } for (Iterator<?> i = document.getDescendants(new ContentFilter(ContentFilter.CDATA)); i.hasNext();) { CDATA c = (CDATA) i.next(); c.setText(VersionRangeUtils.normalizeLineEndings(c.getText(), ls)); } } public static List<String> loadEagerDependencies(String path, String filename) throws MojoExecutionException { if (path == null) { path = Paths.get("").toAbsolutePath().toString(); } if (filename == null) { filename = "version-range-maven-plugin.properties"; } Properties p = new Properties(); try { p.load(new FileInputStream(new File(path, filename))); } catch (FileNotFoundException e) { throw new MojoExecutionException("unable to find '" + filename + "'; path='" + path + "'", e); } catch (IOException e) { throw new MojoExecutionException("IOException while searching '" + filename + "'; path='" + path + "'", e); } // naja ... List<String> list = new ArrayList<String>(); for (Object object : p.keySet()) { list.add(object.toString()); } return list; } }
apache-2.0
Athou/commafeed
src/main/java/com/commafeed/frontend/model/Entries.java
1525
package com.commafeed.frontend.model; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import lombok.Data; @SuppressWarnings("serial") @ApiModel(description = "List of entries with some metadata") @Data public class Entries implements Serializable { @ApiModelProperty(value = "name of the feed or the category requested", required = true) private String name; @ApiModelProperty(value = "error or warning message") private String message; @ApiModelProperty(value = "times the server tried to refresh the feed and failed", required = true) private int errorCount; @ApiModelProperty(value = "URL of the website, extracted from the feed", required = true) private String feedLink; @ApiModelProperty(value = "list generation timestamp", required = true) private long timestamp; @ApiModelProperty(value = "if the query has more elements", required = true) private boolean hasMore; @ApiModelProperty(value = "the requested offset") private int offset; @ApiModelProperty(value = "the requested limit") private int limit; @ApiModelProperty(value = "list of entries", required = true) private List<Entry> entries = new ArrayList<>(); @ApiModelProperty( value = "if true, the unread flag was ignored in the request, all entries are returned regardless of their read status", required = true) private boolean ignoredReadStatus; }
apache-2.0
EnMasseProject/enmasse
address-space-controller/src/test/java/io/enmasse/controller/AddressFinalizerControllerTest.java
5952
/* * Copyright 2019, EnMasse authors. * License: Apache License 2.0 (see the file LICENSE or http://apache.org/licenses/LICENSE-2.0.html). */ package io.enmasse.controller; import static org.hamcrest.core.IsCollectionContaining.hasItems; import static org.hamcrest.core.IsNull.notNullValue; import static org.hamcrest.core.IsNull.nullValue; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; import java.time.Instant; import java.time.ZoneOffset; import java.time.format.DateTimeFormatter; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import io.enmasse.address.model.Address; import io.enmasse.address.model.AddressBuilder; import io.enmasse.address.model.AddressSpace; import io.enmasse.address.model.AddressSpaceBuilder; import io.enmasse.k8s.api.AddressApi; import io.enmasse.k8s.api.AddressSpaceApi; import io.enmasse.k8s.api.TestAddressSpaceApi; import io.enmasse.model.CustomResourceDefinitions; public class AddressFinalizerControllerTest { private AddressFinalizerController controller; private AddressSpaceApi addressSpaceApi; @BeforeAll public static void init () { CustomResourceDefinitions.registerAll(); } @BeforeEach public void setup() { this.addressSpaceApi = new TestAddressSpaceApi(); this.controller = new AddressFinalizerController(addressSpaceApi); } /** * Test calling the finalizer controller with a non-deleted object. */ @Test public void testAddingFinalizer () throws Exception { // given a non-delete object AddressSpace addressSpace = new AddressSpaceBuilder() .withNewMetadata() .withName("foo") .withNamespace("bar") .withFinalizers("foo/bar") .endMetadata() .build(); // when calling the reconcile method of the finalizer controller Controller.ReconcileResult result = controller.reconcileAnyState(addressSpace); assertTrue(result.isPersistAndRequeue()); addressSpace = result.getAddressSpace(); // it should add the finalizer, but not remove existing finalizers assertThat(addressSpace, notNullValue()); assertThat(addressSpace.getMetadata(), notNullValue()); assertThat(addressSpace.getMetadata().getFinalizers(), hasItems("foo/bar", AddressFinalizerController.FINALIZER_ADDRESSES)); } @Test public void testProcessingFinalizer () throws Exception { // given a deleted address space, with the finalizer still present AddressSpace addressSpace = new AddressSpaceBuilder() .withNewMetadata() .withName("foo") .withNamespace("bar") .withDeletionTimestamp(Instant.now().atZone(ZoneOffset.UTC).format(DateTimeFormatter.ISO_OFFSET_DATE_TIME)) .withFinalizers("foo/bar", AddressFinalizerController.FINALIZER_ADDRESSES) .endMetadata() .build(); addressSpaceApi.createAddressSpace(addressSpace); AddressApi addressApi = addressSpaceApi.withAddressSpace(addressSpace); // and given an existing address for this address space Address address = new AddressBuilder() .withNewMetadata() .withName("foo.foo") .withNamespace("bar") .endMetadata() .build(); addressApi.createAddress(address); // and given another address space and address AddressSpace otherAddressSpace = new AddressSpaceBuilder() .withNewMetadata() .withName("foo2") .withNamespace("bar") .withFinalizers("foo/bar", AddressFinalizerController.FINALIZER_ADDRESSES) .endMetadata() .build(); addressSpaceApi.createAddressSpace(otherAddressSpace); AddressApi otherAddressApi = addressSpaceApi.withAddressSpace(otherAddressSpace); // and given an existing address for this address space Address otherAddress = new AddressBuilder() .withNewMetadata() .withName("foo2.foo") .withNamespace("bar") .endMetadata() .build(); otherAddressApi.createAddress(otherAddress); // ensure that the address spaces and addresses should be found assertThat(addressSpaceApi.getAddressSpaceWithName("bar", "foo").orElse(null), notNullValue()); assertThat(addressApi.getAddressWithName("bar", "foo.foo").orElse(null), notNullValue()); assertThat(addressSpaceApi.getAddressSpaceWithName("bar", "foo2").orElse(null), notNullValue()); assertThat(otherAddressApi.getAddressWithName("bar", "foo2.foo").orElse(null), notNullValue()); // when running the reconcile method Controller.ReconcileResult result = controller.reconcileAnyState(addressSpace); assertTrue(result.isPersistAndRequeue()); addressSpace = result.getAddressSpace(); // then the finalizer of this controller should be removed, and the address should be deleted assertThat(addressSpace, notNullValue()); assertThat(addressSpace.getMetadata(), notNullValue()); assertThat(addressSpace.getMetadata().getFinalizers(), hasItems("foo/bar")); assertThat(addressSpaceApi.getAddressSpaceWithName("bar", "foo").orElse(null), notNullValue()); assertThat(addressApi.getAddressWithName("bar", "foo.foo").orElse(null), nullValue()); // but not the "other" address assertThat(addressSpaceApi.getAddressSpaceWithName("bar", "foo2").orElse(null), notNullValue()); assertThat(otherAddressApi.getAddressWithName("bar", "foo2.foo").orElse(null), notNullValue()); } }
apache-2.0
Daemon1993/Pas
app/src/main/java/com/daemon/pas/presenter/activity/WebViewActivity.java
3975
package com.daemon.pas.presenter.activity; import android.graphics.Bitmap; import android.view.View; import android.view.WindowManager; import android.webkit.WebChromeClient; import android.webkit.WebSettings; import android.webkit.WebView; import android.webkit.WebViewClient; import com.daemon.mvp.presenter.ActivityPresenter; import com.daemon.pas.ui.activity.NewsDetailView; import java.lang.reflect.Field; public class WebViewActivity extends ActivityPresenter<NewsDetailView> implements View.OnClickListener { public static final String URL = "url"; private WebView webView; private boolean blockLoadingNetworkImage; private String url; @Override public Class<NewsDetailView> getIViewClass() { return NewsDetailView.class; } @Override protected void bindEventListener() { super.bindEventListener(); setSupportActionBar(iView.toolbar); iView.toolbar.setNavigationOnClickListener(this); getSupportActionBar().setDisplayHomeAsUpEnabled(true); initWebView(); } private void initWebView() { url = getIntent().getStringExtra(URL); webView = new WebView(getApplicationContext()); iView.rlMain.addView(webView); blockLoadingNetworkImage = true; webView.getSettings().setRenderPriority(WebSettings.RenderPriority.HIGH); webView.getSettings().setBlockNetworkImage(true); webView.setWebViewClient(new webViewClient()); //如果访问的页面中有Javascript,则webview必须设置支持Javascript webView.setWebChromeClient( new WebChromeClient() { @Override public void onProgressChanged(WebView view, int newProgress) { super.onProgressChanged(view, newProgress); if (newProgress == 100) { iView.flLoading.setVisibility(View.GONE); if (blockLoadingNetworkImage) { webView.getSettings().setBlockNetworkImage(false); blockLoadingNetworkImage = false; } } } }); webView.loadUrl(url); } @Override public void onClick(View v) { finish(); } class webViewClient extends WebViewClient { @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { iView.flLoading.setVisibility(View.VISIBLE); //说明不是自己的 或者说 不需要webview去加载的 就自己应用来处理 return false; } @Override public void onPageStarted(WebView view, String url, Bitmap favicon) { super.onPageStarted(view, url, favicon); } } @Override public void onDestroy() { // EventBus.getDefault().unregister(this); if (iView.rlMain != null) { iView.rlMain.removeAllViews(); } setConfigCallback(null); super.onDestroy(); if (webView != null) { webView.setVisibility(View.GONE); webView.removeAllViews(); webView.destroy(); } } public void setConfigCallback(WindowManager windowManager) { try { Field field = WebView.class.getDeclaredField("mWebViewCore"); field = field.getType().getDeclaredField("mBrowserFrame"); field = field.getType().getDeclaredField("sConfigCallback"); field.setAccessible(true); Object configCallback = field.get(null); if (null == configCallback) { return; } field = field.getType().getDeclaredField("mWindowManager"); field.setAccessible(true); field.set(configCallback, windowManager); } catch (Exception e) { } } }
apache-2.0
JoelMarcey/buck
src/com/facebook/buck/file/CopyTree.java
3941
/* * Copyright (c) Facebook, Inc. and 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 com.facebook.buck.file; import com.facebook.buck.core.build.context.BuildContext; import com.facebook.buck.core.filesystems.ForwardRelPath; import com.facebook.buck.core.filesystems.RelPath; import com.facebook.buck.core.model.BuildTarget; import com.facebook.buck.core.rulekey.AddToRuleKey; import com.facebook.buck.core.rules.SourcePathRuleFinder; import com.facebook.buck.core.sourcepath.SourcePath; import com.facebook.buck.io.filesystem.ProjectFilesystem; import com.facebook.buck.rules.modern.BuildCellRelativePathFactory; import com.facebook.buck.rules.modern.Buildable; import com.facebook.buck.rules.modern.ModernBuildRule; import com.facebook.buck.rules.modern.OutputPath; import com.facebook.buck.rules.modern.OutputPathResolver; import com.facebook.buck.step.Step; import com.facebook.buck.step.isolatedsteps.common.CopyIsolatedStep; import com.facebook.buck.step.isolatedsteps.common.MkdirIsolatedStep; import com.facebook.buck.util.MoreMaps; import com.google.common.base.Suppliers; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSortedMap; import java.util.HashSet; import java.util.Set; import java.util.function.Supplier; /** Rule which copies files to the output path using the given layout. */ public class CopyTree extends ModernBuildRule<CopyTree.Impl> { public CopyTree( BuildTarget buildTarget, ProjectFilesystem filesystem, SourcePathRuleFinder finder, ImmutableSortedMap<ForwardRelPath, SourcePath> paths) { super(buildTarget, filesystem, finder, new Impl(paths)); } @Override public SourcePath getSourcePathToOutput() { return getSourcePath(Impl.OUTPUT_PATH); } /** Rule implementation. */ static class Impl implements Buildable { private static final OutputPath OUTPUT_PATH = new OutputPath("copy_tree"); // `ForwardRelativePath` cannot be added to rule keys, so we stringify it below. private final ImmutableSortedMap<ForwardRelPath, SourcePath> paths; @AddToRuleKey private final Supplier<ImmutableMap<String, SourcePath>> stringifedPaths; Impl(ImmutableSortedMap<ForwardRelPath, SourcePath> paths) { this.paths = paths; this.stringifedPaths = Suppliers.memoize(() -> MoreMaps.transformKeys(paths, ForwardRelPath::toString)); } @Override public ImmutableList<Step> getBuildSteps( BuildContext buildContext, ProjectFilesystem filesystem, OutputPathResolver outputPathResolver, BuildCellRelativePathFactory buildCellPathFactory) { ImmutableList.Builder<Step> builder = ImmutableList.builder(); RelPath output = outputPathResolver.resolvePath(OUTPUT_PATH); Set<RelPath> dirs = new HashSet<>(); paths.forEach( (name, path) -> { RelPath dest = output.resolve(name); if (dest.getParent() != null && dirs.add(dest.getParent())) { builder.add(MkdirIsolatedStep.of(dest.getParent())); } builder.add( CopyIsolatedStep.forFile( buildContext.getSourcePathResolver().getAbsolutePath(path).getPath(), output.resolve(name.toPath(filesystem.getFileSystem())))); }); return builder.build(); } } }
apache-2.0
googleads/googleads-java-lib
modules/adwords_appengine/src/main/java/com/google/api/ads/adwords/jaxws/v201809/cm/AppFeedItem.java
7728
// Copyright 2018 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 // // 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.api.ads.adwords.jaxws.v201809.cm; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlSchemaType; import javax.xml.bind.annotation.XmlType; /** * * Represents an App extension. * * * <p>Java class for AppFeedItem complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="AppFeedItem"> * &lt;complexContent> * &lt;extension base="{https://adwords.google.com/api/adwords/cm/v201809}ExtensionFeedItem"> * &lt;sequence> * &lt;element name="appStore" type="{https://adwords.google.com/api/adwords/cm/v201809}AppFeedItem.AppStore" minOccurs="0"/> * &lt;element name="appId" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="appLinkText" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="appUrl" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="appFinalUrls" type="{https://adwords.google.com/api/adwords/cm/v201809}UrlList" minOccurs="0"/> * &lt;element name="appFinalMobileUrls" type="{https://adwords.google.com/api/adwords/cm/v201809}UrlList" minOccurs="0"/> * &lt;element name="appTrackingUrlTemplate" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="appFinalUrlSuffix" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="appUrlCustomParameters" type="{https://adwords.google.com/api/adwords/cm/v201809}CustomParameters" minOccurs="0"/> * &lt;/sequence> * &lt;/extension> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "AppFeedItem", propOrder = { "appStore", "appId", "appLinkText", "appUrl", "appFinalUrls", "appFinalMobileUrls", "appTrackingUrlTemplate", "appFinalUrlSuffix", "appUrlCustomParameters" }) public class AppFeedItem extends ExtensionFeedItem { @XmlSchemaType(name = "string") protected AppFeedItemAppStore appStore; protected String appId; protected String appLinkText; protected String appUrl; protected UrlList appFinalUrls; protected UrlList appFinalMobileUrls; protected String appTrackingUrlTemplate; protected String appFinalUrlSuffix; protected CustomParameters appUrlCustomParameters; /** * Gets the value of the appStore property. * * @return * possible object is * {@link AppFeedItemAppStore } * */ public AppFeedItemAppStore getAppStore() { return appStore; } /** * Sets the value of the appStore property. * * @param value * allowed object is * {@link AppFeedItemAppStore } * */ public void setAppStore(AppFeedItemAppStore value) { this.appStore = value; } /** * Gets the value of the appId property. * * @return * possible object is * {@link String } * */ public String getAppId() { return appId; } /** * Sets the value of the appId property. * * @param value * allowed object is * {@link String } * */ public void setAppId(String value) { this.appId = value; } /** * Gets the value of the appLinkText property. * * @return * possible object is * {@link String } * */ public String getAppLinkText() { return appLinkText; } /** * Sets the value of the appLinkText property. * * @param value * allowed object is * {@link String } * */ public void setAppLinkText(String value) { this.appLinkText = value; } /** * Gets the value of the appUrl property. * * @return * possible object is * {@link String } * */ public String getAppUrl() { return appUrl; } /** * Sets the value of the appUrl property. * * @param value * allowed object is * {@link String } * */ public void setAppUrl(String value) { this.appUrl = value; } /** * Gets the value of the appFinalUrls property. * * @return * possible object is * {@link UrlList } * */ public UrlList getAppFinalUrls() { return appFinalUrls; } /** * Sets the value of the appFinalUrls property. * * @param value * allowed object is * {@link UrlList } * */ public void setAppFinalUrls(UrlList value) { this.appFinalUrls = value; } /** * Gets the value of the appFinalMobileUrls property. * * @return * possible object is * {@link UrlList } * */ public UrlList getAppFinalMobileUrls() { return appFinalMobileUrls; } /** * Sets the value of the appFinalMobileUrls property. * * @param value * allowed object is * {@link UrlList } * */ public void setAppFinalMobileUrls(UrlList value) { this.appFinalMobileUrls = value; } /** * Gets the value of the appTrackingUrlTemplate property. * * @return * possible object is * {@link String } * */ public String getAppTrackingUrlTemplate() { return appTrackingUrlTemplate; } /** * Sets the value of the appTrackingUrlTemplate property. * * @param value * allowed object is * {@link String } * */ public void setAppTrackingUrlTemplate(String value) { this.appTrackingUrlTemplate = value; } /** * Gets the value of the appFinalUrlSuffix property. * * @return * possible object is * {@link String } * */ public String getAppFinalUrlSuffix() { return appFinalUrlSuffix; } /** * Sets the value of the appFinalUrlSuffix property. * * @param value * allowed object is * {@link String } * */ public void setAppFinalUrlSuffix(String value) { this.appFinalUrlSuffix = value; } /** * Gets the value of the appUrlCustomParameters property. * * @return * possible object is * {@link CustomParameters } * */ public CustomParameters getAppUrlCustomParameters() { return appUrlCustomParameters; } /** * Sets the value of the appUrlCustomParameters property. * * @param value * allowed object is * {@link CustomParameters } * */ public void setAppUrlCustomParameters(CustomParameters value) { this.appUrlCustomParameters = value; } }
apache-2.0
dustalov/maxmax
src/main/java/org/nlpub/watset/util/IndexedSense.java
1464
/* * Copyright 2018 Dmitry Ustalov * * 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.nlpub.watset.util; import org.jgrapht.alg.util.Pair; import java.util.Locale; import static java.util.Objects.requireNonNull; /** * An integer sense identifier. * * @param <V> the type of value */ public class IndexedSense<V> extends Pair<V, Integer> implements Sense<V> { /** * Create a sense of an object. * * @param value the object * @param sense the sense identifier */ public IndexedSense(V value, Integer sense) { super(value, requireNonNull(sense)); } @Override public V get() { return first; } /** * Get the sense identifier. * * @return the sense identifier */ public Integer getSense() { return second; } @Override public String toString() { return String.format(Locale.ROOT, "%s#%d", first, second); } }
apache-2.0
sabi0/intellij-community
platform/platform-impl/src/com/intellij/openapi/fileEditor/impl/FileDocumentManagerImpl.java
30349
// 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.fileEditor.impl; import com.intellij.AppTopics; import com.intellij.CommonBundle; import com.intellij.application.options.CodeStyle; import com.intellij.openapi.Disposable; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.application.TransactionGuard; import com.intellij.openapi.application.TransactionGuardImpl; import com.intellij.openapi.application.WriteAction; import com.intellij.openapi.command.CommandProcessor; import com.intellij.openapi.command.UndoConfirmationPolicy; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.editor.Document; import com.intellij.openapi.editor.EditorFactory; import com.intellij.openapi.editor.event.DocumentEvent; import com.intellij.openapi.editor.ex.DocumentEx; import com.intellij.openapi.editor.ex.PrioritizedDocumentListener; import com.intellij.openapi.editor.impl.DocumentImpl; import com.intellij.openapi.editor.impl.EditorFactoryImpl; import com.intellij.openapi.editor.impl.TrailingSpacesStripper; import com.intellij.openapi.extensions.Extensions; import com.intellij.openapi.fileEditor.*; import com.intellij.openapi.fileEditor.impl.text.TextEditorImpl; import com.intellij.openapi.fileTypes.BinaryFileTypeDecompilers; import com.intellij.openapi.fileTypes.FileType; import com.intellij.openapi.fileTypes.UnknownFileType; import com.intellij.openapi.project.*; import com.intellij.openapi.ui.DialogWrapper; import com.intellij.openapi.util.Comparing; import com.intellij.openapi.util.Disposer; import com.intellij.openapi.util.Key; import com.intellij.openapi.util.io.FileUtilRt; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.*; import com.intellij.openapi.vfs.encoding.EncodingManager; import com.intellij.openapi.vfs.newvfs.NewVirtualFileSystem; import com.intellij.pom.core.impl.PomModelImpl; import com.intellij.psi.AbstractFileViewProvider; import com.intellij.psi.ExternalChangeAction; import com.intellij.psi.PsiDocumentManager; import com.intellij.psi.PsiFile; import com.intellij.psi.impl.source.PsiFileImpl; import com.intellij.testFramework.LightVirtualFile; import com.intellij.ui.UIBundle; import com.intellij.ui.components.JBScrollPane; import com.intellij.util.ExceptionUtil; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.messages.MessageBus; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.TestOnly; import javax.swing.*; import java.awt.*; import java.io.IOException; import java.lang.reflect.InvocationHandler; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import java.nio.charset.Charset; import java.util.List; import java.util.*; public class FileDocumentManagerImpl extends FileDocumentManager implements VirtualFileListener, VetoableProjectManagerListener, SafeWriteRequestor { private static final Logger LOG = Logger.getInstance("#com.intellij.openapi.fileEditor.impl.FileDocumentManagerImpl"); public static final Key<Document> HARD_REF_TO_DOCUMENT_KEY = Key.create("HARD_REF_TO_DOCUMENT_KEY"); private static final Key<String> LINE_SEPARATOR_KEY = Key.create("LINE_SEPARATOR_KEY"); private static final Key<VirtualFile> FILE_KEY = Key.create("FILE_KEY"); private static final Key<Boolean> MUST_RECOMPUTE_FILE_TYPE = Key.create("Must recompute file type"); private static final Key<Boolean> BIG_FILE_PREVIEW = Key.create("BIG_FILE_PREVIEW"); private final Set<Document> myUnsavedDocuments = ContainerUtil.newConcurrentSet(); private final MessageBus myBus; private static final Object lock = new Object(); private final FileDocumentManagerListener myMultiCaster; private final TrailingSpacesStripper myTrailingSpacesStripper = new TrailingSpacesStripper(); private boolean myOnClose; private volatile MemoryDiskConflictResolver myConflictResolver = new MemoryDiskConflictResolver(); private final PrioritizedDocumentListener myPhysicalDocumentChangeTracker = new PrioritizedDocumentListener() { @Override public int getPriority() { return Integer.MIN_VALUE; } @Override public void documentChanged(DocumentEvent e) { final Document document = e.getDocument(); if (!ApplicationManager.getApplication().hasWriteAction(ExternalChangeAction.ExternalDocumentChange.class)) { myUnsavedDocuments.add(document); } final Runnable currentCommand = CommandProcessor.getInstance().getCurrentCommand(); Project project = currentCommand == null ? null : CommandProcessor.getInstance().getCurrentCommandProject(); if (project == null) project = ProjectUtil.guessProjectForFile(getFile(document)); String lineSeparator = CodeStyle.getProjectOrDefaultSettings(project).getLineSeparator(); document.putUserData(LINE_SEPARATOR_KEY, lineSeparator); // avoid documents piling up during batch processing if (areTooManyDocumentsInTheQueue(myUnsavedDocuments)) { saveAllDocumentsLater(); } } }; public FileDocumentManagerImpl(@NotNull VirtualFileManager virtualFileManager, @NotNull ProjectManager projectManager) { virtualFileManager.addVirtualFileListener(this); projectManager.addProjectManagerListener(this); myBus = ApplicationManager.getApplication().getMessageBus(); myBus.connect().subscribe(ProjectManager.TOPIC, this); InvocationHandler handler = (proxy, method, args) -> { multiCast(method, args); return null; }; final ClassLoader loader = FileDocumentManagerListener.class.getClassLoader(); myMultiCaster = (FileDocumentManagerListener)Proxy.newProxyInstance(loader, new Class[]{FileDocumentManagerListener.class}, handler); } private static void unwrapAndRethrow(@NotNull Exception e) { Throwable unwrapped = e; if (e instanceof InvocationTargetException) { unwrapped = e.getCause() == null ? e : e.getCause(); } ExceptionUtil.rethrowUnchecked(unwrapped); LOG.error(unwrapped); } @SuppressWarnings("OverlyBroadCatchBlock") private void multiCast(@NotNull Method method, Object[] args) { try { method.invoke(myBus.syncPublisher(AppTopics.FILE_DOCUMENT_SYNC), args); } catch (ClassCastException e) { LOG.error("Arguments: "+ Arrays.toString(args), e); } catch (Exception e) { unwrapAndRethrow(e); } // Allows pre-save document modification for (FileDocumentManagerListener listener : getListeners()) { try { method.invoke(listener, args); } catch (Exception e) { unwrapAndRethrow(e); } } // stripping trailing spaces try { method.invoke(myTrailingSpacesStripper, args); } catch (Exception e) { unwrapAndRethrow(e); } } @Override @Nullable public Document getDocument(@NotNull final VirtualFile file) { ApplicationManager.getApplication().assertReadAccessAllowed(); DocumentEx document = (DocumentEx)getCachedDocument(file); if (document == null) { if (!file.isValid() || file.isDirectory() || isBinaryWithoutDecompiler(file)) return null; boolean tooLarge = FileUtilRt.isTooLarge(file.getLength()); if (file.getFileType().isBinary() && tooLarge) return null; final CharSequence text = tooLarge ? LoadTextUtil.loadText(file, getPreviewCharCount(file)) : LoadTextUtil.loadText(file); synchronized (lock) { document = (DocumentEx)getCachedDocument(file); if (document != null) return document; // Double checking document = (DocumentEx)createDocument(text, file); document.setModificationStamp(file.getModificationStamp()); document.putUserData(BIG_FILE_PREVIEW, tooLarge ? Boolean.TRUE : null); final FileType fileType = file.getFileType(); document.setReadOnly(tooLarge || !file.isWritable() || fileType.isBinary()); if (!(file instanceof LightVirtualFile || file.getFileSystem() instanceof NonPhysicalFileSystem)) { document.addDocumentListener(myPhysicalDocumentChangeTracker); } if (file instanceof LightVirtualFile) { registerDocument(document, file); } else { document.putUserData(FILE_KEY, file); cacheDocument(file, document); } } myMultiCaster.fileContentLoaded(file, document); } return document; } public static boolean areTooManyDocumentsInTheQueue(@NotNull Collection<? extends Document> documents) { if (documents.size() > 100) return true; int totalSize = 0; for (Document document : documents) { totalSize += document.getTextLength(); if (totalSize > FileUtilRt.LARGE_FOR_CONTENT_LOADING) return true; } return false; } @NotNull private static Document createDocument(@NotNull CharSequence text, @NotNull VirtualFile file) { boolean acceptSlashR = file instanceof LightVirtualFile && StringUtil.indexOf(text, '\r') >= 0; boolean freeThreaded = Boolean.TRUE.equals(file.getUserData(AbstractFileViewProvider.FREE_THREADED)); DocumentImpl document = (DocumentImpl)((EditorFactoryImpl)EditorFactory.getInstance()).createDocument(text, acceptSlashR, freeThreaded); document.documentCreatedFrom(file); return document; } @Override @Nullable public Document getCachedDocument(@NotNull VirtualFile file) { Document hard = file.getUserData(HARD_REF_TO_DOCUMENT_KEY); return hard != null ? hard : getDocumentFromCache(file); } public static void registerDocument(@NotNull final Document document, @NotNull VirtualFile virtualFile) { synchronized (lock) { document.putUserData(FILE_KEY, virtualFile); virtualFile.putUserData(HARD_REF_TO_DOCUMENT_KEY, document); } } @Override @Nullable public VirtualFile getFile(@NotNull Document document) { return document.getUserData(FILE_KEY); } @TestOnly public void dropAllUnsavedDocuments() { if (!ApplicationManager.getApplication().isUnitTestMode()) { throw new RuntimeException("This method is only for test mode!"); } ApplicationManager.getApplication().assertWriteAccessAllowed(); if (!myUnsavedDocuments.isEmpty()) { myUnsavedDocuments.clear(); fireUnsavedDocumentsDropped(); } } private void saveAllDocumentsLater() { // later because some document might have been blocked by PSI right now ApplicationManager.getApplication().invokeLater(() -> { if (ApplicationManager.getApplication().isDisposed()) { return; } final Document[] unsavedDocuments = getUnsavedDocuments(); for (Document document : unsavedDocuments) { VirtualFile file = getFile(document); if (file == null) continue; Project project = ProjectUtil.guessProjectForFile(file); if (project == null) continue; if (PsiDocumentManager.getInstance(project).isDocumentBlockedByPsi(document)) continue; saveDocument(document); } }); } @Override public void saveAllDocuments() { saveAllDocuments(true); } /** * @param isExplicit caused by user directly (Save action) or indirectly (e.g. Compile) */ public void saveAllDocuments(boolean isExplicit) { ApplicationManager.getApplication().assertIsDispatchThread(); ((TransactionGuardImpl)TransactionGuard.getInstance()).assertWriteActionAllowed(); myMultiCaster.beforeAllDocumentsSaving(); if (myUnsavedDocuments.isEmpty()) return; final Map<Document, IOException> failedToSave = new HashMap<>(); final Set<Document> vetoed = new HashSet<>(); while (true) { int count = 0; for (Document document : myUnsavedDocuments) { if (failedToSave.containsKey(document)) continue; if (vetoed.contains(document)) continue; try { doSaveDocument(document, isExplicit); } catch (IOException e) { //noinspection ThrowableResultOfMethodCallIgnored failedToSave.put(document, e); } catch (SaveVetoException e) { vetoed.add(document); } count++; } if (count == 0) break; } if (!failedToSave.isEmpty()) { handleErrorsOnSave(failedToSave); } } @Override public void saveDocument(@NotNull final Document document) { saveDocument(document, true); } public void saveDocument(@NotNull final Document document, final boolean explicit) { ApplicationManager.getApplication().assertIsDispatchThread(); ((TransactionGuardImpl)TransactionGuard.getInstance()).assertWriteActionAllowed(); if (!myUnsavedDocuments.contains(document)) return; try { doSaveDocument(document, explicit); } catch (IOException e) { handleErrorsOnSave(Collections.singletonMap(document, e)); } catch (SaveVetoException ignored) { } } @Override public void saveDocumentAsIs(@NotNull Document document) { VirtualFile file = getFile(document); boolean spaceStrippingEnabled = true; if (file != null) { spaceStrippingEnabled = TrailingSpacesStripper.isEnabled(file); TrailingSpacesStripper.setEnabled(file, false); } try { saveDocument(document); } finally { if (file != null) { TrailingSpacesStripper.setEnabled(file, spaceStrippingEnabled); } } } private static class SaveVetoException extends Exception {} private void doSaveDocument(@NotNull final Document document, boolean isExplicit) throws IOException, SaveVetoException { VirtualFile file = getFile(document); if (LOG.isTraceEnabled()) LOG.trace("saving: " + file); if (file == null || file instanceof LightVirtualFile || file.isValid() && !isFileModified(file)) { removeFromUnsaved(document); return; } if (file.isValid() && needsRefresh(file)) { LOG.trace(" refreshing..."); file.refresh(false, false); if (!myUnsavedDocuments.contains(document)) return; } if (!maySaveDocument(file, document, isExplicit)) { throw new SaveVetoException(); } LOG.trace(" writing..."); WriteAction.run(() -> doSaveDocumentInWriteAction(document, file)); LOG.trace(" done"); } private boolean maySaveDocument(@NotNull VirtualFile file, @NotNull Document document, boolean isExplicit) { return !myConflictResolver.hasConflict(file) && Arrays.stream(Extensions.getExtensions(FileDocumentSynchronizationVetoer.EP_NAME)).allMatch(vetoer -> vetoer.maySaveDocument(document, isExplicit)); } private void doSaveDocumentInWriteAction(@NotNull final Document document, @NotNull final VirtualFile file) throws IOException { if (!file.isValid()) { removeFromUnsaved(document); return; } if (!file.equals(getFile(document))) { registerDocument(document, file); } boolean saveNeeded = false; IOException ioException = null; try { saveNeeded = isSaveNeeded(document, file); } catch (IOException e) { // in case of corrupted VFS try to stay consistent ioException = e; } if (!saveNeeded) { if (document instanceof DocumentEx) { ((DocumentEx)document).setModificationStamp(file.getModificationStamp()); } removeFromUnsaved(document); updateModifiedProperty(file); if (ioException != null) throw ioException; return; } PomModelImpl.guardPsiModificationsIn(() -> { myMultiCaster.beforeDocumentSaving(document); LOG.assertTrue(file.isValid()); String text = document.getText(); String lineSeparator = getLineSeparator(document, file); if (!lineSeparator.equals("\n")) { text = StringUtil.convertLineSeparators(text, lineSeparator); } Project project = ProjectLocator.getInstance().guessProjectForFile(file); LoadTextUtil.write(project, file, this, text, document.getModificationStamp()); myUnsavedDocuments.remove(document); LOG.assertTrue(!myUnsavedDocuments.contains(document)); myTrailingSpacesStripper.clearLineModificationFlags(document); }); } private static void updateModifiedProperty(@NotNull VirtualFile file) { for (Project project : ProjectManager.getInstance().getOpenProjects()) { FileEditorManager fileEditorManager = FileEditorManager.getInstance(project); for (FileEditor editor : fileEditorManager.getAllEditors(file)) { if (editor instanceof TextEditorImpl) { ((TextEditorImpl)editor).updateModifiedProperty(); } } } } private void removeFromUnsaved(@NotNull Document document) { myUnsavedDocuments.remove(document); fireUnsavedDocumentsDropped(); LOG.assertTrue(!myUnsavedDocuments.contains(document)); } private static boolean isSaveNeeded(@NotNull Document document, @NotNull VirtualFile file) throws IOException { if (file.getFileType().isBinary() || document.getTextLength() > 1000 * 1000) { // don't compare if the file is too big return true; } byte[] bytes = file.contentsToByteArray(); CharSequence loaded = LoadTextUtil.getTextByBinaryPresentation(bytes, file, false, false); return !Comparing.equal(document.getCharsSequence(), loaded); } private static boolean needsRefresh(@NotNull VirtualFile file) { final VirtualFileSystem fs = file.getFileSystem(); return fs instanceof NewVirtualFileSystem && file.getTimeStamp() != ((NewVirtualFileSystem)fs).getTimeStamp(file); } @NotNull public static String getLineSeparator(@NotNull Document document, @NotNull VirtualFile file) { String lineSeparator = LoadTextUtil.getDetectedLineSeparator(file); if (lineSeparator == null) { lineSeparator = document.getUserData(LINE_SEPARATOR_KEY); assert lineSeparator != null : document; } return lineSeparator; } @Override @NotNull public String getLineSeparator(@Nullable VirtualFile file, @Nullable Project project) { String lineSeparator = file == null ? null : LoadTextUtil.getDetectedLineSeparator(file); if (lineSeparator == null) { lineSeparator = CodeStyle.getProjectOrDefaultSettings(project).getLineSeparator(); } return lineSeparator; } @Override public boolean requestWriting(@NotNull Document document, Project project) { final VirtualFile file = getInstance().getFile(document); if (project != null && file != null && file.isValid()) { return !file.getFileType().isBinary() && ReadonlyStatusHandler.ensureFilesWritable(project, file); } if (document.isWritable()) { return true; } document.fireReadOnlyModificationAttempt(); return false; } @Override public void reloadFiles(@NotNull final VirtualFile... files) { for (VirtualFile file : files) { if (file.exists()) { final Document doc = getCachedDocument(file); if (doc != null) { reloadFromDisk(doc); } } } } @Override @NotNull public Document[] getUnsavedDocuments() { if (myUnsavedDocuments.isEmpty()) { return Document.EMPTY_ARRAY; } List<Document> list = new ArrayList<>(myUnsavedDocuments); return list.toArray(Document.EMPTY_ARRAY); } @Override public boolean isDocumentUnsaved(@NotNull Document document) { return myUnsavedDocuments.contains(document); } @Override public boolean isFileModified(@NotNull VirtualFile file) { final Document doc = getCachedDocument(file); return doc != null && isDocumentUnsaved(doc) && doc.getModificationStamp() != file.getModificationStamp(); } @Override public boolean isPartialPreviewOfALargeFile(@NotNull Document document) { return document.getUserData(BIG_FILE_PREVIEW) == Boolean.TRUE; } @Override public void propertyChanged(@NotNull VirtualFilePropertyEvent event) { final VirtualFile file = event.getFile(); if (VirtualFile.PROP_WRITABLE.equals(event.getPropertyName())) { final Document document = getCachedDocument(file); if (document != null) { ApplicationManager.getApplication().runWriteAction((ExternalChangeAction)() -> document.setReadOnly(!file.isWritable())); } } else if (VirtualFile.PROP_NAME.equals(event.getPropertyName())) { Document document = getCachedDocument(file); if (document != null) { // a file is linked to a document - chances are it is an "unknown text file" now if (isBinaryWithoutDecompiler(file)) { unbindFileFromDocument(file, document); } } } } private void unbindFileFromDocument(@NotNull VirtualFile file, @NotNull Document document) { removeDocumentFromCache(file); file.putUserData(HARD_REF_TO_DOCUMENT_KEY, null); document.putUserData(FILE_KEY, null); } private static boolean isBinaryWithDecompiler(@NotNull VirtualFile file) { final FileType ft = file.getFileType(); return ft.isBinary() && BinaryFileTypeDecompilers.INSTANCE.forFileType(ft) != null; } private static boolean isBinaryWithoutDecompiler(@NotNull VirtualFile file) { final FileType fileType = file.getFileType(); return fileType.isBinary() && BinaryFileTypeDecompilers.INSTANCE.forFileType(fileType) == null; } private static final Key<Document> DOCUMENT_WAS_SAVED_TEMPORARILY = Key.create("DOCUMENT_WAS_SAVED_TEMPORARILY"); @Override public void beforeContentsChange(@NotNull VirtualFileEvent event) { VirtualFile virtualFile = event.getFile(); // check file type in second order to avoid content detection running if (virtualFile.getLength() == 0 && virtualFile.getFileType() == UnknownFileType.INSTANCE) { virtualFile.putUserData(MUST_RECOMPUTE_FILE_TYPE, Boolean.TRUE); } if (ourConflictsSolverEnabled) { myConflictResolver.beforeContentChange(event); } Document document = getCachedDocument(virtualFile); if (document == null && DocumentImpl.areRangeMarkersRetainedFor(virtualFile)) { // re-create document with the old contents prior to this event // then contentChanged() will diff the document with the new contents and update the markers document = getDocument(virtualFile); } // save document strongly to make it live until contentChanged() virtualFile.putUserData(DOCUMENT_WAS_SAVED_TEMPORARILY, document); } @Override public void contentsChanged(@NotNull VirtualFileEvent event) { final VirtualFile virtualFile = event.getFile(); final Document document = getCachedDocument(virtualFile); // remove strong ref to allow document to gc virtualFile.putUserData(DOCUMENT_WAS_SAVED_TEMPORARILY, null); if (event.isFromSave()) return; if (document == null || isBinaryWithDecompiler(virtualFile)) { myMultiCaster.fileWithNoDocumentChanged(virtualFile); // This will generate PSI event at FileManagerImpl } if (document != null && (document.getModificationStamp() == event.getOldModificationStamp() || !isDocumentUnsaved(document))) { reloadFromDisk(document); } } @Override public void reloadFromDisk(@NotNull final Document document) { ApplicationManager.getApplication().assertIsDispatchThread(); final VirtualFile file = getFile(document); assert file != null; if (!fireBeforeFileContentReload(file, document)) { return; } final Project project = ProjectLocator.getInstance().guessProjectForFile(file); boolean[] isReloadable = {isReloadable(file, document, project)}; if (isReloadable[0]) { CommandProcessor.getInstance().executeCommand(project, () -> ApplicationManager.getApplication().runWriteAction( new ExternalChangeAction.ExternalDocumentChange(document, project) { @Override public void run() { if (!isBinaryWithoutDecompiler(file)) { LoadTextUtil.clearCharsetAutoDetectionReason(file); file.setBOM(null); // reset BOM in case we had one and the external change stripped it away file.setCharset(null, null, false); boolean wasWritable = document.isWritable(); document.setReadOnly(false); boolean tooLarge = FileUtilRt.isTooLarge(file.getLength()); isReloadable[0] = isReloadable(file, document, project); if (isReloadable[0]) { CharSequence reloaded = tooLarge ? LoadTextUtil.loadText(file, getPreviewCharCount(file)) : LoadTextUtil.loadText(file); ((DocumentEx)document).replaceText(reloaded, file.getModificationStamp()); document.putUserData(BIG_FILE_PREVIEW, tooLarge ? Boolean.TRUE : null); } document.setReadOnly(!wasWritable); } } } ), UIBundle.message("file.cache.conflict.action"), null, UndoConfirmationPolicy.REQUEST_CONFIRMATION); } if (isReloadable[0]) { myMultiCaster.fileContentReloaded(file, document); } else { unbindFileFromDocument(file, document); myMultiCaster.fileWithNoDocumentChanged(file); } myUnsavedDocuments.remove(document); } private static boolean isReloadable(@NotNull VirtualFile file, @NotNull Document document, @Nullable Project project) { PsiFile cachedPsiFile = project == null ? null : PsiDocumentManager.getInstance(project).getCachedPsiFile(document); return !(FileUtilRt.isTooLarge(file.getLength()) && file.getFileType().isBinary()) && (cachedPsiFile == null || cachedPsiFile instanceof PsiFileImpl || isBinaryWithDecompiler(file)); } @TestOnly void setAskReloadFromDisk(@NotNull Disposable disposable, @NotNull MemoryDiskConflictResolver newProcessor) { final MemoryDiskConflictResolver old = myConflictResolver; myConflictResolver = newProcessor; Disposer.register(disposable, () -> myConflictResolver = old); } @Override public void fileDeleted(@NotNull VirtualFileEvent event) { Document doc = getCachedDocument(event.getFile()); if (doc != null) { myTrailingSpacesStripper.documentDeleted(doc); } } public static boolean recomputeFileTypeIfNecessary(@NotNull VirtualFile virtualFile) { if (virtualFile.getUserData(MUST_RECOMPUTE_FILE_TYPE) != null) { virtualFile.getFileType(); virtualFile.putUserData(MUST_RECOMPUTE_FILE_TYPE, null); return true; } return false; } @Override public boolean canClose(@NotNull Project project) { if (!myUnsavedDocuments.isEmpty()) { myOnClose = true; try { saveAllDocuments(); } finally { myOnClose = false; } } return myUnsavedDocuments.isEmpty(); } private void fireUnsavedDocumentsDropped() { myMultiCaster.unsavedDocumentsDropped(); } private boolean fireBeforeFileContentReload(@NotNull VirtualFile file, @NotNull Document document) { for (FileDocumentSynchronizationVetoer vetoer : Extensions.getExtensions(FileDocumentSynchronizationVetoer.EP_NAME)) { try { if (!vetoer.mayReloadFileContent(file, document)) { return false; } } catch (Exception e) { LOG.error(e); } } myMultiCaster.beforeFileContentReload(file, document); return true; } @NotNull private static List<FileDocumentManagerListener> getListeners() { return FileDocumentManagerListener.EP_NAME.getExtensionList(); } private static int getPreviewCharCount(@NotNull VirtualFile file) { Charset charset = EncodingManager.getInstance().getEncoding(file, false); float bytesPerChar = charset == null ? 2 : charset.newEncoder().averageBytesPerChar(); return (int)(FileUtilRt.LARGE_FILE_PREVIEW_SIZE / bytesPerChar); } private void handleErrorsOnSave(@NotNull Map<Document, IOException> failures) { if (ApplicationManager.getApplication().isUnitTestMode()) { IOException ioException = ContainerUtil.getFirstItem(failures.values()); if (ioException != null) { throw new RuntimeException(ioException); } return; } for (IOException exception : failures.values()) { LOG.warn(exception); } final String text = StringUtil.join(failures.values(), Throwable::getMessage, "\n"); final DialogWrapper dialog = new DialogWrapper(null) { { init(); setTitle(UIBundle.message("cannot.save.files.dialog.title")); } @Override protected void createDefaultActions() { super.createDefaultActions(); myOKAction.putValue(Action.NAME, UIBundle .message(myOnClose ? "cannot.save.files.dialog.ignore.changes" : "cannot.save.files.dialog.revert.changes")); myOKAction.putValue(DEFAULT_ACTION, null); if (!myOnClose) { myCancelAction.putValue(Action.NAME, CommonBundle.getCloseButtonText()); } } @Override protected JComponent createCenterPanel() { final JPanel panel = new JPanel(new BorderLayout(0, 5)); panel.add(new JLabel(UIBundle.message("cannot.save.files.dialog.message")), BorderLayout.NORTH); final JTextPane area = new JTextPane(); area.setText(text); area.setEditable(false); area.setMinimumSize(new Dimension(area.getMinimumSize().width, 50)); panel.add(new JBScrollPane(area, ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER), BorderLayout.CENTER); return panel; } }; if (dialog.showAndGet()) { for (Document document : failures.keySet()) { reloadFromDisk(document); } } } private final Map<VirtualFile, Document> myDocumentCache = ContainerUtil.createConcurrentWeakValueMap(); //temp setter for Rider 2017.1 public static boolean ourConflictsSolverEnabled = true; private void cacheDocument(@NotNull VirtualFile file, @NotNull Document document) { myDocumentCache.put(file, document); } private void removeDocumentFromCache(@NotNull VirtualFile file) { myDocumentCache.remove(file); } private Document getDocumentFromCache(@NotNull VirtualFile file) { return myDocumentCache.get(file); } }
apache-2.0
pjagielski/jersey2-starter
src/main/java/pl/pjagielski/TodoEndpoint.java
1432
package pl.pjagielski; import static javax.ws.rs.core.MediaType.APPLICATION_JSON; import static javax.ws.rs.core.Response.Status.CREATED; import static javax.ws.rs.core.Response.Status.OK; import javax.inject.Inject; import javax.ws.rs.Consumes; import javax.ws.rs.NotFoundException; import javax.ws.rs.POST; import javax.ws.rs.PUT; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.core.Response; import pl.pjagielski.constraint.ValidForCreation; import pl.pjagielski.constraint.ValidForModification; import pl.pjagielski.model.Todo; @Path("todo") public class TodoEndpoint { private final TodoRepository service; @Inject public TodoEndpoint(TodoRepository service) { this.service = service; } @POST @Consumes(APPLICATION_JSON) public Response create(@ValidForCreation Todo todo) { service.create(todo); return Response.status(CREATED).type(APPLICATION_JSON) .entity(todo).build(); } @PUT @Path("/{todoId}") @Consumes(APPLICATION_JSON) public Response update(@PathParam("todoId") Long todoId, @ValidForModification Todo todo) { Todo updatedTodo = service.update(todoId, todo); if (updatedTodo == null) { throw new NotFoundException("Todo [" + todoId + "] not found"); } return Response.status(OK).type(APPLICATION_JSON) .entity(updatedTodo).build(); } }
apache-2.0
Git-Yogurt/WeatherApplication
app/src/main/java/com/weather/yogurt/weatherapp/activity/WeatherActivity.java
9501
package com.weather.yogurt.weatherapp.activity; import android.app.Activity; import android.app.ProgressDialog; 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.widget.Button; import android.widget.LinearLayout; import android.widget.TextView; import com.weather.yogurt.weatherapp.R; import com.weather.yogurt.weatherapp.service.AutoUpdateService; import com.weather.yogurt.weatherapp.util.HttpCallbackListener; import com.weather.yogurt.weatherapp.util.HttpUtil; import com.weather.yogurt.weatherapp.util.Utility; import org.json.JSONException; /** * Created by Yogurt on 5/21/16. */ public class WeatherActivity extends Activity implements View.OnClickListener{ private LinearLayout weatherInfoLayout; private TextView cityNameText;//显示城市 private TextView weatherConditionText;//天气大概状况 private TextView weatherTemperatureText; private TextView weatherConditionDetailText,hourlyWeatherCondition; private Button switchCity,refresh; private HttpCallbackListener listener; private ProgressDialog progressDialog; // WeatherDB weatherDB=WeatherDB.getInstance(this); @Override protected void onCreate(Bundle savedInstanceState) { SharedPreferences prefs=PreferenceManager.getDefaultSharedPreferences(this); super.onCreate(savedInstanceState); setContentView(R.layout.weather_layout); weatherInfoLayout= (LinearLayout) findViewById(R.id.weather_info_layout); cityNameText= (TextView) findViewById(R.id.city_name_title); weatherConditionText= (TextView) findViewById(R.id.weather_condition_text); weatherTemperatureText= (TextView) findViewById(R.id.weather_temperature_text); weatherConditionDetailText= (TextView) findViewById(R.id.weather_condition_detail_text); hourlyWeatherCondition= (TextView) findViewById(R.id.hourly_weather_condition); switchCity= (Button) findViewById(R.id.switch_city); refresh= (Button) findViewById(R.id.refresh); requestAddShow(prefs.getString("basic_city","")); switchCity.setOnClickListener(this); refresh.setOnClickListener(this); } /* 从sharedPreferences里面取出天气信息,显示到界面上 */ private void showWeather(){ SharedPreferences prefs= PreferenceManager.getDefaultSharedPreferences(this); //Log.d("AAAAA",prefs.getString("basic_city","")); cityNameText.setText(prefs.getString("basic_city","")); weatherConditionText.setText(prefs.getString("now_cond_txt","")+","+prefs.getString("now_wind_dir","")+" "+prefs.getString("now_wind_sc","")+"级"); weatherTemperatureText.setText(prefs.getString("tmp_min_0","")+"° ~ "+prefs.getString("tmp_max_0","")+"°"); StringBuilder hourlySb=new StringBuilder(); for (int i=0;i<prefs.getInt("hourly_length",0);i++){ String up=prefs.getString("today_date_"+i,"").substring(prefs.getString("today_date_"+i,"").indexOf(" ")); // Log.d("todaydate",prefs.getString("today_date_"+i,"")); hourlySb.append(up.substring(0,3)).append("时").append(":"); hourlySb.append(prefs.getString("today_tmp_"+i,"")).append("°").append(" "); } hourlyWeatherCondition.setText(hourlySb); StringBuilder weatherDetail=new StringBuilder(); for (int i=0;i<7;i++){ StringBuilder sb=new StringBuilder(); //Log.d("dateI",prefs.getString("date_"+i,"")); sb.append(prefs.getString("date_"+i,"").substring(5)).append(" "); String weaD=prefs.getString("cond_txt_d_"+i,""); String weaN=prefs.getString("cond_txt_n_"+i,""); StringBuilder cond=new StringBuilder(); if (weaD.equals(weaN)){ cond.append(weaD); }else { cond.append(weaD).append("转").append(weaN); } int len=cond.length(); for (int j=0;j<=7-len;j++) { cond.append(" "); } sb.append(cond); String maxTmp=prefs.getString("tmp_max_"+i,""); String minTmp=prefs.getString("tmp_min_"+i,""); sb.append(minTmp).append("° ~ ").append(maxTmp).append("°"); sb.append("\r\n"); weatherDetail.append(sb); } weatherDetail.append("\r\n"); weatherDetail.append("舒适度指数:").append(prefs.getString("suggestion_comf_brf","")).append("; ").append(prefs.getString("suggestion_comf_txt","")).append("\r\n\r\n"); weatherDetail.append("洗车指数:").append(prefs.getString("suggestion_cw_brf","")).append("; ").append(prefs.getString("suggestion_cw_txt","")).append("\r\n\r\n"); weatherDetail.append("穿衣指数:").append(prefs.getString("suggestion_drsg_brf","")).append("; ").append(prefs.getString("suggestion_drsg_txt","")).append("\r\n\r\n"); weatherDetail.append("感冒指数:").append(prefs.getString("suggestion_flu_brf","")).append("; ").append(prefs.getString("suggestion_flu_txt","")).append("\r\n\r\n"); weatherDetail.append("运动指数:").append(prefs.getString("suggestion_sport_brf","")).append("; ").append(prefs.getString("suggestion_sport_txt","")).append("\r\n\r\n"); weatherDetail.append("旅游指数:").append(prefs.getString("suggestion_trav_brf","")).append("; ").append(prefs.getString("suggestion_trav_txt","")).append("\r\n\r\n"); weatherDetail.append("紫外线指数:").append(prefs.getString("suggestion_uv_brf","")).append("; ").append(prefs.getString("suggestion_uv_txt","")).append("\r\n\r\n"); weatherConditionDetailText.setText(weatherDetail); Intent intent=new Intent(this, AutoUpdateService.class); startService(intent); } @Override public void onClick(View v) { switch (v.getId()){ case R.id.switch_city: Intent intent=new Intent(WeatherActivity.this,ChooseAreaActivity.class); intent.putExtra("from_weather_activity",true); startActivityForResult(intent,1); break; case R.id.refresh: SharedPreferences prefs=PreferenceManager.getDefaultSharedPreferences(this); // Log.d("basic_city",prefs.getString("basic_city","")); requestAddShow(prefs.getString("basic_city","")); Log.d("refresh","Successful"); break; } } @Override protected void onActivityResult(int requestCode, int resultCode, final Intent data) { switch (resultCode){ case RESULT_OK: if (requestCode==1){ runOnUiThread(new Runnable() { @Override public void run() { showProgressDialog(); } }); new Thread(new Runnable() { @Override public void run() { requestAddShow(data.getStringExtra("country_name_pinyin")); } }).start(); } break; default: break; } } private void requestAddShow(String countryName){ // String basicCity=PreferenceManager.getDefaultSharedPreferences(this).getString("basic_city",""); // if (!countryName.equals(basicCity)){ runOnUiThread(new Runnable() { @Override public void run() { showProgressDialog(); } }); // } listener=new HttpCallbackListener() { @Override public void onFinish(String result) { runOnUiThread(new Runnable() { @Override public void run() { //closeProgressDialog(); } }); try { boolean flag=Utility.handleWeatherConditionResponse(WeatherActivity.this,result); if (flag){ runOnUiThread(new Runnable() { @Override public void run() { closeProgressDialog(); showWeather(); } }); } } catch (JSONException e) { e.printStackTrace(); } } @Override public void onError(Exception e) { e.printStackTrace(); } }; HttpUtil.sendHttpRequest("http://apis.baidu.com/heweather/weather/free?city="+countryName,listener,null); } /* 显示进度对话框 */ private void showProgressDialog() { if (progressDialog==null){ progressDialog=new ProgressDialog(this); progressDialog.setMessage("正在加载..."); progressDialog.setCanceledOnTouchOutside(false); } progressDialog.show(); } private void closeProgressDialog(){ if (progressDialog!=null){ progressDialog.dismiss(); } } }
apache-2.0
nsicontest/nsi-ri
src/org/w3/_2001/_04/xmlenc/AgreementMethodType.java
3856
package org.w3._2001._04.xmlenc; import java.util.ArrayList; import java.util.List; import javax.xml.bind.JAXBElement; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAnyElement; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlElementRef; import javax.xml.bind.annotation.XmlElementRefs; import javax.xml.bind.annotation.XmlMixed; import javax.xml.bind.annotation.XmlSchemaType; import javax.xml.bind.annotation.XmlType; import org.w3._2000._09.xmldsig.KeyInfoType; /** * <p>Java class for AgreementMethodType complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="AgreementMethodType"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="KA-Nonce" type="{http://www.w3.org/2001/XMLSchema}base64Binary" minOccurs="0"/> * &lt;any namespace='##other' maxOccurs="unbounded" minOccurs="0"/> * &lt;element name="OriginatorKeyInfo" type="{http://www.w3.org/2000/09/xmldsig#}KeyInfoType" minOccurs="0"/> * &lt;element name="RecipientKeyInfo" type="{http://www.w3.org/2000/09/xmldsig#}KeyInfoType" minOccurs="0"/> * &lt;/sequence> * &lt;attribute name="Algorithm" use="required" type="{http://www.w3.org/2001/XMLSchema}anyURI" /> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "AgreementMethodType", propOrder = { "content" }) public class AgreementMethodType { @XmlElementRefs({ @XmlElementRef(name = "RecipientKeyInfo", namespace = "http://www.w3.org/2001/04/xmlenc#", type = JAXBElement.class, required = false), @XmlElementRef(name = "KA-Nonce", namespace = "http://www.w3.org/2001/04/xmlenc#", type = JAXBElement.class, required = false), @XmlElementRef(name = "OriginatorKeyInfo", namespace = "http://www.w3.org/2001/04/xmlenc#", type = JAXBElement.class, required = false) }) @XmlMixed @XmlAnyElement(lax = true) protected List<Object> content; @XmlAttribute(name = "Algorithm", required = true) @XmlSchemaType(name = "anyURI") protected String algorithm; /** * Gets the value of the content 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 content property. * * <p> * For example, to add a new item, do as follows: * <pre> * getContent().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link JAXBElement }{@code <}{@link KeyInfoType }{@code >} * {@link String } * {@link Object } * {@link JAXBElement }{@code <}{@link byte[]}{@code >} * {@link JAXBElement }{@code <}{@link KeyInfoType }{@code >} * * */ public List<Object> getContent() { if (content == null) { content = new ArrayList<Object>(); } return this.content; } /** * Gets the value of the algorithm property. * * @return * possible object is * {@link String } * */ public String getAlgorithm() { return algorithm; } /** * Sets the value of the algorithm property. * * @param value * allowed object is * {@link String } * */ public void setAlgorithm(String value) { this.algorithm = value; } }
apache-2.0
googleapis/java-vision
proto-google-cloud-vision-v1p1beta1/src/main/java/com/google/cloud/vision/v1p1beta1/Likelihood.java
5896
/* * 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/vision/v1p1beta1/image_annotator.proto package com.google.cloud.vision.v1p1beta1; /** * * * <pre> * A bucketized representation of likelihood, which is intended to give clients * highly stable results across model upgrades. * </pre> * * Protobuf enum {@code google.cloud.vision.v1p1beta1.Likelihood} */ public enum Likelihood implements com.google.protobuf.ProtocolMessageEnum { /** * * * <pre> * Unknown likelihood. * </pre> * * <code>UNKNOWN = 0;</code> */ UNKNOWN(0), /** * * * <pre> * It is very unlikely that the image belongs to the specified vertical. * </pre> * * <code>VERY_UNLIKELY = 1;</code> */ VERY_UNLIKELY(1), /** * * * <pre> * It is unlikely that the image belongs to the specified vertical. * </pre> * * <code>UNLIKELY = 2;</code> */ UNLIKELY(2), /** * * * <pre> * It is possible that the image belongs to the specified vertical. * </pre> * * <code>POSSIBLE = 3;</code> */ POSSIBLE(3), /** * * * <pre> * It is likely that the image belongs to the specified vertical. * </pre> * * <code>LIKELY = 4;</code> */ LIKELY(4), /** * * * <pre> * It is very likely that the image belongs to the specified vertical. * </pre> * * <code>VERY_LIKELY = 5;</code> */ VERY_LIKELY(5), UNRECOGNIZED(-1), ; /** * * * <pre> * Unknown likelihood. * </pre> * * <code>UNKNOWN = 0;</code> */ public static final int UNKNOWN_VALUE = 0; /** * * * <pre> * It is very unlikely that the image belongs to the specified vertical. * </pre> * * <code>VERY_UNLIKELY = 1;</code> */ public static final int VERY_UNLIKELY_VALUE = 1; /** * * * <pre> * It is unlikely that the image belongs to the specified vertical. * </pre> * * <code>UNLIKELY = 2;</code> */ public static final int UNLIKELY_VALUE = 2; /** * * * <pre> * It is possible that the image belongs to the specified vertical. * </pre> * * <code>POSSIBLE = 3;</code> */ public static final int POSSIBLE_VALUE = 3; /** * * * <pre> * It is likely that the image belongs to the specified vertical. * </pre> * * <code>LIKELY = 4;</code> */ public static final int LIKELY_VALUE = 4; /** * * * <pre> * It is very likely that the image belongs to the specified vertical. * </pre> * * <code>VERY_LIKELY = 5;</code> */ public static final int VERY_LIKELY_VALUE = 5; 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 Likelihood 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 Likelihood forNumber(int value) { switch (value) { case 0: return UNKNOWN; case 1: return VERY_UNLIKELY; case 2: return UNLIKELY; case 3: return POSSIBLE; case 4: return LIKELY; case 5: return VERY_LIKELY; default: return null; } } public static com.google.protobuf.Internal.EnumLiteMap<Likelihood> internalGetValueMap() { return internalValueMap; } private static final com.google.protobuf.Internal.EnumLiteMap<Likelihood> internalValueMap = new com.google.protobuf.Internal.EnumLiteMap<Likelihood>() { public Likelihood findValueByNumber(int number) { return Likelihood.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.vision.v1p1beta1.ImageAnnotatorProto.getDescriptor() .getEnumTypes() .get(0); } private static final Likelihood[] VALUES = values(); public static Likelihood 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 Likelihood(int value) { this.value = value; } // @@protoc_insertion_point(enum_scope:google.cloud.vision.v1p1beta1.Likelihood) }
apache-2.0
nmcl/scratch
AdventOfCode/2019/day20/part1/Traveller.java
5211
import java.util.*; import java.util.stream.*; /* * The Traveller represents the entity moving through * the Maze. */ public class Traveller { public Traveller (Maze maze, boolean debug) { _theMaze = maze; _debug = debug; } public int findAllKeys () { Vector<Wormhole> outerWormholes = _theMaze.outerWormholes(); Vector<Wormhole> innerWormholes = _theMaze.innerWormholes(); Coordinate start = Util.findWormhole(outerWormholes, Maze.START).getLocation(); Coordinate end = Util.findWormhole(outerWormholes, Maze.END).getLocation(); HashMap<Coordinate, List<Route>> routes = findRoutes(_theMaze.innerWormholes(), _theMaze.outerWormholes()); PriorityQueue<Journey> journeys = new PriorityQueue<Journey>(Comparator.comparingInt(r -> r.getSteps())); journeys.offer(new Journey(start)); HashSet<Coordinate> locationsTraversed = new HashSet<Coordinate>(); while (journeys.size() > 0) { Journey theJourney = journeys.poll(); if (theJourney.getLocation().equals(end)) return theJourney.getSteps(); for (Route nextRoute : routes.get(theJourney.getLocation())) { if (locationsTraversed.add(nextRoute.getEnd())) { Journey nextJourney = new Journey(nextRoute.getEnd(), theJourney.getSteps() + nextRoute.numberOfSteps()); journeys.offer(nextJourney); } } } return -1; } private HashMap<Coordinate, List<Route>> findRoutes (Vector<Wormhole> outerWormholes, Vector<Wormhole> innerWormholes) { HashMap<Coordinate, List<Route>> routesForEachCoordinate = new HashMap<Coordinate, List<Route>>(); Set<Wormhole> outerSet = new HashSet<Wormhole>(outerWormholes); Iterator<Wormhole> iter = outerSet.iterator(); while (iter.hasNext()) { Wormhole toCheck = iter.next(); int index = innerWormholes.indexOf(toCheck); if (_debug) System.out.println("Searching for: "+toCheck); if (index != -1) // not present? { if (_debug) System.out.println("Inner wormholes contains "+toCheck); Coordinate innerLocation = innerWormholes.elementAt(index).getLocation(); List<Route> outerRoutes = routesForEachCoordinate.computeIfAbsent(toCheck.getLocation(), (k) -> new ArrayList<>()); outerRoutes.add(new Route(toCheck.getLocation(), innerLocation)); List<Route> innerRoutes = routesForEachCoordinate.computeIfAbsent(innerLocation, (k) -> new ArrayList<>()); innerRoutes.add(new Route(innerLocation, toCheck.getLocation())); } } Vector<Coordinate> outerCoordinates = Util.extractCoordinates(outerWormholes); Vector<Coordinate> innerCoordinates = Util.extractCoordinates(innerWormholes); Vector<Coordinate> theCollection = new Vector<Coordinate>(); theCollection.addAll(outerCoordinates); theCollection.addAll(innerCoordinates); Enumeration<Coordinate> theIter = theCollection.elements(); while (theIter.hasMoreElements()) { Coordinate coord = theIter.nextElement(); routesForEachCoordinate.computeIfAbsent(coord, (k) -> new ArrayList<>()).addAll(findAllRoutes(coord, theCollection)); } return routesForEachCoordinate; } private List<Route> findAllRoutes (Coordinate start, Iterable<Coordinate> allLocations) { ArrayList<Route> allRoutes = new ArrayList<Route>(); for (Coordinate to: allLocations) { if (!start.equals(to)) shortestPath(start, to).ifPresent(allRoutes::add); } return allRoutes; } Optional<Route> shortestPath (Coordinate start, Coordinate destination) { HashMap<Coordinate, Integer> stepsTaken = new HashMap<Coordinate, Integer>(); HashMap<Coordinate, Coordinate> originate = new HashMap<Coordinate, Coordinate>(); PriorityQueue<Coordinate> locations = new PriorityQueue<Coordinate>((Comparator.comparingInt(pos -> Util.cost(stepsTaken, pos, destination)))); stepsTaken.put(start, 0); locations.offer(start); while (locations.size() > 0) { Coordinate coord = locations.poll(); int steps = stepsTaken.get(coord); if (coord.equals(destination)) return Optional.of(new Route(start, destination, steps)); else { coord.directions().stream() .filter(next -> _theMaze.isPassage(next) && !stepsTaken.containsKey(next)) .forEach(next -> { stepsTaken.put(next, steps + 1); originate.put(next, coord); locations.offer(next); }); } } return Optional.empty(); } private Maze _theMaze; private boolean _debug; }
apache-2.0
OpenXIP/avt-mvt
src/com/siemens/cmiv/avt/mvt/outlier/OutlierManager.java
1159
/* Copyright (c) 2010, Siemens Corporate Research a Division of Siemens Corporation All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. 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.siemens.cmiv.avt.mvt.outlier; import java.io.File; import java.util.List; /** * @author Jie Zheng * */ public interface OutlierManager { public boolean loadOutlier (File xmlOutlierFile); public boolean storeOutlier(List<OutlierEntry> outlyings, File xmlOutlierFile); public boolean addOutlierEntry(OutlierEntry entry); public boolean deleteOutlierEntry(int index); public OutlierEntry getOutlierEntry(int i); public List<OutlierEntry> getOutlierEntries(); public int getNumberOfOutlierEntries(); }
apache-2.0
jhrcek/kie-wb-common
kie-wb-common-stunner/kie-wb-common-stunner-sets/kie-wb-common-stunner-bpmn/kie-wb-common-stunner-bpmn-backend/src/test/java/org/kie/workbench/common/stunner/bpmn/backend/service/diagram/marshalling/events/intermediate/CatchingIntermediateEvent.java
9830
/* * Copyright 2018 Red Hat, Inc. and/or its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.kie.workbench.common.stunner.bpmn.backend.service.diagram.marshalling.events.intermediate; import java.util.Arrays; import java.util.List; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.kie.workbench.common.stunner.bpmn.backend.service.diagram.Unmarshalling; import org.kie.workbench.common.stunner.bpmn.backend.service.diagram.marshalling.BPMNDiagramMarshallerBase; import org.kie.workbench.common.stunner.bpmn.backend.service.diagram.marshalling.Marshaller; import org.kie.workbench.common.stunner.bpmn.definition.BaseCatchingIntermediateEvent; import org.kie.workbench.common.stunner.bpmn.definition.property.dataio.AssignmentsInfo; import org.kie.workbench.common.stunner.bpmn.definition.property.dataio.DataIOSet; import org.kie.workbench.common.stunner.bpmn.definition.property.general.BPMNGeneralSet; import org.kie.workbench.common.stunner.core.definition.service.DiagramMarshaller; import org.kie.workbench.common.stunner.core.diagram.Diagram; import org.kie.workbench.common.stunner.core.diagram.Metadata; import org.kie.workbench.common.stunner.core.graph.Graph; import org.kie.workbench.common.stunner.core.graph.Node; import org.kie.workbench.common.stunner.core.graph.content.definition.Definition; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.kie.workbench.common.stunner.bpmn.backend.service.diagram.marshalling.Marshaller.NEW; import static org.kie.workbench.common.stunner.bpmn.backend.service.diagram.marshalling.Marshaller.OLD; @RunWith(Parameterized.class) public abstract class CatchingIntermediateEvent<T extends BaseCatchingIntermediateEvent> extends BPMNDiagramMarshallerBase { static final String EMPTY_VALUE = ""; static final boolean CANCELLING = true; static final boolean NON_CANCELLING = false; static final boolean HAS_INCOME_EDGE = true; static final boolean HAS_NO_INCOME_EDGE = false; static final boolean HAS_OUTGOING_EDGE = true; static final boolean HAS_NO_OUTGOING_EDGE = false; private static final int DEFAULT_AMOUNT_OF_INCOME_EDGES = 1; protected DiagramMarshaller<Graph, Metadata, Diagram<Graph, Metadata>> marshaller = null; CatchingIntermediateEvent(Marshaller marshallerType) { super.init(); switch (marshallerType) { case OLD: marshaller = oldMarshaller; break; case NEW: marshaller = newMarshaller; break; } } @Parameterized.Parameters public static List<Object[]> marshallers() { return Arrays.asList(new Object[][]{ {OLD}, {NEW} }); } @Test public void testMigration() throws Exception { Diagram<Graph, Metadata> oldDiagram = Unmarshalling.unmarshall(oldMarshaller, getBpmnCatchingIntermediateEventFilePath()); Diagram<Graph, Metadata> newDiagram = Unmarshalling.unmarshall(newMarshaller, getBpmnCatchingIntermediateEventFilePath()); // Doesn't work, due to old Marshaller and new Marshaller have different BPMNDefinitionSet uuids // assertEquals(oldDiagram.getGraph(), newDiagram.getGraph()); // Let's check nodes only. assertDiagramEquals(oldDiagram, newDiagram, getBpmnCatchingIntermediateEventFilePath()); } @Test public void testMarshallTopLevelEventFilledProperties() throws Exception { checkEventMarshalling(getFilledTopLevelEventId(), HAS_NO_INCOME_EDGE, HAS_OUTGOING_EDGE); } @Test public void testMarshallTopLevelEventEmptyProperties() throws Exception { checkEventMarshalling(getEmptyTopLevelEventId(), HAS_NO_INCOME_EDGE, HAS_OUTGOING_EDGE); } @Test public void testMarshallSubprocessLevelEventFilledProperties() throws Exception { checkEventMarshalling(getFilledSubprocessLevelEventId(), HAS_NO_INCOME_EDGE, HAS_OUTGOING_EDGE); } @Test public void testMarshallSubprocessLevelEventEmptyProperties() throws Exception { checkEventMarshalling(getEmptySubprocessLevelEventId(), HAS_NO_INCOME_EDGE, HAS_OUTGOING_EDGE); } @Test public void testMarshallTopLevelEventWithEdgesFilledProperties() throws Exception { checkEventMarshalling(getFilledTopLevelEventWithEdgesId(), HAS_INCOME_EDGE, HAS_OUTGOING_EDGE); } @Test public void testMarshallTopLevelEventWithEdgesEmptyProperties() throws Exception { checkEventMarshalling(getEmptyTopLevelEventWithEdgesId(), HAS_INCOME_EDGE, HAS_OUTGOING_EDGE); } @Test public void testMarshallSubprocessLevelEventWithEdgesFilledProperties() throws Exception { checkEventMarshalling(getFilledSubprocessLevelEventWithEdgesId(), HAS_INCOME_EDGE, HAS_OUTGOING_EDGE); } @Test public void testMarshallSubprocessLevelEventWithEdgesEmptyProperties() throws Exception { checkEventMarshalling(getEmptySubprocessLevelEventWithEdgesId(), HAS_INCOME_EDGE, HAS_OUTGOING_EDGE); } public abstract void testUnmarshallTopLevelEventFilledProperties() throws Exception; public abstract void testUnmarshallTopLevelEmptyEventProperties() throws Exception; public abstract void testUnmarshallSubprocessLevelEventFilledProperties() throws Exception; public abstract void testUnmarshallSubprocessLevelEventEmptyProperties() throws Exception; public abstract void testUnmarshallTopLevelEventWithEdgesFilledProperties() throws Exception; public abstract void testUnmarshallTopLevelEventWithEdgesEmptyProperties() throws Exception; public abstract void testUnmarshallSubprocessLevelEventWithEdgesEmptyProperties() throws Exception; public abstract void testUnmarshallSubprocessLevelEventWithEdgesFilledProperties() throws Exception; abstract String getBpmnCatchingIntermediateEventFilePath(); abstract Class<T> getCatchingIntermediateEventType(); abstract String getFilledTopLevelEventId(); abstract String getEmptyTopLevelEventId(); abstract String getFilledSubprocessLevelEventId(); abstract String getEmptySubprocessLevelEventId(); abstract String getFilledTopLevelEventWithEdgesId(); abstract String getEmptyTopLevelEventWithEdgesId(); abstract String getFilledSubprocessLevelEventWithEdgesId(); abstract String getEmptySubprocessLevelEventWithEdgesId(); private void assertNodesEqualsAfterMarshalling(Diagram<Graph, Metadata> before, Diagram<Graph, Metadata> after, String nodeId, boolean hasIncomeEdge, boolean hasOutgoingEdge) { T nodeBeforeMarshalling = getCatchingIntermediateNodeById(before, nodeId, hasIncomeEdge, hasOutgoingEdge); T nodeAfterMarshalling = getCatchingIntermediateNodeById(after, nodeId, hasIncomeEdge, hasOutgoingEdge); assertEquals(nodeBeforeMarshalling, nodeAfterMarshalling); } @SuppressWarnings("unchecked") T getCatchingIntermediateNodeById(Diagram<Graph, Metadata> diagram, String id, boolean hasIncomeEdge, boolean hasOutgoingEdge) { Node<? extends Definition, ?> node = diagram.getGraph().getNode(id); assertNotNull(node); int incomeEdges = hasIncomeEdge ? getDefaultAmountOfIncomdeEdges() + 1 : getDefaultAmountOfIncomdeEdges(); assertEquals(incomeEdges, node.getInEdges().size()); int outgoingEdges = hasOutgoingEdge ? 1 : 0; assertEquals(outgoingEdges, node.getOutEdges().size()); return getCatchingIntermediateEventType().cast(node.getContent().getDefinition()); } @SuppressWarnings("unchecked") void checkEventMarshalling(String nodeID, boolean hasIncomeEdge, boolean hasOutgoingEdge) throws Exception { Diagram<Graph, Metadata> initialDiagram = unmarshall(marshaller, getBpmnCatchingIntermediateEventFilePath()); final int AMOUNT_OF_NODES_IN_DIAGRAM = getNodes(initialDiagram).size(); String resultXml = marshaller.marshall(initialDiagram); Diagram<Graph, Metadata> marshalledDiagram = unmarshall(marshaller, getStream(resultXml)); assertDiagram(marshalledDiagram, AMOUNT_OF_NODES_IN_DIAGRAM); assertNodesEqualsAfterMarshalling(initialDiagram, marshalledDiagram, nodeID, hasIncomeEdge, hasOutgoingEdge); } void assertGeneralSet(BPMNGeneralSet generalSet, String nodeName, String documentation) { assertNotNull(generalSet); assertNotNull(generalSet.getName()); assertNotNull(generalSet.getDocumentation()); assertEquals(nodeName, generalSet.getName().getValue()); assertEquals(documentation, generalSet.getDocumentation().getValue()); } void assertDataIOSet(DataIOSet dataIOSet, String value) { assertNotNull(dataIOSet); AssignmentsInfo assignmentsInfo = dataIOSet.getAssignmentsinfo(); assertNotNull(assignmentsInfo); assertEquals(value, assignmentsInfo.getValue()); } protected int getDefaultAmountOfIncomdeEdges() { return DEFAULT_AMOUNT_OF_INCOME_EDGES; } }
apache-2.0
MythTV-Clients/MythTV-Service-API
src/main/java/org/mythtv/services/api/v028/beans/Input.java
4655
/* * Copyright (c) 2014 TIKINOU LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mythtv.services.api.v028.beans; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; /** * <b>Auto-generated file, do not modify manually !!!!</b> * * @author Sebastien Astie */ @JsonIgnoreProperties( ignoreUnknown = true ) public class Input { @JsonProperty( "Id" ) private Integer id; @JsonProperty( "CardId" ) private Integer cardId; @JsonProperty( "SourceId" ) private Integer sourceId; @JsonProperty( "InputName" ) private String inputName; @JsonProperty( "DisplayName" ) private String displayName; @JsonProperty( "QuickTune" ) private Boolean quickTune; @JsonProperty( "RecPriority" ) private Integer recPriority; @JsonProperty( "ScheduleOrder" ) private Integer scheduleOrder; @JsonProperty( "LiveTVOrder" ) private Integer liveTVOrder; /** * @return the id */ public Integer getId() { return id; } /** * @param id the id to set */ public void setId( Integer id ) { this.id = id; } /** * @return the cardId */ public Integer getCardId() { return cardId; } /** * @param cardId the cardId to set */ public void setCardId( Integer cardId ) { this.cardId = cardId; } /** * @return the sourceId */ public Integer getSourceId() { return sourceId; } /** * @param sourceId the sourceId to set */ public void setSourceId( Integer sourceId ) { this.sourceId = sourceId; } /** * @return the inputName */ public String getInputName() { return inputName; } /** * @param inputName the inputName to set */ public void setInputName( String inputName ) { this.inputName = inputName; } /** * @return the displayName */ public String getDisplayName() { return displayName; } /** * @param displayName the displayName to set */ public void setDisplayName( String displayName ) { this.displayName = displayName; } /** * @return the quickTune */ public Boolean isQuickTune() { return quickTune; } /** * @param quickTune the quickTune to set */ public void setQuickTune( Boolean quickTune ) { this.quickTune = quickTune; } /** * @return the recPriority */ public Integer getRecPriority() { return recPriority; } /** * @param recPriority the recPriority to set */ public void setRecPriority( Integer recPriority ) { this.recPriority = recPriority; } /** * @return the scheduleOrder */ public Integer getScheduleOrder() { return scheduleOrder; } /** * @param scheduleOrder the scheduleOrder to set */ public void setScheduleOrder( Integer scheduleOrder ) { this.scheduleOrder = scheduleOrder; } /** * @return the liveTVOrder */ public Integer getLiveTVOrder() { return liveTVOrder; } /** * @param liveTVOrder the liveTVOrder to set */ public void setLiveTVOrder( Integer liveTVOrder ) { this.liveTVOrder = liveTVOrder; } }
apache-2.0
cuba-platform/cuba
modules/web-tests/src/com/haulmont/cuba/web/testsupport/ui/TestWindowConfig.java
978
/* * Copyright (c) 2008-2019 Haulmont. * * 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.haulmont.cuba.web.testsupport.ui; import com.haulmont.cuba.gui.config.WindowConfig; import com.haulmont.cuba.gui.sys.UiControllersConfiguration; import java.util.List; public class TestWindowConfig extends WindowConfig { public void setConfigurations(List<UiControllersConfiguration> configurations) { this.configurations = configurations; } }
apache-2.0
hortonworks/cloudbreak
core/src/main/java/com/sequenceiq/cloudbreak/reactor/api/event/orchestration/SetupRecoverySuccess.java
268
package com.sequenceiq.cloudbreak.reactor.api.event.orchestration; import com.sequenceiq.cloudbreak.reactor.api.event.StackEvent; public class SetupRecoverySuccess extends StackEvent { public SetupRecoverySuccess(Long stackId) { super(stackId); } }
apache-2.0
spring-projects/spring-framework
spring-core/src/main/java/org/springframework/aot/generator/ProtectedElement.java
1854
/* * Copyright 2002-2022 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.aot.generator; import java.lang.reflect.Member; import org.springframework.lang.Nullable; /** * A {@link Member} that is non-public, with the related type. * * @author Stephane Nicoll * @since 6.0 */ public final class ProtectedElement { private final Class<?> type; @Nullable private final Member target; private ProtectedElement(Class<?> type, @Nullable Member member) { this.type = type; this.target = member; } /** * Return the {@link Class type} that is non-public. For a plain * protected {@link Member member} access, the type of the declaring class * is used. Otherwise, the type in the member signature, such as a parameter * type for an executable, or the return type of a field is used. If the * type is generic, the type that is protected in the generic signature is * used. * @return the type that is not public */ public Class<?> getType() { return this.type; } /** * Return the {@link Member} that is not publicly accessible. * @return the member */ @Nullable public Member getMember() { return this.target; } static ProtectedElement of(Class<?> type, @Nullable Member member) { return new ProtectedElement(type, member); } }
apache-2.0
eSDK/esdk_cloud_fm_r3_native_java
source/FM/V1R5/esdk_fm_neadp_1.5_native_java/src/main/java/com/huawei/esdk/fusionmanager/local/model/storage/ModifyVolumeReqEx.java
1207
package com.huawei.esdk.fusionmanager.local.model.storage; /** * 修改磁盘扩展请求消息。 * <p> * @since eSDK Cloud V100R003C30 */ public class ModifyVolumeReqEx { /** * 【必选】当前操作用户所在VDC编码。 */ private String vdcId; /** * 【必选】VPC ID。 */ private String vpcId; /** * 【必选】磁盘编码。 */ private String volumeId; /** * 【必选】云资源池编码。 */ private String cloudInfraId; public String getVdcId() { return vdcId; } public void setVdcId(String vdcId) { this.vdcId = vdcId; } public String getVpcId() { return vpcId; } public void setVpcId(String vpcId) { this.vpcId = vpcId; } public String getVolumeId() { return volumeId; } public void setVolumeId(String volumeId) { this.volumeId = volumeId; } public String getCloudInfraId() { return cloudInfraId; } public void setCloudInfraId(String cloudInfraId) { this.cloudInfraId = cloudInfraId; } }
apache-2.0
ctripcorp/dal
dal-client/src/main/java/com/ctrip/platform/dal/dao/helper/DalListMerger.java
762
package com.ctrip.platform.dal.dao.helper; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; import com.ctrip.platform.dal.dao.ResultMerger; public class DalListMerger<T> implements ResultMerger<List<T>> { private List<T> result = new ArrayList<>(); private Comparator<T> comparator; public DalListMerger() { this(null); } public DalListMerger(Comparator<T> comparator) { this.comparator = comparator; } @Override public void addPartial(String shard, List<T> partial) { if(partial!=null) result.addAll(partial); } @Override public List<T> merge() { if(comparator != null) Collections.sort(result, comparator); return result; } }
apache-2.0
dev-blogs/hibernate-without-annotations
src/main/java/DAO/ItemDAO.java
402
package DAO; import java.sql.SQLException; import java.util.Collection; import model.Item; public interface ItemDAO { public void addItem(Item item) throws SQLException; public void updateItem(Item item) throws SQLException; public Item getItemById(Long id) throws SQLException; public Collection<Item> getAllItems() throws SQLException; public void deleteItem(Item item) throws SQLException; }
apache-2.0
escidoc-ng/escidoc-ng
escidocng-backend/src/main/java/de/escidocng/controller/DescribeController.java
2001
/* * Copyright 2014 FIZ Karlsruhe * * 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 ROLE_ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.escidocng.controller; import java.io.IOException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.stereotype.Component; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.ResponseStatus; import de.escidocng.model.Describe; import de.escidocng.service.RepositoryService; /** * Web controller class responsible for creating {@link de.escidocng.model.Describe} views */ @Controller @RequestMapping("/describe") @Component public class DescribeController extends AbstractEscidocngController { @Autowired private RepositoryService repositoryService; /** * Controller method which creates a JSON response of a {@link de.escidocng.model.Describe} object * containing some information about the repository state * * @return A Describe object which gets converted to a JSON string by Spring MVC * @throws IOException */ @RequestMapping(method = RequestMethod.GET) @ResponseBody @ResponseStatus(HttpStatus.OK) public Describe describe() throws IOException { return repositoryService.describe(); } }
apache-2.0
zhangdaiscott/jeewx-api
src/main/java/org/jeewx/api/coupon/qrcode/model/ActionInfo.java
88
package org.jeewx.api.coupon.qrcode.model; public class ActionInfo extends Card { }
apache-2.0
oehme/analysing-gradle-performance
my-app/src/test/java/org/gradle/test/performance/mediummonolithicjavaproject/p292/Test5847.java
2111
package org.gradle.test.performance.mediummonolithicjavaproject.p292; import org.junit.Test; import static org.junit.Assert.*; public class Test5847 { Production5847 objectUnderTest = new Production5847(); @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()); } }
apache-2.0
thiagoandrade6/proxy-test
src/main/java/org/proxy/handler/CarInvocationHandler.java
774
package org.proxy.handler; import org.proxy.domain.Car; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; /** * Created by thiago on 24/09/14. */ public class CarInvocationHandler implements InvocationHandler { private static final Logger log = LoggerFactory.getLogger(CarInvocationHandler.class); private Object target; public CarInvocationHandler(Object target) { this.target = target; } @Override public Object invoke(Object proxy, Method method, Object[] params) throws Throwable { log.info("Init Car Custom Handler"); Car car = (Car) params[0]; car.setColor("black"); return method.invoke(target, car); } }
apache-2.0
Danihelsan/GoUbiquitous
mobile/src/main/java/pe/asomapps/udacity/goubiquitous/widget/TodayWidgetIntentService.java
7149
/* * Copyright (C) 2015 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package pe.asomapps.udacity.goubiquitous.widget; import android.annotation.TargetApi; import android.app.IntentService; import android.app.PendingIntent; import android.appwidget.AppWidgetManager; import android.content.ComponentName; import android.content.Intent; import android.database.Cursor; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.util.DisplayMetrics; import android.util.TypedValue; import android.widget.RemoteViews; import pe.asomapps.udacity.goubiquitous.MainActivity; import pe.asomapps.udacity.goubiquitous.R; import pe.asomapps.udacity.goubiquitous.Utility; import pe.asomapps.udacity.goubiquitous.data.WeatherContract; /** * IntentService which handles updating all Today widgets with the latest data */ public class TodayWidgetIntentService extends IntentService { private static final String[] FORECAST_COLUMNS = { WeatherContract.WeatherEntry.COLUMN_WEATHER_ID, WeatherContract.WeatherEntry.COLUMN_SHORT_DESC, WeatherContract.WeatherEntry.COLUMN_MAX_TEMP, WeatherContract.WeatherEntry.COLUMN_MIN_TEMP }; // these indices must match the projection private static final int INDEX_WEATHER_ID = 0; private static final int INDEX_SHORT_DESC = 1; private static final int INDEX_MAX_TEMP = 2; private static final int INDEX_MIN_TEMP = 3; public TodayWidgetIntentService() { super("TodayWidgetIntentService"); } @Override protected void onHandleIntent(Intent intent) { // Retrieve all of the Today widget ids: these are the widgets we need to update AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(this); int[] appWidgetIds = appWidgetManager.getAppWidgetIds(new ComponentName(this, TodayWidgetProvider.class)); // Get today's data from the ContentProvider String location = Utility.getPreferredLocation(this); Uri weatherForLocationUri = WeatherContract.WeatherEntry.buildWeatherLocationWithStartDate( location, System.currentTimeMillis()); Cursor data = getContentResolver().query(weatherForLocationUri, FORECAST_COLUMNS, null, null, WeatherContract.WeatherEntry.COLUMN_DATE + " ASC"); if (data == null) { return; } if (!data.moveToFirst()) { data.close(); return; } // Extract the weather data from the Cursor int weatherId = data.getInt(INDEX_WEATHER_ID); int weatherArtResourceId = Utility.getArtResourceForWeatherCondition(weatherId); String description = data.getString(INDEX_SHORT_DESC); double maxTemp = data.getDouble(INDEX_MAX_TEMP); double minTemp = data.getDouble(INDEX_MIN_TEMP); String formattedMaxTemperature = Utility.formatTemperature(this, maxTemp); String formattedMinTemperature = Utility.formatTemperature(this, minTemp); data.close(); // Perform this loop procedure for each Today widget for (int appWidgetId : appWidgetIds) { // Find the correct layout based on the widget's width int widgetWidth = getWidgetWidth(appWidgetManager, appWidgetId); int defaultWidth = getResources().getDimensionPixelSize(R.dimen.widget_today_default_width); int largeWidth = getResources().getDimensionPixelSize(R.dimen.widget_today_large_width); int layoutId; if (widgetWidth >= largeWidth) { layoutId = R.layout.widget_today_large; } else if (widgetWidth >= defaultWidth) { layoutId = R.layout.widget_today; } else { layoutId = R.layout.widget_today_small; } RemoteViews views = new RemoteViews(getPackageName(), layoutId); // Add the data to the RemoteViews views.setImageViewResource(R.id.widget_icon, weatherArtResourceId); // Content Descriptions for RemoteViews were only added in ICS MR1 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH_MR1) { setRemoteContentDescription(views, description); } views.setTextViewText(R.id.widget_description, description); views.setTextViewText(R.id.widget_high_temperature, formattedMaxTemperature); views.setTextViewText(R.id.widget_low_temperature, formattedMinTemperature); // Create an Intent to launch MainActivity Intent launchIntent = new Intent(this, MainActivity.class); PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, launchIntent, 0); views.setOnClickPendingIntent(R.id.widget, pendingIntent); // Tell the AppWidgetManager to perform an update on the current app widget appWidgetManager.updateAppWidget(appWidgetId, views); } } private int getWidgetWidth(AppWidgetManager appWidgetManager, int appWidgetId) { // Prior to Jelly Bean, widgets were always their default size if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) { return getResources().getDimensionPixelSize(R.dimen.widget_today_default_width); } // For Jelly Bean and higher devices, widgets can be resized - the current size can be // retrieved from the newly added App Widget Options return getWidgetWidthFromOptions(appWidgetManager, appWidgetId); } @TargetApi(Build.VERSION_CODES.JELLY_BEAN) private int getWidgetWidthFromOptions(AppWidgetManager appWidgetManager, int appWidgetId) { Bundle options = appWidgetManager.getAppWidgetOptions(appWidgetId); if (options.containsKey(AppWidgetManager.OPTION_APPWIDGET_MIN_WIDTH)) { int minWidthDp = options.getInt(AppWidgetManager.OPTION_APPWIDGET_MIN_WIDTH); // The width returned is in dp, but we'll convert it to pixels to match the other widths DisplayMetrics displayMetrics = getResources().getDisplayMetrics(); return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, minWidthDp, displayMetrics); } return getResources().getDimensionPixelSize(R.dimen.widget_today_default_width); } @TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH_MR1) private void setRemoteContentDescription(RemoteViews views, String description) { views.setContentDescription(R.id.widget_icon, description); } }
apache-2.0
heriram/incubator-asterixdb
asterixdb/asterix-external-data/src/test/java/org/apache/asterix/external/input/record/reader/RecordWithPKTestReaderFactory.java
2841
/* * 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.asterix.external.input.record.reader; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Map; import org.apache.asterix.common.api.IApplicationContext; import org.apache.asterix.external.api.IExternalDataSourceFactory; import org.apache.asterix.external.api.IRecordReader; import org.apache.asterix.external.api.IRecordReaderFactory; import org.apache.asterix.external.input.record.RecordWithPK; import org.apache.hyracks.algebricks.common.constraints.AlgebricksAbsolutePartitionConstraint; import org.apache.hyracks.algebricks.common.exceptions.AlgebricksException; import org.apache.hyracks.api.application.IServiceContext; import org.apache.hyracks.api.context.IHyracksTaskContext; public class RecordWithPKTestReaderFactory implements IRecordReaderFactory<RecordWithPK<char[]>> { private static final long serialVersionUID = 1L; private transient AlgebricksAbsolutePartitionConstraint clusterLocations; private transient IServiceContext serviceCtx; private static final List<String> recordReaderNames = Collections.unmodifiableList(Arrays.asList()); @Override public AlgebricksAbsolutePartitionConstraint getPartitionConstraint() throws AlgebricksException { clusterLocations = IExternalDataSourceFactory .getPartitionConstraints((IApplicationContext) serviceCtx.getApplicationContext(), clusterLocations, 1); return clusterLocations; } @Override public void configure(IServiceContext serviceCtx, final Map<String, String> configuration) { this.serviceCtx = serviceCtx; } @Override public IRecordReader<? extends RecordWithPK<char[]>> createRecordReader(final IHyracksTaskContext ctx, final int partition) { return new TestAsterixMembersReader(); } @Override public Class<?> getRecordClass() { return RecordWithPK.class; } @Override public List<String> getRecordReaderNames() { return recordReaderNames; } }
apache-2.0
aicer/hibiscus-http-client
src/main/java/org/aicer/hibiscus/util/HashGenerator.java
4395
/** * Copyright 2012-2013 American Institute for Computing Education and Research 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.aicer.hibiscus.util; import java.io.UnsupportedEncodingException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import org.aicer.hibiscus.exception.HibiscusException; /** * Hash Generator * * Used to generate MD5 and SHA1 hash from strings * * Uses UTF-8 Internally to convert strings to bytes before generating the hash values for those strings * */ public abstract class HashGenerator { private static final int MESSAGE_DIGEST_UPDATE_OFFSET = 0; private static final int BYTE_LENGTH_SHA1 = 40; private static final int BYTE_LENGTH_MD5 = 32; private static final String ENCODING_CHARSET_NAME = "utf-8"; private static final String MESSAGE_DIGEST_ALGORITHM_SHA1 = "SHA-1"; private static final String MESSAGE_DIGEST_ALGORITHM_MD5 = "MD5"; /** * Converts an array of bytes to its hexadecimal equivalent * * @param data * @return String Hexadecimal equivalent of the byte array */ private static String convertToHex(byte[] data) { final StringBuffer buffer = new StringBuffer(); for (int i = 0; i < data.length; i++) { int halfByte = (data[i] >>> 4) & 0x0F; int twoHalves = 0; do { if ((0 <= halfByte) && (halfByte <= 9)) { buffer.append((char) ('0' + halfByte)); } else { buffer.append((char) ('a' + (halfByte - 10))); } halfByte = data[i] & 0x0F; } while(twoHalves++ < 1); } return buffer.toString(); } /** * Returns the SHA1 hash of the input string * * @param input Input string * @return String The sha1 hash of the input string * @throws HibiscusException */ public static String getSHA1Hash(final String input) throws HibiscusException { String hashValue = null; try { final MessageDigest messageDigest = MessageDigest.getInstance(MESSAGE_DIGEST_ALGORITHM_SHA1); byte[] sha1Hash = new byte[BYTE_LENGTH_SHA1]; messageDigest.update(input.getBytes(ENCODING_CHARSET_NAME), MESSAGE_DIGEST_UPDATE_OFFSET, input.length()); sha1Hash = messageDigest.digest(); hashValue = convertToHex(sha1Hash); } catch (NoSuchAlgorithmException e) { throw new HibiscusException("Unsupported Message Digest Algorithm " + MESSAGE_DIGEST_ALGORITHM_SHA1, e); } catch (UnsupportedEncodingException e) { throw new HibiscusException("Unsupported Encoding " + ENCODING_CHARSET_NAME , e); } return hashValue; } /** * Returns the MD5 hash of the input string * * @param input Input string * @return String The md5 hash of the input string * @throws HibiscusException */ public static String getMD5Hash(final String input) throws HibiscusException { String hashValue = null; try { final MessageDigest messageDigest = MessageDigest.getInstance(MESSAGE_DIGEST_ALGORITHM_MD5); byte[] md5Hash = new byte[BYTE_LENGTH_MD5]; messageDigest.update(input.getBytes(ENCODING_CHARSET_NAME), MESSAGE_DIGEST_UPDATE_OFFSET, input.length()); md5Hash = messageDigest.digest(); hashValue = convertToHex(md5Hash); } catch (NoSuchAlgorithmException e) { throw new HibiscusException("Unsupported Message Digest Algorithm " + MESSAGE_DIGEST_ALGORITHM_MD5, e); } catch (UnsupportedEncodingException e) { throw new HibiscusException("Unsupported Encoding " + ENCODING_CHARSET_NAME , e); } return hashValue; } }
apache-2.0
nostra/semispace
semispace-comet/semispace-comet-webapp/src/test/java/org/semispace/comet/client/notification/NoticeC.java
838
/* * Copyright 2010 Erlend Nossum * * 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.semispace.comet.client.notification; public class NoticeC { private String field; public String getField() { return this.field; } public void setField(String field) { this.field = field; } }
apache-2.0
DmitryMalkovich/gito-github-client
app/src/main/java/com/dmitrymalkovich/android/githubanalytics/settings/SettingsActivity.java
10259
package com.dmitrymalkovich.android.githubanalytics.settings; /* * Copyright 2016. Dmitry Malkovich * * 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. */ import android.annotation.TargetApi; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.content.res.Configuration; import android.os.Build; import android.os.Bundle; import android.preference.ListPreference; import android.preference.Preference; import android.preference.PreferenceActivity; import android.preference.PreferenceFragment; import android.preference.PreferenceManager; import android.support.annotation.IntDef; import android.support.v7.app.ActionBar; import android.view.MenuItem; import com.dmitrymalkovich.android.githubanalytics.R; import com.dmitrymalkovich.android.githubanalytics.navigation.NavigationViewActivity; import java.lang.annotation.Retention; import java.util.List; import static java.lang.annotation.RetentionPolicy.SOURCE; /** * A {@link PreferenceActivity} that presents a set of application settings. On * handset devices, settings are presented as a single list. On tablets, * settings are split by category, with category headers shown to the left of * the list of settings. * <p> * See <a href="http://developer.android.com/design/patterns/settings.html"> * Android Design: Settings</a> for design guidelines and the <a * href="http://developer.android.com/guide/topics/ui/settings.html">Settings * API Guide</a> for more information on developing a Settings UI. */ public class SettingsActivity extends AppCompatPreferenceActivity { public final static String KEY_PREF_THEME = "theme"; /** * A preference value change listener that updates the preference's summary * to reflect its new value. */ private static Preference.OnPreferenceChangeListener sBindPreferenceSummaryToValueListener = new Preference.OnPreferenceChangeListener() { @Override public boolean onPreferenceChange(Preference preference, Object value) { String stringValue = value.toString(); if (preference instanceof ListPreference) { // For list preferences, look up the correct display value in // the preference's 'entries' list. ListPreference listPreference = (ListPreference) preference; int index = listPreference.findIndexOfValue(stringValue); // Set the summary to reflect the new value. preference.setSummary( index >= 0 ? listPreference.getEntries()[index] : null); } else { // For all other preferences, set the summary to the value's // simple string representation. preference.setSummary(stringValue); } return true; } }; /** * Helper method to determine if the device has an extra-large screen. For * example, 10" tablets are extra-large. */ private static boolean isXLargeTablet(Context context) { return (context.getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) >= Configuration.SCREENLAYOUT_SIZE_XLARGE; } /** * Binds a preference's summary to its value. More specifically, when the * preference's value is changed, its summary (line of text below the * preference title) is updated to reflect the value. The summary is also * immediately updated upon calling this method. The exact display format is * dependent on the type of preference. * * @see #sBindPreferenceSummaryToValueListener */ private static void bindPreferenceSummaryToValue(Preference preference) { // Set the listener to watch for value changes. preference.setOnPreferenceChangeListener(sBindPreferenceSummaryToValueListener); // Trigger the listener immediately with the preference's // current value. sBindPreferenceSummaryToValueListener.onPreferenceChange(preference, PreferenceManager .getDefaultSharedPreferences(preference.getContext()) .getString(preference.getKey(), "")); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setupActionBar(); } /** * Set up the {@link android.app.ActionBar}, if the API is available. */ private void setupActionBar() { ActionBar actionBar = getSupportActionBar(); if (actionBar != null) { // Show the Up button in the action bar. actionBar.setDisplayHomeAsUpEnabled(true); } } @Override public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); if (id == android.R.id.home) { finish(); return true; } return super.onOptionsItemSelected(item); } /** * {@inheritDoc} */ @Override public boolean onIsMultiPane() { return isXLargeTablet(this); } /** * {@inheritDoc} */ @Override @TargetApi(Build.VERSION_CODES.HONEYCOMB) public void onBuildHeaders(List<PreferenceActivity.Header> target) { loadHeadersFromResource(R.xml.pref_headers, target); } /** * This method stops fragment injection in malicious applications. * Make sure to deny any unknown fragments here. */ protected boolean isValidFragment(String fragmentName) { return PreferenceFragment.class.getName().equals(fragmentName) || ThemePreferenceFragment.class.getName().equals(fragmentName); } /** * This fragment shows theme preferences only. It is used when the * activity is showing a two-pane settings UI. */ @TargetApi(Build.VERSION_CODES.HONEYCOMB) public static class ThemePreferenceFragment extends PreferenceFragment implements SharedPreferences.OnSharedPreferenceChangeListener { private static final String THEME_LIGHT = "light"; @SuppressWarnings("unused") private static final String THEME_DARK = "dark"; public static boolean isLight(Context context) { SharedPreferences preference = PreferenceManager .getDefaultSharedPreferences(context); return preference.getString(KEY_PREF_THEME, THEME_DARK).equals(THEME_LIGHT); } public static int getTheme(Context context, @THEME_TYPE int themeType) { switch (themeType) { case THEME_TYPE.NO_ACTION_BAR: { if (isLight(context)) { return R.style.AppTheme; } else { return R.style.AppTheme_Dark; } } case THEME_TYPE.ACTION_BAR: { if (isLight(context)) { return R.style.AppTheme_Settings; } else { return R.style.AppTheme_Dark_Settings; } } default: case THEME_TYPE.NO_ACTION_BAR_AND_COLORED_STATUS_BAR: { if (isLight(context)) { return R.style.AppTheme_ColoredStatusBar; } else { return R.style.AppTheme_Dark_ColoredStatusBar; } } } } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); addPreferencesFromResource(R.xml.pref_header_theme); setHasOptionsMenu(true); // Bind the summaries of EditText/List/Dialog/Ringtone preferences // to their values. When their values change, their summaries are // updated to reflect the new value, per the Android Design // guidelines. bindPreferenceSummaryToValue(findPreference(KEY_PREF_THEME)); } @Override public void onResume() { super.onResume(); // Set up a listener whenever a key changes getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener(this); } @Override public void onPause() { super.onPause(); // Set up a listener whenever a key changes getPreferenceScreen().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(this); } @Override public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); if (id == android.R.id.home) { startActivity(new Intent(getActivity(), SettingsActivity.class)); return true; } return super.onOptionsItemSelected(item); } @Override public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) { if (key.equals(KEY_PREF_THEME)) { Intent intent = new Intent(getActivity(), NavigationViewActivity.class); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK); startActivity(intent); } } @Retention(SOURCE) @IntDef({THEME_TYPE.NO_ACTION_BAR, THEME_TYPE.NO_ACTION_BAR_AND_COLORED_STATUS_BAR, THEME_TYPE.ACTION_BAR}) public @interface THEME_TYPE { int NO_ACTION_BAR = 0; int NO_ACTION_BAR_AND_COLORED_STATUS_BAR = 1; int ACTION_BAR = 2; } } }
apache-2.0
kuznetsovsergeyymailcom/homework
chapter_001/expandArray/src/main/java/ru/skuznetsov/Turn.java
551
package ru.skuznetsov; /** * Created by Sergey on 27.11.2016. */ public class Turn { /** * Method takes an array as argument and expand it. * @param array - array for expanding * */ public void back(int[] array) { if (array == null) { throw new IllegalArgumentException("null on argument"); } for (int i = 0; i < array.length / 2; i++) { int temp = array[i]; array[i] = array[array.length - i - 1]; array[array.length - i - 1] = temp; } } }
apache-2.0
zhiaixinyang/LightThink
greatbook/src/main/java/com/example/greatbook/utils/permission/PermissionGrantCallback.java
522
package com.example.greatbook.utils.permission; /** * 权限请求结果回调 * <p> * 配合{@link PermissionUtils}使用 * * @author MDove on 2017/9/15. * */ public interface PermissionGrantCallback { /** * 权限请求被批准 * * @param requestCode */ void permissionGranted(int requestCode); /** * 权限请求被拒绝 * * @param requestCode true 需要告知申请该权限的原因, false 请忽略 */ void permissionRefused(int requestCode); }
apache-2.0
orientechnologies/orientdb
object/src/main/java/com/orientechnologies/orient/object/enumerations/OObjectEnumLazySet.java
4757
/* * Copyright 2010-2016 OrientDB LTD (http://orientdb.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.orientechnologies.orient.object.enumerations; import com.orientechnologies.orient.core.record.ORecord; import java.io.Serializable; import java.util.Collection; import java.util.HashSet; import java.util.Iterator; import java.util.Map; import java.util.Set; /** @author Luca Molino (molino.luca--at--gmail.com) */ @SuppressWarnings("unchecked") public class OObjectEnumLazySet<TYPE extends Enum> extends HashSet<TYPE> implements OObjectLazyEnumSerializer<Set<TYPE>>, Serializable { private static final long serialVersionUID = -7698875159671927472L; private final ORecord sourceRecord; private final Set<Object> underlying; private boolean converted = false; private final Class<Enum> enumClass; public OObjectEnumLazySet( final Class<Enum> iEnumClass, final ORecord iSourceRecord, final Set<Object> iRecordSource) { this.sourceRecord = iSourceRecord; this.underlying = iRecordSource; this.enumClass = iEnumClass; } public OObjectEnumLazySet( final Class<Enum> iEnumClass, final ORecord iSourceRecord, final Set<Object> iRecordSource, final Set<? extends TYPE> iSourceCollection) { this.sourceRecord = iSourceRecord; this.underlying = iRecordSource; this.enumClass = iEnumClass; convertAll(); addAll(iSourceCollection); } public Iterator<TYPE> iterator() { return (Iterator<TYPE>) new OObjectEnumLazyIterator<TYPE>(enumClass, sourceRecord, underlying.iterator()); } public int size() { return underlying.size(); } public boolean isEmpty() { return underlying.isEmpty(); } public boolean contains(final Object o) { boolean underlyingContains = underlying.contains(o.toString()); return underlyingContains || super.contains(o); } public Object[] toArray() { return toArray(new Object[size()]); } public <T> T[] toArray(final T[] a) { convertAll(); return super.toArray(a); } public boolean add(final TYPE e) { underlying.add(e.name()); return super.add(e); } public boolean remove(final Object e) { underlying.remove(e.toString()); return super.remove(e); } public boolean containsAll(final Collection<?> c) { for (Object o : c) if (!super.contains(o) && !underlying.contains(o.toString())) return false; return true; } public boolean addAll(final Collection<? extends TYPE> c) { boolean modified = false; setDirty(); for (Object o : c) modified = add((TYPE) o) || modified; return modified; } public boolean retainAll(final Collection<?> c) { boolean modified = false; Iterator<TYPE> e = iterator(); while (e.hasNext()) { if (!c.contains(e.next())) { remove(e); modified = true; } } return modified; } public void clear() { setDirty(); underlying.clear(); } public boolean removeAll(final Collection<?> c) { setDirty(); boolean modified = super.removeAll(c); for (Object o : c) { modified = modified || underlying.remove(o.toString()); } return modified; } public boolean isConverted() { return converted; } @Override public String toString() { return underlying.toString(); } public void setDirty() { if (sourceRecord != null) sourceRecord.setDirty(); } public void detach() { convertAll(); } public void detach(boolean nonProxiedInstance) { convertAll(); } public void detachAll( boolean nonProxiedInstance, Map<Object, Object> alreadyDetached, Map<Object, Object> lazyObjects) { convertAll(); } @Override public Set<TYPE> getNonOrientInstance() { Set<TYPE> set = new HashSet<TYPE>(); set.addAll(this); return set; } @Override public Object getUnderlying() { return underlying; } protected void convertAll() { if (converted) return; super.clear(); for (Object o : underlying) { if (o instanceof Number) o = enumClass.getEnumConstants()[((Number) o).intValue()]; else o = Enum.valueOf(enumClass, o.toString()); super.add((TYPE) o); } converted = true; } }
apache-2.0
crate/crate
server/src/main/java/io/crate/blob/PutChunkAction.java
1356
/* * Licensed to Crate.io GmbH ("Crate") under one or more contributor * license agreements. See the NOTICE file distributed with this work for * additional information regarding copyright ownership. Crate 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. * * However, if you have executed another commercial license agreement * with Crate these terms will supersede the license and you may use the * software solely pursuant to the terms of the relevant commercial agreement. */ package io.crate.blob; import org.elasticsearch.action.ActionType; public class PutChunkAction extends ActionType<PutChunkResponse> { public static final PutChunkAction INSTANCE = new PutChunkAction(); public static final String NAME = "internal:crate:blob/put_chunk"; protected PutChunkAction() { super(NAME); } }
apache-2.0
ua-eas/ksd-kc5.2.1-rice2.3.6-ua
rice-middleware/it/kew/src/test/java/org/kuali/rice/kew/docsearch/DocumentSearchSecurityTest.java
15188
/** * Copyright 2005-2013 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.docsearch; import org.junit.Test; import org.kuali.rice.kew.api.WorkflowDocument; import org.kuali.rice.kew.api.WorkflowDocumentFactory; import org.kuali.rice.kew.api.document.attribute.WorkflowAttributeDefinition; import org.kuali.rice.kew.api.document.search.DocumentSearchCriteria; import org.kuali.rice.kew.api.document.search.DocumentSearchResults; import org.kuali.rice.kew.docsearch.service.DocumentSearchService; import org.kuali.rice.kew.engine.RouteContext; import org.kuali.rice.kew.service.KEWServiceLocator; import org.kuali.rice.kew.test.KEWTestCase; import org.kuali.rice.kim.api.KimConstants; import org.kuali.rice.kim.api.group.Group; import org.kuali.rice.kim.api.identity.Person; import org.kuali.rice.kim.api.services.KimApiServiceLocator; import static org.junit.Assert.*; /** * This is a description of what this class does - jjhanso don't forget to fill this in. * * @author Kuali Rice Team (rice.collab@kuali.org) * */ public class DocumentSearchSecurityTest extends KEWTestCase { private static final String WORKFLOW_ADMIN_USER_NETWORK_ID = "bmcgough"; private static final String APPROVER_USER_NETWORK_ID = "user2"; private static final String STANDARD_USER_NETWORK_ID = "user1"; DocumentSearchService docSearchService; @Override protected void setUpAfterDataLoad() throws Exception { docSearchService = (DocumentSearchService)KEWServiceLocator.getService(KEWServiceLocator.DOCUMENT_SEARCH_SERVICE); } @Override protected void loadTestData() throws Exception { loadXmlFile("SearchSecurityConfig.xml"); } /** * Test for https://test.kuali.org/jira/browse/KULRICE-1968 - Document search fails when users are missing * Tests that we can safely search on docs whose initiator no longer exists in the identity management system * This test searches by doc type name criteria. * @throws Exception */ @Test public void testDocSearchSecurityPermissionDocType() throws Exception { String documentTypeName = "SecurityDoc_PermissionOnly"; String userNetworkId = "arh14"; // route a document to enroute and route one to final WorkflowDocument workflowDocument = WorkflowDocumentFactory.createDocument(getPrincipalId(userNetworkId), documentTypeName); workflowDocument.setTitle("testDocSearch_PermissionSecurity"); workflowDocument.route("routing this document."); Person user = KimApiServiceLocator.getPersonService().getPersonByPrincipalName("edna"); DocumentSearchCriteria.Builder criteria = DocumentSearchCriteria.Builder.create(); criteria.setDocumentTypeName(documentTypeName); DocumentSearchResults results = docSearchService.lookupDocuments(user.getPrincipalId(), criteria.build()); assertEquals(0, results.getNumberOfSecurityFilteredResults()); assertEquals("Search returned invalid number of documents", 1, results.getSearchResults().size()); } @Test public void testDocSearchBadPermission() throws Exception { String documentTypeName = "SecurityDoc_InvalidPermissionOnly"; String userNetworkId = "arh14"; // route a document to enroute and route one to final WorkflowDocument workflowDocument = WorkflowDocumentFactory.createDocument(getPrincipalId(userNetworkId), documentTypeName); workflowDocument.setTitle("testDocSearch_PermissionSecurity"); workflowDocument.route("routing this document."); Person user = KimApiServiceLocator.getPersonService().getPersonByPrincipalName("edna"); DocumentSearchCriteria.Builder criteria = DocumentSearchCriteria.Builder.create(); criteria.setDocumentTypeName(documentTypeName); DocumentSearchResults results = docSearchService.lookupDocuments(user.getPrincipalId(), criteria.build()); assertEquals("Search returned invalid number of documents", 0, results.getSearchResults().size()); } @Test public void testFilteringInitiator() throws Exception { String documentType = "SecurityDoc_InitiatorOnly"; String initiator = getPrincipalId(STANDARD_USER_NETWORK_ID); WorkflowDocument document = WorkflowDocumentFactory.createDocument(initiator, documentType); document.route(""); assertFalse("Document should not be in init status after routing", document.isInitiated()); DocumentSearchCriteria.Builder criteria = DocumentSearchCriteria.Builder.create(); criteria.setDocumentId(document.getDocumentId()); DocumentSearchResults results = KEWServiceLocator.getDocumentSearchService().lookupDocuments(initiator, criteria.build()); assertEquals("Should retrive one record from search", 1, results.getSearchResults().size()); assertEquals("No rows should have been filtered due to security", 0, results.getNumberOfSecurityFilteredResults()); criteria = DocumentSearchCriteria.Builder.create(); criteria.setDocumentId(document.getDocumentId()); results = KEWServiceLocator.getDocumentSearchService().lookupDocuments(getPrincipalId("user3"), criteria.build()); assertEquals("Should retrive no records from search", 0, results.getSearchResults().size()); assertEquals("One row should have been filtered due to security", 1, results.getNumberOfSecurityFilteredResults()); criteria = DocumentSearchCriteria.Builder.create(); criteria.setDocumentId(document.getDocumentId()); results = KEWServiceLocator.getDocumentSearchService().lookupDocuments(getPrincipalId(WORKFLOW_ADMIN_USER_NETWORK_ID), criteria.build()); assertEquals("Should retrive one record from search", 1, results.getSearchResults().size()); assertEquals("No rows should have been filtered due to security", 0, results.getNumberOfSecurityFilteredResults()); } @Test public void testFiltering_Workgroup() throws Exception { String documentType = "SecurityDoc_WorkgroupOnly"; String initiator = getPrincipalId(STANDARD_USER_NETWORK_ID); WorkflowDocument document = WorkflowDocumentFactory.createDocument(initiator, documentType); document.route(""); assertFalse("Document should not be in init status after routing", document.isInitiated()); // verify that initiator cannot see the document DocumentSearchCriteria.Builder criteria = DocumentSearchCriteria.Builder.create(); criteria.setDocumentId(document.getDocumentId()); DocumentSearchResults results = KEWServiceLocator.getDocumentSearchService().lookupDocuments(initiator, criteria.build()); assertEquals("Should retrive no records from search", 0, results.getSearchResults().size()); assertEquals("One row should have been filtered due to security", 1, results.getNumberOfSecurityFilteredResults()); // verify that workgroup can see the document String workgroupName = "Test_Security_Group"; Group group = KimApiServiceLocator.getGroupService().getGroupByNamespaceCodeAndName( KimConstants.KIM_GROUP_WORKFLOW_NAMESPACE_CODE, workgroupName); assertNotNull("Workgroup '" + workgroupName + "' should be valid", group); for (String workgroupUserId : KimApiServiceLocator.getGroupService().getMemberPrincipalIds(group.getId())) { Person workgroupUser = KimApiServiceLocator.getPersonService().getPerson(workgroupUserId); criteria = DocumentSearchCriteria.Builder.create(); criteria.setDocumentId(document.getDocumentId()); results = KEWServiceLocator.getDocumentSearchService().lookupDocuments(workgroupUser.getPrincipalId(), criteria.build()); assertEquals("Should retrive one record from search for user " + workgroupUser, 1, results.getSearchResults().size()); assertEquals("No rows should have been filtered due to security for user " + workgroupUser, 0, results.getNumberOfSecurityFilteredResults()); } // verify that user3 cannot see the document criteria = DocumentSearchCriteria.Builder.create(); criteria.setDocumentId(document.getDocumentId()); results = KEWServiceLocator.getDocumentSearchService().lookupDocuments(getPrincipalId("user3"), criteria.build()); assertEquals("Should retrive no records from search", 0, results.getSearchResults().size()); assertEquals("One row should have been filtered due to security", 1, results.getNumberOfSecurityFilteredResults()); // verify that WorkflowAdmin can see the document criteria = DocumentSearchCriteria.Builder.create(); criteria.setDocumentId(document.getDocumentId()); results = KEWServiceLocator.getDocumentSearchService().lookupDocuments(getPrincipalId(WORKFLOW_ADMIN_USER_NETWORK_ID), criteria.build()); assertEquals("Should retrive one record from search", 1, results.getSearchResults().size()); assertEquals("No rows should have been filtered due to security", 0, results.getNumberOfSecurityFilteredResults()); } @Test public void testFiltering_SearchAttribute() throws Exception { String searchAttributeName = "UserEmployeeId"; String searchAttributeFieldName = "employeeId"; String documentTypeName = "SecurityDoc_SearchAttributeOnly"; String initiatorNetworkId = STANDARD_USER_NETWORK_ID; WorkflowDocument document = WorkflowDocumentFactory.createDocument(getPrincipalId(initiatorNetworkId), documentTypeName); WorkflowAttributeDefinition.Builder definition = WorkflowAttributeDefinition.Builder.create(searchAttributeName); definition.addPropertyDefinition(searchAttributeFieldName, "user3"); document.addSearchableDefinition(definition.build()); document.route(""); assertFalse("Document should not be in init status after routing", document.isInitiated()); // verify that initiator cannot see the document DocumentSearchCriteria.Builder criteria = DocumentSearchCriteria.Builder.create(); criteria.setDocumentId(document.getDocumentId()); DocumentSearchResults results = KEWServiceLocator.getDocumentSearchService().lookupDocuments(getPrincipalId(initiatorNetworkId), criteria.build()); assertEquals("Should retrive no records from search", 0, results.getSearchResults().size()); assertEquals("One row should have been filtered due to security", 1, results.getNumberOfSecurityFilteredResults()); // verify that user3 can see the document criteria = DocumentSearchCriteria.Builder.create(); criteria.setDocumentId(document.getDocumentId()); results = KEWServiceLocator.getDocumentSearchService().lookupDocuments(getPrincipalId("user3"), criteria.build()); assertEquals("Should retrive one record from search", 1, results.getSearchResults().size()); assertEquals("No rows should have been filtered due to security", 0, results.getNumberOfSecurityFilteredResults()); // verify that user2 cannot see the document criteria = DocumentSearchCriteria.Builder.create(); criteria.setDocumentId(document.getDocumentId()); results = KEWServiceLocator.getDocumentSearchService().lookupDocuments(getPrincipalId("user2"), criteria.build()); assertEquals("Should retrive no records from search", 0, results.getSearchResults().size()); assertEquals("One row should have been filtered due to security", 1, results.getNumberOfSecurityFilteredResults()); // verify that WorkflowAdmin can see the document criteria = DocumentSearchCriteria.Builder.create(); criteria.setDocumentId(document.getDocumentId()); results = KEWServiceLocator.getDocumentSearchService().lookupDocuments(getPrincipalId(WORKFLOW_ADMIN_USER_NETWORK_ID), criteria.build()); assertEquals("Should retrive one record from search", 1, results.getSearchResults().size()); assertEquals("No rows should have been filtered due to security", 0, results.getNumberOfSecurityFilteredResults()); RouteContext.clearCurrentRouteContext(); document = WorkflowDocumentFactory.loadDocument(getPrincipalId(APPROVER_USER_NETWORK_ID), document.getDocumentId()); document.clearSearchableContent(); definition = WorkflowAttributeDefinition.Builder.create(searchAttributeName); definition.addPropertyDefinition(searchAttributeFieldName, "user2"); document.addSearchableDefinition(definition.build()); document.saveDocumentData(); // verify that user2 can see the document criteria = DocumentSearchCriteria.Builder.create(); criteria.setDocumentId(document.getDocumentId()); results = KEWServiceLocator.getDocumentSearchService().lookupDocuments(getPrincipalId("user2"), criteria.build()); assertEquals("Should retrive one record from search", 1, results.getSearchResults().size()); assertEquals("No rows should have been filtered due to security", 0, results.getNumberOfSecurityFilteredResults()); // verify that user3 cannot see the document criteria = DocumentSearchCriteria.Builder.create(); criteria.setDocumentId(document.getDocumentId()); results = KEWServiceLocator.getDocumentSearchService().lookupDocuments(getPrincipalId("user3"), criteria.build()); assertEquals("Should retrive no records from search", 0, results.getSearchResults().size()); assertEquals("One row should have been filtered due to security", 1, results.getNumberOfSecurityFilteredResults()); // verify that initiator cannot see the document criteria = DocumentSearchCriteria.Builder.create(); criteria.setDocumentId(document.getDocumentId()); results = KEWServiceLocator.getDocumentSearchService().lookupDocuments(getPrincipalId(initiatorNetworkId), criteria.build()); assertEquals("Should retrive no records from search", 0, results.getSearchResults().size()); assertEquals("One row should have been filtered due to security", 1, results.getNumberOfSecurityFilteredResults()); } private String getPrincipalId(String principalName) { return KimApiServiceLocator.getIdentityService().getPrincipalByPrincipalName(principalName).getPrincipalId(); } }
apache-2.0
agwlvssainokuni/springapp2
galleryapp/gallery-web/src/main/java/cherry/gallery/web/applied/ex60/AppliedEx61SubFormBase.java
4405
/* * Copyright 2016 agwlvssainokuni * * 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 cherry.gallery.web.applied.ex60; import java.io.Serializable; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.Setter; import lombok.ToString; import org.springframework.context.MessageSourceResolvable; import cherry.fundamental.bizerror.BizErrorUtil; @Getter @Setter @EqualsAndHashCode @ToString @javax.annotation.Generated(value = "cherry.gradle.task.generator.GenerateForm") public abstract class AppliedEx61SubFormBase implements Serializable { private static final long serialVersionUID = 1L; @javax.validation.constraints.NotNull(groups = { javax.validation.groups.Default.class }) @org.springframework.format.annotation.NumberFormat(pattern = cherry.gallery.web.FormatPattern.LONG) private Long id; @org.hibernate.validator.constraints.NotEmpty(groups = { javax.validation.groups.Default.class }) @cherry.fundamental.validator.MaxLength(value = 10, groups = { javax.validation.groups.Default.class }) @cherry.fundamental.validator.CharTypeAlphaNumeric(groups = { javax.validation.groups.Default.class }) private String text10; @cherry.fundamental.validator.MaxLength(value = 100, groups = { javax.validation.groups.Default.class }) private String text100; @javax.validation.constraints.Min(value = -1000000000, groups = { javax.validation.groups.Default.class }) @javax.validation.constraints.Max(value = 1000000000, groups = { javax.validation.groups.Default.class }) @org.springframework.format.annotation.NumberFormat(pattern = cherry.gallery.web.FormatPattern.LONG) private Long int64; @javax.validation.constraints.DecimalMin(value = "-1000000000", groups = { javax.validation.groups.Default.class }) @javax.validation.constraints.DecimalMax(value = "1000000000", groups = { javax.validation.groups.Default.class }) @cherry.fundamental.validator.NumberScale(1) @org.springframework.format.annotation.NumberFormat(pattern = cherry.gallery.web.FormatPattern.DECIMAL_1) private java.math.BigDecimal decimal1; @javax.validation.constraints.DecimalMin(value = "-1000000000", groups = { javax.validation.groups.Default.class }) @javax.validation.constraints.DecimalMax(value = "1000000000", groups = { javax.validation.groups.Default.class }) @cherry.fundamental.validator.NumberScale(3) @org.springframework.format.annotation.NumberFormat(pattern = cherry.gallery.web.FormatPattern.DECIMAL_3) private java.math.BigDecimal decimal3; @org.springframework.format.annotation.DateTimeFormat(pattern = cherry.gallery.web.FormatPattern.DATE) private java.time.LocalDate dt; @org.springframework.format.annotation.DateTimeFormat(pattern = cherry.gallery.web.FormatPattern.TIME) private java.time.LocalTime tm; @org.springframework.format.annotation.DateTimeFormat(pattern = cherry.gallery.web.FormatPattern.DATETIME) private java.time.LocalDateTime dtm; private Integer lockVersion; @Getter public enum Prop { Id("id", "appliedEx61SubForm.id"), // Text10("text10", "appliedEx61SubForm.text10"), // Text100("text100", "appliedEx61SubForm.text100"), // Int64("int64", "appliedEx61SubForm.int64"), // Decimal1("decimal1", "appliedEx61SubForm.decimal1"), // Decimal3("decimal3", "appliedEx61SubForm.decimal3"), // Dt("dt", "appliedEx61SubForm.dt"), // Tm("tm", "appliedEx61SubForm.tm"), // Dtm("dtm", "appliedEx61SubForm.dtm"), // LockVersion("lockVersion", "appliedEx61SubForm.lockVersion"), // DUMMY("dummy", "dummy"); private final String name; private final String nameWithForm; private Prop(String name, String nameWithForm) { this.name = name; this.nameWithForm = nameWithForm; } public MessageSourceResolvable resolve() { return BizErrorUtil.resolve(nameWithForm); } } }
apache-2.0
kkysen/QuickTrip
src/main/java/io/github/kkysen/quicktrip/apis/google/places/GoogleNearbyAirportsRequest.java
617
package io.github.kkysen.quicktrip.apis.google.places; import io.github.kkysen.quicktrip.apis.google.LatLng; import lombok.Getter; import lombok.RequiredArgsConstructor; /** * * * @author Khyber Sen */ @RequiredArgsConstructor public class GoogleNearbyAirportsRequest extends GoogleNearbyRequest<NearbyAirports, NearbyAirport> { @Override protected String getPlaceType() { return "airport"; } private final @Getter(onMethod = @__(@Override)) LatLng location; private final @Getter(onMethod = @__(@Override)) int radius; // meters }
apache-2.0
scouter-project/bytescope
bytescope.agent/src/main/java/scouter/javassist/compiler/ast/CallExpr.java
1531
/* * Javassist, a Java-bytecode translator toolkit. * Copyright (C) 1999- Shigeru Chiba. All Rights Reserved. * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. Alternatively, the contents of this file may be used under * the terms of the GNU Lesser General Public License Version 2.1 or later, * or the Apache License Version 2.0. * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. */ package scouter.javassist.compiler.ast; import scouter.javassist.compiler.CompileError; import scouter.javassist.compiler.MemberResolver; import scouter.javassist.compiler.TokenId; /** * Method call expression. */ public class CallExpr extends Expr { private MemberResolver.Method method; // cached result of lookupMethod() private CallExpr(ASTree _head, ASTList _tail) { super(TokenId.CALL, _head, _tail); method = null; } public void setMethod(MemberResolver.Method m) { method = m; } public MemberResolver.Method getMethod() { return method; } public static CallExpr makeCall(ASTree target, ASTree args) { return new CallExpr(target, new ASTList(args)); } public void accept(Visitor v) throws CompileError { v.atCallExpr(this); } }
apache-2.0
learningtcc/dubbox
dubbo-transactiontree/src/test/java/com/alibaba/dubbo/transactiontreetest/case3/ClientImpl.java
1408
package com.alibaba.dubbo.transactiontreetest.case3; import java.util.Random; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.alibaba.dubbo.transactiontree.api.TransactionManager; @Service public class ClientImpl implements Client { @Autowired private TransactionManager transactionManager; @Override public String m1(String p1, String p2) { System.out.println(Thread.currentThread() + " ClientImpl m1 " + p1); if (new Random().nextInt(100) < 10) { throw new RuntimeException("m1 error"); } return null; } @Override public void m1_confirm(String p1, String p2) { System.out.println(Thread.currentThread() + " ClientImpl m1_confirm " + p1); if (new Random().nextInt(100) < 50) { throw new RuntimeException("m1_confirm error"); } // try { // Thread.sleep(10000L); // } catch (InterruptedException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } transactionManager.getTransactionRepository(); } @Override public void r1_cannel(String p1, String p2) { System.out.println(Thread.currentThread() + " ClientImpl r1_cannel " + p1); // try { // Thread.sleep(10000L); // } catch (InterruptedException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } } }
apache-2.0
ggeorg/chillverse
async-http-client/src/test/java/com/ning/http/client/async/grizzly/GrizzlyMaxTotalConnectionTest.java
1170
/* * Copyright (c) 2012 Sonatype, Inc. All rights reserved. * * This program is licensed to you under the Apache License Version 2.0, * and you may not use this file except in compliance with the Apache License Version 2.0. * You may obtain a copy of the Apache License Version 2.0 at http://www.apache.org/licenses/LICENSE-2.0. * * Unless required by applicable law or agreed to in writing, * software distributed under the Apache License Version 2.0 is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the Apache License Version 2.0 for the specific language governing permissions and limitations there under. */ package com.ning.http.client.async.grizzly; import com.ning.http.client.AsyncHttpClient; import com.ning.http.client.AsyncHttpClientConfig; import com.ning.http.client.async.MaxTotalConnectionTest; import com.ning.http.client.async.ProviderUtil; public class GrizzlyMaxTotalConnectionTest extends MaxTotalConnectionTest { @Override public AsyncHttpClient getAsyncHttpClient(AsyncHttpClientConfig config) { return ProviderUtil.grizzlyProvider(config); } }
apache-2.0
EduTheodoro/Reclamacao_online
src/main/java/br/com/preventsenior/reclamacao/model/Setor.java
1848
package br.com.preventsenior.reclamacao.model; import java.util.List; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.NamedQuery; import javax.persistence.OneToMany; import javax.persistence.Table; @Entity @Table(name="setores") @NamedQuery(name="Setore.findAll", query="SELECT s FROM Setor s") public class Setor { @Id @Column(name="ID") @GeneratedValue(strategy=GenerationType.IDENTITY) private int id; @Column(name="SETOR_DESCRICAO") private String setorDescricao; @Column(name="SETOR_NOME") private String setorNome; //bi-directional many-to-one association to Reclamacao @OneToMany(mappedBy="setor") private List<Reclamacao> reclamacaos; //bi-directional many-to-one association to Usuario @OneToMany(mappedBy="setore") private List<Usuario> usuarios; @Column(name="IC_ATIVO") private boolean ativo; public Setor() { } public int getId() { return this.id; } public void setId(int id) { this.id = id; } public String getSetorDescricao() { return this.setorDescricao; } public void setSetorDescricao(String setorDescricao) { this.setorDescricao = setorDescricao; } public String getSetorNome() { return this.setorNome; } public void setSetorNome(String setorNome) { this.setorNome = setorNome; } public List<Reclamacao> getReclamacaos() { return this.reclamacaos; } public void setReclamacaos(List<Reclamacao> reclamacaos) { this.reclamacaos = reclamacaos; } public List<Usuario> getUsuarios() { return this.usuarios; } public void setUsuarios(List<Usuario> usuarios) { this.usuarios = usuarios; } public boolean isAtivo() { return ativo; } public void setAtivo(boolean ativo) { this.ativo = ativo; } }
apache-2.0
jakabandras/HumanBerCalc
src/com/andrewsoft/humanbercalc/FizuSzamol.java
512
package com.andrewsoft.humanbercalc; import java.util.HashMap; import java.util.Map; public class FizuSzamol { private WorkTime myWt; private Map<String, Integer> times = new HashMap<>(); public FizuSzamol( WorkTime worktime) { // TODO Auto-generated constructor stub myWt = worktime; times.put("8 óra délelõtt",(Integer) myWt.work_8_de); times.put("8 óra délután", (Integer) myWt.work_8_de); } public int Calculate(String what) { return 0; } }
apache-2.0
Bingka/CoolWeather
src/com/bingka/weathercool/WeatherCoolOpenHelper.java
1717
package com.bingka.weathercool; import android.content.Context; import android.database.DatabaseErrorHandler; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteDatabase.CursorFactory; import android.database.sqlite.SQLiteOpenHelper; public class WeatherCoolOpenHelper extends SQLiteOpenHelper { public static final String PROVINCE_TABLE = "Province"; public static final String CITY_TABLE = "City"; public static final String COUNTY_TABLE = "County"; /** * Province±í½¨±íÓï¾ä(Ê¡) */ public static final String CREATE_PROVINCE = "create table Province(" + "id integer primary key autoincrement, " + "province_name text, " + "province_code text)"; /** * City±í½¨±íÓï¾ä(ÊÐ) */ public static final String CREATE_CITY = "create table City(" + "id integer primary key autoincrement, " + "city_name text, " + "city_code text, " + "province_id integer)"; /** * County±í½¨±íÓï¾ä(ÏØ) */ public static final String CREATE_COUNTY = "create table County(" + "id integer primary key autoincrement, " + "county_name text, " + "county_code text, " + "city_id integer)"; public WeatherCoolOpenHelper(Context context, String name, CursorFactory factory, int version, DatabaseErrorHandler errorHandler) { super(context, name, factory, version, errorHandler); } @Override public void onCreate(SQLiteDatabase db) { db.execSQL(CREATE_PROVINCE); // ´´½¨Province±í db.execSQL(CREATE_CITY); // ´´½¨City±í db.execSQL(CREATE_COUNTY); // ´´½¨County±í } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { } }
apache-2.0
sonu283304/onos
core/store/primitives/src/main/java/org/onosproject/store/primitives/impl/DefaultAsyncAtomicValue.java
6969
/* * Copyright 2016 Open Networking Laboratory * * 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.onosproject.store.primitives.impl; import static com.google.common.base.Preconditions.checkNotNull; import java.util.Map; import java.util.concurrent.CompletableFuture; import org.onosproject.store.service.AsyncAtomicValue; import org.onosproject.store.service.AsyncConsistentMap; import org.onosproject.store.service.AtomicValueEvent; import org.onosproject.store.service.AtomicValueEventListener; import org.onosproject.store.service.MapEvent; import org.onosproject.store.service.MapEventListener; import org.onosproject.store.service.Serializer; import org.onosproject.store.service.Versioned; import com.google.common.base.Throwables; import com.google.common.collect.Maps; import org.onosproject.utils.MeteringAgent; public class DefaultAsyncAtomicValue<V> implements AsyncAtomicValue<V> { private final String name; private final Serializer serializer; private final AsyncConsistentMap<String, byte[]> backingMap; private final Map<AtomicValueEventListener<V>, MapEventListener<String, byte[]>> listeners = Maps.newIdentityHashMap(); private final MeteringAgent monitor; private static final String COMPONENT_NAME = "atomicValue"; private static final String GET = "get"; private static final String GET_AND_SET = "getAndSet"; private static final String SET = "set"; private static final String COMPARE_AND_SET = "compareAndSet"; private static final String ADD_LISTENER = "addListener"; private static final String REMOVE_LISTENER = "removeListener"; private static final String NOTIFY_LISTENER = "notifyListener"; public DefaultAsyncAtomicValue(String name, Serializer serializer, AsyncConsistentMap<String, byte[]> backingMap) { this.name = checkNotNull(name, "name must not be null"); this.serializer = checkNotNull(serializer, "serializer must not be null"); this.backingMap = checkNotNull(backingMap, "backingMap must not be null"); this.monitor = new MeteringAgent(COMPONENT_NAME, name, true); } @Override public String name() { return name; } @Override public CompletableFuture<Boolean> compareAndSet(V expect, V update) { final MeteringAgent.Context newTimer = monitor.startTimer(COMPARE_AND_SET); return backingMap.replace(name, serializer.encode(expect), serializer.encode(update)) .whenComplete((r, e) -> newTimer.stop(e)); } @Override public CompletableFuture<V> get() { final MeteringAgent.Context newTimer = monitor.startTimer(GET); return backingMap.get(name) .thenApply(Versioned::valueOrNull) .thenApply(v -> v == null ? null : serializer.<V>decode(v)) .whenComplete((r, e) -> newTimer.stop(e)); } @Override public CompletableFuture<V> getAndSet(V value) { final MeteringAgent.Context newTimer = monitor.startTimer(GET_AND_SET); if (value == null) { return backingMap.remove(name) .thenApply(Versioned::valueOrNull) .thenApply(v -> v == null ? null : serializer.<V>decode(v)) .whenComplete((r, e) -> newTimer.stop(e)); } return backingMap.put(name, serializer.encode(value)) .thenApply(Versioned::valueOrNull) .thenApply(v -> v == null ? null : serializer.<V>decode(v)) .whenComplete((r, e) -> newTimer.stop(e)); } @Override public CompletableFuture<Void> set(V value) { final MeteringAgent.Context newTimer = monitor.startTimer(SET); if (value == null) { return backingMap.remove(name) .whenComplete((r, e) -> newTimer.stop(e)) .thenApply(v -> null); } return backingMap.put(name, serializer.encode(value)) .whenComplete((r, e) -> newTimer.stop(e)) .thenApply(v -> null); } @Override public CompletableFuture<Void> addListener(AtomicValueEventListener<V> listener) { checkNotNull(listener, "listener must not be null"); final MeteringAgent.Context newTimer = monitor.startTimer(ADD_LISTENER); MapEventListener<String, byte[]> mapListener = listeners.computeIfAbsent(listener, key -> new InternalMapValueEventListener(listener)); return backingMap.addListener(mapListener).whenComplete((r, e) -> newTimer.stop(e)); } @Override public CompletableFuture<Void> removeListener(AtomicValueEventListener<V> listener) { checkNotNull(listener, "listener must not be null"); final MeteringAgent.Context newTimer = monitor.startTimer(REMOVE_LISTENER); MapEventListener<String, byte[]> mapListener = listeners.remove(listener); if (mapListener != null) { return backingMap.removeListener(mapListener) .whenComplete((r, e) -> newTimer.stop(e)); } else { newTimer.stop(null); return CompletableFuture.completedFuture(null); } } private class InternalMapValueEventListener implements MapEventListener<String, byte[]> { private final AtomicValueEventListener<V> listener; InternalMapValueEventListener(AtomicValueEventListener<V> listener) { this.listener = listener; } @Override public void event(MapEvent<String, byte[]> event) { if (event.key().equals(name)) { final MeteringAgent.Context newTimer = monitor.startTimer(NOTIFY_LISTENER); byte[] rawNewValue = Versioned.valueOrNull(event.newValue()); byte[] rawOldValue = Versioned.valueOrNull(event.oldValue()); try { listener.event(new AtomicValueEvent<>(name, rawNewValue == null ? null : serializer.decode(rawNewValue), rawOldValue == null ? null : serializer.decode(rawOldValue))); newTimer.stop(null); } catch (Exception e) { newTimer.stop(e); Throwables.propagate(e); } } } } }
apache-2.0
googlemaps/android-samples
ApiDemos/java/app/src/gms/java/com/example/mapdemo/BackgroundColorCustomizationProgrammaticDemoActivity.java
3328
// Copyright 2021 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 // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.example.mapdemo; import android.graphics.Color; import android.os.Bundle; import android.widget.CheckBox; import androidx.annotation.Nullable; import androidx.appcompat.app.AppCompatActivity; import androidx.fragment.app.FragmentTransaction; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.GoogleMapOptions; import com.google.android.gms.maps.OnMapReadyCallback; import com.google.android.gms.maps.SupportMapFragment; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.MarkerOptions; /** * This shows how to to instantiate a SupportMapFragment programmatically with a custom background * color applied to the map, and add a marker on the map. */ public class BackgroundColorCustomizationProgrammaticDemoActivity extends AppCompatActivity implements OnMapReadyCallback { private static final String MAP_FRAGMENT_TAG = "map"; private static final Integer LIGHT_PINK_COLOR = Color.argb(153, 240, 178, 221); @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.background_color_customization_programmatic_demo); // It isn't possible to set a fragment's id programmatically so we set a tag instead and // search for it using that. SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentByTag(MAP_FRAGMENT_TAG); // We only create a fragment if it doesn't already exist. if (mapFragment == null) { // To programmatically add the map, we first create a SupportMapFragment, with the // GoogleMapOptions to set the custom background color displayed before the map tiles load. mapFragment = SupportMapFragment.newInstance(new GoogleMapOptions().backgroundColor(LIGHT_PINK_COLOR)); // Then we add the fragment using a FragmentTransaction. FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction(); fragmentTransaction.replace(R.id.map, mapFragment, MAP_FRAGMENT_TAG); fragmentTransaction.commit(); } mapFragment.getMapAsync(this); } @Override public void onMapReady(GoogleMap map) { map.setMapType(GoogleMap.MAP_TYPE_NONE); CheckBox mapTypeToggleCheckbox = (CheckBox) findViewById(R.id.map_type_toggle); mapTypeToggleCheckbox.setOnCheckedChangeListener( (view, isChecked) -> map.setMapType(isChecked ? GoogleMap.MAP_TYPE_NORMAL : GoogleMap.MAP_TYPE_NONE)); map.addMarker(new MarkerOptions().position(new LatLng(0, 0)).title("Marker")); } }
apache-2.0
jnpr-shinma/yangfile
hitel/src/hctaEpc/ConnectedActionTypesEnum.java
1447
/* * @(#)ConnectedActionTypesEnum.java 1.0 09/12/14 * * This file has been auto-generated by JNC, the * Java output format plug-in of pyang. * Origin: module "hcta-epc", revision: "2014-09-18". */ package hctaEpc; import YangException; import com.tailf.jnc.YangEnumeration; /** * This class represents an element from * the namespace * generated to "src/hctaEpc/connectedActionTypes-enum" * <p> * See line 218 in * cmdCommonHcta.yang * * @version 1.0 2014-12-09 * @author Auto Generated */ public class ConnectedActionTypesEnum extends YangEnumeration { private static final long serialVersionUID = 1L; /** * Constructor for ConnectedActionTypesEnum object from a string. * @param value Value to construct the ConnectedActionTypesEnum from. */ public ConnectedActionTypesEnum(String value) throws YangException { super(value, new String[] { "passive", "offload-user-inactivity", "offload-all", "detach", } ); check(); } /** * Sets the value using a string value. * @param value The value to set. */ public void setValue(String value) throws YangException { super.setValue(value); check(); } /** * Checks all restrictions (if any). */ public void check() throws YangException { super.check(); } }
apache-2.0
geofeedia/migrations
src/main/java/org/apache/ibatis/migration/MigrationReader.java
4320
/** * Copyright 2010-2015 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.ibatis.migration; import org.apache.ibatis.parsing.PropertyParser; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; import java.io.StringReader; import java.io.UnsupportedEncodingException; import java.util.Arrays; import java.util.HashSet; import java.util.Properties; import java.util.Set; public class MigrationReader extends Reader { // FEFF because this is the Unicode char represented by the UTF-8 byte order mark (EF BB BF). public static final String UTF8_BOM = "\uFEFF"; private static final String LINE_SEPARATOR = System.getProperty("line.separator", "\n"); private Reader target; public MigrationReader(File file, String charset, boolean undo, Properties properties) throws IOException { this(new FileInputStream(file), charset, undo, properties); } public MigrationReader(InputStream inputStream, String charset, boolean undo, Properties properties) throws IOException { final Reader source = scriptFileReader(inputStream, charset); final Properties variables = filterVariables(properties == null ? new Properties() : properties); try { BufferedReader reader = new BufferedReader(source); StringBuilder doBuilder = new StringBuilder(); StringBuilder undoBuilder = new StringBuilder(); StringBuilder currentBuilder = doBuilder; String line; boolean firstLine = true; while ((line = reader.readLine()) != null) { if (firstLine) { if ("UTF-8".equalsIgnoreCase(charset) && line.startsWith(UTF8_BOM)) { line = line.substring(1); } firstLine = false; } if (line.trim().matches("^--\\s*//.*$")) { if (line.contains("@UNDO")) { currentBuilder = undoBuilder; } line = line.replaceFirst("--\\s*//", "-- "); } currentBuilder.append(line); currentBuilder.append(LINE_SEPARATOR); } if (undo) { target = new StringReader(PropertyParser.parse(undoBuilder.toString(), variables)); } else { target = new StringReader(PropertyParser.parse(doBuilder.toString(), variables)); } } finally { source.close(); } } public int read(char[] cbuf, int off, int len) throws IOException { return target.read(cbuf, off, len); } public void close() throws IOException { target.close(); } protected Reader scriptFileReader(InputStream inputStream, String charset) throws FileNotFoundException, UnsupportedEncodingException { if (charset == null || charset.length() == 0) { return new InputStreamReader(inputStream); } else { return new InputStreamReader(inputStream, charset); } } @SuppressWarnings("serial") private Properties filterVariables(final Properties properties) { final Set<String> KNOWN_PROPERTIES_TO_IGNORE = new HashSet<String>() {{ addAll(Arrays.asList( "time_zone", "script_char_set", "driver", "url", "username", "password", "send_full_script", "delimiter", "full_line_delimiter", "auto_commit", "driver_path")); }}; return new Properties() { @Override public synchronized boolean containsKey(Object o) { return !KNOWN_PROPERTIES_TO_IGNORE.contains(o) && properties.containsKey(o); } @Override public String getProperty(String key) { return KNOWN_PROPERTIES_TO_IGNORE.contains(key) ? null : properties.getProperty(key); } }; } }
apache-2.0
vipshop/Saturn
saturn-console-api/src/test/java/com/vip/saturn/job/console/com/vip/saturn/job/console/mybatis/repository/DashboardHistoryRepositoryTest.java
5741
/** * Copyright 2016 vip.com. * <p> * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * 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. * </p> **/ package com.vip.saturn.job.console.com.vip.saturn.job.console.mybatis.repository; import com.vip.saturn.job.console.mybatis.entity.DashboardHistory; import com.vip.saturn.job.console.mybatis.repository.DashboardHistoryRepository; import org.junit.Assert; import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.transaction.annotation.Transactional; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.List; /** * @author Ray Leung */ @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = "classpath:applicationContext.xml") public class DashboardHistoryRepositoryTest { @Autowired private DashboardHistoryRepository dashboardHistoryRepository; @Test @Ignore @Transactional public void testCreateHistory() { dashboardHistoryRepository.createOrUpdateHistory("zk", "Domain", "DomainStatistics", "somecontent", new Date()); List<String> zkClusters = new ArrayList<>(); zkClusters.add("zk"); List<DashboardHistory> dashboardHistories = dashboardHistoryRepository .selectByZkClustersAndTypeAndTopicAndFromStartDateToEndDate(zkClusters, "Domain", "DomainStatistics", new Date(), new Date()); Assert.assertEquals(1, dashboardHistories.size()); } @Test @Ignore @Transactional public void testUpdateHistory() { dashboardHistoryRepository.createOrUpdateHistory("zk", "Domain", "DomainStatistics", "somecontent", new Date()); List<String> zkClusters = new ArrayList<>(); zkClusters.add("zk"); List<DashboardHistory> dashboardHistories = dashboardHistoryRepository .selectByZkClustersAndTypeAndTopicAndFromStartDateToEndDate(zkClusters, "Domain", "DomainStatistics", new Date(), new Date()); Assert.assertEquals(1, dashboardHistories.size()); dashboardHistoryRepository.createOrUpdateHistory("zk", "Domain", "DomainStatistics", "newcontent", new Date()); dashboardHistories = dashboardHistoryRepository .selectByZkClustersAndTypeAndTopicAndFromStartDateToEndDate(zkClusters, "Domain", "DomainStatistics", new Date(), new Date()); Assert.assertEquals(1, dashboardHistories.size()); } @Test @Ignore @Transactional public void testQueryFromToDate() { Calendar yesterday = Calendar.getInstance(); yesterday.add(Calendar.DATE, -1); Calendar theDayBeforeYesterday = Calendar.getInstance(); theDayBeforeYesterday.add(Calendar.DATE, -2); List<String> zkClusters = new ArrayList<>(); zkClusters.add("zk"); dashboardHistoryRepository .createOrUpdateHistory("zk", "Domain", "DomainStatistics", "somecontent", yesterday.getTime()); dashboardHistoryRepository.createOrUpdateHistory("zk", "Domain", "DomainStatistics", "somecontent", theDayBeforeYesterday.getTime()); dashboardHistoryRepository.createOrUpdateHistory("zk", "Domain", "DomainStatistics", "somecontent", new Date()); List<DashboardHistory> dashboardHistories = dashboardHistoryRepository .selectByZkClustersAndTypeAndTopicAndFromStartDateToEndDate(zkClusters, "Domain", "DomainStatistics", theDayBeforeYesterday.getTime(), yesterday.getTime()); Assert.assertEquals(2, dashboardHistories.size()); } @Test @Ignore @Transactional public void testBatchCreate() { List<DashboardHistory> dashboardHistories = new ArrayList<>(); for (int i = 0; i < 5; i++) { DashboardHistory dashboardHistory = new DashboardHistory("zk", "type" + String.valueOf(i), "topic", String.valueOf(i), new Date()); dashboardHistories.add(dashboardHistory); } dashboardHistoryRepository.batchCreateOrUpdateHistory(dashboardHistories); List<String> zkClusters = new ArrayList<>(); zkClusters.add("zk"); List<DashboardHistory> result = dashboardHistoryRepository .selectByZkClustersAndTypeAndTopicAndFromStartDateToEndDate(zkClusters, null, null, null, null); Assert.assertEquals(5, result.size()); } @Test @Ignore @Transactional public void testBatchUpdate() { List<DashboardHistory> dashboardHistories = new ArrayList<>(); for (int i = 0; i < 2; i++) { DashboardHistory dashboardHistory = new DashboardHistory("zk", "type" + String.valueOf(i), "topic", "hello", new Date()); dashboardHistories.add(dashboardHistory); } dashboardHistoryRepository.batchCreateOrUpdateHistory(dashboardHistories); for (int i = 0; i < 2; i++) { DashboardHistory dashboardHistory = new DashboardHistory("zk", "type" + String.valueOf(i), "topic", "hello world", new Date()); dashboardHistories.add(dashboardHistory); } dashboardHistoryRepository.batchCreateOrUpdateHistory(dashboardHistories); List<String> zkClusters = new ArrayList<>(); zkClusters.add("zk"); List<DashboardHistory> result = dashboardHistoryRepository .selectByZkClustersAndTypeAndTopicAndFromStartDateToEndDate(zkClusters, null, null, null, null); for (DashboardHistory history : result) { Assert.assertEquals("hello world", history.getContent()); } } }
apache-2.0
obourgain/elasticsearch-http
src/main/java/com/github/obourgain/elasticsearch/http/response/entity/aggs/Terms.java
3894
package com.github.obourgain.elasticsearch.http.response.entity.aggs; import java.io.IOException; import java.util.ArrayList; import java.util.List; import org.apache.commons.lang3.tuple.Pair; import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.common.xcontent.XContentParser; import lombok.AllArgsConstructor; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.NoArgsConstructor; @Getter public class Terms extends AbstractAggregation { private long sumOtherDocCount = -1; private long docCountErrorUpperBound = -1; private List<Bucket> buckets; public Terms(String name) { super(name); } public static Terms parse(XContentParser parser, String name) { try { Terms terms = new Terms(name); XContentParser.Token token; String currentFieldName = null; while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) { if (token == XContentParser.Token.FIELD_NAME) { currentFieldName = parser.currentName(); } else if (token.isValue()) { if ("doc_count_error_upper_bound".equals(currentFieldName)) { terms.docCountErrorUpperBound = parser.longValue(); } else if ("sum_other_doc_count".equals(currentFieldName)) { terms.sumOtherDocCount = parser.longValue(); } } else if (token == XContentParser.Token.START_ARRAY) { if ("buckets".equals(currentFieldName)) { terms.buckets = parseBuckets(parser); } } } return terms; } catch (IOException e) { throw new RuntimeException(e); } } protected static List<Bucket> parseBuckets(XContentParser parser) throws IOException { XContentParser.Token token; List<Bucket> result = new ArrayList<>(); while ((token = parser.nextToken()) != XContentParser.Token.END_ARRAY) { if (token == XContentParser.Token.START_OBJECT) { result.add(parseBucket(parser)); } } return result; } protected static Bucket parseBucket(XContentParser parser) throws IOException { XContentParser.Token token; String currentFieldName = null; Bucket bucket = new Bucket(); while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) { if (token == XContentParser.Token.FIELD_NAME) { currentFieldName = parser.currentName(); } else if (token.isValue()) { if ("doc_count_error_upper_bound".equals(currentFieldName)) { bucket.docCountErrorUpperBound = parser.longValue(); } else if ("key".equals(currentFieldName)) { bucket.key = parser.text(); } else if ("key_as_string".equals(currentFieldName)) { // ignore for now } else if ("doc_count".equals(currentFieldName)) { bucket.docCount = parser.longValue(); } } else if (token == XContentParser.Token.START_OBJECT && currentFieldName != null) { // parse as sub agg only if not at first level Pair<String, XContentBuilder> agg = Aggregations.parseInnerAgg(parser, currentFieldName); bucket.addSubAgg(agg.getKey(), agg.getValue()); } } return bucket; } @Getter @EqualsAndHashCode(callSuper = true) @AllArgsConstructor @NoArgsConstructor public static class Bucket extends AbstractBucket { private long docCountErrorUpperBound; private String key; // private String keyAsString; private long docCount; } }
apache-2.0
tomasdavidorg/android-vehicle-routing-problem
app/src/main/java/org/tomasdavid/vehicleroutingproblem/MainActivity.java
3052
/* * Copyright 2015 Tomas David * * 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.tomasdavid.vehicleroutingproblem; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.widget.DrawerLayout; import android.support.v7.app.ActionBarActivity; import android.support.v7.widget.Toolbar; import android.view.Gravity; import org.tomasdavid.vehicleroutingproblem.components.StopSolverDialog; import org.tomasdavid.vehicleroutingproblem.fragments.MainFragment; import org.tomasdavid.vehicleroutingproblem.fragments.VrpFragment; import org.tomasdavid.vehicleroutingproblem.tasks.VrpSolverTask; /** * Main and only activity of application. * * @author Tomas David */ public class MainActivity extends ActionBarActivity { /** * Navigation drawer for displaying statistics. */ private DrawerLayout statsDrawer; /** * Unlock navigation drawer. */ public void unlockDrawer() { statsDrawer.setDrawerLockMode(DrawerLayout.VISIBLE); } /** * Hide and lock navigation drawer. */ public void lockDrawer() { statsDrawer.closeDrawer(Gravity.START); statsDrawer.setDrawerLockMode(DrawerLayout.INVISIBLE); } /** * {@inheritDoc} */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); toolbar.setTitle(R.string.app_name); setSupportActionBar(toolbar); statsDrawer = (DrawerLayout) findViewById(R.id.drawer_layout); lockDrawer(); if (savedInstanceState == null) { MainFragment fragment = new MainFragment(); getSupportFragmentManager().beginTransaction().add(R.id.activity_main, fragment).commit(); } } /** * {@inheritDoc} */ @Override public void onBackPressed() { Fragment fragment = getSupportFragmentManager().findFragmentById(R.id.activity_main); if (fragment instanceof VrpFragment) { VrpSolverTask vrpSolverTask = ((VrpFragment) fragment).getVrpSolverTask(); if (vrpSolverTask.isRunning()) { new StopSolverDialog().show(getSupportFragmentManager(), null); return; } else { lockDrawer(); ((Toolbar) findViewById(R.id.toolbar)).setNavigationIcon(null); } } super.onBackPressed(); } }
apache-2.0
JackAnansi/NHLPlayoffsSim
app/src/main/java/com/ambrogio/dan/playoffs/MainActivity.java
2917
package com.ambrogio.dan.playoffs; import android.app.Activity; import android.content.Intent; import android.content.SharedPreferences; import android.support.v7.app.ActionBarActivity; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.TextView; public class MainActivity extends ActionBarActivity { public static final String MYPREFS = "MYSHAREDPREFERENCES"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // Show the last cup winner // Default: LA Kings (2014 winner) SharedPreferences prefs = getSharedPreferences(MYPREFS, Activity.MODE_PRIVATE); // Get the "lastwinner" value, or L.A. Kings if there isn't one String lastWinner = prefs.getString("lastwinner", "L.A. Kings"); TextView winner = (TextView)findViewById(R.id.winnerTextView); winner.setText("Last Winner: " + lastWinner); MyDBHandler db = MyDBHandler.getInstance(getApplicationContext()); } @Override protected void onResume(){ super.onResume(); SharedPreferences prefs = getSharedPreferences(MYPREFS, Activity.MODE_PRIVATE); // Get the "lastwinner" value, or L.A. Kings if there isn't one String lastWinner = prefs.getString("lastwinner", "L.A. Kings"); TextView winner = (TextView)findViewById(R.id.winnerTextView); winner.setText("Last Winner: " + lastWinner); } /** * Goes to the "Edit a Team" screen. * @param v */ public void editTeamOnClick(View v){ // Go to the Edit Team screen //Button editTeam = (Button)findViewById(R.id.menuBtnEdit); startActivity(new Intent(getApplicationContext(), EditTeam.class)); } public void runSimOnClick(View v){ // Go to the Run Sim screen startActivity(new Intent(getApplicationContext(), SelectTeam.class)); } public void showStatsOnClick(View v){ startActivity(new Intent(getApplicationContext(), ShowStats.class)); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_main, 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(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } }
apache-2.0
cdegroot/river
src/net/jini/jeri/OutboundRequest.java
10222
/* * 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.jeri; import java.io.InputStream; import java.io.OutputStream; import java.util.Collection; import net.jini.core.constraint.ConstraintAlternatives; import net.jini.core.constraint.Integrity; import net.jini.core.constraint.InvocationConstraints; /** * Represents a request that is being sent and the corresponding * response received in reply. * * <p>An <code>OutboundRequest</code> can be used to write out the * contents of the request and to read in the response. * * <p>The communication protocol used by the implementation of this * interface must guarantee that for each instance of this interface, * any request data must only be delivered to the recipient (in the * form of an <code>InboundRequest</code> passed to {@link * RequestDispatcher#dispatch RequestDispatcher.dispatch}) <i>at most * once</i>. The {@link #getDeliveryStatus getDeliveryStatus} method * can be used to determine whether or not at least partial delivery * of the request might have occurred. * * <p>When finished using an <code>OutboundRequest</code>, in order to * allow the implementation to free resources associated with the * request, users should either invoke <code>close</code> on the * streams returned by the <code>getRequestOutputStream</code> and * <code>getResponseInputStream</code> methods, or invoke the * <code>abort</code> method. * * * @see InboundRequest * @since 2.0 **/ public interface OutboundRequest { /** * Populates the supplied collection with context information * representing this request. * * @param context the context collection to populate * * @throws NullPointerException if <code>context</code> is * <code>null</code> * * @throws UnsupportedOperationException if <code>context</code> * is unmodifiable and if any elements need to be added **/ void populateContext(Collection context); /** * Returns the requirements that must be at least partially * implemented by higher layers in order to fully satisfy the * requirements for this request. This method may also return * preferences that must be at least partially implemented by * higher layers in order to fully satisfy some of the preferences * for this request. * * <p>For any given constraint, there must be a clear delineation * of which aspects (if any) must be implemented by the transport * layer. This method must not return a constraint (as a * requirement or a preference, directly or as an element of * another constraint) unless this request implements all of those * aspects. Also, this method must not return a constraint for * which all aspects must be implemented by the transport layer. * Most of the constraints in the {@link net.jini.core.constraint} * package must be fully implemented by the transport layer and * thus must not be returned by this method; the one exception is * {@link Integrity}, for which the transport layer is responsible * for the data integrity aspect and higher layers are responsible * for the code integrity aspect. * * <p>For any {@link ConstraintAlternatives} in the constraints * for this request, this method should only return a * corresponding constraint if all of the alternatives satisfied * by this request need to be at least partially implemented by * higher layers in order to be fully satisfied. * * @return the constraints for this request that must be partially * or fully implemented by higher layers **/ InvocationConstraints getUnfulfilledConstraints(); /** * Returns an <code>OutputStream</code> to write the request data * to. The sequence of bytes written to the returned stream will * be the sequence of bytes sent as the body of this request. * * <p>After the entirety of the request has been written to the * stream, the stream's <code>close</code> method must be invoked * to ensure complete delivery of the request. It is possible * that none of the data written to the returned stream will be * delivered before <code>close</code> has been invoked (even if * the stream's <code>flush</code> method had been invoked at any * time). Note, however, that some or all of the data written to * the stream may be delivered to (and processed by) the recipient * before the stream's <code>close</code> method has been invoked. * * <p>After the stream's <code>close</code> method has been * invoked, no more data may be written to the stream; writes * subsequent to a <code>close</code> invocation will fail with an * <code>IOException</code>. * * <p>If this method is invoked more than once, it will always * return the identical stream object that it returned the first * time (although the stream may be in a different state than it * was upon return from the first invocation). * * @return the output stream to write request data to **/ OutputStream getRequestOutputStream(); /** * Returns an <code>InputStream</code> to read the response data * from. The sequence of bytes produced by reading from the * returned stream will be the sequence of bytes received as the * response data. When the entirety of the response has been * successfully read, reading from the stream will indicate an * EOF. * * <p>Users of an <code>OutboundRequest</code> must not expect any * data to be available from the returned stream before the * <code>close</code> method has been invoked on the stream * returned by <code>getRequestOutputStream</code>; in other * words, the user's request/response protocol must not require * any part of a request to be a function of any part of its * response. * * <p>It is possible, however, for data to be available from the * returned stream before the <code>close</code> method has been * invoked on, or even before the entirety of the request has been * written to, the stream returned by * <code>getRequestOutputStream</code>. Because such an early * response might indicate, depending on the user's * request/response protocol, that the recipient will not consider * the entirety of the request, perhaps due to an error or other * abnormal condition, the user may wish to process it * expeditiously, rather than continuing to write the remainder of * the request. * * <p>Invoking the <code>close</code> method of the returned * stream will cause any subsequent read operations on the stream * to fail with an <code>IOException</code>, although it will not * terminate this request as a whole; in particular, the request * may still be subsequently written to the stream returned by the * <code>getRequestOutputStream</code> method. After * <code>close</code> has been invoked on both the returned stream * and the stream returned by <code>getRequestOutputStream</code>, * the implementation may free all resources associated with this * request. * * <p>If this method is invoked more than once, it will always * return the identical stream object that it returned the first * time (although the stream may be in a different state than it * was upon return from the first invocation). * * @return the input stream to read response data from **/ InputStream getResponseInputStream(); /** * Returns <code>false</code> if it is guaranteed that no data * written for this request has been processed by the recipient. * This guarantee remains valid until any subsequent I/O operation * has been attempted on this request. * * If this method returns <code>true</code>, then data written for * this request may have been at least partially processed by the * recipient (the <code>RequestDispatcher</code> receiving the * corresponding <code>InboundRequest</code>). * * @return <code>false</code> if data written for this request has * definitely not been processed by the recipient, and * <code>true</code> if data written for this request may have * been at least partially processed by the recipient **/ boolean getDeliveryStatus(); /** * Terminates this request, freeing all associated resources. * * <p>This method may be invoked at any stage of the processing of * the request. * * <p>After this method has been invoked, I/O operations on the * streams returned by the <code>getRequestOutputStream</code> and * <code>getResponseInputStream</code> methods will fail with an * <code>IOException</code>, except some operations that may * succeed because they only affect data in local I/O buffers. * * <p>If this method is invoked before the <code>close</code> * method has been invoked on the stream returned by * <code>getRequestOutputStream</code>, there is no guarantee that * any or none of the data written to the stream so far will be * delivered; the implication of such an invocation of this method * is that the user is no longer interested in the successful * delivery of the request. **/ void abort(); }
apache-2.0
justice-code/Thrush
base/src/main/java/org/eddy/solve/NotifyThreadFactory.java
1432
package org.eddy.solve; import java.util.concurrent.ThreadFactory; import java.util.concurrent.atomic.AtomicInteger; /** * Created by Justice-love on 2017/7/17. */ public class NotifyThreadFactory implements ThreadFactory{ private static final AtomicInteger poolNumber = new AtomicInteger(1); private final ThreadGroup group; private final AtomicInteger threadNumber = new AtomicInteger(1); private final String namePrefix; public NotifyThreadFactory() { SecurityManager s = System.getSecurityManager(); group = (s != null) ? s.getThreadGroup() : Thread.currentThread().getThreadGroup(); namePrefix = "pool-notify-" + poolNumber.getAndIncrement() + "-thread-"; } /** * Constructs a new {@code Thread}. Implementations may also initialize * priority, name, daemon status, {@code ThreadGroup}, etc. * * @param r a runnable to be executed by new thread instance * @return constructed thread, or {@code null} if the request to * create a thread is rejected */ @Override public Thread newThread(Runnable r) { Thread t = new Thread(group, r, namePrefix + threadNumber.getAndIncrement(), 0); if (t.isDaemon()) t.setDaemon(false); if (t.getPriority() != Thread.NORM_PRIORITY) t.setPriority(Thread.NORM_PRIORITY); return t; } }
apache-2.0
henrichg/PhoneProfilesPlus
phoneProfilesPlus/src/main/java/sk/henrichg/phoneprofilesplus/NFCEventEndBroadcastReceiver.java
3918
package sk.henrichg.phoneprofilesplus; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.os.Handler; import android.os.PowerManager; public class NFCEventEndBroadcastReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { // PPApplication.logE("[IN_BROADCAST] NFCEventEndBroadcastReceiver.onReceive", "xxx"); //CallsCounter.logCounter(context, "NFCEventEndBroadcastReceiver.onReceive", "NFCEventEndBroadcastReceiver_onReceive"); String action = intent.getAction(); if (action != null) { //PPApplication.logE("NFCEventEndBroadcastReceiver.onReceive", "action=" + action); doWork(/*true,*/ context); } } private void doWork(/*boolean useHandler,*/ Context context) { //PPApplication.logE("[HANDLER] NFCEventEndBroadcastReceiver.doWork", "useHandler="+useHandler); //final Context appContext = context.getApplicationContext(); if (!PPApplication.getApplicationStarted(true)) // application is not started return; if (Event.getGlobalEventsRunning()) { //if (useHandler) { final Context appContext = context.getApplicationContext(); PPApplication.startHandlerThreadBroadcast(/*"NFCEventEndBroadcastReceiver.doWork"*/); final Handler __handler = new Handler(PPApplication.handlerThreadBroadcast.getLooper()); //__handler.post(new PPApplication.PPHandlerThreadRunnable( // context.getApplicationContext()) { __handler.post(() -> { // PPApplication.logE("[IN_THREAD_HANDLER] PPApplication.startHandlerThread", "START run - from=NFCEventEndBroadcastReceiver.doWork"); //Context appContext= appContextWeakRef.get(); //if (appContext != null) { PowerManager powerManager = (PowerManager) appContext.getSystemService(Context.POWER_SERVICE); PowerManager.WakeLock wakeLock = null; try { if (powerManager != null) { wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, PPApplication.PACKAGE_NAME + ":NFCEventEndBroadcastReceiver_doWork"); wakeLock.acquire(10 * 60 * 1000); } // PPApplication.logE("[EVENTS_HANDLER_CALL] NFCEventEndBroadcastReceiver.doWork", "sensorType=SENSOR_TYPE_NFC_EVENT_END"); EventsHandler eventsHandler = new EventsHandler(appContext); eventsHandler.handleEvents(EventsHandler.SENSOR_TYPE_NFC_EVENT_END); //PPApplication.logE("****** EventsHandler.handleEvents", "END run - from=NFCEventEndBroadcastReceiver.doWork"); } catch (Exception e) { // PPApplication.logE("[IN_THREAD_HANDLER] PPApplication.startHandlerThread", Log.getStackTraceString(e)); PPApplication.recordException(e); } finally { if ((wakeLock != null) && wakeLock.isHeld()) { try { wakeLock.release(); } catch (Exception ignored) { } } } //} }); /*} else { if (Event.getGlobalEventsRunning(appContext)) { PPApplication.logE("NFCEventEndBroadcastReceiver.doWork", "handle events"); EventsHandler eventsHandler = new EventsHandler(appContext); eventsHandler.handleEvents(EventsHandler.SENSOR_TYPE_NFC_EVENT_END); } }*/ } } }
apache-2.0
robzor92/hops
hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/web/resources/GetOpParam.java
2657
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.hdfs.web.resources; import java.net.HttpURLConnection; /** * Http GET operation parameter. */ public class GetOpParam extends HttpOpParam<GetOpParam.Op> { /** * Get operations. */ public static enum Op implements HttpOpParam.Op { OPEN(true, HttpURLConnection.HTTP_OK), GETFILESTATUS(false, HttpURLConnection.HTTP_OK), LISTSTATUS(false, HttpURLConnection.HTTP_OK), GETCONTENTSUMMARY(false, HttpURLConnection.HTTP_OK), GETFILECHECKSUM(true, HttpURLConnection.HTTP_OK), GETHOMEDIRECTORY(false, HttpURLConnection.HTTP_OK), GETDELEGATIONTOKEN(false, HttpURLConnection.HTTP_OK), /** * GET_BLOCK_LOCATIONS is a private unstable op. */ GET_BLOCK_LOCATIONS(false, HttpURLConnection.HTTP_OK), NULL(false, HttpURLConnection.HTTP_NOT_IMPLEMENTED); final boolean redirect; final int expectedHttpResponseCode; Op(final boolean redirect, final int expectedHttpResponseCode) { this.redirect = redirect; this.expectedHttpResponseCode = expectedHttpResponseCode; } @Override public HttpOpParam.Type getType() { return HttpOpParam.Type.GET; } @Override public boolean getDoOutput() { return false; } @Override public boolean getRedirect() { return redirect; } @Override public int getExpectedHttpResponseCode() { return expectedHttpResponseCode; } @Override public String toQueryString() { return NAME + "=" + this; } } private static final Domain<Op> DOMAIN = new Domain<>(NAME, Op.class); /** * Constructor. * * @param str * a string representation of the parameter value. */ public GetOpParam(final String str) { super(DOMAIN, DOMAIN.parse(str)); } @Override public String getName() { return NAME; } }
apache-2.0
axonivy/project-build-plugin
src/main/java/ch/ivyteam/ivy/maven/util/CompilerResult.java
2239
/* * Copyright (C) 2021 Axon Ivy AG * * 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 ch.ivyteam.ivy.maven.util; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.util.Map; import java.util.Map.Entry; import java.util.Properties; import org.apache.maven.project.MavenProject; import ch.ivyteam.ivy.maven.engine.MavenProjectBuilderProxy.Result; /** * @author Reguel Wermelinger * @since 6.0.3 */ public class CompilerResult { public static void store(Map<String, Object> result, MavenProject project) throws IOException { Properties properties = new Properties(); for(Entry<String, Object> entry : result.entrySet()) { properties.setProperty(entry.getKey(), entry.getValue().toString()); } File propertyFile = new SharedFile(project).getCompileResultProperties(); try(FileOutputStream fos = new FileOutputStream(propertyFile)) { properties.store(fos, "ivy project build results"); } } public static CompilerResult load(MavenProject project) throws IOException { File propertyFile = new SharedFile(project).getCompileResultProperties(); Properties compileResults = new Properties(); try(FileInputStream fis = new FileInputStream(propertyFile)) { compileResults.load(fis); } return new CompilerResult(compileResults); } private final Properties result; public CompilerResult(Properties result) { this.result = result; } public String getTestOutputDirectory() { if (!result.stringPropertyNames().contains(Result.TEST_OUTPUT_DIR)) { return null; } return result.getProperty(Result.TEST_OUTPUT_DIR); } }
apache-2.0
rdblue/incubator-nifi
commons/nifi-expression-language/src/main/java/org/apache/nifi/attribute/expression/language/evaluation/functions/LessThanEvaluator.java
2257
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.nifi.attribute.expression.language.evaluation.functions; import java.util.Map; import org.apache.nifi.attribute.expression.language.evaluation.BooleanEvaluator; import org.apache.nifi.attribute.expression.language.evaluation.BooleanQueryResult; import org.apache.nifi.attribute.expression.language.evaluation.Evaluator; import org.apache.nifi.attribute.expression.language.evaluation.NumberEvaluator; import org.apache.nifi.attribute.expression.language.evaluation.QueryResult; public class LessThanEvaluator extends BooleanEvaluator { private final NumberEvaluator subject; private final NumberEvaluator comparison; public LessThanEvaluator(final NumberEvaluator subject, final NumberEvaluator comparison) { this.subject = subject; this.comparison = comparison; } @Override public QueryResult<Boolean> evaluate(final Map<String, String> attributes) { final Long subjectValue = subject.evaluate(attributes).getValue(); if (subjectValue == null) { return new BooleanQueryResult(false); } final Long comparisonValue = comparison.evaluate(attributes).getValue(); if (comparisonValue == null) { return new BooleanQueryResult(false); } return new BooleanQueryResult(subjectValue < comparisonValue); } ; @Override public Evaluator<?> getSubjectEvaluator() { return subject; } }
apache-2.0
dorzey/assertj-core
src/test/java/org/assertj/core/api/optional/OptionalAssert_isEmpty_Test.java
1532
/** * 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.optional; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.error.OptionalShouldBeEmpty.shouldBeEmpty; import static org.assertj.core.util.FailureMessages.actualIsNull; import java.util.Optional; import org.assertj.core.api.BaseTest; import org.junit.Test; public class OptionalAssert_isEmpty_Test extends BaseTest { @Test public void should_pass_if_optional_is_empty() throws Exception { assertThat(Optional.empty()).isEmpty(); } @Test public void should_fail_when_optional_is_null() throws Exception { thrown.expectAssertionError(actualIsNull()); assertThat((Optional<String>) null).isEmpty(); } @Test public void should_fail_if_optional_is_present() throws Exception { Optional<String> actual = Optional.of("not-empty"); thrown.expectAssertionError(shouldBeEmpty(actual).create()); assertThat(actual).isEmpty(); } }
apache-2.0
KayuraTeam/kayura-activiti
src/main/java/org/kayura/activiti/vo/FormPropertyVo.java
2328
package org.kayura.activiti.vo; import java.io.Serializable; import java.util.Map; import org.activiti.engine.form.FormProperty; import org.kayura.utils.StringUtils; public class FormPropertyVo implements Serializable { private static final long serialVersionUID = 1607099846369884335L; private String id; private String name; private String value; private String type; private String datePattern; private Map<String, String> items; private boolean readable = true; private boolean writeable = true; private boolean required; @SuppressWarnings("unchecked") public FormPropertyVo(FormProperty formProperty) { this.id = formProperty.getId(); this.name = formProperty.getName(); this.value = formProperty.getValue(); this.type = formProperty.getType().getName(); this.datePattern = StringUtils.toString(formProperty.getType().getInformation("datePattern")); this.setItems(((Map<String, String>) formProperty.getType().getInformation("values"))); this.readable = formProperty.isReadable(); this.writeable = formProperty.isWritable(); this.required = formProperty.isRequired(); } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getType() { return type; } public void setType(String type) { this.type = type; } public String getDatePattern() { return datePattern; } public void setDatePattern(String datePattern) { this.datePattern = datePattern; } public boolean isReadable() { return readable; } public void setReadable(boolean readable) { this.readable = readable; } public boolean isWriteable() { return writeable; } public void setWriteable(boolean writeable) { this.writeable = writeable; } public boolean isRequired() { return required; } public void setRequired(boolean required) { this.required = required; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } public Map<String, String> getItems() { return items; } public void setItems(Map<String, String> items) { this.items = items; } }
apache-2.0
googleapis/java-vision
samples/spring-framework/src/main/java/com/example/vision/VisionController.java
3300
/* * Copyright 2019 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.example.vision; import com.google.cloud.vision.v1.AnnotateImageResponse; import com.google.cloud.vision.v1.EntityAnnotation; import com.google.cloud.vision.v1.Feature.Type; import java.util.LinkedHashMap; import java.util.Map; import java.util.stream.Collectors; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cloud.gcp.vision.CloudVisionTemplate; import org.springframework.core.io.ResourceLoader; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.servlet.ModelAndView; /** * Code sample demonstrating Cloud Vision usage within the context of Spring Framework using Spring * Cloud GCP libraries. The sample is written as a Spring Boot application to demonstrate a * practical application of this usage. */ @RestController public class VisionController { @Autowired private ResourceLoader resourceLoader; // [START spring_vision_autowire] @Autowired private CloudVisionTemplate cloudVisionTemplate; // [END spring_vision_autowire] /** * This method downloads an image from a URL and sends its contents to the Vision API for label * detection. * * @param imageUrl the URL of the image * @param map the model map to use * @return a string with the list of labels and percentage of certainty */ @GetMapping("/extractLabels") public ModelAndView extractLabels(String imageUrl, ModelMap map) { // [START spring_vision_image_labelling] AnnotateImageResponse response = this.cloudVisionTemplate.analyzeImage( this.resourceLoader.getResource(imageUrl), Type.LABEL_DETECTION); Map<String, Float> imageLabels = response.getLabelAnnotationsList().stream() .collect( Collectors.toMap( EntityAnnotation::getDescription, EntityAnnotation::getScore, (u, v) -> { throw new IllegalStateException(String.format("Duplicate key %s", u)); }, LinkedHashMap::new)); // [END spring_vision_image_labelling] map.addAttribute("annotations", imageLabels); map.addAttribute("imageUrl", imageUrl); return new ModelAndView("result", map); } @GetMapping("/extractText") public String extractText(String imageUrl) { // [START spring_vision_text_extraction] String textFromImage = this.cloudVisionTemplate.extractTextFromImage(this.resourceLoader.getResource(imageUrl)); return "Text from image: " + textFromImage; // [END spring_vision_text_extraction] } }
apache-2.0
wjsl/jaredcumulo
server/src/main/java/org/apache/accumulo/server/monitor/servlets/XMLServlet.java
8340
/* * 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.accumulo.server.monitor.servlets; import java.util.Map.Entry; import java.util.SortedMap; import java.util.TreeMap; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.accumulo.core.client.Instance; import org.apache.accumulo.core.client.impl.Tables; import org.apache.accumulo.core.master.thrift.Compacting; import org.apache.accumulo.core.master.thrift.DeadServer; import org.apache.accumulo.core.master.thrift.TableInfo; import org.apache.accumulo.core.master.thrift.TabletServerStatus; import org.apache.accumulo.server.client.HdfsZooInstance; import org.apache.accumulo.server.master.state.TabletServerState; import org.apache.accumulo.server.monitor.Monitor; import org.apache.accumulo.server.monitor.util.celltypes.TServerLinkType; public class XMLServlet extends BasicServlet { private static final long serialVersionUID = 1L; @Override protected String getTitle(HttpServletRequest req) { return "XML Report"; } @Override protected void pageStart(HttpServletRequest req, HttpServletResponse resp, StringBuilder sb) { resp.setContentType("text/xml;charset=UTF-8"); sb.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"); sb.append("<stats>\n"); } @Override protected void pageBody(HttpServletRequest req, HttpServletResponse resp, StringBuilder sb) { double totalIngest = 0.; double totalQuery = 0.; double disk = 0.0; long totalEntries = 0L; sb.append("\n<servers>\n"); if (Monitor.getMmi() == null || Monitor.getMmi().tableMap == null) { sb.append("</servers>\n"); return; } SortedMap<String,TableInfo> tableStats = new TreeMap<String,TableInfo>(Monitor.getMmi().tableMap); for (TabletServerStatus status : Monitor.getMmi().tServerInfo) { sb.append("\n<server id='").append(status.name).append("'>\n"); sb.append("<hostname>").append(TServerLinkType.displayName(status.name)).append("</hostname>"); sb.append("<lastContact>").append(System.currentTimeMillis() - status.lastContact).append("</lastContact>\n"); sb.append("<osload>").append(status.osLoad).append("</osload>\n"); TableInfo summary = Monitor.summarizeTableStats(status); sb.append("<compactions>\n"); sb.append("<major>").append("<running>").append(summary.majors.running).append("</running>").append("<queued>").append(summary.majors.queued) .append("</queued>").append("</major>\n"); sb.append("<minor>").append("<running>").append(summary.minors.running).append("</running>").append("<queued>").append(summary.minors.queued) .append("</queued>").append("</minor>\n"); sb.append("</compactions>\n"); sb.append("<tablets>").append(summary.tablets).append("</tablets>\n"); sb.append("<ingest>").append(summary.ingestRate).append("</ingest>\n"); sb.append("<query>").append(summary.queryRate).append("</query>\n"); sb.append("<ingestMB>").append(summary.ingestByteRate / 1000000.0).append("</ingestMB>\n"); sb.append("<queryMB>").append(summary.queryByteRate / 1000000.0).append("</queryMB>\n"); sb.append("<scans>").append(summary.scans.running + summary.scans.queued).append("</scans>"); sb.append("<scansessions>").append(Monitor.getLookupRate()).append("</scansessions>\n"); sb.append("<holdtime>").append(status.holdTime).append("</holdtime>\n"); totalIngest += summary.ingestRate; totalQuery += summary.queryRate; totalEntries += summary.recs; sb.append("</server>\n"); } sb.append("\n</servers>\n"); sb.append("\n<masterGoalState>" + Monitor.getMmi().goalState + "</masterGoalState>\n"); sb.append("\n<masterState>" + Monitor.getMmi().state + "</masterState>\n"); sb.append("\n<badTabletServers>\n"); for (Entry<String,Byte> entry : Monitor.getMmi().badTServers.entrySet()) { sb.append(String.format("<badTabletServer id='%s' status='%s'/>\n", entry.getKey(), TabletServerState.getStateById(entry.getValue()))); } sb.append("\n</badTabletServers>\n"); sb.append("\n<tabletServersShuttingDown>\n"); for (String server : Monitor.getMmi().serversShuttingDown) { sb.append(String.format("<server id='%s'/>\n", server)); } sb.append("\n</tabletServersShuttingDown>\n"); sb.append(String.format("\n<unassignedTablets>%d</unassignedTablets>\n", Monitor.getMmi().unassignedTablets)); sb.append("\n<deadTabletServers>\n"); for (DeadServer dead : Monitor.getMmi().deadTabletServers) { sb.append(String.format("<deadTabletServer id='%s' lastChange='%d' status='%s'/>\n", dead.server, dead.lastStatus, dead.status)); } sb.append("\n</deadTabletServers>\n"); sb.append("\n<deadLoggers>\n"); for (DeadServer dead : Monitor.getMmi().deadTabletServers) { sb.append(String.format("<deadLogger id='%s' lastChange='%d' status='%s'/>\n", dead.server, dead.lastStatus, dead.status)); } sb.append("\n</deadLoggers>\n"); sb.append("\n<tables>\n"); Instance instance = HdfsZooInstance.getInstance(); for (Entry<String,TableInfo> entry : tableStats.entrySet()) { TableInfo tableInfo = entry.getValue(); sb.append("\n<table>\n"); String tableId = entry.getKey(); String tableName = "unknown"; String tableState = "unknown"; try { tableName = Tables.getTableName(instance, tableId); tableState = Tables.getTableState(instance, tableId).toString(); } catch (Exception ex) { log.warn(ex, ex); } sb.append("<tablename>").append(tableName).append("</tablename>\n"); sb.append("<tableId>").append(tableId).append("</tableId>\n"); sb.append("<tableState>").append(tableState).append("</tableState>\n"); sb.append("<tablets>").append(tableInfo.tablets).append("</tablets>\n"); sb.append("<onlineTablets>").append(tableInfo.onlineTablets).append("</onlineTablets>\n"); sb.append("<recs>").append(tableInfo.recs).append("</recs>\n"); sb.append("<recsInMemory>").append(tableInfo.recsInMemory).append("</recsInMemory>\n"); sb.append("<ingest>").append(tableInfo.ingestRate).append("</ingest>\n"); sb.append("<ingestByteRate>").append(tableInfo.ingestByteRate).append("</ingestByteRate>\n"); sb.append("<query>").append(tableInfo.queryRate).append("</query>\n"); sb.append("<queryByteRate>").append(tableInfo.queryRate).append("</queryByteRate>\n"); int running = 0; int queued = 0; Compacting compacting = entry.getValue().majors; if (compacting != null) { running = compacting.running; queued = compacting.queued; } sb.append("<majorCompactions>").append("<running>").append(running).append("</running>").append("<queued>").append(queued).append("</queued>") .append("</majorCompactions>\n"); sb.append("</table>\n"); } sb.append("\n</tables>\n"); sb.append("\n<totals>\n"); sb.append("<ingestrate>").append(totalIngest).append("</ingestrate>\n"); sb.append("<queryrate>").append(totalQuery).append("</queryrate>\n"); sb.append("<diskrate>").append(disk).append("</diskrate>\n"); sb.append("<numentries>").append(totalEntries).append("</numentries>\n"); sb.append("</totals>\n"); } @Override protected void pageEnd(HttpServletRequest req, HttpServletResponse resp, StringBuilder sb) { sb.append("\n</stats>\n"); } }
apache-2.0
xionggit/BootLoginService
src/main/java/com/ecochain/service/impl/AclResourcesServiceImpl.java
1374
package com.ecochain.service.impl; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.ecochain.service.AclResourcesService; import com.ecochain.user.entity.AclResources; import com.ecochain.user.entity.AclResourcesExample; import com.ecochain.user.entity.Auth; import com.ecochain.user.mapper.AclResourcesMapper; /** * Created by Athos on 2016-07-12. */ @Service public class AclResourcesServiceImpl implements AclResourcesService { @Autowired AclResourcesMapper resourcesMapper; protected AclResourcesMapper getMapper() { return resourcesMapper; } @Override public List<AclResources> selectAclResourcesTypeOfRequest() { return getMapper().selectAclResourcesTypeOfRequest(); } @Override public List<AclResources> selectAclResourcesByResourceIds(String resourceIds) { return getMapper().selectAclResourcesByResourceIds(resourceIds.split(",")); } @Override public List<Auth> findResourcesByResourceIds(String ids) { return resourcesMapper.findResourcesByResourceIds(ids.split(",")); } @Override public List<AclResources> selectAllResources() { return resourcesMapper.selectByExample(new AclResourcesExample()); } }
apache-2.0
a642500/DataCenter
datacenter/src/main/java/co/yishun/library/datacenter/SuperRecyclerViewRefreshable.java
1297
package co.yishun.library.datacenter; import android.support.v4.widget.SwipeRefreshLayout; import com.malinskiy.superrecyclerview.SuperRecyclerView; /** * Created by carlos on 2/6/16. */ public class SuperRecyclerViewRefreshable implements Refreshable { private final SuperRecyclerView mSuperRecyclerView; public SuperRecyclerViewRefreshable(SuperRecyclerView mSuperRecyclerView) { this.mSuperRecyclerView = mSuperRecyclerView; } @Override public void setOnRefreshListener(final OnRefreshListener listener) { mSuperRecyclerView.setRefreshListener(new SwipeRefreshLayout.OnRefreshListener() { @Override public void onRefresh() { listener.onRefresh(); } }); } @Override public void setRefreshing(boolean refreshing) { SwipeRefreshLayout swipeRefreshLayout = mSuperRecyclerView.getSwipeToRefresh(); if (swipeRefreshLayout != null) { swipeRefreshLayout.setRefreshing(refreshing); } } @Override public void setEnabled(boolean enabled) { SwipeRefreshLayout swipeRefreshLayout = mSuperRecyclerView.getSwipeToRefresh(); if (swipeRefreshLayout != null) { swipeRefreshLayout.setEnabled(enabled); } } }
apache-2.0
Camelion/nasc-decompiler
src/main/scala/ru/jts/decompiler/ll/stack/MathEvent.java
4419
/* * Copyright 2015-2017 JTS * * 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 ru.jts.decompiler.ll.stack; /** * Created by Дмитрий on 16.05.2015. */ public class MathEvent extends StackObject { private static final int ADD = 0; private static final int SUB = 1; private static final int MUL = 2; private static final int DIV = 3; private static final int MOD = 4; private StackObject owner; private int operationType; private StackObject rightOperand; private boolean braces; public MathEvent(StackObject owner) { super(owner.aiClass); this.owner = owner; } public static StackObject add(StackObject left, StackObject right) { if (left instanceof BitOperation) { ((BitOperation) left).setBraces(true); } if (right instanceof BitOperation) { ((BitOperation) right).setBraces(true); } MathEvent event = new MathEvent(left); event.operationType = ADD; event.rightOperand = right; return event; } public static MathEvent mul(StackObject left, StackObject right) { if (right instanceof MathEvent && (((MathEvent) right).operationType == ADD || ((MathEvent) right).operationType == SUB)) { ((MathEvent) right).setBraces(true); } MathEvent event = new MathEvent(left); event.operationType = MUL; event.rightOperand = right; return event; } public void setBraces(boolean braces) { this.braces = braces; } public static MathEvent sub(StackObject left, StackObject right) { MathEvent event = new MathEvent(left); event.operationType = SUB; event.rightOperand = right; return event; } public static MathEvent div(StackObject left, StackObject right) { if (right instanceof MathEvent && (((MathEvent) right).operationType == ADD || ((MathEvent) right).operationType == SUB)) { ((MathEvent) right).setBraces(true); } MathEvent event = new MathEvent(left); event.operationType = DIV; event.rightOperand = right; return event; } public static MathEvent add_string(StackObject left, StackObject right) { if (right instanceof MathEvent && ((MathEvent) right).owner instanceof EventObject && ((EventObject) ((MathEvent) right).owner).getEventType() != String.class) { ((MathEvent) right).setBraces(true); } MathEvent event = new MathEvent(left); event.operationType = ADD; event.rightOperand = right; return event; } public static MathEvent mod(StackObject left, StackObject right) { MathEvent event = new MathEvent(left); event.operationType = MOD; event.rightOperand = right; return event; } @Override public String toString() { String str = ""; if (owner instanceof EventObject || owner instanceof MathEvent || owner instanceof StringObject || owner instanceof IntObject || owner instanceof ParameterObject || owner instanceof FloatObject || owner instanceof BitOperation) { str = owner.toString() + " " + operationToString() + " " + rightOperand.toString(); if (braces) str = "(" + str + ")"; } else { System.err.println("MathEvent: Unknown owner type: " + owner.getClass()); } return str; } private String operationToString() { String str = ""; switch (operationType) { case ADD: return "+"; case MUL: return "*"; case SUB: return "-"; case DIV: return "/"; case MOD: return "%"; } return str; } }
apache-2.0
bogeo/simsamples
src/de/hsbo/geo/simsamples/applications/RandomMovementExample.java
2985
package de.hsbo.geo.simsamples.applications; import java.text.DecimalFormat; import java.text.NumberFormat; import java.util.ArrayList; import java.util.Locale; import de.hsbo.geo.simsamples.markov.instances.SimpleMarkovChain; /** * Simple Markov model describing a random movement between two absorbers. * The example is taken from the lecture "Spatiotemporal modelling and * simulation" of the Master course Geoinformatics at Bochum University of * Applied Sciences (chapter 4, "Random modelling"). * * @author Benno Schmidt */ public class RandomMovementExample { double p = 0.4; // Probability to move right (for states "2" ... "7") double q = 1. - p; // Probability to move left (for states "2" ... "7") String[] states = new String[] { "1", "2", "3", "4", "5", "6", "7", "8"}; String sInit = "5"; // initial state // The element M1[i][j] of the transition matrix gives the probability // that the object will move from state i to state j: double[][] M1 = new double[][] { {1, 0, 0, 0, 0, 0, 0, 0}, {q, 0, p, 0, 0, 0, 0, 0}, {0, q, 0, p, 0, 0, 0, 0}, {0, 0, q, 0, p, 0, 0, 0}, {0, 0, 0, q, 0, p, 0, 0}, {0, 0, 0, 0, q, 0, p, 0}, {0, 0, 0, 0, 0, q, 0, p}, {0, 0, 0, 0, 0, 0, 0, 1} }; public static void main(String[] args) throws Exception { new RandomMovementExample().run(); } public void run() throws Exception { ArrayList<Object> stateSet = new ArrayList<Object>(); for (String s : states) stateSet.add(s); SimpleMarkovChain a = new SimpleMarkovChain( stateSet, sInit, M1); int numberOfSteps = 20; a.execute(numberOfSteps); a.dumpResult("Time", 0, 10); showTransitionMatrices(); } private void showTransitionMatrices() { // The elements Mk[i][j] of the transition matrix Mk give the probabilities // the object's moves from state i to state j during the next k time steps. double[][] M2 = mult(M1, M1), M3 = mult(M2, M1); System.out.println("M1:"); printMatrix(M1); System.out.println("M2:"); printMatrix(M2); System.out.println("M3:"); printMatrix(M3); double[][] M = mult(M1, M1); int N = 20; for (int i = 3; i <= N; i++) { M = mult(M, M1); } System.out.println("M" + N + ":"); printMatrix(M); } static public void printMatrix(double[][] M) { NumberFormat numberFormat = NumberFormat.getNumberInstance(Locale.US); ((DecimalFormat) numberFormat).applyPattern("###.##"); for (int i = 0; i < M.length; i++) { for (int j = 0; j < M[i].length; j++) { String out = numberFormat.format(new Double(M[i][j])); System.out.print("\t" + out); } System.out.println(); } } static public double[][] mult(double[][] A, double[][] B) { double[][] C = new double[A.length][A[0].length]; for (int i = 0; i < A.length; i++) { for (int j = 0; j < A[i].length; j++) { C[i][j] = 0; for (int k = 0; k < A.length; k++) { C[i][j] += A[i][k] * B[k][j]; } } } return C; } }
apache-2.0
zhukic/Sectioned-RecyclerView
sectioned-recyclerview/src/test/java/com/zhukic/sectionedrecyclerview/SectionTest.java
388
package com.zhukic.sectionedrecyclerview; import org.junit.Test; import static org.junit.Assert.*; public class SectionTest { @Test public void checkConstructor() { Section section = new Section(10); assertEquals(10, section.getSubheaderPosition()); assertEquals(0, section.getItemCount()); assertEquals(true, section.isExpanded()); } }
apache-2.0
tripodsan/jackrabbit-oak
oak-segment-tar/src/main/java/org/apache/jackrabbit/oak/segment/http/HttpStoreRevisions.java
2535
/* * 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.jackrabbit.oak.segment.http; import static com.google.common.base.Charsets.UTF_8; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.MalformedURLException; import java.net.URLConnection; import javax.annotation.Nonnull; import com.google.common.base.Function; import org.apache.jackrabbit.oak.segment.RecordId; import org.apache.jackrabbit.oak.segment.Revisions; public class HttpStoreRevisions implements Revisions { @Nonnull private final HttpStore store; public HttpStoreRevisions(@Nonnull HttpStore store) { this.store = store; } @Nonnull @Override public RecordId getHead() { try { URLConnection connection = store.get(null); try ( InputStream stream = connection.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(stream, UTF_8)) ) { return RecordId.fromString(store, reader.readLine()); } } catch (IllegalArgumentException | MalformedURLException e) { throw new IllegalStateException(e); } catch (IOException e) { throw new RuntimeException(e); } } @Override public boolean setHead( @Nonnull RecordId base, @Nonnull RecordId head, @Nonnull Option... options) { throw new UnsupportedOperationException(); } @Override public boolean setHead( @Nonnull Function<RecordId, RecordId> newHead, @Nonnull Option... options) throws InterruptedException { throw new UnsupportedOperationException(); } }
apache-2.0
marques-work/gocd
common/src/test/java/com/thoughtworks/go/serverhealth/HealthStateScopeTest.java
6236
/* * Copyright 2021 ThoughtWorks, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.thoughtworks.go.serverhealth; import com.thoughtworks.go.config.CaseInsensitiveString; import com.thoughtworks.go.config.CruiseConfig; import com.thoughtworks.go.config.materials.mercurial.HgMaterialConfig; import com.thoughtworks.go.config.materials.svn.SvnMaterial; import com.thoughtworks.go.config.remote.ConfigRepoConfig; import com.thoughtworks.go.helper.GoConfigMother; import com.thoughtworks.go.helper.MaterialConfigsMother; import com.thoughtworks.go.helper.MaterialsMother; import org.junit.Test; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.not; import static org.junit.Assert.assertThat; public class HealthStateScopeTest { private static final SvnMaterial MATERIAL1 = MaterialsMother.svnMaterial("url1"); private static final SvnMaterial MATERIAL2 = MaterialsMother.svnMaterial("url2"); @Test public void shouldHaveAUniqueScopeForEachMaterial() throws Exception { HealthStateScope scope1 = HealthStateScope.forMaterial(MATERIAL1); HealthStateScope scope2 = HealthStateScope.forMaterial(MATERIAL1); assertThat(scope1, is(scope2)); } @Test public void shouldHaveDifferentScopeForDifferentMaterials() throws Exception { HealthStateScope scope1 = HealthStateScope.forMaterial(MATERIAL1); HealthStateScope scope2 = HealthStateScope.forMaterial(MATERIAL2); assertThat(scope1, not(scope2)); } @Test public void shouldHaveDifferentScopeWhenAutoUpdateHasChanged() throws Exception { SvnMaterial mat = MaterialsMother.svnMaterial("url1"); HealthStateScope scope1 = HealthStateScope.forMaterial(mat); mat.setAutoUpdate(false); HealthStateScope scope2 = HealthStateScope.forMaterial(mat); assertThat(scope1, not(scope2)); } @Test public void shouldHaveUniqueScopeForStages() throws Exception { HealthStateScope scope1 = HealthStateScope.forStage("blahPipeline","blahStage"); HealthStateScope scope2 = HealthStateScope.forStage("blahPipeline","blahStage"); HealthStateScope scope25 = HealthStateScope.forStage("blahPipeline","blahOtherStage"); HealthStateScope scope3 = HealthStateScope.forStage("blahOtherPipeline","blahOtherStage"); assertThat(scope1, is(scope2)); assertThat(scope1, not(scope25)); assertThat(scope1, not(scope3)); } @Test public void shouldRemoveScopeWhenMaterialIsRemovedFromConfig() throws Exception { HgMaterialConfig hgMaterialConfig = MaterialConfigsMother.hgMaterialConfig(); CruiseConfig config = GoConfigMother.pipelineHavingJob("blahPipeline", "blahStage", "blahJob", "fii", "baz"); config.pipelineConfigByName(new CaseInsensitiveString("blahPipeline")).addMaterialConfig(hgMaterialConfig); assertThat(HealthStateScope.forMaterialConfig(hgMaterialConfig).isRemovedFromConfig(config),is(false)); assertThat(HealthStateScope.forMaterial(MaterialsMother.svnMaterial("file:///bar")).isRemovedFromConfig(config),is(true)); } @Test public void shouldNotRemoveScopeWhenMaterialBelongsToConfigRepoMaterial() throws Exception { HgMaterialConfig hgMaterialConfig = MaterialConfigsMother.hgMaterialConfig(); CruiseConfig config = GoConfigMother.pipelineHavingJob("blahPipeline", "blahStage", "blahJob", "fii", "baz"); config.getConfigRepos().add(ConfigRepoConfig.createConfigRepoConfig(hgMaterialConfig, "id1", "foo")); assertThat(HealthStateScope.forMaterialConfig(hgMaterialConfig).isRemovedFromConfig(config),is(false)); } @Test public void shouldNotRemoveScopeWhenMaterialUpdateBelongsToConfigRepoMaterial() throws Exception { HgMaterialConfig hgMaterialConfig = MaterialConfigsMother.hgMaterialConfig(); CruiseConfig config = GoConfigMother.pipelineHavingJob("blahPipeline", "blahStage", "blahJob", "fii", "baz"); config.getConfigRepos().add(ConfigRepoConfig.createConfigRepoConfig(hgMaterialConfig, "id1", "foo")); assertThat(HealthStateScope.forMaterialConfigUpdate(hgMaterialConfig).isRemovedFromConfig(config),is(false)); } @Test public void shouldRemoveScopeWhenStageIsRemovedFromConfig() throws Exception { CruiseConfig config = GoConfigMother.pipelineHavingJob("blahPipeline", "blahStage", "blahJob", "fii", "baz"); assertThat(HealthStateScope.forPipeline("fooPipeline").isRemovedFromConfig(config),is(true)); assertThat(HealthStateScope.forPipeline("blahPipeline").isRemovedFromConfig(config),is(false)); assertThat(HealthStateScope.forStage("fooPipeline","blahStage").isRemovedFromConfig(config),is(true)); assertThat(HealthStateScope.forStage("blahPipeline","blahStageRemoved").isRemovedFromConfig(config),is(true)); assertThat(HealthStateScope.forStage("blahPipeline","blahStage").isRemovedFromConfig(config),is(false)); } @Test public void shouldRemoveScopeWhenJobIsRemovedFromConfig() throws Exception { CruiseConfig config = GoConfigMother.pipelineHavingJob("blahPipeline", "blahStage", "blahJob", "fii", "baz"); assertThat(HealthStateScope.forJob("fooPipeline","blahStage", "barJob").isRemovedFromConfig(config),is(true)); assertThat(HealthStateScope.forJob("blahPipeline", "blahStage", "blahJob").isRemovedFromConfig(config),is(false)); } @Test public void shouldUnderstandPluginScope() { HealthStateScope scope = HealthStateScope.aboutPlugin("plugin.one"); assertThat(scope.getScope(), is("plugin.one")); assertThat(scope.getType(), is(HealthStateScope.ScopeType.PLUGIN)); } }
apache-2.0
welterde/ewok
com/planet_ink/coffee_mud/Races/Deer.java
5029
package com.planet_ink.coffee_mud.Races; import com.planet_ink.coffee_mud.core.interfaces.*; import com.planet_ink.coffee_mud.core.*; import com.planet_ink.coffee_mud.Abilities.interfaces.*; import com.planet_ink.coffee_mud.Areas.interfaces.*; import com.planet_ink.coffee_mud.Behaviors.interfaces.*; import com.planet_ink.coffee_mud.CharClasses.interfaces.*; import com.planet_ink.coffee_mud.Commands.interfaces.*; import com.planet_ink.coffee_mud.Common.interfaces.*; import com.planet_ink.coffee_mud.Exits.interfaces.*; import com.planet_ink.coffee_mud.Items.interfaces.*; import com.planet_ink.coffee_mud.Locales.interfaces.*; import com.planet_ink.coffee_mud.MOBS.interfaces.*; import com.planet_ink.coffee_mud.Races.interfaces.*; import java.util.*; /* Copyright 2000-2010 Bo Zimmerman Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ @SuppressWarnings("unchecked") public class Deer extends StdRace { public String ID(){ return "Deer"; } public String name(){ return "Deer"; } public int shortestMale(){return 38;} public int shortestFemale(){return 38;} public int heightVariance(){return 6;} public int lightestWeight(){return 150;} public int weightVariance(){return 50;} public long forbiddenWornBits(){return Integer.MAX_VALUE-Wearable.WORN_FEET-Wearable.WORN_NECK-Wearable.WORN_EARS-Wearable.WORN_EYES;} public String racialCategory(){return "Equine";} // an ey ea he ne ar ha to le fo no gi mo wa ta wi private static final int[] parts={0 ,2 ,2 ,1 ,1 ,0 ,0 ,1 ,4 ,4 ,1 ,0 ,1 ,1 ,1 ,0 }; public int[] bodyMask(){return parts;} private int[] agingChart={0,1,2,4,7,15,20,21,22}; public int[] getAgingChart(){return agingChart;} protected static Vector resources=new Vector(); public int availabilityCode(){return Area.THEME_FANTASY|Area.THEME_SKILLONLYMASK;} public void affectCharStats(MOB affectedMOB, CharStats affectableStats) { super.affectCharStats(affectedMOB, affectableStats); affectableStats.setRacialStat(CharStats.STAT_STRENGTH,3); affectableStats.setRacialStat(CharStats.STAT_DEXTERITY,18); affectableStats.setRacialStat(CharStats.STAT_INTELLIGENCE,1); } public Weapon myNaturalWeapon() { if(naturalWeapon==null) { naturalWeapon=CMClass.getWeapon("StdWeapon"); naturalWeapon.setName("a set of sharp horns"); naturalWeapon.setWeaponType(Weapon.TYPE_PIERCING); } return naturalWeapon; } public String healthText(MOB viewer, MOB mob) { double pct=(CMath.div(mob.curState().getHitPoints(),mob.maxState().getHitPoints())); if(pct<.10) return "^r" + mob.displayName(viewer) + "^r is hovering on deaths door!^N"; else if(pct<.20) return "^r" + mob.displayName(viewer) + "^r is covered in blood and matted hair.^N"; else if(pct<.30) return "^r" + mob.displayName(viewer) + "^r is bleeding badly from lots of wounds.^N"; else if(pct<.40) return "^y" + mob.displayName(viewer) + "^y has large patches of bloody matted fur.^N"; else if(pct<.50) return "^y" + mob.displayName(viewer) + "^y has some bloody matted fur.^N"; else if(pct<.60) return "^p" + mob.displayName(viewer) + "^p has a lot of cuts and gashes.^N"; else if(pct<.70) return "^p" + mob.displayName(viewer) + "^p has a few cut patches.^N"; else if(pct<.80) return "^g" + mob.displayName(viewer) + "^g has a cut patch of fur.^N"; else if(pct<.90) return "^g" + mob.displayName(viewer) + "^g has some disheveled fur.^N"; else if(pct<.99) return "^g" + mob.displayName(viewer) + "^g has some misplaced hairs.^N"; else return "^c" + mob.displayName(viewer) + "^c is in perfect health.^N"; } public Vector myResources() { synchronized(resources) { if(resources.size()==0) { resources.addElement(makeResource ("a pair of "+name().toLowerCase()+" horns",RawMaterial.RESOURCE_BONE)); for(int i=0;i<7;i++) resources.addElement(makeResource ("a strip of "+name().toLowerCase()+" leather",RawMaterial.RESOURCE_LEATHER)); for(int i=0;i<3;i++) resources.addElement(makeResource ("a pound of "+name().toLowerCase()+" meat",RawMaterial.RESOURCE_BEEF)); resources.addElement(makeResource ("some "+name().toLowerCase()+" blood",RawMaterial.RESOURCE_BLOOD)); resources.addElement(makeResource ("a pile of "+name().toLowerCase()+" bones",RawMaterial.RESOURCE_BONE)); } } return resources; } }
apache-2.0
linger1216/labelview
lib/src/main/java/com/lid/lib/LabelTextView.java
2507
package com.lid.lib; import android.content.Context; import android.graphics.Canvas; import android.util.AttributeSet; import android.widget.TextView; public class LabelTextView extends TextView { LabelViewHelper utils; public LabelTextView(Context context) { this(context, null); } public LabelTextView(Context context, AttributeSet attrs) { this(context, attrs, 0); } public LabelTextView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); utils = new LabelViewHelper(context, attrs, defStyleAttr); } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); utils.onDraw(canvas, getMeasuredWidth(), getMeasuredHeight()); } public void setLabelHeight(int height) { utils.setLabelHeight(this, height); } public int getLabelHeight() { return utils.getLabelHeight(); } public void setLabelDistance(int distance) { utils.setLabelDistance(this, distance); } public int getLabelDistance() { return utils.getLabelDistance(); } public boolean isLabelEnable() { return utils.isLabelVisual(); } public void setLabelEnable(boolean enable) { utils.setLabelVisual(this, enable); } public int getLabelOrientation() { return utils.getLabelOrientation(); } public void setLabelOrientation(int orientation) { utils.setLabelOrientation(this, orientation); } public int getLabelTextColor() { return utils.getLabelTextColor(); } public void setLabelTextColor(int textColor) { utils.setLabelTextColor(this, textColor); } public int getLabelBackgroundColor() { return utils.getLabelBackgroundColor(); } public void setLabelBackgroundColor(int backgroundColor) { utils.setLabelBackgroundColor(this, backgroundColor); } public String getLabelText() { return utils.getLabelText(); } public void setLabelText(String text) { utils.setLabelText(this, text); } public int getLabelTextSize() { return utils.getLabelTextSize(); } public void setLabelTextSize(int textSize) { utils.setLabelTextSize(this, textSize); } public int getLabelTextStyle(){ return utils.getLabelTextStyle(); } public void setLabelTextStyle(int textStyle){ utils.setLabelTextStyle(this, textStyle); } }
apache-2.0
ExplorViz/ExplorViz
src-external/de/cau/cs/kieler/klay/layered/properties/InternalProperties.java
17880
/* * KIELER - Kiel Integrated Environment for Layout Eclipse RichClient * * http://www.informatik.uni-kiel.de/rtsys/kieler/ * * Copyright 2010 by * + Christian-Albrechts-University of Kiel * + Department of Computer Science * + Real-Time and Embedded Systems Group * * This code is provided under the terms of the Eclipse Public License (EPL). * See the file epl-v10.html for the license text. */ package de.cau.cs.kieler.klay.layered.properties; import java.util.ArrayList; import java.util.EnumSet; import java.util.List; import java.util.Random; import java.util.Set; import com.google.common.base.Function; import com.google.common.collect.Multimap; import de.cau.cs.kieler.core.math.KVector; import de.cau.cs.kieler.core.math.KVectorChain; import de.cau.cs.kieler.core.properties.IProperty; import de.cau.cs.kieler.core.properties.Property; import de.cau.cs.kieler.kiml.options.EdgeRouting; import de.cau.cs.kieler.kiml.options.LayoutOptions; import de.cau.cs.kieler.kiml.options.PortSide; import de.cau.cs.kieler.kiml.util.nodespacing.LabelSide; import de.cau.cs.kieler.kiml.util.nodespacing.Spacing.Margins; import de.cau.cs.kieler.klay.layered.ILayoutProcessor; import de.cau.cs.kieler.klay.layered.IntermediateProcessingConfiguration; import de.cau.cs.kieler.klay.layered.compound.CrossHierarchyEdge; import de.cau.cs.kieler.klay.layered.graph.LEdge; import de.cau.cs.kieler.klay.layered.graph.LGraph; import de.cau.cs.kieler.klay.layered.graph.LLabel; import de.cau.cs.kieler.klay.layered.graph.LNode; import de.cau.cs.kieler.klay.layered.graph.LPort; import de.cau.cs.kieler.klay.layered.p3order.NodeGroup; import de.cau.cs.kieler.klay.layered.p5edges.splines.ConnectedSelfLoopComponent; import de.cau.cs.kieler.klay.layered.p5edges.splines.LoopSide; /** * Container for property definitions for internal use of the algorithm. These properties should * not be accessed from outside. * * @author msp * @author cds * @author uru * @kieler.design proposed by msp * @kieler.rating proposed yellow by msp */ public final class InternalProperties { /** * The original object from which a graph element was created. */ public static final IProperty<Object> ORIGIN = new Property<Object>("origin"); /** * The intermediate processing configuration for an input graph. */ public static final IProperty<IntermediateProcessingConfiguration> CONFIGURATION = new Property<IntermediateProcessingConfiguration>("processingConfiguration"); /** * The list of layout processors executed for an input graph. */ public static final IProperty<List<ILayoutProcessor>> PROCESSORS = new Property<List<ILayoutProcessor>>("processors"); /** * Whether the original node an LNode was created from was a compound node or not. This might * influence certain layout decisions, such as where to place inside port labels so that they * don't overlap edges. */ public static final IProperty<Boolean> COMPOUND_NODE = new Property<Boolean>("compoundNode", false); /** * Whether the original port an LPort was created from was a compound port with connections to * or from descendants of its node. This might influence certain layout decisions, such as where * to place its inside port label. */ public static final IProperty<Boolean> INSIDE_CONNECTIONS = new Property<Boolean>( "insideConnections", false); /** * An LNode that represents a compound node can hold a reference to a nested LGraph which * represents the graph that is contained within the compound node. */ public static final IProperty<LGraph> NESTED_LGRAPH = new Property<LGraph>("nestedLGraph"); /** * A nested LGraph has a reference to the LNode that contains it. */ public static final IProperty<LNode> PARENT_LNODE = new Property<LNode>("parentLNode"); /** * The original bend points of an edge. */ public static final IProperty<KVectorChain> ORIGINAL_BENDPOINTS = new Property<KVectorChain>( "originalBendpoints"); /** * In interactive layout settings, this property can be set to indicate where a dummy node that * represents an edge in a given layer was probably placed in that layer. This information can * be calculated during the crossing minimization phase and later be used by an interactive node * placement algorithm. */ public static final IProperty<Double> ORIGINAL_DUMMY_NODE_POSITION = new Property<Double>( "originalDummyNodePosition"); /** * The edge a label originally belonged to. This property was introduced to remember which * cross-hierarchy edge a label originally belonged to. */ public static final IProperty<LEdge> ORIGINAL_LABEL_EDGE = new Property<LEdge>( "originalLabelEdge"); /** * Edge labels represented by an edge label dummy node. */ public static final IProperty<List<LLabel>> REPRESENTED_LABELS = new Property<List<LLabel>>("representedLabels"); /** * The side (of an edge) a label is placed on. */ public static final IProperty<LabelSide> LABEL_SIDE = new Property<LabelSide>( "labelSide", LabelSide.UNKNOWN); /** * Flag for reversed edges. */ public static final IProperty<Boolean> REVERSED = new Property<Boolean>("reversed", false); /** * Random number generator for the algorithm. */ public static final IProperty<Random> RANDOM = new Property<Random>("random"); /** * The source port of a long edge before it was broken into multiple segments. */ public static final IProperty<LPort> LONG_EDGE_SOURCE = new Property<LPort>("longEdgeSource", null); /** * The target port of a long edge before it was broken into multiple segments. */ public static final IProperty<LPort> LONG_EDGE_TARGET = new Property<LPort>("longEdgeTarget", null); /** * Edge constraints for nodes. */ public static final IProperty<EdgeConstraint> EDGE_CONSTRAINT = new Property<EdgeConstraint>( "edgeConstraint", EdgeConstraint.NONE); /** * The layout unit a node belongs to. This property only makes sense for nodes. A layout unit is * a set of nodes between which no nodes belonging to other layout units may be placed. Nodes * not belonging to any layout unit may be placed arbitrarily between nodes of a layout unit. * Layer layout units are identified through one of their nodes. */ public static final IProperty<LNode> IN_LAYER_LAYOUT_UNIT = new Property<LNode>( "inLayerLayoutUnit"); /** * The in-layer constraint placed on a node. This indicates whether this node should be handled * like any other node, or if it must be placed at the top or bottom of a layer. This is * important for external port dummy nodes. Crossing minimizers are not required to respect this * constraint. If they don't, however, they must include a dependency on * {@link de.cau.cs.kieler.klay.layered.intermediate.InLayerConstraintProcessor}. */ public static final IProperty<InLayerConstraint> IN_LAYER_CONSTRAINT = new Property<InLayerConstraint>("inLayerConstraint", InLayerConstraint.NONE); /** * Indicates that a node {@code x} may only appear inside a layer before the node {@code y} the * property is set to. That is, having {@code x} appear after {@code y} would violate this * constraint. This property only makes sense for nodes. */ public static final IProperty<List<LNode>> IN_LAYER_SUCCESSOR_CONSTRAINTS = new Property<List<LNode>>("inLayerSuccessorConstraint", new ArrayList<LNode>()); /** * A property set on ports indicating a dummy node created for that port. This is not set for * all ports that have dummy nodes created for them. */ public static final IProperty<LNode> PORT_DUMMY = new Property<LNode>("portDummy"); /** * The node group of an LNode as used in the crossing minimization phase. */ public static final IProperty<NodeGroup> NODE_GROUP = new Property<NodeGroup>("nodeGroup"); /** * Crossing hint used for in-layer cross counting with northern and southern port dummies. This * is effectively the number of different ports a northern or southern port dummy represents. */ public static final IProperty<Integer> CROSSING_HINT = new Property<Integer>("crossingHint", 0); /** * Flags indicating the properties of a graph. */ public static final IProperty<Set<GraphProperties>> GRAPH_PROPERTIES = new Property<Set<GraphProperties>>("graphProperties", EnumSet.noneOf(GraphProperties.class)); /** * The side of an external port a dummy node was created for. */ public static final IProperty<PortSide> EXT_PORT_SIDE = new Property<PortSide>( "externalPortSide", PortSide.UNDEFINED); /** * Original size of the external port a dummy node was created for. */ public static final IProperty<KVector> EXT_PORT_SIZE = new Property<KVector>( "externalPortSize", new KVector()); /** * External port dummies that represent northern or southern external ports are replaced by new * dummy nodes during layout. In these cases, this property is set to the original dummy node. */ public static final IProperty<LNode> EXT_PORT_REPLACED_DUMMY = new Property<LNode>( "externalPortReplacedDummy"); /** * The port sides of external ports a connected component connects to. This property is set on * the layered graph that represents a connected component and defaults to no connections. If a * connected component connects to an external port on the EAST side and to another external * port on the NORTH side, this enumeration will list both sides. */ public static final IProperty<Set<PortSide>> EXT_PORT_CONNECTIONS = new Property<Set<PortSide>>("externalPortConnections", EnumSet.noneOf(PortSide.class)); /** * The original position or position-to-node-size ratio of a port. This property has two use * cases: * <ol> * <li>For external port dummies. In this use case, the property gives the original position of * the external port (if port constraints are set to {@code FIXED_POS}) or the original * position-to-node-size ratio of the external port ((if port constraints are set to * {@code FIXED_RATIO}).</li> * <li>For ports of regular nodes with port constraints set to {@code FIXED_RATIO}. Since * regular nodes may be resized, the original ratio must be remembered for the new port position * to be determined.</li> * </ol> * <p> * This is a one-dimensional value since the side of the port determines the other dimension. * (For eastern and western ports, the x coordinate is determined automatically; for northern * and southern ports, the y coordinate is determined automatically) * </p> */ public static final IProperty<Double> PORT_RATIO_OR_POSITION = new Property<Double>( "portRatioOrPosition", 0.0); /** * A list of nodes whose barycenters should go into the barycenter calculation of the node this * property is set on. Nodes in this list are expected to be in the same layer as the node the * property is set on. This is primarily used when edges are rerouted from a node to dummy * nodes. * <p> * This property is currently not declared as one of the layout options offered by KLay Layered * and should be considered highly experimental. */ public static final IProperty<List<LNode>> BARYCENTER_ASSOCIATES = new Property<List<LNode>>( "barycenterAssociates"); /** * List of comment boxes that are placed on top of a node. */ public static final IProperty<List<LNode>> TOP_COMMENTS = new Property<List<LNode>>( "TopSideComments"); /** * List of comment boxes that are placed in the bottom of of a node. */ public static final IProperty<List<LNode>> BOTTOM_COMMENTS = new Property<List<LNode>>( "BottomSideComments"); /** * The port of a node that originally connected a comment box with that node. */ public static final IProperty<LPort> COMMENT_CONN_PORT = new Property<LPort>( "CommentConnectionPort"); /** * Whether a port is used to collect all incoming edges of a node. */ public static final IProperty<Boolean> INPUT_COLLECT = new Property<Boolean>("inputCollect", false); /** * Whether a port is used to collect all outgoing edges of a node. */ public static final IProperty<Boolean> OUTPUT_COLLECT = new Property<Boolean>("outputCollect", false); /** * Property of a LayeredGraph. Whether the graph has been processed by the cycle breaker and the * cycle breaker has detected cycles and reverted edges. */ public static final IProperty<Boolean> CYCLIC = new Property<Boolean>("cyclic", false); /** * Determines the original size of a big node. */ public static final IProperty<Float> BIG_NODE_ORIGINAL_SIZE = new Property<Float>( "bigNodeOriginalSize", 0f); /** * Specifies if the corresponding node is the first node in a big node chain. */ public static final IProperty<Boolean> BIG_NODE_INITIAL = new Property<Boolean>( "bigNodeInitial", false); /** * Original labels of a big node. */ public static final IProperty<List<LLabel>> BIGNODES_ORIG_LABELS = new Property<List<LLabel>>( "de.cau.cs.kieler.klay.layered.bigNodeLabels", new ArrayList<LLabel>()); /** * A post processing function that is called during big nodes post processing. */ public static final IProperty<Function<Void, Void>> BIGNODES_POST_PROCESS = new Property<Function<Void, Void>>("de.cau.cs.kieler.klay.layered.postProcess", null); /** * Map of original hierarchy crossing edges to a set of dummy edges by which the original edge * has been replaced. */ public static final IProperty<Multimap<LEdge, CrossHierarchyEdge>> CROSS_HIERARCHY_MAP = new Property<Multimap<LEdge, CrossHierarchyEdge>>("crossHierarchyMap"); /** * Offset to be added to the target anchor point of an edge when the layout is applied back to * the origin. */ public static final IProperty<KVector> TARGET_OFFSET = new Property<KVector>("targetOffset"); /** * Combined size of all edge labels of a spline self loop. */ public static final IProperty<KVector> SPLINE_LABEL_SIZE = new Property<KVector>("splineLabelSize", new KVector()); /** * Determines the loop side of an edge. */ public static final IProperty<LoopSide> SPLINE_LOOPSIDE = new Property<LoopSide>("splineLoopSide", LoopSide.UNDEFINED); /** * A port with this property set will be handled from the SplineSelfLoopPre- and Postprocessor. */ public static final IProperty<List<ConnectedSelfLoopComponent>> SPLINE_SELFLOOP_COMPONENTS = new Property<List<ConnectedSelfLoopComponent>>("splineSelfLoopComponents", new ArrayList<ConnectedSelfLoopComponent>()); /** * A node's property storing the margins of a node required for it's self loops. */ public static final IProperty<Margins> SPLINE_SELF_LOOP_MARGINS = new Property<Margins>( "splineSelfLoopMargins", new Margins()); /** * List of ports on north/south dummies connected to a north/south port on a normal node. */ public static final IProperty<List<LPort>> CONNECTED_NORTH_SOUTH_PORT_DUMMIES = new Property<List<LPort>>("connectedNorthSouthPorts", new ArrayList<LPort>()); // ///////////////////////////////////////////////////////////////////////////// // OVERWRITTEN PROPERTIES /** * Offset of port position to the node border. An offset of 0 means that the port touches its * parent node on the outside, positive offsets move the port away from the node, and negative * offset move the port towards the inside. */ public static final IProperty<Float> OFFSET = new Property<Float>(LayoutOptions.OFFSET, 0.0f); /** * Minimal spacing between objects. */ public static final Property<Float> SPACING = new Property<Float>(LayoutOptions.SPACING, 20.0f, 1.0f); /** * Minimal spacing between ports. */ public static final Property<Float> PORT_SPACING = new Property<Float>(LayoutOptions.PORT_SPACING, 10.0f, 1.0f); /** * Spacing to the border of the drawing. */ public static final Property<Float> BORDER_SPACING = new Property<Float>( LayoutOptions.BORDER_SPACING, 12.0f, 0.0f); /** * Priority of elements. controls how much single edges are emphasized. */ public static final Property<Integer> PRIORITY = new Property<Integer>(LayoutOptions.PRIORITY, 0); /** * The aspect ratio for packing connected components. */ public static final Property<Float> ASPECT_RATIO = new Property<Float>( LayoutOptions.ASPECT_RATIO, 1.6f, 0.0f); /** * How to route edges. */ public static final Property<EdgeRouting> EDGE_ROUTING = new Property<EdgeRouting>( LayoutOptions.EDGE_ROUTING, EdgeRouting.ORTHOGONAL); // ///////////////////////////////////////////////////////////////////////////// // CONSTRUCTOR /** * Hidden default constructor. */ private InternalProperties() { } }
apache-2.0
SocraticGrid/UCS-Implementation
ucs-nifi-common/src/main/java/org/socraticgrid/hl7/ucs/nifi/common/serialization/ConversationInfoSerializer.java
4734
/* * Copyright 2015 Cognitive Medical Systems, Inc (http://www.cognitivemedicine.com). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.socraticgrid.hl7.ucs.nifi.common.serialization; import java.io.ByteArrayInputStream; import java.io.InputStream; import java.io.StringWriter; import java.util.List; import javax.xml.bind.JAXBContext; import javax.xml.bind.Marshaller; import javax.xml.bind.Unmarshaller; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.socraticgrid.hl7.ucs.nifi.common.model.ConversationInfoWrapper; import org.socraticgrid.hl7.ucs.nifi.common.model.XMLListWrapper; /** * * @author esteban */ public class ConversationInfoSerializer { private static final Logger logger = LoggerFactory.getLogger(ConversationInfoSerializer.class); public static String serializeConversationInfoWrappers(XMLListWrapper<ConversationInfoWrapper> conversations) throws MessageSerializationException { try { logger.debug("Serializing XMLListWrapper {}", conversations); JAXBContext context = JAXBContext.newInstance(XMLListWrapper.class, ConversationInfoWrapper.class); Marshaller m = context.createMarshaller(); StringWriter result = new StringWriter(); m.marshal(conversations, result); return result.toString(); } catch (Exception e) { throw new MessageSerializationException("Exception in Conversation serialization.", e); } } public static String serializeConversationInfoWrappers(List<ConversationInfoWrapper> conversations) throws MessageSerializationException { return serializeConversationInfoWrappers(new XMLListWrapper<>(conversations)); } public static String serializeConversationInfoWrapper(ConversationInfoWrapper conversation) throws MessageSerializationException { try { logger.debug("Serializing ConversationInfoWrapper {}", conversation); JAXBContext context = JAXBContext.newInstance(ConversationInfoWrapper.class); Marshaller m = context.createMarshaller(); StringWriter result = new StringWriter(); m.marshal(conversation, result); return result.toString(); } catch (Exception e) { throw new MessageSerializationException("Exception in Conversation serialization.", e); } } public static XMLListWrapper<ConversationInfoWrapper> deserializeConversationInfoWrappers(InputStream conversations) throws MessageSerializationException { try { logger.debug("Deserializing ConversationInfoWrapper"); JAXBContext context = JAXBContext.newInstance(XMLListWrapper.class, ConversationInfoWrapper.class); Unmarshaller u = context.createUnmarshaller(); return (XMLListWrapper<ConversationInfoWrapper>)u.unmarshal(conversations); } catch (Exception e) { throw new MessageSerializationException("Exception in ConversationInfoWrapper deserialization.", e); } } public static XMLListWrapper<ConversationInfoWrapper> deserializeConversationInfoWrappers(String conversations) throws MessageSerializationException { return deserializeConversationInfoWrappers(new ByteArrayInputStream(conversations.getBytes())); } public static ConversationInfoWrapper deserializeConversationInfoWrapper(InputStream conversation) throws MessageSerializationException { try { logger.debug("Deserializing ConversationInfoWrapper"); JAXBContext context = JAXBContext.newInstance(ConversationInfoWrapper.class); Unmarshaller u = context.createUnmarshaller(); return (ConversationInfoWrapper)u.unmarshal(conversation); } catch (Exception e) { throw new MessageSerializationException("Exception in ConversationInfoWrapper deserialization.", e); } } public static ConversationInfoWrapper deserializeConversationInfoWrapper(String conversation) throws MessageSerializationException { return deserializeConversationInfoWrapper(new ByteArrayInputStream(conversation.getBytes())); } }
apache-2.0
vespa-engine/vespa
config-model/src/main/java/com/yahoo/config/model/ApplicationConfigProducerRoot.java
11848
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. package com.yahoo.config.model; import com.yahoo.cloud.config.ApplicationIdConfig; import com.yahoo.cloud.config.ClusterListConfig; import com.yahoo.cloud.config.ModelConfig; import com.yahoo.cloud.config.ModelConfig.Hosts; import com.yahoo.cloud.config.ModelConfig.Hosts.Services; import com.yahoo.cloud.config.ModelConfig.Hosts.Services.Ports; import com.yahoo.cloud.config.SlobroksConfig; import com.yahoo.cloud.config.ZookeepersConfig; import com.yahoo.cloud.config.log.LogdConfig; import com.yahoo.component.Version; import com.yahoo.config.model.api.ModelContext; import com.yahoo.config.model.deploy.DeployState; import com.yahoo.config.model.producer.AbstractConfigProducer; import com.yahoo.config.provision.ApplicationId; import com.yahoo.document.config.DocumenttypesConfig; import com.yahoo.document.config.DocumentmanagerConfig; import com.yahoo.documentapi.messagebus.protocol.DocumentrouteselectorpolicyConfig; import com.yahoo.documentapi.messagebus.protocol.DocumentProtocolPoliciesConfig; import com.yahoo.messagebus.MessagebusConfig; import com.yahoo.vespa.config.content.AllClustersBucketSpacesConfig; import com.yahoo.vespa.config.content.DistributionConfig; import com.yahoo.vespa.config.content.LoadTypeConfig; import com.yahoo.vespa.configmodel.producers.DocumentManager; import com.yahoo.vespa.configmodel.producers.DocumentTypes; import com.yahoo.vespa.documentmodel.DocumentModel; import com.yahoo.vespa.model.ConfigProducer; import com.yahoo.vespa.model.HostResource; import com.yahoo.vespa.model.HostSystem; import com.yahoo.vespa.model.PortsMeta; import com.yahoo.vespa.model.Service; import com.yahoo.vespa.model.VespaModel; import com.yahoo.vespa.model.admin.Admin; import com.yahoo.vespa.model.clients.Clients; import com.yahoo.vespa.model.content.cluster.ContentCluster; import com.yahoo.vespa.model.filedistribution.FileDistributionConfigProducer; import com.yahoo.vespa.model.routing.Routing; import java.util.ArrayList; import java.util.Collections; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Set; /** * This is the parent of all ConfigProducers in the system resulting from configuring an application. * * @author gjoranv */ public class ApplicationConfigProducerRoot extends AbstractConfigProducer<AbstractConfigProducer<?>> implements CommonConfigsProducer { private final DocumentModel documentModel; private Routing routing = null; // The ConfigProducers contained in this Vespa. (configId->producer) Map<String, ConfigProducer> id2producer = new LinkedHashMap<>(); private Admin admin = null; private HostSystem hostSystem = null; private final Version vespaVersion; private final ApplicationId applicationId; /** * Creates and initializes a new Vespa from the service config file * in the given application directory. * * @param parent the parent, usually VespaModel * @param name the name, used as configId * @param documentModel DocumentModel to serve global document config from. */ public ApplicationConfigProducerRoot(AbstractConfigProducer parent, String name, DocumentModel documentModel, Version vespaVersion, ApplicationId applicationId) { super(parent, name); this.documentModel = documentModel; this.vespaVersion = vespaVersion; this.applicationId = applicationId; } private boolean useV8GeoPositions = false; private boolean useV8DocManagerCfg = false; public void useFeatureFlags(ModelContext.FeatureFlags featureFlags) { this.useV8GeoPositions = featureFlags.useV8GeoPositions(); this.useV8DocManagerCfg = featureFlags.useV8DocManagerCfg(); } /** * @return an unmodifiable copy of the set of configIds in this VespaModel. */ public Set<String> getConfigIds() { return Collections.unmodifiableSet(id2producer.keySet()); } /** * Returns the ConfigProducer with the given id, or null if no such * configId exists. * * @param configId The configId, e.g. "search.0/tld.0" * @return ConfigProducer with the given configId */ public ConfigProducer getConfigProducer(String configId) { return id2producer.get(configId); } /** * Returns the Service with the given id, or null if no such * configId exists or if it belongs to a non-Service ConfigProducer. * * @param configId The configId, e.g. "search.0/tld.0" * @return Service with the given configId */ public Service getService(String configId) { ConfigProducer cp = getConfigProducer(configId); if (cp == null || !(cp instanceof Service)) { return null; } return (Service) cp; } /** * Adds the descendant (at any depth level), so it can be looked up * on configId in the Map. * * @param descendant The configProducer descendant to add */ // TODO: Make protected if this moves to the same package as AbstractConfigProducer public void addDescendant(AbstractConfigProducer descendant) { id2producer.put(descendant.getConfigId(), descendant); } /** * Prepares the model for start. The {@link VespaModel} calls * this methods after it has loaded this and all plugins have been loaded and * their initialize() methods have been called. * * @param plugins All initialized plugins of the vespa model. */ public void prepare(ConfigModelRepo plugins) { if (routing != null) { routing.deriveCommonSettings(plugins); } } public void setupAdmin(Admin admin) { this.admin = admin; } // TODO: Do this as another config model depending on the other models public void setupRouting(DeployState deployState, VespaModel vespaModel, ConfigModelRepo configModels) { if (admin != null) { Routing routing = configModels.getRouting(); if (routing == null) { routing = new Routing(ConfigModelContext.create(deployState, vespaModel, configModels, this, "routing")); configModels.add(routing); } this.routing = routing; } } @Override public void getConfig(DocumentmanagerConfig.Builder builder) { new DocumentManager() .useV8GeoPositions(this.useV8GeoPositions) .useV8DocManagerCfg(this.useV8DocManagerCfg) .produce(documentModel, builder); } @Override public void getConfig(DocumenttypesConfig.Builder builder) { new DocumentTypes() .useV8GeoPositions(this.useV8GeoPositions) .produce(documentModel, builder); } @Override public void getConfig(DocumentrouteselectorpolicyConfig.Builder builder) { if (routing != null) { routing.getConfig(builder); } } @Override public void getConfig(DocumentProtocolPoliciesConfig.Builder builder) { if (routing != null) { routing.getConfig(builder); } } @Override public void getConfig(MessagebusConfig.Builder builder) { if (routing != null) { routing.getConfig(builder); } } @Override public void getConfig(LogdConfig.Builder builder) { if (admin != null) { admin.getConfig(builder); } } @Override public void getConfig(SlobroksConfig.Builder builder) { if (admin != null) { admin.getConfig(builder); } } @Override public void getConfig(ZookeepersConfig.Builder builder) { if (admin != null) { admin.getConfig(builder); } } @Override public void getConfig(LoadTypeConfig.Builder builder) { VespaModel model = (VespaModel) getRoot(); Clients clients = model.getClients(); if (clients != null) { clients.getConfig(builder); } } @Override public void getConfig(ClusterListConfig.Builder builder) { VespaModel model = (VespaModel) getRoot(); for (ContentCluster cluster : model.getContentClusters().values()) { ClusterListConfig.Storage.Builder storage = new ClusterListConfig.Storage.Builder(); storage.name(cluster.getName()); storage.configid(cluster.getConfigId()); builder.storage(storage); } } @Override public void getConfig(DistributionConfig.Builder builder) { for (ContentCluster cluster : ((VespaModel) getRoot()).getContentClusters().values()) { cluster.getConfig(builder); } } @Override public void getConfig(AllClustersBucketSpacesConfig.Builder builder) { VespaModel model = (VespaModel) getRoot(); for (ContentCluster cluster : model.getContentClusters().values()) { builder.cluster(cluster.getName(), cluster.clusterBucketSpaceConfigBuilder()); } } @Override public void getConfig(ModelConfig.Builder builder) { builder.vespaVersion(vespaVersion.toFullString()); for (HostResource modelHost : hostSystem().getHosts()) { builder.hosts(new Hosts.Builder() .name(modelHost.getHostname()) .services(getServices(modelHost)) ); } } private List<Services.Builder> getServices(HostResource modelHost) { List<Services.Builder> ret = new ArrayList<>(); for (Service modelService : modelHost.getServices()) { ret.add(new Services.Builder() .name(modelService.getServiceName()) .type(modelService.getServiceType()) .configid(modelService.getConfigId()) .clustertype(modelService.getServicePropertyString("clustertype", "")) .clustername(modelService.getServicePropertyString("clustername", "")) .index(Integer.parseInt(modelService.getServicePropertyString("index", "999999"))) .ports(getPorts(modelService)) ); } return ret; } private List<Ports.Builder> getPorts(Service modelService) { List<Ports.Builder> ret = new ArrayList<>(); PortsMeta portsMeta = modelService.getPortsMeta(); for (int i = 0; i < portsMeta.getNumPorts(); i++) { ret.add(new Ports.Builder() .number(modelService.getRelativePort(i)) .tags(getPortTags(portsMeta, i)) ); } return ret; } public static String getPortTags(PortsMeta portsMeta, int portNumber) { StringBuilder sb = new StringBuilder(); boolean firstTag = true; for (String s : portsMeta.getTagsAt(portNumber)) { if (!firstTag) { sb.append(" "); } else { firstTag = false; } sb.append(s); } return sb.toString(); } public void setHostSystem(HostSystem hostSystem) { this.hostSystem = hostSystem; } @Override public HostSystem hostSystem() { return hostSystem; } public FileDistributionConfigProducer getFileDistributionConfigProducer() { if (admin == null) return null; // no admin if standalone return admin.getFileDistributionConfigProducer(); } public Admin getAdmin() { return admin; } @Override public void getConfig(ApplicationIdConfig.Builder builder) { builder.tenant(applicationId.tenant().value()); builder.application(applicationId.application().value()); builder.instance(applicationId.instance().value()); } }
apache-2.0
googleads/google-ads-java
google-ads-stubs-v9/src/main/java/com/google/ads/googleads/v9/services/MutateAdGroupAdResultOrBuilder.java
1960
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/ads/googleads/v9/services/ad_group_ad_service.proto package com.google.ads.googleads.v9.services; public interface MutateAdGroupAdResultOrBuilder extends // @@protoc_insertion_point(interface_extends:google.ads.googleads.v9.services.MutateAdGroupAdResult) com.google.protobuf.MessageOrBuilder { /** * <pre> * The resource name returned for successful operations. * </pre> * * <code>string resource_name = 1;</code> * @return The resourceName. */ java.lang.String getResourceName(); /** * <pre> * The resource name returned for successful operations. * </pre> * * <code>string resource_name = 1;</code> * @return The bytes for resourceName. */ com.google.protobuf.ByteString getResourceNameBytes(); /** * <pre> * The mutated ad group ad with only mutable fields after mutate. The field * will only be returned when response_content_type is set to * "MUTABLE_RESOURCE". * </pre> * * <code>.google.ads.googleads.v9.resources.AdGroupAd ad_group_ad = 2;</code> * @return Whether the adGroupAd field is set. */ boolean hasAdGroupAd(); /** * <pre> * The mutated ad group ad with only mutable fields after mutate. The field * will only be returned when response_content_type is set to * "MUTABLE_RESOURCE". * </pre> * * <code>.google.ads.googleads.v9.resources.AdGroupAd ad_group_ad = 2;</code> * @return The adGroupAd. */ com.google.ads.googleads.v9.resources.AdGroupAd getAdGroupAd(); /** * <pre> * The mutated ad group ad with only mutable fields after mutate. The field * will only be returned when response_content_type is set to * "MUTABLE_RESOURCE". * </pre> * * <code>.google.ads.googleads.v9.resources.AdGroupAd ad_group_ad = 2;</code> */ com.google.ads.googleads.v9.resources.AdGroupAdOrBuilder getAdGroupAdOrBuilder(); }
apache-2.0
olegz/spring-cloud-function
spring-cloud-function-web/src/main/java/org/springframework/cloud/function/web/mvc/ReactorAutoConfiguration.java
2664
/* * Copyright 2012-2020 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.cloud.function.web.mvc; import reactor.core.publisher.Flux; import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; import org.springframework.boot.autoconfigure.AutoConfigureAfter; import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication; import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication.Type; import org.springframework.boot.autoconfigure.gson.GsonAutoConfiguration; import org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration; import org.springframework.cloud.function.context.FunctionCatalog; import org.springframework.cloud.function.web.BasicStringConverter; import org.springframework.cloud.function.web.RequestProcessor; import org.springframework.cloud.function.web.StringConverter; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; import org.springframework.web.method.support.AsyncHandlerMethodReturnValueHandler; /** * @author Dave Syer * @author Mark Fisher * @author Oleg Zhurakousky */ @Configuration(proxyBeanMethods = false) @ConditionalOnWebApplication(type = Type.SERVLET) @ConditionalOnClass({ Flux.class, AsyncHandlerMethodReturnValueHandler.class }) @Import({ FunctionController.class, RequestProcessor.class }) @AutoConfigureAfter({ JacksonAutoConfiguration.class, GsonAutoConfiguration.class }) public class ReactorAutoConfiguration { @Bean public FunctionHandlerMapping functionHandlerMapping(FunctionCatalog catalog, FunctionController controller) { return new FunctionHandlerMapping(catalog, controller); } @Bean @ConditionalOnMissingBean public StringConverter functionStringConverter(ConfigurableListableBeanFactory beanFactory) { return new BasicStringConverter(beanFactory); } }
apache-2.0
JavaDogs/cws
cws-core/src/test/java/net/haugr/cws/core/ShareBeanTest.java
4161
/* * CWS, Cryptographic Web Share - open source Cryptographic Sharing system. * Copyright (c) 2016-2022, haugr.net * mailto: cws AT haugr DOT net * * CWS is free software; you can redistribute it and/or modify it under the * terms of the Apache License, as published by the Apache Software Foundation. * * CWS is distributed in the hope that it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the Apache License for more details. * * You should have received a copy of the Apache License, version 2, along with * this program; If not, you can download a copy of the License * here: https://www.apache.org/licenses/ */ package net.haugr.cws.core; import static org.junit.jupiter.api.Assertions.assertEquals; import net.haugr.cws.api.common.Action; import net.haugr.cws.api.common.ReturnCode; import net.haugr.cws.api.requests.FetchDataRequest; import net.haugr.cws.api.requests.ProcessDataRequest; import net.haugr.cws.api.responses.CwsResponse; import net.haugr.cws.api.responses.FetchDataResponse; import net.haugr.cws.api.responses.ProcessDataResponse; import net.haugr.cws.core.exceptions.CWSException; import java.nio.charset.Charset; import net.haugr.cws.core.setup.DatabaseSetup; import org.junit.jupiter.api.Test; /** * <p>During the development of an application, using CWS to store data, it was * discovered that an exception was thrown with the following text:</p> * * <p><i>Given final block not properly padded. Such issues can arise if a bad * key is used during decryption.</i></p> * * <p>This test is written to see if it is possible to reproduce the error.</p> * * @author Kim Jensen * @since CWS 1.1.1 */ final class ShareBeanTest extends DatabaseSetup { private static final String DATA_NAME = "status"; @Test void testUpdateEncryptedObject() { final ShareBean bean = prepareShareBean(); final String initContent = "NEW"; final String updateContent = "ACCEPTED"; // Step 2; Add & Update Data Objects final String dataId = addData(bean, toBytes(initContent)); updateData(bean, dataId, toBytes(updateContent)); // Step 3; Check the stored content of the Circle final byte[] read = readData(bean, dataId); assertEquals(updateContent, toString(read)); } private String addData(final ShareBean bean, final byte[] data) { final ProcessDataRequest request = prepareRequest(ProcessDataRequest.class, MEMBER_1); request.setAction(Action.ADD); request.setCircleId(CIRCLE_1_ID); request.setDataName(DATA_NAME); request.setData(data); final ProcessDataResponse response = bean.processData(request); throwIfFailed(response); return response.getDataId(); } private void updateData(final ShareBean bean, final String dataId, final byte[] data) { final ProcessDataRequest request = prepareRequest(ProcessDataRequest.class, MEMBER_1); request.setAction(Action.UPDATE); request.setCircleId(CIRCLE_1_ID); request.setDataId(dataId); request.setDataName(DATA_NAME); request.setData(data); final ProcessDataResponse response = bean.processData(request); throwIfFailed(response); } private byte[] readData(final ShareBean bean, final String dataId) { final FetchDataRequest request = prepareRequest(FetchDataRequest.class, MEMBER_1); request.setDataId(dataId); final FetchDataResponse response = bean.fetchData(request); throwIfFailed(response); return response.getData(); } private static byte[] toBytes(final String str) { return str.getBytes(Charset.defaultCharset()); } private static String toString(final byte[] bytes) { return new String(bytes, Charset.defaultCharset()); } private static void throwIfFailed(final CwsResponse response) { if (!response.isOk()) { throw new CWSException(ReturnCode.findReturnCode(response.getReturnCode()), response.getReturnMessage()); } } }
apache-2.0
neovera/jdiablo
src/main/java/org/neovera/jdiablo/OptionPropertyAccessor.java
1138
/** * 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; import java.lang.reflect.Method; import org.neovera.jdiablo.annotation.Option; /** * Information about a command line option. */ public interface OptionPropertyAccessor { /** * @return Name of the property */ public String getPropertyName(); /** * @return Setter method to manipulate property. */ public Method getSetterMethod(); /** * @return Option annotation for the property */ public Option getOption(); }
apache-2.0
alancnet/artifactory
base/api/src/main/java/org/artifactory/api/repo/Request.java
1561
/* * Artifactory is a binaries repository manager. * Copyright (C) 2012 JFrog Ltd. * * Artifactory is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Artifactory is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with Artifactory. If not, see <http://www.gnu.org/licenses/>. */ package org.artifactory.api.repo; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Inherited; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Request annotation. Used when needed to mark the begining and the end of a logical action * * @author Noam Tenne */ @Target({ElementType.METHOD}) @Retention(RetentionPolicy.RUNTIME) @Inherited @Documented public @interface Request { /** * Indicates if the occurring of events should be notified at the end of the request, or be aggregated for certain * time window * * @return True if events should be aggregated. False if not */ boolean aggregateEventsByTimeWindow() default false; }
apache-2.0
sguilhen/wildfly-elytron
src/main/java/org/wildfly/security/auth/client/SetCredentialsConfiguration.java
5677
/* * JBoss, Home of Professional Open Source. * Copyright 2016 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.security.auth.client; import java.io.IOException; import java.security.GeneralSecurityException; import java.util.Set; import java.util.function.Function; import java.util.function.Supplier; import javax.security.auth.callback.Callback; import javax.security.auth.callback.PasswordCallback; import javax.security.auth.callback.UnsupportedCallbackException; import org.wildfly.security.auth.callback.CredentialCallback; import org.wildfly.security.auth.client.AuthenticationConfiguration.CredentialSetting; import org.wildfly.security.auth.server.IdentityCredentials; import org.wildfly.security.credential.Credential; import org.wildfly.security.credential.PasswordCredential; import org.wildfly.security.password.PasswordFactory; import org.wildfly.security.password.TwoWayPassword; import org.wildfly.security.password.interfaces.ClearPassword; import org.wildfly.security.password.spec.ClearPasswordSpec; import org.wildfly.security.sasl.util.SaslMechanismInformation; /** * @author <a href="mailto:david.lloyd@redhat.com">David M. Lloyd</a> */ class SetCredentialsConfiguration extends AuthenticationConfiguration implements CredentialSetting { private final Function<String, IdentityCredentials> credentialsFunction; SetCredentialsConfiguration(final AuthenticationConfiguration parent, final Function<String, IdentityCredentials> credentialsFunction) { super(parent.without(CredentialSetting.class)); this.credentialsFunction = credentialsFunction; } SetCredentialsConfiguration(final AuthenticationConfiguration parent, final Supplier<IdentityCredentials> credentials) { this(parent, prompt -> credentials.get()); } void handleCallback(final Callback[] callbacks, final int index) throws UnsupportedCallbackException, IOException { Callback callback = callbacks[index]; if (callback instanceof CredentialCallback) { final CredentialCallback credentialCallback = (CredentialCallback) callback; final Credential credential = credentialsFunction.apply(null).getCredential(credentialCallback.getCredentialType(), credentialCallback.getAlgorithm()); if (credential != null && credentialCallback.isCredentialSupported(credential)) { credentialCallback.setCredential(credential); return; } } else if (callback instanceof PasswordCallback) { final PasswordCallback passwordCallback = (PasswordCallback) callback; IdentityCredentials credentials = credentialsFunction.apply(passwordCallback.getPrompt()); if (credentials != null) { final TwoWayPassword password = credentials.applyToCredential(PasswordCredential.class, ClearPassword.ALGORITHM_CLEAR, c -> c.getPassword(TwoWayPassword.class)); if (password instanceof ClearPassword) { // shortcut passwordCallback.setPassword(((ClearPassword) password).getPassword()); return; } else if (password != null) try { PasswordFactory passwordFactory = PasswordFactory.getInstance(password.getAlgorithm()); ClearPasswordSpec clearPasswordSpec = passwordFactory.getKeySpec(passwordFactory.translate(password), ClearPasswordSpec.class); passwordCallback.setPassword(clearPasswordSpec.getEncodedPassword()); return; } catch (GeneralSecurityException e) { // fall out } } } super.handleCallback(callbacks, index); } boolean filterOneSaslMechanism(final String mechanismName) { Set<Class<? extends Credential>> types = SaslMechanismInformation.getSupportedClientCredentialTypes(mechanismName); final IdentityCredentials credentials = credentialsFunction.apply(null); for (Class<? extends Credential> type : types) { Set<String> algorithms = SaslMechanismInformation.getSupportedClientCredentialAlgorithms(mechanismName, type); if (algorithms.contains("*")) { if (credentials.contains(type, null)) { return true; } } else { for (String algorithm : algorithms) { if (credentials.contains(type, algorithm)) { return true; } } } } return super.filterOneSaslMechanism(mechanismName); } Function<String, IdentityCredentials> getCredentialsFunction() { return credentialsFunction; } AuthenticationConfiguration reparent(final AuthenticationConfiguration newParent) { return new SetCredentialsConfiguration(newParent, credentialsFunction); } @Override StringBuilder asString(StringBuilder sb) { return parentAsString(sb).append("Credentials,"); } }
apache-2.0
dump247/aws-sdk-java
aws-java-sdk-emr/src/main/java/com/amazonaws/services/elasticmapreduce/model/transform/ClusterJsonMarshaller.java
7285
/* * 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.elasticmapreduce.model.transform; import static com.amazonaws.util.StringUtils.UTF8; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.OutputStreamWriter; import java.io.StringWriter; import java.io.Writer; import java.util.Map; import java.util.List; import com.amazonaws.AmazonClientException; import com.amazonaws.services.elasticmapreduce.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.*; /** * ClusterMarshaller */ public class ClusterJsonMarshaller { /** * Marshall the given parameter object, and output to a SdkJsonGenerator */ public void marshall(Cluster cluster, SdkJsonGenerator jsonGenerator) { if (cluster == null) { throw new AmazonClientException( "Invalid argument passed to marshall(...)"); } try { jsonGenerator.writeStartObject(); if (cluster.getId() != null) { jsonGenerator.writeFieldName("Id").writeValue(cluster.getId()); } if (cluster.getName() != null) { jsonGenerator.writeFieldName("Name").writeValue( cluster.getName()); } if (cluster.getStatus() != null) { jsonGenerator.writeFieldName("Status"); ClusterStatusJsonMarshaller.getInstance().marshall( cluster.getStatus(), jsonGenerator); } if (cluster.getEc2InstanceAttributes() != null) { jsonGenerator.writeFieldName("Ec2InstanceAttributes"); Ec2InstanceAttributesJsonMarshaller.getInstance().marshall( cluster.getEc2InstanceAttributes(), jsonGenerator); } if (cluster.getLogUri() != null) { jsonGenerator.writeFieldName("LogUri").writeValue( cluster.getLogUri()); } if (cluster.getRequestedAmiVersion() != null) { jsonGenerator.writeFieldName("RequestedAmiVersion").writeValue( cluster.getRequestedAmiVersion()); } if (cluster.getRunningAmiVersion() != null) { jsonGenerator.writeFieldName("RunningAmiVersion").writeValue( cluster.getRunningAmiVersion()); } if (cluster.getReleaseLabel() != null) { jsonGenerator.writeFieldName("ReleaseLabel").writeValue( cluster.getReleaseLabel()); } if (cluster.getAutoTerminate() != null) { jsonGenerator.writeFieldName("AutoTerminate").writeValue( cluster.getAutoTerminate()); } if (cluster.getTerminationProtected() != null) { jsonGenerator.writeFieldName("TerminationProtected") .writeValue(cluster.getTerminationProtected()); } if (cluster.getVisibleToAllUsers() != null) { jsonGenerator.writeFieldName("VisibleToAllUsers").writeValue( cluster.getVisibleToAllUsers()); } com.amazonaws.internal.SdkInternalList<Application> applicationsList = (com.amazonaws.internal.SdkInternalList<Application>) cluster .getApplications(); if (!applicationsList.isEmpty() || !applicationsList.isAutoConstruct()) { jsonGenerator.writeFieldName("Applications"); jsonGenerator.writeStartArray(); for (Application applicationsListValue : applicationsList) { if (applicationsListValue != null) { ApplicationJsonMarshaller.getInstance().marshall( applicationsListValue, jsonGenerator); } } jsonGenerator.writeEndArray(); } com.amazonaws.internal.SdkInternalList<Tag> tagsList = (com.amazonaws.internal.SdkInternalList<Tag>) cluster .getTags(); if (!tagsList.isEmpty() || !tagsList.isAutoConstruct()) { jsonGenerator.writeFieldName("Tags"); jsonGenerator.writeStartArray(); for (Tag tagsListValue : tagsList) { if (tagsListValue != null) { TagJsonMarshaller.getInstance().marshall(tagsListValue, jsonGenerator); } } jsonGenerator.writeEndArray(); } if (cluster.getServiceRole() != null) { jsonGenerator.writeFieldName("ServiceRole").writeValue( cluster.getServiceRole()); } if (cluster.getNormalizedInstanceHours() != null) { jsonGenerator.writeFieldName("NormalizedInstanceHours") .writeValue(cluster.getNormalizedInstanceHours()); } if (cluster.getMasterPublicDnsName() != null) { jsonGenerator.writeFieldName("MasterPublicDnsName").writeValue( cluster.getMasterPublicDnsName()); } com.amazonaws.internal.SdkInternalList<Configuration> configurationsList = (com.amazonaws.internal.SdkInternalList<Configuration>) cluster .getConfigurations(); if (!configurationsList.isEmpty() || !configurationsList.isAutoConstruct()) { jsonGenerator.writeFieldName("Configurations"); jsonGenerator.writeStartArray(); for (Configuration configurationsListValue : configurationsList) { if (configurationsListValue != null) { ConfigurationJsonMarshaller.getInstance().marshall( configurationsListValue, jsonGenerator); } } jsonGenerator.writeEndArray(); } jsonGenerator.writeEndObject(); } catch (Throwable t) { throw new AmazonClientException( "Unable to marshall request to JSON: " + t.getMessage(), t); } } private static ClusterJsonMarshaller instance; public static ClusterJsonMarshaller getInstance() { if (instance == null) instance = new ClusterJsonMarshaller(); return instance; } }
apache-2.0
arquillian/arquillian-core
junit/container/src/test/java/org/jboss/arquillian/junit/container/JUnitTestBaseClass.java
6363
/* * JBoss, Home of Professional Open Source * Copyright 2011 Red Hat Inc. and/or its affiliates and other contributors * as indicated by the @authors tag. All rights reserved. * See the copyright.txt in the distribution for a * full listing of individual contributors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jboss.arquillian.junit.container; import java.lang.reflect.Method; import java.util.HashMap; import java.util.Map; import org.jboss.arquillian.junit.event.AfterRules; import org.jboss.arquillian.junit.event.BeforeRules; import org.jboss.arquillian.test.spi.LifecycleMethodExecutor; import org.jboss.arquillian.test.spi.TestMethodExecutor; import org.jboss.arquillian.test.spi.TestResult; import org.jboss.arquillian.test.spi.TestRunnerAdaptor; import org.jboss.arquillian.test.spi.TestRunnerAdaptorBuilder; import org.jboss.arquillian.test.spi.event.suite.TestLifecycleEvent; import org.junit.After; import org.junit.Assert; import org.junit.runner.JUnitCore; import org.junit.runner.Result; import org.junit.runner.notification.RunListener; import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.isA; import static org.mockito.Mockito.doAnswer; /** * JUnitTestBaseClass * * @author <a href="mailto:aslak@redhat.com">Aslak Knutsen</a> * @version $Revision: $ */ public class JUnitTestBaseClass { /* * Setup / Clear the static callback info. */ private static Map<Cycle, Integer> callbackCount = new HashMap<Cycle, Integer>(); private static Map<Cycle, Throwable> callbackException = new HashMap<Cycle, Throwable>(); static { for (Cycle tmp : Cycle.values()) { callbackCount.put(tmp, 0); } } public static void wasCalled(Cycle cycle) throws Throwable { if (callbackCount.containsKey(cycle)) { callbackCount.put(cycle, callbackCount.get(cycle) + 1); } else { throw new RuntimeException("Unknown callback: " + cycle); } if (callbackException.containsKey(cycle)) { throw callbackException.get(cycle); } } @After public void clearCallbacks() { callbackCount.clear(); for (Cycle tmp : Cycle.values()) { callbackCount.put(tmp, 0); } callbackException.clear(); } /* * Internal Helpers */ protected void executeAllLifeCycles(TestRunnerAdaptor adaptor) throws Exception { doAnswer(new ExecuteLifecycle()).when(adaptor).fireCustomLifecycle(isA(BeforeRules.class)); doAnswer(new ExecuteLifecycle()).when(adaptor).fireCustomLifecycle(isA(AfterRules.class)); doAnswer(new ExecuteLifecycle()).when(adaptor).beforeClass(any(Class.class), any(LifecycleMethodExecutor.class)); doAnswer(new ExecuteLifecycle()).when(adaptor).afterClass(any(Class.class), any(LifecycleMethodExecutor.class)); doAnswer(new ExecuteLifecycle()).when(adaptor) .before(any(Object.class), any(Method.class), any(LifecycleMethodExecutor.class)); doAnswer(new ExecuteLifecycle()).when(adaptor) .after(any(Object.class), any(Method.class), any(LifecycleMethodExecutor.class)); doAnswer(new TestExecuteLifecycle(TestResult.passed())).when(adaptor).test(any(TestMethodExecutor.class)); } public void assertCycle(int count, Cycle... cycles) { for (Cycle cycle : cycles) { Assert.assertEquals("Verify " + cycle + " called N times", count, (int) callbackCount.get(cycle)); } } protected Result run(TestRunnerAdaptor adaptor, Class<?>... classes) throws Exception { return run(adaptor, null, classes); } protected Result run(TestRunnerAdaptor adaptor, RunListener listener, Class<?>... classes) throws Exception { try { setAdaptor(adaptor); JUnitCore core = new JUnitCore(); if (listener != null) { core.addListener(listener); } return core.run(classes); } finally { setAdaptor(null); } } // force set the TestRunnerAdaptor to use private void setAdaptor(TestRunnerAdaptor adaptor) throws Exception { Method method = TestRunnerAdaptorBuilder.class.getMethod("set", TestRunnerAdaptor.class); method.setAccessible(true); method.invoke(null, adaptor); } public enum Cycle { BEFORE_CLASS_RULE, BEFORE_RULE, BEFORE_CLASS, BEFORE, TEST, AFTER, AFTER_CLASS, AFTER_RULE, AFTER_CLASS_RULE; } /* * Mockito Answers for invoking the LifeCycle callbacks. */ public static class ExecuteLifecycle implements Answer<Object> { @Override public Object answer(org.mockito.invocation.InvocationOnMock invocation) throws Throwable { for (Object argument : invocation.getArguments()) { if (argument instanceof LifecycleMethodExecutor) { ((LifecycleMethodExecutor) argument).invoke(); } else if (argument instanceof TestMethodExecutor) { ((TestMethodExecutor) argument).invoke(); } else if (argument instanceof TestLifecycleEvent) { ((TestLifecycleEvent) argument).getExecutor().invoke(); } } return null; } } public static class TestExecuteLifecycle extends ExecuteLifecycle { private TestResult result; public TestExecuteLifecycle(TestResult result) { this.result = result; } @Override public Object answer(InvocationOnMock invocation) throws Throwable { super.answer(invocation); return result; } } }
apache-2.0
googleapis/google-api-java-client-services
clients/google-api-services-streetviewpublish/v1/1.31.0/com/google/api/services/streetviewpublish/v1/StreetViewPublish.java
65530
/* * 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.streetviewpublish.v1; /** * Service definition for StreetViewPublish (v1). * * <p> * Publishes 360 photos to Google Maps, along with position, orientation, and connectivity metadata. Apps can offer an interface for positioning, connecting, and uploading user-generated Street View images. * </p> * * <p> * For more information about this service, see the * <a href="https://developers.google.com/streetview/publish/" target="_blank">API Documentation</a> * </p> * * <p> * This service uses {@link StreetViewPublishRequestInitializer} to initialize global parameters via its * {@link Builder}. * </p> * * @since 1.3 * @author Google, Inc. */ @SuppressWarnings("javadoc") public class StreetViewPublish extends com.google.api.client.googleapis.services.json.AbstractGoogleJsonClient { // Note: Leave this static initializer at the top of the file. static { com.google.api.client.util.Preconditions.checkState( com.google.api.client.googleapis.GoogleUtils.MAJOR_VERSION == 1 && (com.google.api.client.googleapis.GoogleUtils.MINOR_VERSION >= 32 || (com.google.api.client.googleapis.GoogleUtils.MINOR_VERSION == 31 && com.google.api.client.googleapis.GoogleUtils.BUGFIX_VERSION >= 1)), "You are currently running with version %s of google-api-client. " + "You need at least version 1.31.1 of google-api-client to run version " + "1.32.1 of the Street View Publish API library.", com.google.api.client.googleapis.GoogleUtils.VERSION); } /** * The default encoded root URL of the service. This is determined when the library is generated * and normally should not be changed. * * @since 1.7 */ public static final String DEFAULT_ROOT_URL = "https://streetviewpublish.googleapis.com/"; /** * The default encoded mTLS root URL of the service. This is determined when the library is generated * and normally should not be changed. * * @since 1.31 */ public static final String DEFAULT_MTLS_ROOT_URL = "https://streetviewpublish.mtls.googleapis.com/"; /** * The default encoded service path of the service. This is determined when the library is * generated and normally should not be changed. * * @since 1.7 */ public static final String DEFAULT_SERVICE_PATH = ""; /** * The default encoded batch path of the service. This is determined when the library is * generated and normally should not be changed. * * @since 1.23 */ public static final String DEFAULT_BATCH_PATH = "batch"; /** * The default encoded base URL of the service. This is determined when the library is generated * and normally should not be changed. */ public static final String DEFAULT_BASE_URL = DEFAULT_ROOT_URL + DEFAULT_SERVICE_PATH; /** * Constructor. * * <p> * Use {@link Builder} if you need to specify any of the optional parameters. * </p> * * @param transport HTTP transport, which should normally be: * <ul> * <li>Google App Engine: * {@code com.google.api.client.extensions.appengine.http.UrlFetchTransport}</li> * <li>Android: {@code newCompatibleTransport} from * {@code com.google.api.client.extensions.android.http.AndroidHttp}</li> * <li>Java: {@link com.google.api.client.googleapis.javanet.GoogleNetHttpTransport#newTrustedTransport()} * </li> * </ul> * @param jsonFactory JSON factory, which may be: * <ul> * <li>Jackson: {@code com.google.api.client.json.jackson2.JacksonFactory}</li> * <li>Google GSON: {@code com.google.api.client.json.gson.GsonFactory}</li> * <li>Android Honeycomb or higher: * {@code com.google.api.client.extensions.android.json.AndroidJsonFactory}</li> * </ul> * @param httpRequestInitializer HTTP request initializer or {@code null} for none * @since 1.7 */ public StreetViewPublish(com.google.api.client.http.HttpTransport transport, com.google.api.client.json.JsonFactory jsonFactory, com.google.api.client.http.HttpRequestInitializer httpRequestInitializer) { this(new Builder(transport, jsonFactory, httpRequestInitializer)); } /** * @param builder builder */ StreetViewPublish(Builder builder) { super(builder); } @Override protected void initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest<?> httpClientRequest) throws java.io.IOException { super.initialize(httpClientRequest); } /** * An accessor for creating requests from the Photo collection. * * <p>The typical use is:</p> * <pre> * {@code StreetViewPublish streetviewpublish = new StreetViewPublish(...);} * {@code StreetViewPublish.Photo.List request = streetviewpublish.photo().list(parameters ...)} * </pre> * * @return the resource collection */ public Photo photo() { return new Photo(); } /** * The "photo" collection of methods. */ public class Photo { /** * After the client finishes uploading the photo with the returned UploadRef, CreatePhoto publishes * the uploaded Photo to Street View on Google Maps. Currently, the only way to set heading, pitch, * and roll in CreatePhoto is through the [Photo Sphere XMP * metadata](https://developers.google.com/streetview/spherical-metadata) in the photo bytes. * CreatePhoto ignores the `pose.heading`, `pose.pitch`, `pose.roll`, `pose.altitude`, and * `pose.level` fields in Pose. This method returns the following error codes: * * google.rpc.Code.INVALID_ARGUMENT if the request is malformed or if the uploaded photo is not a * 360 photo. * google.rpc.Code.NOT_FOUND if the upload reference does not exist. * * google.rpc.Code.RESOURCE_EXHAUSTED if the account has reached the storage limit. * * Create a request for the method "photo.create". * * This request holds the parameters needed by the streetviewpublish server. After setting any * optional parameters, call the {@link Create#execute()} method to invoke the remote operation. * * @param content the {@link com.google.api.services.streetviewpublish.v1.model.Photo} * @return the request */ public Create create(com.google.api.services.streetviewpublish.v1.model.Photo content) throws java.io.IOException { Create result = new Create(content); initialize(result); return result; } public class Create extends StreetViewPublishRequest<com.google.api.services.streetviewpublish.v1.model.Photo> { private static final String REST_PATH = "v1/photo"; /** * After the client finishes uploading the photo with the returned UploadRef, CreatePhoto * publishes the uploaded Photo to Street View on Google Maps. Currently, the only way to set * heading, pitch, and roll in CreatePhoto is through the [Photo Sphere XMP * metadata](https://developers.google.com/streetview/spherical-metadata) in the photo bytes. * CreatePhoto ignores the `pose.heading`, `pose.pitch`, `pose.roll`, `pose.altitude`, and * `pose.level` fields in Pose. This method returns the following error codes: * * google.rpc.Code.INVALID_ARGUMENT if the request is malformed or if the uploaded photo is not a * 360 photo. * google.rpc.Code.NOT_FOUND if the upload reference does not exist. * * google.rpc.Code.RESOURCE_EXHAUSTED if the account has reached the storage limit. * * Create a request for the method "photo.create". * * This request holds the parameters needed by the the streetviewpublish server. After setting * any optional parameters, call the {@link Create#execute()} method to invoke the remote * operation. <p> {@link * Create#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} must * be called to initialize this instance immediately after invoking the constructor. </p> * * @param content the {@link com.google.api.services.streetviewpublish.v1.model.Photo} * @since 1.13 */ protected Create(com.google.api.services.streetviewpublish.v1.model.Photo content) { super(StreetViewPublish.this, "POST", REST_PATH, content, com.google.api.services.streetviewpublish.v1.model.Photo.class); } @Override public Create set$Xgafv(java.lang.String $Xgafv) { return (Create) super.set$Xgafv($Xgafv); } @Override public Create setAccessToken(java.lang.String accessToken) { return (Create) super.setAccessToken(accessToken); } @Override public Create setAlt(java.lang.String alt) { return (Create) super.setAlt(alt); } @Override public Create setCallback(java.lang.String callback) { return (Create) super.setCallback(callback); } @Override public Create setFields(java.lang.String fields) { return (Create) super.setFields(fields); } @Override public Create setKey(java.lang.String key) { return (Create) super.setKey(key); } @Override public Create setOauthToken(java.lang.String oauthToken) { return (Create) super.setOauthToken(oauthToken); } @Override public Create setPrettyPrint(java.lang.Boolean prettyPrint) { return (Create) super.setPrettyPrint(prettyPrint); } @Override public Create setQuotaUser(java.lang.String quotaUser) { return (Create) super.setQuotaUser(quotaUser); } @Override public Create setUploadType(java.lang.String uploadType) { return (Create) super.setUploadType(uploadType); } @Override public Create setUploadProtocol(java.lang.String uploadProtocol) { return (Create) super.setUploadProtocol(uploadProtocol); } @Override public Create set(String parameterName, Object value) { return (Create) super.set(parameterName, value); } } /** * Deletes a Photo and its metadata. This method returns the following error codes: * * google.rpc.Code.PERMISSION_DENIED if the requesting user did not create the requested photo. * * google.rpc.Code.NOT_FOUND if the photo ID does not exist. * * Create a request for the method "photo.delete". * * This request holds the parameters needed by the streetviewpublish server. After setting any * optional parameters, call the {@link Delete#execute()} method to invoke the remote operation. * * @param photoId Required. ID of the Photo. * @return the request */ public Delete delete(java.lang.String photoId) throws java.io.IOException { Delete result = new Delete(photoId); initialize(result); return result; } public class Delete extends StreetViewPublishRequest<com.google.api.services.streetviewpublish.v1.model.Empty> { private static final String REST_PATH = "v1/photo/{photoId}"; /** * Deletes a Photo and its metadata. This method returns the following error codes: * * google.rpc.Code.PERMISSION_DENIED if the requesting user did not create the requested photo. * * google.rpc.Code.NOT_FOUND if the photo ID does not exist. * * Create a request for the method "photo.delete". * * This request holds the parameters needed by the the streetviewpublish server. After setting * any optional parameters, call the {@link Delete#execute()} method to invoke the remote * operation. <p> {@link * Delete#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} must * be called to initialize this instance immediately after invoking the constructor. </p> * * @param photoId Required. ID of the Photo. * @since 1.13 */ protected Delete(java.lang.String photoId) { super(StreetViewPublish.this, "DELETE", REST_PATH, null, com.google.api.services.streetviewpublish.v1.model.Empty.class); this.photoId = com.google.api.client.util.Preconditions.checkNotNull(photoId, "Required parameter photoId must be specified."); } @Override public Delete set$Xgafv(java.lang.String $Xgafv) { return (Delete) super.set$Xgafv($Xgafv); } @Override public Delete setAccessToken(java.lang.String accessToken) { return (Delete) super.setAccessToken(accessToken); } @Override public Delete setAlt(java.lang.String alt) { return (Delete) super.setAlt(alt); } @Override public Delete setCallback(java.lang.String callback) { return (Delete) super.setCallback(callback); } @Override public Delete setFields(java.lang.String fields) { return (Delete) super.setFields(fields); } @Override public Delete setKey(java.lang.String key) { return (Delete) super.setKey(key); } @Override public Delete setOauthToken(java.lang.String oauthToken) { return (Delete) super.setOauthToken(oauthToken); } @Override public Delete setPrettyPrint(java.lang.Boolean prettyPrint) { return (Delete) super.setPrettyPrint(prettyPrint); } @Override public Delete setQuotaUser(java.lang.String quotaUser) { return (Delete) super.setQuotaUser(quotaUser); } @Override public Delete setUploadType(java.lang.String uploadType) { return (Delete) super.setUploadType(uploadType); } @Override public Delete setUploadProtocol(java.lang.String uploadProtocol) { return (Delete) super.setUploadProtocol(uploadProtocol); } /** Required. ID of the Photo. */ @com.google.api.client.util.Key private java.lang.String photoId; /** Required. ID of the Photo. */ public java.lang.String getPhotoId() { return photoId; } /** Required. ID of the Photo. */ public Delete setPhotoId(java.lang.String photoId) { this.photoId = photoId; return this; } @Override public Delete set(String parameterName, Object value) { return (Delete) super.set(parameterName, value); } } /** * Gets the metadata of the specified Photo. This method returns the following error codes: * * google.rpc.Code.PERMISSION_DENIED if the requesting user did not create the requested Photo. * * google.rpc.Code.NOT_FOUND if the requested Photo does not exist. * google.rpc.Code.UNAVAILABLE if * the requested Photo is still being indexed. * * Create a request for the method "photo.get". * * This request holds the parameters needed by the streetviewpublish server. After setting any * optional parameters, call the {@link Get#execute()} method to invoke the remote operation. * * @param photoId Required. ID of the Photo. * @return the request */ public Get get(java.lang.String photoId) throws java.io.IOException { Get result = new Get(photoId); initialize(result); return result; } public class Get extends StreetViewPublishRequest<com.google.api.services.streetviewpublish.v1.model.Photo> { private static final String REST_PATH = "v1/photo/{photoId}"; /** * Gets the metadata of the specified Photo. This method returns the following error codes: * * google.rpc.Code.PERMISSION_DENIED if the requesting user did not create the requested Photo. * * google.rpc.Code.NOT_FOUND if the requested Photo does not exist. * google.rpc.Code.UNAVAILABLE * if the requested Photo is still being indexed. * * Create a request for the method "photo.get". * * This request holds the parameters needed by the the streetviewpublish server. After setting * any optional parameters, call the {@link Get#execute()} method to invoke the remote operation. * <p> {@link * Get#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} must be * called to initialize this instance immediately after invoking the constructor. </p> * * @param photoId Required. ID of the Photo. * @since 1.13 */ protected Get(java.lang.String photoId) { super(StreetViewPublish.this, "GET", REST_PATH, null, com.google.api.services.streetviewpublish.v1.model.Photo.class); this.photoId = com.google.api.client.util.Preconditions.checkNotNull(photoId, "Required parameter photoId must be specified."); } @Override public com.google.api.client.http.HttpResponse executeUsingHead() throws java.io.IOException { return super.executeUsingHead(); } @Override public com.google.api.client.http.HttpRequest buildHttpRequestUsingHead() throws java.io.IOException { return super.buildHttpRequestUsingHead(); } @Override public Get set$Xgafv(java.lang.String $Xgafv) { return (Get) super.set$Xgafv($Xgafv); } @Override public Get setAccessToken(java.lang.String accessToken) { return (Get) super.setAccessToken(accessToken); } @Override public Get setAlt(java.lang.String alt) { return (Get) super.setAlt(alt); } @Override public Get setCallback(java.lang.String callback) { return (Get) super.setCallback(callback); } @Override public Get setFields(java.lang.String fields) { return (Get) super.setFields(fields); } @Override public Get setKey(java.lang.String key) { return (Get) super.setKey(key); } @Override public Get setOauthToken(java.lang.String oauthToken) { return (Get) super.setOauthToken(oauthToken); } @Override public Get setPrettyPrint(java.lang.Boolean prettyPrint) { return (Get) super.setPrettyPrint(prettyPrint); } @Override public Get setQuotaUser(java.lang.String quotaUser) { return (Get) super.setQuotaUser(quotaUser); } @Override public Get setUploadType(java.lang.String uploadType) { return (Get) super.setUploadType(uploadType); } @Override public Get setUploadProtocol(java.lang.String uploadProtocol) { return (Get) super.setUploadProtocol(uploadProtocol); } /** Required. ID of the Photo. */ @com.google.api.client.util.Key private java.lang.String photoId; /** Required. ID of the Photo. */ public java.lang.String getPhotoId() { return photoId; } /** Required. ID of the Photo. */ public Get setPhotoId(java.lang.String photoId) { this.photoId = photoId; return this; } /** * The BCP-47 language code, such as "en-US" or "sr-Latn". For more information, see * http://www.unicode.org/reports/tr35/#Unicode_locale_identifier. If language_code is * unspecified, the user's language preference for Google services is used. */ @com.google.api.client.util.Key private java.lang.String languageCode; /** The BCP-47 language code, such as "en-US" or "sr-Latn". For more information, see http://www.unicode.org/reports/tr35/#Unicode_locale_identifier. If language_code is unspecified, the user's language preference for Google services is used. */ public java.lang.String getLanguageCode() { return languageCode; } /** * The BCP-47 language code, such as "en-US" or "sr-Latn". For more information, see * http://www.unicode.org/reports/tr35/#Unicode_locale_identifier. If language_code is * unspecified, the user's language preference for Google services is used. */ public Get setLanguageCode(java.lang.String languageCode) { this.languageCode = languageCode; return this; } /** * Required. Specifies if a download URL for the photo bytes should be returned in the Photo * response. */ @com.google.api.client.util.Key private java.lang.String view; /** Required. Specifies if a download URL for the photo bytes should be returned in the Photo response. */ public java.lang.String getView() { return view; } /** * Required. Specifies if a download URL for the photo bytes should be returned in the Photo * response. */ public Get setView(java.lang.String view) { this.view = view; return this; } @Override public Get set(String parameterName, Object value) { return (Get) super.set(parameterName, value); } } /** * Creates an upload session to start uploading photo bytes. The method uses the upload URL of the * returned UploadRef to upload the bytes for the Photo. In addition to the photo requirements shown * in https://support.google.com/maps/answer/7012050?ref_topic=6275604, the photo must meet the * following requirements: * Photo Sphere XMP metadata must be included in the photo metadata. See * https://developers.google.com/streetview/spherical-metadata for the required fields. * The pixel * size of the photo must meet the size requirements listed in * https://support.google.com/maps/answer/7012050?ref_topic=6275604, and the photo must be a full * 360 horizontally. After the upload completes, the method uses UploadRef with CreatePhoto to * create the Photo object entry. * * Create a request for the method "photo.startUpload". * * This request holds the parameters needed by the streetviewpublish server. After setting any * optional parameters, call the {@link StartUpload#execute()} method to invoke the remote * operation. * * @param content the {@link com.google.api.services.streetviewpublish.v1.model.Empty} * @return the request */ public StartUpload startUpload(com.google.api.services.streetviewpublish.v1.model.Empty content) throws java.io.IOException { StartUpload result = new StartUpload(content); initialize(result); return result; } public class StartUpload extends StreetViewPublishRequest<com.google.api.services.streetviewpublish.v1.model.UploadRef> { private static final String REST_PATH = "v1/photo:startUpload"; /** * Creates an upload session to start uploading photo bytes. The method uses the upload URL of the * returned UploadRef to upload the bytes for the Photo. In addition to the photo requirements * shown in https://support.google.com/maps/answer/7012050?ref_topic=6275604, the photo must meet * the following requirements: * Photo Sphere XMP metadata must be included in the photo metadata. * See https://developers.google.com/streetview/spherical-metadata for the required fields. * The * pixel size of the photo must meet the size requirements listed in * https://support.google.com/maps/answer/7012050?ref_topic=6275604, and the photo must be a full * 360 horizontally. After the upload completes, the method uses UploadRef with CreatePhoto to * create the Photo object entry. * * Create a request for the method "photo.startUpload". * * This request holds the parameters needed by the the streetviewpublish server. After setting * any optional parameters, call the {@link StartUpload#execute()} method to invoke the remote * operation. <p> {@link * StartUpload#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} * must be called to initialize this instance immediately after invoking the constructor. </p> * * @param content the {@link com.google.api.services.streetviewpublish.v1.model.Empty} * @since 1.13 */ protected StartUpload(com.google.api.services.streetviewpublish.v1.model.Empty content) { super(StreetViewPublish.this, "POST", REST_PATH, content, com.google.api.services.streetviewpublish.v1.model.UploadRef.class); } @Override public StartUpload set$Xgafv(java.lang.String $Xgafv) { return (StartUpload) super.set$Xgafv($Xgafv); } @Override public StartUpload setAccessToken(java.lang.String accessToken) { return (StartUpload) super.setAccessToken(accessToken); } @Override public StartUpload setAlt(java.lang.String alt) { return (StartUpload) super.setAlt(alt); } @Override public StartUpload setCallback(java.lang.String callback) { return (StartUpload) super.setCallback(callback); } @Override public StartUpload setFields(java.lang.String fields) { return (StartUpload) super.setFields(fields); } @Override public StartUpload setKey(java.lang.String key) { return (StartUpload) super.setKey(key); } @Override public StartUpload setOauthToken(java.lang.String oauthToken) { return (StartUpload) super.setOauthToken(oauthToken); } @Override public StartUpload setPrettyPrint(java.lang.Boolean prettyPrint) { return (StartUpload) super.setPrettyPrint(prettyPrint); } @Override public StartUpload setQuotaUser(java.lang.String quotaUser) { return (StartUpload) super.setQuotaUser(quotaUser); } @Override public StartUpload setUploadType(java.lang.String uploadType) { return (StartUpload) super.setUploadType(uploadType); } @Override public StartUpload setUploadProtocol(java.lang.String uploadProtocol) { return (StartUpload) super.setUploadProtocol(uploadProtocol); } @Override public StartUpload set(String parameterName, Object value) { return (StartUpload) super.set(parameterName, value); } } /** * Updates the metadata of a Photo, such as pose, place association, connections, etc. Changing the * pixels of a photo is not supported. Only the fields specified in the updateMask field are used. * If `updateMask` is not present, the update applies to all fields. This method returns the * following error codes: * google.rpc.Code.PERMISSION_DENIED if the requesting user did not create * the requested photo. * google.rpc.Code.INVALID_ARGUMENT if the request is malformed. * * google.rpc.Code.NOT_FOUND if the requested photo does not exist. * google.rpc.Code.UNAVAILABLE if * the requested Photo is still being indexed. * * Create a request for the method "photo.update". * * This request holds the parameters needed by the streetviewpublish server. After setting any * optional parameters, call the {@link Update#execute()} method to invoke the remote operation. * * @param id A unique identifier for a photo. * @param content the {@link com.google.api.services.streetviewpublish.v1.model.Photo} * @return the request */ public Update update(java.lang.String id, com.google.api.services.streetviewpublish.v1.model.Photo content) throws java.io.IOException { Update result = new Update(id, content); initialize(result); return result; } public class Update extends StreetViewPublishRequest<com.google.api.services.streetviewpublish.v1.model.Photo> { private static final String REST_PATH = "v1/photo/{id}"; /** * Updates the metadata of a Photo, such as pose, place association, connections, etc. Changing * the pixels of a photo is not supported. Only the fields specified in the updateMask field are * used. If `updateMask` is not present, the update applies to all fields. This method returns the * following error codes: * google.rpc.Code.PERMISSION_DENIED if the requesting user did not * create the requested photo. * google.rpc.Code.INVALID_ARGUMENT if the request is malformed. * * google.rpc.Code.NOT_FOUND if the requested photo does not exist. * google.rpc.Code.UNAVAILABLE * if the requested Photo is still being indexed. * * Create a request for the method "photo.update". * * This request holds the parameters needed by the the streetviewpublish server. After setting * any optional parameters, call the {@link Update#execute()} method to invoke the remote * operation. <p> {@link * Update#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} must * be called to initialize this instance immediately after invoking the constructor. </p> * * @param id A unique identifier for a photo. * @param content the {@link com.google.api.services.streetviewpublish.v1.model.Photo} * @since 1.13 */ protected Update(java.lang.String id, com.google.api.services.streetviewpublish.v1.model.Photo content) { super(StreetViewPublish.this, "PUT", REST_PATH, content, com.google.api.services.streetviewpublish.v1.model.Photo.class); this.id = com.google.api.client.util.Preconditions.checkNotNull(id, "Required parameter id must be specified."); } @Override public Update set$Xgafv(java.lang.String $Xgafv) { return (Update) super.set$Xgafv($Xgafv); } @Override public Update setAccessToken(java.lang.String accessToken) { return (Update) super.setAccessToken(accessToken); } @Override public Update setAlt(java.lang.String alt) { return (Update) super.setAlt(alt); } @Override public Update setCallback(java.lang.String callback) { return (Update) super.setCallback(callback); } @Override public Update setFields(java.lang.String fields) { return (Update) super.setFields(fields); } @Override public Update setKey(java.lang.String key) { return (Update) super.setKey(key); } @Override public Update setOauthToken(java.lang.String oauthToken) { return (Update) super.setOauthToken(oauthToken); } @Override public Update setPrettyPrint(java.lang.Boolean prettyPrint) { return (Update) super.setPrettyPrint(prettyPrint); } @Override public Update setQuotaUser(java.lang.String quotaUser) { return (Update) super.setQuotaUser(quotaUser); } @Override public Update setUploadType(java.lang.String uploadType) { return (Update) super.setUploadType(uploadType); } @Override public Update setUploadProtocol(java.lang.String uploadProtocol) { return (Update) super.setUploadProtocol(uploadProtocol); } /** A unique identifier for a photo. */ @com.google.api.client.util.Key private java.lang.String id; /** A unique identifier for a photo. */ public java.lang.String getId() { return id; } /** A unique identifier for a photo. */ public Update setId(java.lang.String id) { this.id = id; return this; } /** * Required. Mask that identifies fields on the photo metadata to update. If not present, the * old Photo metadata is entirely replaced with the new Photo metadata in this request. The * update fails if invalid fields are specified. Multiple fields can be specified in a comma- * delimited list. The following fields are valid: * `pose.heading` * `pose.latLngPair` * * `pose.pitch` * `pose.roll` * `pose.level` * `pose.altitude` * `connections` * `places` > * Note: When updateMask contains repeated fields, the entire set of repeated values get * replaced with the new contents. For example, if updateMask contains `connections` and * `UpdatePhotoRequest.photo.connections` is empty, all connections are removed. */ @com.google.api.client.util.Key private String updateMask; /** Required. Mask that identifies fields on the photo metadata to update. If not present, the old Photo metadata is entirely replaced with the new Photo metadata in this request. The update fails if invalid fields are specified. Multiple fields can be specified in a comma-delimited list. The following fields are valid: * `pose.heading` * `pose.latLngPair` * `pose.pitch` * `pose.roll` * `pose.level` * `pose.altitude` * `connections` * `places` > Note: When updateMask contains repeated fields, the entire set of repeated values get replaced with the new contents. For example, if updateMask contains `connections` and `UpdatePhotoRequest.photo.connections` is empty, all connections are removed. */ public String getUpdateMask() { return updateMask; } /** * Required. Mask that identifies fields on the photo metadata to update. If not present, the * old Photo metadata is entirely replaced with the new Photo metadata in this request. The * update fails if invalid fields are specified. Multiple fields can be specified in a comma- * delimited list. The following fields are valid: * `pose.heading` * `pose.latLngPair` * * `pose.pitch` * `pose.roll` * `pose.level` * `pose.altitude` * `connections` * `places` > * Note: When updateMask contains repeated fields, the entire set of repeated values get * replaced with the new contents. For example, if updateMask contains `connections` and * `UpdatePhotoRequest.photo.connections` is empty, all connections are removed. */ public Update setUpdateMask(String updateMask) { this.updateMask = updateMask; return this; } @Override public Update set(String parameterName, Object value) { return (Update) super.set(parameterName, value); } } } /** * An accessor for creating requests from the Photos collection. * * <p>The typical use is:</p> * <pre> * {@code StreetViewPublish streetviewpublish = new StreetViewPublish(...);} * {@code StreetViewPublish.Photos.List request = streetviewpublish.photos().list(parameters ...)} * </pre> * * @return the resource collection */ public Photos photos() { return new Photos(); } /** * The "photos" collection of methods. */ public class Photos { /** * Deletes a list of Photos and their metadata. Note that if BatchDeletePhotos fails, either * critical fields are missing or there is an authentication error. Even if BatchDeletePhotos * succeeds, individual photos in the batch may have failures. These failures are specified in each * PhotoResponse.status in BatchDeletePhotosResponse.results. See DeletePhoto for specific failures * that can occur per photo. * * Create a request for the method "photos.batchDelete". * * This request holds the parameters needed by the streetviewpublish server. After setting any * optional parameters, call the {@link BatchDelete#execute()} method to invoke the remote * operation. * * @param content the {@link com.google.api.services.streetviewpublish.v1.model.BatchDeletePhotosRequest} * @return the request */ public BatchDelete batchDelete(com.google.api.services.streetviewpublish.v1.model.BatchDeletePhotosRequest content) throws java.io.IOException { BatchDelete result = new BatchDelete(content); initialize(result); return result; } public class BatchDelete extends StreetViewPublishRequest<com.google.api.services.streetviewpublish.v1.model.BatchDeletePhotosResponse> { private static final String REST_PATH = "v1/photos:batchDelete"; /** * Deletes a list of Photos and their metadata. Note that if BatchDeletePhotos fails, either * critical fields are missing or there is an authentication error. Even if BatchDeletePhotos * succeeds, individual photos in the batch may have failures. These failures are specified in * each PhotoResponse.status in BatchDeletePhotosResponse.results. See DeletePhoto for specific * failures that can occur per photo. * * Create a request for the method "photos.batchDelete". * * This request holds the parameters needed by the the streetviewpublish server. After setting * any optional parameters, call the {@link BatchDelete#execute()} method to invoke the remote * operation. <p> {@link * BatchDelete#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} * must be called to initialize this instance immediately after invoking the constructor. </p> * * @param content the {@link com.google.api.services.streetviewpublish.v1.model.BatchDeletePhotosRequest} * @since 1.13 */ protected BatchDelete(com.google.api.services.streetviewpublish.v1.model.BatchDeletePhotosRequest content) { super(StreetViewPublish.this, "POST", REST_PATH, content, com.google.api.services.streetviewpublish.v1.model.BatchDeletePhotosResponse.class); } @Override public BatchDelete set$Xgafv(java.lang.String $Xgafv) { return (BatchDelete) super.set$Xgafv($Xgafv); } @Override public BatchDelete setAccessToken(java.lang.String accessToken) { return (BatchDelete) super.setAccessToken(accessToken); } @Override public BatchDelete setAlt(java.lang.String alt) { return (BatchDelete) super.setAlt(alt); } @Override public BatchDelete setCallback(java.lang.String callback) { return (BatchDelete) super.setCallback(callback); } @Override public BatchDelete setFields(java.lang.String fields) { return (BatchDelete) super.setFields(fields); } @Override public BatchDelete setKey(java.lang.String key) { return (BatchDelete) super.setKey(key); } @Override public BatchDelete setOauthToken(java.lang.String oauthToken) { return (BatchDelete) super.setOauthToken(oauthToken); } @Override public BatchDelete setPrettyPrint(java.lang.Boolean prettyPrint) { return (BatchDelete) super.setPrettyPrint(prettyPrint); } @Override public BatchDelete setQuotaUser(java.lang.String quotaUser) { return (BatchDelete) super.setQuotaUser(quotaUser); } @Override public BatchDelete setUploadType(java.lang.String uploadType) { return (BatchDelete) super.setUploadType(uploadType); } @Override public BatchDelete setUploadProtocol(java.lang.String uploadProtocol) { return (BatchDelete) super.setUploadProtocol(uploadProtocol); } @Override public BatchDelete set(String parameterName, Object value) { return (BatchDelete) super.set(parameterName, value); } } /** * Gets the metadata of the specified Photo batch. Note that if BatchGetPhotos fails, either * critical fields are missing or there is an authentication error. Even if BatchGetPhotos succeeds, * individual photos in the batch may have failures. These failures are specified in each * PhotoResponse.status in BatchGetPhotosResponse.results. See GetPhoto for specific failures that * can occur per photo. * * Create a request for the method "photos.batchGet". * * This request holds the parameters needed by the streetviewpublish server. After setting any * optional parameters, call the {@link BatchGet#execute()} method to invoke the remote operation. * * @return the request */ public BatchGet batchGet() throws java.io.IOException { BatchGet result = new BatchGet(); initialize(result); return result; } public class BatchGet extends StreetViewPublishRequest<com.google.api.services.streetviewpublish.v1.model.BatchGetPhotosResponse> { private static final String REST_PATH = "v1/photos:batchGet"; /** * Gets the metadata of the specified Photo batch. Note that if BatchGetPhotos fails, either * critical fields are missing or there is an authentication error. Even if BatchGetPhotos * succeeds, individual photos in the batch may have failures. These failures are specified in * each PhotoResponse.status in BatchGetPhotosResponse.results. See GetPhoto for specific failures * that can occur per photo. * * Create a request for the method "photos.batchGet". * * This request holds the parameters needed by the the streetviewpublish server. After setting * any optional parameters, call the {@link BatchGet#execute()} method to invoke the remote * operation. <p> {@link * BatchGet#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} * must be called to initialize this instance immediately after invoking the constructor. </p> * * @since 1.13 */ protected BatchGet() { super(StreetViewPublish.this, "GET", REST_PATH, null, com.google.api.services.streetviewpublish.v1.model.BatchGetPhotosResponse.class); } @Override public com.google.api.client.http.HttpResponse executeUsingHead() throws java.io.IOException { return super.executeUsingHead(); } @Override public com.google.api.client.http.HttpRequest buildHttpRequestUsingHead() throws java.io.IOException { return super.buildHttpRequestUsingHead(); } @Override public BatchGet set$Xgafv(java.lang.String $Xgafv) { return (BatchGet) super.set$Xgafv($Xgafv); } @Override public BatchGet setAccessToken(java.lang.String accessToken) { return (BatchGet) super.setAccessToken(accessToken); } @Override public BatchGet setAlt(java.lang.String alt) { return (BatchGet) super.setAlt(alt); } @Override public BatchGet setCallback(java.lang.String callback) { return (BatchGet) super.setCallback(callback); } @Override public BatchGet setFields(java.lang.String fields) { return (BatchGet) super.setFields(fields); } @Override public BatchGet setKey(java.lang.String key) { return (BatchGet) super.setKey(key); } @Override public BatchGet setOauthToken(java.lang.String oauthToken) { return (BatchGet) super.setOauthToken(oauthToken); } @Override public BatchGet setPrettyPrint(java.lang.Boolean prettyPrint) { return (BatchGet) super.setPrettyPrint(prettyPrint); } @Override public BatchGet setQuotaUser(java.lang.String quotaUser) { return (BatchGet) super.setQuotaUser(quotaUser); } @Override public BatchGet setUploadType(java.lang.String uploadType) { return (BatchGet) super.setUploadType(uploadType); } @Override public BatchGet setUploadProtocol(java.lang.String uploadProtocol) { return (BatchGet) super.setUploadProtocol(uploadProtocol); } /** * Optional. The BCP-47 language code, such as "en-US" or "sr-Latn". For more information, see * http://www.unicode.org/reports/tr35/#Unicode_locale_identifier. If language_code is * unspecified, the user's language preference for Google services is used. */ @com.google.api.client.util.Key private java.lang.String languageCode; /** Optional. The BCP-47 language code, such as "en-US" or "sr-Latn". For more information, see http://www.unicode.org/reports/tr35/#Unicode_locale_identifier. If language_code is unspecified, the user's language preference for Google services is used. */ public java.lang.String getLanguageCode() { return languageCode; } /** * Optional. The BCP-47 language code, such as "en-US" or "sr-Latn". For more information, see * http://www.unicode.org/reports/tr35/#Unicode_locale_identifier. If language_code is * unspecified, the user's language preference for Google services is used. */ public BatchGet setLanguageCode(java.lang.String languageCode) { this.languageCode = languageCode; return this; } /** * Required. IDs of the Photos. For HTTP GET requests, the URL query parameter should be * `photoIds==&...`. */ @com.google.api.client.util.Key private java.util.List<java.lang.String> photoIds; /** Required. IDs of the Photos. For HTTP GET requests, the URL query parameter should be `photoIds==&...`. */ public java.util.List<java.lang.String> getPhotoIds() { return photoIds; } /** * Required. IDs of the Photos. For HTTP GET requests, the URL query parameter should be * `photoIds==&...`. */ public BatchGet setPhotoIds(java.util.List<java.lang.String> photoIds) { this.photoIds = photoIds; return this; } /** * Required. Specifies if a download URL for the photo bytes should be returned in the Photo * response. */ @com.google.api.client.util.Key private java.lang.String view; /** Required. Specifies if a download URL for the photo bytes should be returned in the Photo response. */ public java.lang.String getView() { return view; } /** * Required. Specifies if a download URL for the photo bytes should be returned in the Photo * response. */ public BatchGet setView(java.lang.String view) { this.view = view; return this; } @Override public BatchGet set(String parameterName, Object value) { return (BatchGet) super.set(parameterName, value); } } /** * Updates the metadata of Photos, such as pose, place association, connections, etc. Changing the * pixels of photos is not supported. Note that if BatchUpdatePhotos fails, either critical fields * are missing or there is an authentication error. Even if BatchUpdatePhotos succeeds, individual * photos in the batch may have failures. These failures are specified in each PhotoResponse.status * in BatchUpdatePhotosResponse.results. See UpdatePhoto for specific failures that can occur per * photo. Only the fields specified in updateMask field are used. If `updateMask` is not present, * the update applies to all fields. The number of UpdatePhotoRequest messages in a * BatchUpdatePhotosRequest must not exceed 20. > Note: To update Pose.altitude, Pose.latLngPair has * to be filled as well. Otherwise, the request will fail. * * Create a request for the method "photos.batchUpdate". * * This request holds the parameters needed by the streetviewpublish server. After setting any * optional parameters, call the {@link BatchUpdate#execute()} method to invoke the remote * operation. * * @param content the {@link com.google.api.services.streetviewpublish.v1.model.BatchUpdatePhotosRequest} * @return the request */ public BatchUpdate batchUpdate(com.google.api.services.streetviewpublish.v1.model.BatchUpdatePhotosRequest content) throws java.io.IOException { BatchUpdate result = new BatchUpdate(content); initialize(result); return result; } public class BatchUpdate extends StreetViewPublishRequest<com.google.api.services.streetviewpublish.v1.model.BatchUpdatePhotosResponse> { private static final String REST_PATH = "v1/photos:batchUpdate"; /** * Updates the metadata of Photos, such as pose, place association, connections, etc. Changing the * pixels of photos is not supported. Note that if BatchUpdatePhotos fails, either critical fields * are missing or there is an authentication error. Even if BatchUpdatePhotos succeeds, individual * photos in the batch may have failures. These failures are specified in each * PhotoResponse.status in BatchUpdatePhotosResponse.results. See UpdatePhoto for specific * failures that can occur per photo. Only the fields specified in updateMask field are used. If * `updateMask` is not present, the update applies to all fields. The number of UpdatePhotoRequest * messages in a BatchUpdatePhotosRequest must not exceed 20. > Note: To update Pose.altitude, * Pose.latLngPair has to be filled as well. Otherwise, the request will fail. * * Create a request for the method "photos.batchUpdate". * * This request holds the parameters needed by the the streetviewpublish server. After setting * any optional parameters, call the {@link BatchUpdate#execute()} method to invoke the remote * operation. <p> {@link * BatchUpdate#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} * must be called to initialize this instance immediately after invoking the constructor. </p> * * @param content the {@link com.google.api.services.streetviewpublish.v1.model.BatchUpdatePhotosRequest} * @since 1.13 */ protected BatchUpdate(com.google.api.services.streetviewpublish.v1.model.BatchUpdatePhotosRequest content) { super(StreetViewPublish.this, "POST", REST_PATH, content, com.google.api.services.streetviewpublish.v1.model.BatchUpdatePhotosResponse.class); } @Override public BatchUpdate set$Xgafv(java.lang.String $Xgafv) { return (BatchUpdate) super.set$Xgafv($Xgafv); } @Override public BatchUpdate setAccessToken(java.lang.String accessToken) { return (BatchUpdate) super.setAccessToken(accessToken); } @Override public BatchUpdate setAlt(java.lang.String alt) { return (BatchUpdate) super.setAlt(alt); } @Override public BatchUpdate setCallback(java.lang.String callback) { return (BatchUpdate) super.setCallback(callback); } @Override public BatchUpdate setFields(java.lang.String fields) { return (BatchUpdate) super.setFields(fields); } @Override public BatchUpdate setKey(java.lang.String key) { return (BatchUpdate) super.setKey(key); } @Override public BatchUpdate setOauthToken(java.lang.String oauthToken) { return (BatchUpdate) super.setOauthToken(oauthToken); } @Override public BatchUpdate setPrettyPrint(java.lang.Boolean prettyPrint) { return (BatchUpdate) super.setPrettyPrint(prettyPrint); } @Override public BatchUpdate setQuotaUser(java.lang.String quotaUser) { return (BatchUpdate) super.setQuotaUser(quotaUser); } @Override public BatchUpdate setUploadType(java.lang.String uploadType) { return (BatchUpdate) super.setUploadType(uploadType); } @Override public BatchUpdate setUploadProtocol(java.lang.String uploadProtocol) { return (BatchUpdate) super.setUploadProtocol(uploadProtocol); } @Override public BatchUpdate set(String parameterName, Object value) { return (BatchUpdate) super.set(parameterName, value); } } /** * Lists all the Photos that belong to the user. > Note: Recently created photos that are still * being indexed are not returned in the response. * * Create a request for the method "photos.list". * * This request holds the parameters needed by the streetviewpublish server. After setting any * optional parameters, call the {@link List#execute()} method to invoke the remote operation. * * @return the request */ public List list() throws java.io.IOException { List result = new List(); initialize(result); return result; } public class List extends StreetViewPublishRequest<com.google.api.services.streetviewpublish.v1.model.ListPhotosResponse> { private static final String REST_PATH = "v1/photos"; /** * Lists all the Photos that belong to the user. > Note: Recently created photos that are still * being indexed are not returned in the response. * * Create a request for the method "photos.list". * * This request holds the parameters needed by the the streetviewpublish server. After setting * any optional parameters, call the {@link List#execute()} method to invoke the remote operation. * <p> {@link * List#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} must be * called to initialize this instance immediately after invoking the constructor. </p> * * @since 1.13 */ protected List() { super(StreetViewPublish.this, "GET", REST_PATH, null, com.google.api.services.streetviewpublish.v1.model.ListPhotosResponse.class); } @Override public com.google.api.client.http.HttpResponse executeUsingHead() throws java.io.IOException { return super.executeUsingHead(); } @Override public com.google.api.client.http.HttpRequest buildHttpRequestUsingHead() throws java.io.IOException { return super.buildHttpRequestUsingHead(); } @Override public List set$Xgafv(java.lang.String $Xgafv) { return (List) super.set$Xgafv($Xgafv); } @Override public List setAccessToken(java.lang.String accessToken) { return (List) super.setAccessToken(accessToken); } @Override public List setAlt(java.lang.String alt) { return (List) super.setAlt(alt); } @Override public List setCallback(java.lang.String callback) { return (List) super.setCallback(callback); } @Override public List setFields(java.lang.String fields) { return (List) super.setFields(fields); } @Override public List setKey(java.lang.String key) { return (List) super.setKey(key); } @Override public List setOauthToken(java.lang.String oauthToken) { return (List) super.setOauthToken(oauthToken); } @Override public List setPrettyPrint(java.lang.Boolean prettyPrint) { return (List) super.setPrettyPrint(prettyPrint); } @Override public List setQuotaUser(java.lang.String quotaUser) { return (List) super.setQuotaUser(quotaUser); } @Override public List setUploadType(java.lang.String uploadType) { return (List) super.setUploadType(uploadType); } @Override public List setUploadProtocol(java.lang.String uploadProtocol) { return (List) super.setUploadProtocol(uploadProtocol); } /** * Optional. The filter expression. For example: `placeId=ChIJj61dQgK6j4AR4GeTYWZsKWw`. The * filters supported are: `placeId`, `min_latitude`, `max_latitude`, `min_longitude`, and * `max_longitude`. See https://google.aip.dev/160 for more information. */ @com.google.api.client.util.Key private java.lang.String filter; /** Optional. The filter expression. For example: `placeId=ChIJj61dQgK6j4AR4GeTYWZsKWw`. The filters supported are: `placeId`, `min_latitude`, `max_latitude`, `min_longitude`, and `max_longitude`. See https://google.aip.dev/160 for more information. */ public java.lang.String getFilter() { return filter; } /** * Optional. The filter expression. For example: `placeId=ChIJj61dQgK6j4AR4GeTYWZsKWw`. The * filters supported are: `placeId`, `min_latitude`, `max_latitude`, `min_longitude`, and * `max_longitude`. See https://google.aip.dev/160 for more information. */ public List setFilter(java.lang.String filter) { this.filter = filter; return this; } /** * Optional. The BCP-47 language code, such as "en-US" or "sr-Latn". For more information, see * http://www.unicode.org/reports/tr35/#Unicode_locale_identifier. If language_code is * unspecified, the user's language preference for Google services is used. */ @com.google.api.client.util.Key private java.lang.String languageCode; /** Optional. The BCP-47 language code, such as "en-US" or "sr-Latn". For more information, see http://www.unicode.org/reports/tr35/#Unicode_locale_identifier. If language_code is unspecified, the user's language preference for Google services is used. */ public java.lang.String getLanguageCode() { return languageCode; } /** * Optional. The BCP-47 language code, such as "en-US" or "sr-Latn". For more information, see * http://www.unicode.org/reports/tr35/#Unicode_locale_identifier. If language_code is * unspecified, the user's language preference for Google services is used. */ public List setLanguageCode(java.lang.String languageCode) { this.languageCode = languageCode; return this; } /** * Optional. The maximum number of photos to return. `pageSize` must be non-negative. If * `pageSize` is zero or is not provided, the default page size of 100 is used. The number of * photos returned in the response may be less than `pageSize` if the number of photos that * belong to the user is less than `pageSize`. */ @com.google.api.client.util.Key private java.lang.Integer pageSize; /** Optional. The maximum number of photos to return. `pageSize` must be non-negative. If `pageSize` is zero or is not provided, the default page size of 100 is used. The number of photos returned in the response may be less than `pageSize` if the number of photos that belong to the user is less than `pageSize`. */ public java.lang.Integer getPageSize() { return pageSize; } /** * Optional. The maximum number of photos to return. `pageSize` must be non-negative. If * `pageSize` is zero or is not provided, the default page size of 100 is used. The number of * photos returned in the response may be less than `pageSize` if the number of photos that * belong to the user is less than `pageSize`. */ public List setPageSize(java.lang.Integer pageSize) { this.pageSize = pageSize; return this; } /** Optional. The nextPageToken value returned from a previous ListPhotos request, if any. */ @com.google.api.client.util.Key private java.lang.String pageToken; /** Optional. The nextPageToken value returned from a previous ListPhotos request, if any. */ public java.lang.String getPageToken() { return pageToken; } /** Optional. The nextPageToken value returned from a previous ListPhotos request, if any. */ public List setPageToken(java.lang.String pageToken) { this.pageToken = pageToken; return this; } /** * Required. Specifies if a download URL for the photos bytes should be returned in the Photos * response. */ @com.google.api.client.util.Key private java.lang.String view; /** Required. Specifies if a download URL for the photos bytes should be returned in the Photos response. */ public java.lang.String getView() { return view; } /** * Required. Specifies if a download URL for the photos bytes should be returned in the Photos * response. */ public List setView(java.lang.String view) { this.view = view; return this; } @Override public List set(String parameterName, Object value) { return (List) super.set(parameterName, value); } } } /** * Builder for {@link StreetViewPublish}. * * <p> * Implementation is not thread-safe. * </p> * * @since 1.3.0 */ public static final class Builder extends com.google.api.client.googleapis.services.json.AbstractGoogleJsonClient.Builder { private static String chooseEndpoint(com.google.api.client.http.HttpTransport transport) { // If the GOOGLE_API_USE_MTLS_ENDPOINT environment variable value is "always", use mTLS endpoint. // If the env variable is "auto", use mTLS endpoint if and only if the transport is mTLS. // Use the regular endpoint for all other cases. String useMtlsEndpoint = System.getenv("GOOGLE_API_USE_MTLS_ENDPOINT"); useMtlsEndpoint = useMtlsEndpoint == null ? "auto" : useMtlsEndpoint; if ("always".equals(useMtlsEndpoint) || ("auto".equals(useMtlsEndpoint) && transport != null && transport.isMtls())) { return DEFAULT_MTLS_ROOT_URL; } return DEFAULT_ROOT_URL; } /** * Returns an instance of a new builder. * * @param transport HTTP transport, which should normally be: * <ul> * <li>Google App Engine: * {@code com.google.api.client.extensions.appengine.http.UrlFetchTransport}</li> * <li>Android: {@code newCompatibleTransport} from * {@code com.google.api.client.extensions.android.http.AndroidHttp}</li> * <li>Java: {@link com.google.api.client.googleapis.javanet.GoogleNetHttpTransport#newTrustedTransport()} * </li> * </ul> * @param jsonFactory JSON factory, which may be: * <ul> * <li>Jackson: {@code com.google.api.client.json.jackson2.JacksonFactory}</li> * <li>Google GSON: {@code com.google.api.client.json.gson.GsonFactory}</li> * <li>Android Honeycomb or higher: * {@code com.google.api.client.extensions.android.json.AndroidJsonFactory}</li> * </ul> * @param httpRequestInitializer HTTP request initializer or {@code null} for none * @since 1.7 */ public Builder(com.google.api.client.http.HttpTransport transport, com.google.api.client.json.JsonFactory jsonFactory, com.google.api.client.http.HttpRequestInitializer httpRequestInitializer) { super( transport, jsonFactory, Builder.chooseEndpoint(transport), DEFAULT_SERVICE_PATH, httpRequestInitializer, false); setBatchPath(DEFAULT_BATCH_PATH); } /** Builds a new instance of {@link StreetViewPublish}. */ @Override public StreetViewPublish build() { return new StreetViewPublish(this); } @Override public Builder setRootUrl(String rootUrl) { return (Builder) super.setRootUrl(rootUrl); } @Override public Builder setServicePath(String servicePath) { return (Builder) super.setServicePath(servicePath); } @Override public Builder setBatchPath(String batchPath) { return (Builder) super.setBatchPath(batchPath); } @Override public Builder setHttpRequestInitializer(com.google.api.client.http.HttpRequestInitializer httpRequestInitializer) { return (Builder) super.setHttpRequestInitializer(httpRequestInitializer); } @Override public Builder setApplicationName(String applicationName) { return (Builder) super.setApplicationName(applicationName); } @Override public Builder setSuppressPatternChecks(boolean suppressPatternChecks) { return (Builder) super.setSuppressPatternChecks(suppressPatternChecks); } @Override public Builder setSuppressRequiredParameterChecks(boolean suppressRequiredParameterChecks) { return (Builder) super.setSuppressRequiredParameterChecks(suppressRequiredParameterChecks); } @Override public Builder setSuppressAllChecks(boolean suppressAllChecks) { return (Builder) super.setSuppressAllChecks(suppressAllChecks); } /** * Set the {@link StreetViewPublishRequestInitializer}. * * @since 1.12 */ public Builder setStreetViewPublishRequestInitializer( StreetViewPublishRequestInitializer streetviewpublishRequestInitializer) { return (Builder) super.setGoogleClientRequestInitializer(streetviewpublishRequestInitializer); } @Override public Builder setGoogleClientRequestInitializer( com.google.api.client.googleapis.services.GoogleClientRequestInitializer googleClientRequestInitializer) { return (Builder) super.setGoogleClientRequestInitializer(googleClientRequestInitializer); } } }
apache-2.0
apetresc/aws-sdk-for-java-on-gae
src/main/java/com/amazonaws/services/identitymanagement/model/transform/RemoveUserFromGroupRequestMarshaller.java
2071
/* * Copyright 2010-2011 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.identitymanagement.model.transform; import java.util.HashMap; import java.util.List; import java.util.Map; import com.amazonaws.Request; import com.amazonaws.DefaultRequest; import com.amazonaws.services.identitymanagement.model.*; import com.amazonaws.transform.Marshaller; import com.amazonaws.util.StringUtils; /** * Remove User From Group Request Marshaller */ public class RemoveUserFromGroupRequestMarshaller implements Marshaller<Request<RemoveUserFromGroupRequest>, RemoveUserFromGroupRequest> { public Request<RemoveUserFromGroupRequest> marshall(RemoveUserFromGroupRequest removeUserFromGroupRequest) { Request<RemoveUserFromGroupRequest> request = new DefaultRequest<RemoveUserFromGroupRequest>(removeUserFromGroupRequest, "AmazonIdentityManagement"); request.addParameter("Action", "RemoveUserFromGroup"); request.addParameter("Version", "2010-05-08"); if (removeUserFromGroupRequest != null) { if (removeUserFromGroupRequest.getGroupName() != null) { request.addParameter("GroupName", StringUtils.fromString(removeUserFromGroupRequest.getGroupName())); } } if (removeUserFromGroupRequest != null) { if (removeUserFromGroupRequest.getUserName() != null) { request.addParameter("UserName", StringUtils.fromString(removeUserFromGroupRequest.getUserName())); } } return request; } }
apache-2.0
sisbell/jvending
javax-provisioning/src/main/java/javax/provisioning/Deliverable.java
2591
/** * Copyright 2003-2010 Shane Isbell * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package javax.provisioning; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.URL; import java.util.logging.Logger; /** * Class representing a file that could be delivered to a client. Subclasses may have methods that allow * the file to be modified. * * @author Shane Isbell * @version 1.0 */ public class Deliverable { private static Logger logger = Logger.getLogger("Deliverable"); private final URL url; private final String mimeType; /** * Constructor * * @param url the URL of this deliverable * @param mimeType the mime-type of this deliverable */ public Deliverable(URL url, String mimeType) { this.url = url; this.mimeType = mimeType; } /** * Client is responsible for closing inputstream on failure. */ public InputStream getInputStream() throws IOException { if (url == null) throw new IOException("JV-1000-001: URL Value is Null"); logger.finest("JV-1000-002: Obtaining Input Stream: " + toString()); return getURL().openStream(); } /** * Returns the mime-type for this deliverable. * * @return the mime-type for this deliverable */ public String getMimeType() { return mimeType; } public URL getURL() { return url; } /** * Client is responsible for closing outputstream. This allows the client to append to the * outputstream; */ public void writeContents(OutputStream os) throws IOException { InputStream is = getInputStream(); byte[] buffer = new byte[1024]; int n; while ((n = is.read(buffer)) >= 0) { os.write(buffer, 0, n); } } public String toString() { return "URL = " + url + ", Mime Type = " + mimeType; } }
apache-2.0
MaximTar/satellite
src/main/resources/libs/JAT/jat/measurements/ObservationMeasurementList.java
19780
/* JAT: Java Astrodynamics Toolkit * * Copyright (c) 2003 The JAT Project. All rights reserved. * * This file is part of JAT. JAT is free software; you can * redistribute it and/or modify it under the terms of the * NASA Open Source Agreement, version 1.3 or later. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * NASA Open Source Agreement for more details. * * You should have received a copy of the NASA Open Source Agreement * along with this program; if not, write to the NASA Goddard * Space Flight Center at opensource@gsfc.nasa.gov. * * * File Created on 3 October 2005 * Created by Kathryn Bradley, Emergent Space Technologies * */ package jat.measurements; import jat.gps.GPS_Measurement; import jat.matvec.data.Matrix; import jat.matvec.data.RotationMatrix; import jat.matvec.data.VectorN; import jat.sim.initializer; import jat.spacetime.CalDate; import jat.spacetime.EarthRef; import jat.spacetime.FitIERS; import jat.spacetime.GPSTimeFormat; import jat.spacetime.Time; import jat.traj.Trajectory; import jat.util.FileUtil; import java.io.BufferedReader; import java.io.EOFException; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.StringTokenizer; import java.util.Vector; public class ObservationMeasurementList { int count=0; int numOfSatellites=0; int timeStep = 0; int currentIndex = 0; int observationNumber=0; int dataCount=0; double version; double timeMjd; double current_mjd; boolean notDone = true; boolean timeStamp = false; String line; String lineNew; Vector data = new Vector(); Vector observationType= new Vector(); Vector prns = new Vector(); ArrayList list = new ArrayList(); GPSmeasurementModel model_gps; GPSStateMeasurementModel model_gpsstate; rangeMeasurementModel model_range; stateMeasurementModel model_state; stateUpdateMeasurementModel model_stateupdate; private HashMap input; public ObservationMeasurementList(){} public ObservationMeasurementList(HashMap hm){ this.input = hm; for(int i=0; i<initializer.parseInt(input, "MEAS.types"); i++){ if(initializer.parseString(input, "MEAS."+i+".desc").equalsIgnoreCase("GPS")){ model_gps = new GPSmeasurementModel(hm); }else if(initializer.parseString(input, "MEAS."+i+".desc").equalsIgnoreCase("pseudoGPS")){ model_gpsstate = new GPSStateMeasurementModel(hm); }else if(initializer.parseString(input, "MEAS."+i+".desc").equalsIgnoreCase("range")){ model_range = new rangeMeasurementModel(hm); }else if(initializer.parseString(input, "MEAS."+i+".desc").equalsIgnoreCase("stateUpdate")){ model_state = new stateMeasurementModel(hm); }else{ model_stateupdate = new stateUpdateMeasurementModel(hm); } } } public static void main(String[] args) // Main Method throws IOException{ ObservationMeasurementList x = new ObservationMeasurementList(); String path = FileUtil.getClassFilePath("jat.measurements","ObservationMeasurementList"); String fs = FileUtil.file_separator(); //x.processRINEX(path+fs+"ExampleRINEXGEONS.rnx"); //x.processRINEX(path+fs+"Case-820.rnx"); x.processStateUpdateFile(path+fs+"test1_8.rnx",50985,50999); } public void processStateUpdateFile(String fileName, double mjd0, double mjdf) throws IOException { BufferedReader in = new BufferedReader(new FileReader(new File(fileName))); boolean loop = true; Time time; EarthRef earth; RotationMatrix rot; VectorN r = new VectorN(3); int year, day,i; double sec, mjd; GPSTimeFormat date; double x,y,z,clock; String line = "start"; StringTokenizer tok; boolean processedOther = false; ObservationMeasurement om; Vector v_type = new Vector(); v_type.add("S3"); Vector v_data; if(this.list.size()>0) processedOther = true; line = in.readLine(); while(!line.equals("") && loop){ try{ tok = new StringTokenizer(line, " "); year = Integer.parseInt(tok.nextToken()); day = Integer.parseInt(tok.nextToken()); sec = Double.parseDouble(tok.nextToken()); date = new GPSTimeFormat(year,day,0,0,sec); mjd = date.mjd(); if(mjd>=mjd0 && mjd<= mjdf){ x = Double.parseDouble(tok.nextToken()); y = Double.parseDouble(tok.nextToken()); z = Double.parseDouble(tok.nextToken()); clock = Double.parseDouble(tok.nextToken())/jat.cm.Constants.c; mjd = mjd - (clock)/86400; r = new VectorN(x,y,z); time = new Time(mjd); //*TODO watch earth = new EarthRef(time); FitIERS iers = new FitIERS(); //iers.process(); //* don't need this double[] param = iers.search(time.mjd_tt()); earth.setIERS(param[0],param[1]); time.set_UT1_UTC(param[2]); //earth.computePole(time); Matrix tmp = earth.eci2ecef(time); rot = new RotationMatrix(tmp.transpose()); r = rot.transform(r); v_data = new Vector(); v_data.add(""+r.x[0]); v_data.add(""+r.x[1]); v_data.add(""+r.x[2]); if(processedOther){ i = searchListMJD(mjd); for(int snum=0; snum<3; snum++){ om = new ObservationMeasurement(mjd,v_type,v_data,"0",this.input, this.model_gpsstate,ObservationMeasurement.TYPE_GPSSTATE); om.set_whichState(snum); System.out.println(om.toString()); list.add(i,om); } }else{ for(int snum=0; snum<3; snum++){ om = new ObservationMeasurement(mjd,v_type,v_data,"0",this.input, this.model_gpsstate,ObservationMeasurement.TYPE_GPSSTATE); om.set_whichState(snum); System.out.println(om.toString()); list.add(om); } } } line = in.readLine(); }catch(EOFException eof){ loop = false; } } } /** Method Class which accesses the other classes to read the RINEX observation files.*/ public void processRINEX(String fileName) //Needs the fileName throws IOException{ File inputFile = new File(fileName); FileReader fr = new FileReader(inputFile); BufferedReader in = new BufferedReader(fr); while (notDone) //Reading the Header information in this While loop { count++; line = in.readLine(); StringTokenizer tok = new StringTokenizer(line, " "); if (count == 1) { version = Double.parseDouble(tok.nextToken()); } else if (count == 2) { observationNumber = Integer.parseInt(tok.nextToken()); for (int k =0; k < observationNumber; k++) { observationType.add(tok.nextToken()); } } else { ObservationMeasurementList headerFinished = new ObservationMeasurementList(); notDone = headerFinished.setHeaderReader(tok, count); //Returns false if header has been read } } while (in.ready()) //Reading the file blocks with the measurement data { /**dataCount is invented for first line of data. The timeStamp is true if the data from the previous time has already been read. Initially timeStamp is set to false and dataCount is set to zero*/ dataCount++; if ((dataCount==1) || (timeStamp == true)) { lineNew = in.readLine(); //ObservationMeasurementList date = new ObservationMeasurementList(); GPSTimeFormat newDate = ObservationMeasurementList.setDateStuff(lineNew); timeMjd =newDate.mjd(); //if(timeMjd > 52189.06403935186){ //int stop_to_debug = 0; //} if(currentIndex <0){ current_mjd = timeMjd; currentIndex = 0; } //ObservationMeasurementList num = new ObservationMeasurementList(); numOfSatellites = ObservationMeasurementList.setNumberOfSatellites(lineNew); //data.add(new Integer(numOfSatellites)); int newNumOfSatellites = numOfSatellites; int start = 32; if (numOfSatellites >12) { newNumOfSatellites =12; } //prns.clear(); prns = new Vector(); for (int t=0; t<newNumOfSatellites; t++) { String prnIds = new String(lineNew.substring(start, start+3)); prns.add(prnIds); start = start + 3; } if (numOfSatellites > 12){ String secondLine = in.readLine(); int secondLineSatellites = numOfSatellites-12; int secondStart = 33; for (int n=0; n<secondLineSatellites; n++) { String prnIds = new String (secondLine.substring(secondStart, secondStart+2)); prns.add(prnIds); secondStart = secondStart +3; } } timeStamp = false; //Resets timeStamp to read the data for the time stamp } else { for (int j=0; j<numOfSatellites; j++ ) { String lineNew = in.readLine(); StringTokenizer tokNew = new StringTokenizer(lineNew, " "); //data.clear(); data = new Vector(); for (int t=0; t<observationNumber; t++) { String dataNew = tokNew.nextToken(); data.add(dataNew); } ObservationMeasurement info; switch(ObservationMeasurement.chooseType((String)prns.get(j))){ case ObservationMeasurement.TYPE_GPS: info = new ObservationMeasurement(timeMjd,observationType, data, prns.get(j), input,model_gps,ObservationMeasurement.TYPE_GPS); EarthRef earth = new EarthRef(new Time(timeMjd)); RotationMatrix R = new RotationMatrix(earth.ECI2ECEF()); info.set_ECF2ECI(R); break; case ObservationMeasurement.TYPE_STATEUPDATE: info = new ObservationMeasurement(timeMjd,observationType, data,prns.get(j), input,model_stateupdate,ObservationMeasurement.TYPE_STATEUPDATE); break; case ObservationMeasurement.TYPE_RANGE: info = new ObservationMeasurement(timeMjd,observationType, data, prns.get(j), input,model_range, ObservationMeasurement.TYPE_RANGE); break; //* TODO Include the rest of the model types default: info = new ObservationMeasurement( timeMjd,observationType, data, prns.get(j),input,model_gps, ObservationMeasurement.TYPE_GPS); } this.add(info); String meas = info.toString(); System.out.println(meas); } timeStamp = true; //Resets timeStamp to read the next time stamp line timeStep++; //keeps track of the number of time steps, initially zero } } } public void processRINEX(String fileName,boolean useGPS, boolean useCross) //Needs the fileName throws IOException{ File inputFile = new File(fileName); FileReader fr = new FileReader(inputFile); BufferedReader in = new BufferedReader(fr); double MJDF = initializer.parseDouble(input, "init.MJDF")+initializer.parseDouble(input, "init.TF")/86400.0; while (notDone) //Reading the Header information in this While loop { count++; line = in.readLine(); StringTokenizer tok = new StringTokenizer(line, " "); try{ if (count == 1) { version = Double.parseDouble(tok.nextToken()); } else if (count == 2) { observationNumber = Integer.parseInt(tok.nextToken()); for (int k =0; k < observationNumber; k++) { observationType.add(tok.nextToken()); } } else { ObservationMeasurementList headerFinished = new ObservationMeasurementList(); notDone = headerFinished.setHeaderReader(tok, count); //Returns false if header has been read } }catch(Exception e){ ObservationMeasurementList headerFinished = new ObservationMeasurementList(); notDone = headerFinished.setHeaderReader(tok, count); //Returns false if header has been read } } while (in.ready()) //Reading the file blocks with the measurement data { /**dataCount is invented for first line of data. The timeStamp is true if the data from the previous time has already been read. Initially timeStamp is set to false and dataCount is set to zero*/ dataCount++; if ((dataCount==1) || (timeStamp == true)) { lineNew = in.readLine(); //ObservationMeasurementList date = new ObservationMeasurementList(); GPSTimeFormat newDate = ObservationMeasurementList.setDateStuff(lineNew); //timeMjd =newDate.mjd(); //* TODO Watch this timeMjd =newDate.mjd_utc();//-13.0/86400.0; if(timeMjd > MJDF) break; //if(timeMjd > 52189.06403935186){ //int stop_to_debug = 0; //} if(currentIndex <0){ current_mjd = timeMjd; currentIndex = 0; } //ObservationMeasurementList num = new ObservationMeasurementList(); numOfSatellites = ObservationMeasurementList.setNumberOfSatellites(lineNew); //data.add(new Integer(numOfSatellites)); int newNumOfSatellites = numOfSatellites; int start = 32; if (numOfSatellites >12) { newNumOfSatellites =12; } //prns.clear(); prns = new Vector(); for (int t=0; t<newNumOfSatellites; t++) { String prnIds = new String(lineNew.substring(start, start+3)); prns.add(prnIds); start = start + 3; } if (numOfSatellites > 12){ String secondLine = in.readLine(); int secondLineSatellites = numOfSatellites-12; int secondStart = 33; for (int n=0; n<secondLineSatellites; n++) { String prnIds = new String (secondLine.substring(secondStart, secondStart+2)); prns.add(prnIds); secondStart = secondStart +3; } } timeStamp = false; //Resets timeStamp to read the data for the time stamp } else { for (int j=0; j<numOfSatellites; j++ ) { String lineNew = in.readLine(); StringTokenizer tokNew = new StringTokenizer(lineNew, " "); //data.clear(); data = new Vector(); for (int t=0; t<observationNumber; t++) { String dataNew = tokNew.nextToken(); data.add(dataNew); } ObservationMeasurement info; String meas; switch(ObservationMeasurement.chooseType((String)prns.get(j))){ case ObservationMeasurement.TYPE_GPS: if(useGPS){ info = new ObservationMeasurement(timeMjd,observationType, data, prns.get(j), input,model_gps,ObservationMeasurement.TYPE_GPS); EarthRef earth = new EarthRef(new Time(timeMjd)); RotationMatrix R = new RotationMatrix(earth.ECI2ECEF()); info.set_ECF2ECI(R); if(!(info.prn.equals("G17") || info.prn.equals("G24") || info.prn.equals("G30"))){ this.add(info); } meas = info.toString(); System.out.println(meas); } break; case ObservationMeasurement.TYPE_STATEUPDATE: info = new ObservationMeasurement(timeMjd,observationType, data,prns.get(j), input,model_stateupdate,ObservationMeasurement.TYPE_STATEUPDATE); this.add(info); meas = info.toString(); System.out.println(meas); break; case ObservationMeasurement.TYPE_RANGE: if(useCross){ info = new ObservationMeasurement(timeMjd,observationType, data, prns.get(j), input,model_range, ObservationMeasurement.TYPE_RANGE); this.add(info); meas = info.toString(); System.out.println(meas); } break; //* TODO Include the rest of the model types default: info = new ObservationMeasurement( timeMjd,observationType, data, prns.get(j),input,model_gps, ObservationMeasurement.TYPE_GPS); this.add(info); meas = info.toString(); System.out.println(meas); } } timeStamp = true; //Resets timeStamp to read the next time stamp line timeStep++; //keeps track of the number of time steps, initially zero } } } public void assignModels(){ for(int i=0; i<this.list.size(); i++){ ObservationMeasurement o = get(i); } } /** Add an Observation Measurement to the collection * @param meas ObservationMeasurementList object */ public void add(ObservationMeasurement meas) { list.add(meas); } /** Get an ObservationMeasurementList out of the collection * @param index Index of the measurement * @return the ObservationMeasurementList */ public ObservationMeasurement get(int index) { return (ObservationMeasurement) list.get(index); } public ObservationMeasurement getCurrent(){ ObservationMeasurement om = (ObservationMeasurement)list.get(currentIndex); return om; } public ObservationMeasurement getNext(){ if(currentIndex>=(list.size()-1)){ //currentIndex=(list.size()-1); return null; }else currentIndex++; ObservationMeasurement om = (ObservationMeasurement)list.get(currentIndex); return om; } public ObservationMeasurement getPrev(){ if(currentIndex>0) currentIndex--; else currentIndex=0; ObservationMeasurement om = (ObservationMeasurement)list.get(currentIndex); return om; } public ObservationMeasurement getFirst(){ currentIndex = 0; return (ObservationMeasurement)list.get(currentIndex); } public int getIndex(){ return currentIndex; } public Trajectory get_meas_traj(){ Trajectory traj = new Trajectory(); double t; double[] data = new double[6]; ObservationMeasurement tmp; for(int i=0; i<this.list.size(); i++){ tmp = (ObservationMeasurement)list.get(i); if(tmp.get_type()==ObservationMeasurement.TYPE_GPSSTATE){ t = tmp.get_mjd(); for(int j=0; j<3; j++) data[j] = tmp.get_state(3).x[j]; for(int j=3; j<6; j++) data[j] = 0.0; traj.add(t,data); } } return traj; } /** * Search the list and return the first index of the element which is later than or equal to mjd. * @param mjd Modified Julian Date to search for * @return Index */ public int searchListMJD(double mjd){ int i; for(i=0; i<list.size(); i++){ if(((ObservationMeasurement)list.get(i)).time_mjd()>=mjd) return i; } return i; } /** This method setNumberOfSatellites gets the number of satellites from the * file and returns it to the process method. */ private static int setNumberOfSatellites(String lineNew) { int num; StringTokenizer satelliteToken = new StringTokenizer(lineNew.substring(29,32), " "); String numDum = satelliteToken.nextToken(); num = Integer.parseInt(numDum); return num; } /** This method setDateStuff reads the time stamp from the line being fed * in and then calls two methods GPSTimeFormat and CalDate to determine the * time in GPS time. This time is then sent to the Process method to be * stored. */ private static GPSTimeFormat setDateStuff(String lineNew) { StringTokenizer newTok = new StringTokenizer(lineNew, " "); String yrsString = newTok.nextToken(); String monString = newTok.nextToken(); String dayString = newTok.nextToken(); String hrString = newTok.nextToken(); String minString = newTok.nextToken(); String secString = newTok.nextToken(); int month = Integer.parseInt(monString); int day = Integer.parseInt(dayString); int hour =Integer.parseInt(hrString); int min = Integer.parseInt(minString); double sec = Double.parseDouble(secString); int years = Integer.parseInt(yrsString); int year = 0; if (years < 50) { year = (years + 2000); } else { year = (years + 1900); } CalDate toc_dt = new CalDate(year, month, day, hour, min, sec); GPSTimeFormat date = new GPSTimeFormat(toc_dt); return date; } /** This method setHeaderRead determines if the header has finished being * read. If the header is finished being read then it returns a false * to the Process method. */ public boolean setHeaderReader(StringTokenizer tok, int count) { String end = "END"; String header = "HEADER"; String of = "OF"; int check=0; boolean headerFinished = true; while(tok.hasMoreTokens()) { String temp = tok.nextToken(); if ((temp.equals(end))||(temp.equals(of))||(temp.equals(header))) check++; { if (check > 2) { headerFinished = false; } } } return headerFinished; } }
apache-2.0
foreveruseful/smartkey
apt/src/main/java/link/anyauto/smartkey/apt/ClazzNames.java
4050
package link.anyauto.smartkey.apt; import com.google.common.collect.Sets; import com.squareup.javapoet.ClassName; import com.squareup.javapoet.ParameterizedTypeName; import com.squareup.javapoet.TypeName; import java.util.Set; public class ClazzNames { public static final ClassName APPLICATION = ClassName.get("android.app", "Application"); public static final ClassName ACTIVITY = ClassName.get("android.app", "Activity"); public static final ClassName CONTEXT = ClassName.get("android.content", "Context"); public static final ClassName CLAZZ = ClassName.get("java.lang", "Class"); public static final ClassName INTENT = ClassName.get("android.content", "Intent"); public static final ClassName BUNDLE = ClassName.get("android.os", "Bundle"); public static final ClassName INTENT_KEY_MAPPER = ClassName.get("link.anyauto.smartkey.sdks", "IntentKeyMapper"); public static final ClassName INTENT_KEY_MAPPER_BASE = ClassName.get("link.anyauto.smartkey.sdks", "BaseIntentKeyMapper"); public static final ClassName ARRAYLIST = ClassName.get("java.util", "ArrayList"); public static final ClassName SET = ClassName.get("java.util", "Set"); public static final TypeName BOOLEAN = ClassName.get("java.lang", "Boolean"); public static final TypeName BYTE = ClassName.get("java.lang", "Byte"); public static final TypeName SHORT = ClassName.get("java.lang", "Short"); public static final TypeName CHARACTER = ClassName.get("java.lang", "Character"); public static final TypeName INTEGER = ClassName.get("java.lang", "Integer"); public static final TypeName LONG = ClassName.get("java.lang", "Long"); public static final TypeName FLOAT = ClassName.get("java.lang", "Float"); public static final TypeName DOUBLE = ClassName.get("java.lang", "Double"); public static final Set<TypeName> WRAPPERS = Sets.newHashSet(BOOLEAN, BYTE, SHORT, CHARACTER, INTEGER, LONG, FLOAT, DOUBLE); public static final TypeName STRING = ClassName.get("java.lang", "String"); public static final TypeName STRING_SET = ParameterizedTypeName.get(SET, STRING); public static final TypeName CHARSEQUENCE = ClassName.get("java.lang", "CharSequence"); public static final TypeName PARCELABLE = ClassName.get("android.os", "Parcelable"); public static final TypeName URI = ClassName.get("android.net", "Uri"); public static final ParameterizedTypeName PARCELABLE_ARRAYLIST = ParameterizedTypeName.get(ARRAYLIST, PARCELABLE); public static final ParameterizedTypeName URI_ARRAYLIST = ParameterizedTypeName.get(ARRAYLIST, URI); public static final ParameterizedTypeName INTEGER_ARRAYLIST = ParameterizedTypeName.get(ARRAYLIST, INTEGER); public static final ParameterizedTypeName STRING_ARRAYLIST = ParameterizedTypeName.get(ARRAYLIST, STRING); public static final ParameterizedTypeName CHARSEQUENCE_ARRAYLIST = ParameterizedTypeName.get(ARRAYLIST, CHARSEQUENCE); public static final TypeName INTENT_VALUE_GETTER = ClassName.get("link.anyauto.smartkey.sdks", "IntentValueGetter"); public static final TypeName STORAGE_HELPER = ClassName.get("link.anyauto.smartkey.sdks", "StorageHelper"); public static final TypeName GSON_HELPER = ClassName.get("link.anyauto.smartkey.sdks", "GsonHelper"); public static final TypeName TYPE_TOKEN = ClassName.get("com.google.gson.reflect", "TypeToken"); public static final ClassName ACTIVITY_TARGET = ClassName.get("link.anyauto.smartkey.sdks.targets", "ActivityTarget"); public static final ClassName SERVICE_TARGET = ClassName.get("link.anyauto.smartkey.sdks.targets", "ServiceTarget"); public static final ClassName NOT_DETERMINED_ACTIVITY_TARGET = ClassName.get("link.anyauto.smartkey.sdks.targets", "NotDeterminedActivityTarget"); public static final ClassName NOT_DETERMINED_SERVICE_TARGET = ClassName.get("link.anyauto.smartkey.sdks.targets", "NotDeterminedServiceTarget"); public static final ClassName BACK_RESULT = ClassName.get("link.anyauto.smartkey.sdks.targets", "BackResult"); }
apache-2.0
enetwiz/vaadin-examples
mvp-example/src/main/java/com.enetwiz/BodyViewImpl.java
1371
package com.enetwiz; import com.vaadin.navigator.ViewChangeListener.ViewChangeEvent; import com.vaadin.spring.annotation.SpringView; import com.vaadin.spring.annotation.UIScope; import com.vaadin.ui.Button; import com.vaadin.ui.Component; import com.vaadin.ui.Label; import com.vaadin.ui.VerticalLayout; import javax.annotation.PostConstruct; import org.springframework.beans.factory.annotation.Autowired; import org.vaadin.spring.events.EventBus; @UIScope @SpringView(name = BodyView.NAME) public class BodyViewImpl extends VerticalLayout implements BodyView { @Autowired private EventBus.SessionEventBus eventBus; /** * Welcome button */ private Button button; /** * Build the view content */ @PostConstruct private void init() { setMargin(true); button = new Button("Hello Spring!"); button.addClickListener(new Button.ClickListener() { @Override public void buttonClick(Button.ClickEvent event) { eventBus.publish(this, event); } }); addComponent(button); } @Override public void enter(ViewChangeEvent event) { } @Override public Component getMainComponent() { return this; } @Override public void showAnswer(String answer) { addComponent(new Label(answer)); } }
apache-2.0
amedia/meteo
meteo-jaxb/src/main/java/no/api/meteo/jaxb/sunrise/v1_1/Astrodata.java
2744
// // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.8-b130911.1802 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2018.02.17 at 03:24:40 PM CET // package no.api.meteo.jaxb.sunrise.v1_1; 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.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for anonymous complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="meta" type="{}metaType"/> * &lt;element name="time" type="{}timeType" maxOccurs="unbounded"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "meta", "time" }) @XmlRootElement(name = "astrodata") public class Astrodata { @XmlElement(required = true) protected MetaType meta; @XmlElement(required = true) protected List<TimeType> time; /** * Gets the value of the meta property. * * @return * possible object is * {@link MetaType } * */ public MetaType getMeta() { return meta; } /** * Sets the value of the meta property. * * @param value * allowed object is * {@link MetaType } * */ public void setMeta(MetaType value) { this.meta = value; } /** * Gets the value of the time 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 time property. * * <p> * For example, to add a new item, do as follows: * <pre> * getTime().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link TimeType } * * */ public List<TimeType> getTime() { if (time == null) { time = new ArrayList<TimeType>(); } return this.time; } }
apache-2.0
gavin2lee/incubator
docs/sourcecodes/OpenBridge-base/ob-elk/src/main/java/com/harmazing/openbridge/mod/operations/elasticsearch/bean/AppMonitorForm.java
1910
package com.harmazing.openbridge.mod.operations.elasticsearch.bean; import java.util.HashMap; import java.util.Map; public class AppMonitorForm { private String appId; private String containId; private String envId; private String beginDate; private String endDate; //d h m private String xtype; private String strfilter; /** * 0是 1否 */ private String showStaticSource; private int top; private Map<String,Object> filter = new HashMap<String,Object>(); public String getAppId() { return appId; } public void setAppId(String appId) { this.appId = appId; } public String getContainId() { return containId; } public void setContainId(String containId) { this.containId = containId; } public String getBeginDate() { return beginDate; } public void setBeginDate(String beginDate) { this.beginDate = beginDate; } public String getEndDate() { return endDate; } public void setEndDate(String endDate) { this.endDate = endDate; } public int getTop() { return top; } public void setTop(int top) { this.top = top; } public Map<String, Object> getFilter() { return filter; } public void setFilter(Map<String, Object> filter) { this.filter = filter; } public String getXtype() { return xtype; } public void setXtype(String xtype) { this.xtype = xtype; } public String getEnvId() { return envId; } public void setEnvId(String envId) { this.envId = envId; } public String getStrfilter() { return strfilter; } public void setStrfilter(String strfilter) { this.strfilter = strfilter; } public String getShowStaticSource() { return showStaticSource; } public void setShowStaticSource(String showStaticSource) { this.showStaticSource = showStaticSource; } }
apache-2.0
guohan/hadoop
tdh_hbase/src/com/hbase/HBaseTest.java
7249
package com.hbase; import java.io.IOException; import java.util.ArrayList; import java.util.List; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.hbase.HBaseConfiguration; import org.apache.hadoop.hbase.HColumnDescriptor; import org.apache.hadoop.hbase.HTableDescriptor; import org.apache.hadoop.hbase.KeyValue; import org.apache.hadoop.hbase.MasterNotRunningException; import org.apache.hadoop.hbase.ZooKeeperConnectionException; import org.apache.hadoop.hbase.client.Delete; import org.apache.hadoop.hbase.client.Get; import org.apache.hadoop.hbase.client.HBaseAdmin; import org.apache.hadoop.hbase.client.HTable; import org.apache.hadoop.hbase.client.Result; import org.apache.hadoop.hbase.client.ResultScanner; import org.apache.hadoop.hbase.client.Scan; import org.apache.hadoop.hbase.client.Put; import org.apache.hadoop.hbase.util.Bytes; public class HBaseTest { private static Configuration conf =null; /** * 初始化配置 */ static { conf = HBaseConfiguration.create(); } /** * 创建一张表 */ public static void creatTable(String tableName, String[] familys) throws Exception { conf.set("hbase.zookeeper.quorum", "master");//使用eclipse时必须添加这个,否则无法定位 conf.set("hbase.zookeeper.property.clientPort", "2181"); HBaseAdmin admin = new HBaseAdmin(conf); if (admin.tableExists(tableName)) { System.out.println("table already exists!"); } else { HTableDescriptor tableDesc = new HTableDescriptor(tableName); for(int i=0; i<familys.length; i++){ tableDesc.addFamily(new HColumnDescriptor(familys[i])); } admin.createTable(tableDesc); System.out.println("create table " + tableName + " ok."); } } /** * 删除表 */ public static void deleteTable(String tableName) throws Exception { try { HBaseAdmin admin = new HBaseAdmin(conf); admin.disableTable(tableName); admin.deleteTable(tableName); System.out.println("delete table " + tableName + " ok."); } catch (MasterNotRunningException e) { e.printStackTrace(); } catch (ZooKeeperConnectionException e) { e.printStackTrace(); } } /** * 插入一行记录 */ public static void addRecord (String tableName, String rowKey, String family, String qualifier, String value) throws Exception{ try { HTable table = new HTable(conf, tableName); Put put = new Put(Bytes.toBytes(rowKey)); put.add(Bytes.toBytes(family),Bytes.toBytes(qualifier),Bytes.toBytes(value)); table.put(put); System.out.println("insert recored " + rowKey + " to table " + tableName +" ok."); } catch (IOException e) { e.printStackTrace(); } } /** * 删除一行记录 */ public static void delRecord (String tableName, String rowKey) throws IOException{ HTable table = new HTable(conf, tableName); List list = new ArrayList(); Delete del = new Delete(rowKey.getBytes()); list.add(del); table.delete(list); System.out.println("del recored " + rowKey + " ok."); } /** * 查找一行记录 */ public static void getOneRecord (String tableName, String rowKey) throws IOException{ HTable table = new HTable(conf, tableName); Get get = new Get(rowKey.getBytes()); Result rs = table.get(get); for(KeyValue kv : rs.raw()){ System.out.print(new String(kv.getRow()) + " " ); System.out.print(new String(kv.getFamily()) + ":" ); System.out.print(new String(kv.getQualifier()) + " " ); System.out.print(kv.getTimestamp() + " " ); System.out.println(new String(kv.getValue())); } } /** * 显示所有数据 */ public static void getAllRecord (String tableName) { try{ HTable table = new HTable(conf, tableName); Scan s = new Scan(); ResultScanner ss = table.getScanner(s); for(Result r:ss){ for(KeyValue kv : r.raw()){ System.out.print(new String(kv.getRow()) + " "); System.out.print(new String(kv.getFamily()) + ":"); System.out.print(new String(kv.getQualifier()) + " "); System.out.print(kv.getTimestamp() + " "); System.out.println(new String(kv.getValue())); } } } catch (IOException e){ e.printStackTrace(); } } public static void main (String [] agrs) { try { String tablename = "scores"; String[] familys = {"grade", "course"}; HBaseTest.creatTable(tablename, familys); //add record zkb HBaseTest.addRecord(tablename,"zkb","grade","","5"); HBaseTest.addRecord(tablename,"zkb","course","","90"); HBaseTest.addRecord(tablename,"zkb","course","math","97"); HBaseTest.addRecord(tablename,"zkb","course","art","87"); //add record baoniu HBaseTest.addRecord(tablename,"baoniu","grade","","4"); HBaseTest.addRecord(tablename,"baoniu","course","math","89"); System.out.println("===========get one record========"); HBaseTest.getOneRecord(tablename, "zkb"); System.out.println("===========show all record========"); HBaseTest.getAllRecord(tablename); System.out.println("===========del one record========"); HBaseTest.delRecord(tablename, "baoniu"); HBaseTest.getAllRecord(tablename); System.out.println("===========show all record========"); HBaseTest.getAllRecord(tablename); } catch (Exception e) { e.printStackTrace(); } } }
apache-2.0
shin285/KOMORAN
core/src/test/java/kr/co/shineware/nlp/komoran/benchmark/DataStructureSpeedTestInterface.java
409
package kr.co.shineware.nlp.komoran.benchmark; import kr.co.shineware.nlp.komoran.corpus.model.Dictionary; import kr.co.shineware.nlp.komoran.parser.KoreanUnitParser; import java.util.List; public interface DataStructureSpeedTestInterface { KoreanUnitParser koreanUnitParser = new KoreanUnitParser(); void load(Dictionary dictionary); long doTestAndGetAverageElapsedTime(List<String> lines); }
apache-2.0
isisaddons/isis-app-kitchensink
fixture/src/main/java/org/isisaddons/app/kitchensink/fixture/other/OtherBoundedObjectsFixture.java
1448
/* * Copyright 2014 Dan Haywood * * 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.isisaddons.app.kitchensink.fixture.other; import org.isisaddons.app.kitchensink.dom.other.OtherBoundedObjects; import org.apache.isis.applib.fixturescripts.FixtureScript; public class OtherBoundedObjectsFixture extends FixtureScript { @Override protected void execute(ExecutionContext executionContext) { // create create("Foo", executionContext, null); create("Bar", executionContext, null); create("Baz", executionContext, null); } private org.isisaddons.app.kitchensink.dom.other.OtherBoundedObject create(final String name, ExecutionContext executionContext, String description) { return executionContext.addResult(this, otherBoundedObjects.create(name, description)); } @javax.inject.Inject private OtherBoundedObjects otherBoundedObjects; }
apache-2.0
sabotuer99/SpringDataJpaTutorial
src/test/java/com/guitar/db/LocationPersistenceTests.java
4667
package com.guitar.db; import static org.junit.Assert.*; import java.util.List; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.transaction.annotation.Transactional; import com.guitar.db.model.Location; import com.guitar.db.repository.LocationJpaRepository; import com.guitar.db.repository.LocationRepository; @ContextConfiguration(locations={"classpath:com/guitar/db/applicationTests-context.xml"}) @RunWith(SpringJUnit4ClassRunner.class) public class LocationPersistenceTests { // @Autowired // private LocationRepository locationRepository; @Autowired private LocationJpaRepository locationJpaRepository; @PersistenceContext private EntityManager entityManager; @Test public void testJpaFind(){ List<Location> locations = locationJpaRepository.findAll(); assertNotNull(locations); } @Test public void testJpaNot(){ List<Location> locations = locationJpaRepository.findByStateNot("Alabama"); assertNotSame("Alabama", locations.get(0).getState()); } @Test public void testJpaAnd(){ List<Location> locations = locationJpaRepository.findByStateAndCountry("Utah", "United States"); assertNotNull(locations); assertEquals("Utah", locations.get(0).getState()); } @Test public void testJpaOr(){ List<Location> locations = locationJpaRepository.findByStateIsOrCountryEquals("Utah", "France"); assertNotNull(locations); assertEquals("Utah", locations.get(0).getState()); } @Test @Transactional public void testSaveAndGetAndDelete() throws Exception { Location location = new Location(); location.setCountry("Canada"); location.setState("British Columbia"); //location = locationRepository.create(location); location = locationJpaRepository.saveAndFlush(location); // clear the persistence context so we don't return the previously cached location object // this is a test only thing and normally doesn't need to be done in prod code entityManager.clear(); //Location otherLocation = locationRepository.find(location.getId()); Location otherLocation = locationJpaRepository.findOne(location.getId()); assertEquals("Canada", otherLocation.getCountry()); assertEquals("British Columbia", otherLocation.getState()); //delete BC location now //locationRepository.delete(otherLocation); locationJpaRepository.delete(otherLocation); } @Test public void testFindWithLike() throws Exception { List<Location> locs = locationJpaRepository.findByStateLike("New%");//locationRepository.getLocationByStateName("New"); assertEquals(4, locs.size()); } @Test public void testFindWithLikeIgnoreCase() throws Exception { List<Location> locs = locationJpaRepository.findByStateLikeIgnoreCase("new%");//locationRepository.getLocationByStateName("New"); assertEquals(4, locs.size()); } @Test public void testFindFirstWithLikeIgnoreCase() throws Exception { Location loc = locationJpaRepository.findFirstByStateLikeIgnoreCase("new%");//locationRepository.getLocationByStateName("New"); assertNotNull(loc); } @Test public void testFindStartingWith() throws Exception { List<Location> locs = locationJpaRepository.findByStateStartingWith("New");//locationRepository.getLocationByStateName("New"); assertEquals(4, locs.size()); } @Test public void testFindWithNotLike() throws Exception { List<Location> locs = locationJpaRepository.findByStateNotLike("New%");//locationRepository.getLocationByStateName("New"); assertEquals(46, locs.size()); } @Test public void testFindWithNotLikeOrderBy() throws Exception { List<Location> locs = locationJpaRepository.findByStateNotLikeOrderByStateAsc("New%");//locationRepository.getLocationByStateName("New"); assertEquals("Alabama", locs.get(0).getState()); assertEquals(46, locs.size()); for(Location loc : locs){ System.out.println(loc.getState()); } } @Test @Transactional //note this is needed because we will get a lazy load exception unless we are in a tx public void testFindWithChildren() throws Exception { Location arizona = locationJpaRepository.findOne(3L);//locationRepository.find(3L); assertEquals("United States", arizona.getCountry()); assertEquals("Arizona", arizona.getState()); assertEquals(1, arizona.getManufacturers().size()); assertEquals("Fender Musical Instruments Corporation", arizona.getManufacturers().get(0).getName()); } }
apache-2.0
Pyknic/stiletto
src/main/java/com/github/pyknic/stiletto/internal/util/ReflectionUtil.java
2883
/** * * Copyright (c) 2017, Emil Forslund. 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.github.pyknic.stiletto.internal.util; import java.lang.reflect.Field; import java.util.stream.Stream; /** * Some common utility methods for analyzing classes with reflection. * * @author Emil Forslund * @since 1.0.0 */ public final class ReflectionUtil { /** * Returns a stream of all the member fields for the specified class, * including inherited fields from any ancestors. This includes public, * private, protected and package private fields. * * @param clazz the class to traverse * @return stream of fields */ public static Stream<Field> traverseFields(Class<?> clazz) { final Class<?> parent = clazz.getSuperclass(); final Stream<Field> inherited; if (parent != null) { inherited = traverseFields(parent); } else { inherited = Stream.empty(); } return Stream.concat(inherited, Stream.of(clazz.getDeclaredFields())); } /** * Returns a stream of all the classes upwards in the inheritance tree of * the specified class, including the class specified as the first element * and {@code java.lang.Object} as the last one. * * @param clazz the first class in the tree * @return stream of ancestors (including {@code clazz}) */ public static Stream<Class<?>> traverseAncestors(Class<?> clazz) { final Class<?>[] interfaces = clazz.getInterfaces(); if (clazz.getSuperclass() == null) { if (interfaces.length == 0) { return Stream.of(clazz); } else { return Stream.concat( Stream.of(clazz), Stream.of(clazz.getInterfaces()) .flatMap(ReflectionUtil::traverseAncestors) ).distinct(); } } else { return Stream.concat( Stream.of(clazz), Stream.concat( Stream.of(clazz.getSuperclass()), Stream.of(clazz.getInterfaces()) ).flatMap(ReflectionUtil::traverseAncestors) ).distinct(); } } /** * Should never be invoked. */ private ReflectionUtil() {} }
apache-2.0
zuolg/MagazineBlog
src/main/java/com/zlg/blog/dao/ContentModelMapper.java
169
package com.zlg.blog.dao; import com.zlg.blog.core.Mapper; import com.zlg.blog.model.ContentModel; public interface ContentModelMapper extends Mapper<ContentModel> { }
apache-2.0
ifnul/ums-backend
is-lnu-rest-api/src/test/java/org/lnu/is/web/rest/controller/person/award/PersonAwardControllerTest.java
6111
package org.lnu.is.web.rest.controller.person.award; import static org.mockito.Matchers.any; import static org.mockito.Matchers.anyLong; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import java.nio.file.AccessDeniedException; import java.text.MessageFormat; import java.util.Arrays; import java.util.Collections; import java.util.List; import org.junit.Test; import org.junit.runner.RunWith; import org.lnu.is.facade.facade.Facade; import org.lnu.is.pagination.OrderBy; import org.lnu.is.resource.message.MessageResource; import org.lnu.is.resource.message.MessageType; import org.lnu.is.resource.person.award.PersonAwardResource; import org.lnu.is.resource.search.PagedRequest; import org.lnu.is.resource.search.PagedResultResource; import org.lnu.is.web.rest.controller.AbstractControllerTest; import org.lnu.is.web.rest.controller.BaseController; import org.mockito.InjectMocks; import org.mockito.Matchers; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; import org.springframework.http.MediaType; @RunWith(MockitoJUnitRunner.class) public class PersonAwardControllerTest extends AbstractControllerTest { @Mock private Facade<PersonAwardResource, PersonAwardResource, Long> facade; @InjectMocks private PersonAwardController unit; @Override protected BaseController getUnit() { return unit; } @Test public void testCreatePersonAward() throws Exception { // Given Long personId = 1L; PersonAwardResource personAwardResource = new PersonAwardResource(); // When String request = getJson(personAwardResource, true); String response = getJson(personAwardResource, false); when(facade.createResource(any(PersonAwardResource.class))).thenReturn(personAwardResource); // Then mockMvc.perform(post("/persons/{0}/awards", personId) .contentType(MediaType.APPLICATION_JSON) .content(request)) .andExpect(status().isCreated()) .andExpect(content().string(response)); verify(facade).createResource(personAwardResource); } @Test public void testUpdatePersonAward() throws Exception { // Given Long id = 1L; Long personId = 1L; PersonAwardResource personAwardResource = new PersonAwardResource(); MessageResource responseResource = new MessageResource(MessageType.INFO, "Person Award Updated"); // When String request = getJson(personAwardResource, true); String response = getJson(responseResource, false); // Then mockMvc.perform(put("/persons/{personId}/awards/{id}", personId, id) .contentType(MediaType.APPLICATION_JSON) .content(request)) .andExpect(status().isOk()) .andExpect(content().string(response)); verify(facade).updateResource(id, personAwardResource); } @Test public void testGetSpecoffer() throws Exception { // Given Long id = 1L; Long personId = 1L; PersonAwardResource personAwardResource = new PersonAwardResource(); // When String response = getJson(personAwardResource, false); when(facade.getResource(anyLong())).thenReturn(personAwardResource); // Then mockMvc.perform(get("/persons/{personId}/awards/{id}", personId, id)) .andExpect(status().isOk()) .andExpect(content().string(response)); verify(facade).getResource(id); } @Test public void testDeletePersonAward() throws Exception { // Given Long personId = 2L; Long id = 1L; // When // Then mockMvc.perform(delete("/persons/{personId}/awards/{id}", personId, id)) .andExpect(status().is(204)); verify(facade).removeResource(id); } @Test public void testGetPersonAwards() throws Exception { // Given Long id = 1L; Long personId = 2L; PersonAwardResource personAwardResource = new PersonAwardResource(); personAwardResource.setId(id); long count = 100; int limit = 25; Integer offset = 10; String uri = MessageFormat.format("/persons/{0}/awards", personId); List<PersonAwardResource> entities = Arrays.asList(personAwardResource); PagedResultResource<PersonAwardResource> expectedResource = new PagedResultResource<>(); expectedResource.setCount(count); expectedResource.setLimit(limit); expectedResource.setOffset(offset); expectedResource.setUri(uri); expectedResource.setResources(entities); PersonAwardResource resource = new PersonAwardResource(); resource.setPersonId(personId); PagedRequest<PersonAwardResource> pagedRequest = new PagedRequest<PersonAwardResource>(resource, offset, limit, Collections.<OrderBy>emptyList()); // When when(facade.getResources(Matchers.<PagedRequest<PersonAwardResource>>any())).thenReturn(expectedResource); String response = getJson(expectedResource, false); // Then mockMvc.perform(get("/persons/{personId}/awards", personId) .param("offset", String.valueOf(offset)) .param("limit", String.valueOf(limit))) .andExpect(status().isOk()) .andExpect(content().string(response)); verify(facade).getResources(pagedRequest); } @Test(expected = AccessDeniedException.class) public void testGetResourceWithAccessDeniedException() throws Exception { // Given Long id = 1L; Long personId = 2L; // When doThrow(AccessDeniedException.class).when(facade).getResource(anyLong()); // Then mockMvc.perform(get("/persons/{personId}/awards/{id}", personId, id)); verify(facade).getResource(id); } }
apache-2.0