repo_name
stringlengths
5
108
path
stringlengths
6
333
size
stringlengths
1
6
content
stringlengths
4
977k
license
stringclasses
15 values
jtracey/Signal-Android
src/org/thoughtcrime/securesms/video/ClassicEncryptedMediaDataSource.java
1585
package org.thoughtcrime.securesms.video; import android.media.MediaDataSource; import androidx.annotation.NonNull; import androidx.annotation.RequiresApi; import org.thoughtcrime.securesms.crypto.AttachmentSecret; import org.thoughtcrime.securesms.crypto.ClassicDecryptingPartInputStream; import org.thoughtcrime.securesms.util.Util; import java.io.File; import java.io.IOException; import java.io.InputStream; @RequiresApi(23) final class ClassicEncryptedMediaDataSource extends MediaDataSource { private final AttachmentSecret attachmentSecret; private final File mediaFile; private final long length; ClassicEncryptedMediaDataSource(@NonNull AttachmentSecret attachmentSecret, @NonNull File mediaFile, long length) { this.attachmentSecret = attachmentSecret; this.mediaFile = mediaFile; this.length = length; } @Override public int readAt(long position, byte[] bytes, int offset, int length) throws IOException { try (InputStream inputStream = ClassicDecryptingPartInputStream.createFor(attachmentSecret, mediaFile)) { byte[] buffer = new byte[4096]; long headerRemaining = position; while (headerRemaining > 0) { int read = inputStream.read(buffer, 0, Util.toIntExact(Math.min((long)buffer.length, headerRemaining))); if (read == -1) return -1; headerRemaining -= read; } return inputStream.read(bytes, offset, length); } } @Override public long getSize() { return length; } @Override public void close() {} }
gpl-3.0
Jules-/terraingis
src/TerrainGIS/src/com/vividsolutions/jts/index/chain/MonotoneChainBuilder.java
4504
/* * The JTS Topology Suite is a collection of Java classes that * implement the fundamental operations required to validate a given * geo-spatial data set to a known topological specification. * * Copyright (C) 2001 Vivid Solutions * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * For more information, contact: * * Vivid Solutions * Suite #1A * 2328 Government Street * Victoria BC V8T 5G5 * Canada * * (250)385-6040 * www.vividsolutions.com */ package com.vividsolutions.jts.index.chain; import java.util.*; import com.vividsolutions.jts.geom.Coordinate; import com.vividsolutions.jts.geomgraph.Quadrant; /** * Constructs {@link MonotoneChain}s * for sequences of {@link Coordinate}s. * * @version 1.7 */ public class MonotoneChainBuilder { public static int[] toIntArray(List list) { int[] array = new int[list.size()]; for (int i = 0; i < array.length; i++) { array[i] = ((Integer) list.get(i)).intValue(); } return array; } public static List getChains(Coordinate[] pts) { return getChains(pts, null); } /** * Return a list of the {@link MonotoneChain}s * for the given list of coordinates. */ public static List getChains(Coordinate[] pts, Object context) { List mcList = new ArrayList(); int[] startIndex = getChainStartIndices(pts); for (int i = 0; i < startIndex.length - 1; i++) { MonotoneChain mc = new MonotoneChain(pts, startIndex[i], startIndex[i + 1], context); mcList.add(mc); } return mcList; } /** * Return an array containing lists of start/end indexes of the monotone chains * for the given list of coordinates. * The last entry in the array points to the end point of the point array, * for use as a sentinel. */ public static int[] getChainStartIndices(Coordinate[] pts) { // find the startpoint (and endpoints) of all monotone chains in this edge int start = 0; List startIndexList = new ArrayList(); startIndexList.add(new Integer(start)); do { int last = findChainEnd(pts, start); startIndexList.add(new Integer(last)); start = last; } while (start < pts.length - 1); // copy list to an array of ints, for efficiency int[] startIndex = toIntArray(startIndexList); return startIndex; } /** * Finds the index of the last point in a monotone chain * starting at a given point. * Any repeated points (0-length segments) will be included * in the monotone chain returned. * * @return the index of the last point in the monotone chain * starting at <code>start</code>. */ private static int findChainEnd(Coordinate[] pts, int start) { int safeStart = start; // skip any zero-length segments at the start of the sequence // (since they cannot be used to establish a quadrant) while (safeStart < pts.length - 1 && pts[safeStart].equals2D(pts[safeStart + 1])) { safeStart++; } // check if there are NO non-zero-length segments if (safeStart >= pts.length - 1) { return pts.length - 1; } // determine overall quadrant for chain (which is the starting quadrant) int chainQuad = Quadrant.quadrant(pts[safeStart], pts[safeStart + 1]); int last = start + 1; while (last < pts.length) { // skip zero-length segments, but include them in the chain if (! pts[last - 1].equals2D(pts[last])) { // compute quadrant for next possible segment in chain int quad = Quadrant.quadrant(pts[last - 1], pts[last]); if (quad != chainQuad) break; } last++; } return last - 1; } public MonotoneChainBuilder() { } }
gpl-3.0
HossainKhademian/Studio3
plugins/com.aptana.ui.io/src/com/aptana/ide/ui/io/navigator/ProjectExplorerContentProvider.java
3028
/** * Aptana Studio * Copyright (c) 2005-2012 by Appcelerator, Inc. All Rights Reserved. * Licensed under the terms of the GNU Public License (GPL) v3 (with exceptions). * Please see the license.html included with this distribution for details. * Any modifications to this file must keep this entire header intact. */ package com.aptana.ide.ui.io.navigator; import java.util.ArrayList; import java.util.List; import org.eclipse.core.resources.IResource; import org.eclipse.core.resources.IResourceChangeEvent; import org.eclipse.core.resources.IResourceChangeListener; import org.eclipse.core.resources.IResourceDelta; import org.eclipse.core.resources.IWorkspaceRoot; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.jface.viewers.Viewer; import com.aptana.core.util.ArrayUtil; import com.aptana.ide.core.io.CoreIOPlugin; import com.aptana.ui.util.UIUtils; public class ProjectExplorerContentProvider extends FileTreeContentProvider { private static final String LOCAL_SHORTCUTS_ID = "com.aptana.ide.core.io.localShortcuts"; //$NON-NLS-1$ private Viewer treeViewer; private IResourceChangeListener resourceListener = new IResourceChangeListener() { public void resourceChanged(IResourceChangeEvent event) { // to fix https://jira.appcelerator.org/browse/TISTUD-1695, we need to force a selection update when a // project is closed or opened if (shouldUpdateActions(event.getDelta())) { UIUtils.getDisplay().asyncExec(new Runnable() { public void run() { treeViewer.setSelection(treeViewer.getSelection()); } }); } } }; public ProjectExplorerContentProvider() { ResourcesPlugin.getWorkspace().addResourceChangeListener(resourceListener, IResourceChangeEvent.POST_CHANGE); } @Override public void dispose() { ResourcesPlugin.getWorkspace().removeResourceChangeListener(resourceListener); super.dispose(); } @Override public Object[] getChildren(Object parentElement) { if (parentElement instanceof IResource) { return ArrayUtil.NO_OBJECTS; } return super.getChildren(parentElement); } @Override public Object[] getElements(Object inputElement) { if (inputElement instanceof IWorkspaceRoot) { List<Object> children = new ArrayList<Object>(); children.add(LocalFileSystems.getInstance()); children.add(CoreIOPlugin.getConnectionPointManager().getConnectionPointCategory(LOCAL_SHORTCUTS_ID)); return children.toArray(new Object[children.size()]); } return super.getElements(inputElement); } @Override public void inputChanged(Viewer viewer, Object oldInput, Object newInput) { treeViewer = viewer; super.inputChanged(viewer, oldInput, newInput); } private boolean shouldUpdateActions(IResourceDelta delta) { if (delta.getFlags() == IResourceDelta.OPEN) { return true; } IResourceDelta[] children = delta.getAffectedChildren(); for (IResourceDelta child : children) { if (shouldUpdateActions(child)) { return true; } } return false; } }
gpl-3.0
wolffcm/voltdb
src/frontend/org/voltdb/groovy/Tuplerator.java
5058
/* This file is part of VoltDB. * Copyright (C) 2008-2015 VoltDB Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with VoltDB. If not, see <http://www.gnu.org/licenses/>. */ package org.voltdb.groovy; import static java.lang.Character.toLowerCase; import static java.lang.Character.toUpperCase; import groovy.lang.Closure; import groovy.lang.GString; import groovy.lang.GroovyObjectSupport; import java.util.NavigableMap; import org.voltdb.VoltTable; import org.voltdb.VoltType; import com.google_voltpatches.common.collect.ImmutableSortedMap; /** * Groovy table access expediter. It allows you to easily navigate a VoltTable, * and access its column values. * <p> * Example usage on a query that returns results for the : * <code><pre> * cr = client.callProcedure('@AdHoc','select INTEGER_COL, STRING_COL from FOO') * tuplerator(cr.results[0]).eachRow { * * integerColValueByIndex = it[0] * stringColValueByIndex = it[1] * * integerColValueByName = it['integerCol'] * stringColValyeByName = it['stringCol'] * * integerColValueByField = it.integerCol * stringColValyeByField = it.stringCol * } * * </code></pre> * */ public class Tuplerator extends GroovyObjectSupport { private final VoltTable table; private final VoltType [] byIndex; private final NavigableMap<String, Integer> byName; public static Tuplerator newInstance(VoltTable table) { return new Tuplerator(table); } public Tuplerator(final VoltTable table) { this.table = table; this.byIndex = new VoltType[table.getColumnCount()]; ImmutableSortedMap.Builder<String, Integer> byNameBuilder = ImmutableSortedMap.naturalOrder(); for (int c = 0; c < byIndex.length; ++c) { VoltType cType = table.getColumnType(c); StringBuilder cName = new StringBuilder(table.getColumnName(c)); byIndex[c] = cType; boolean upperCaseIt = false; for (int i = 0; i < cName.length();) { char chr = cName.charAt(i); if (chr == '_' || chr == '.' || chr == '$') { cName.deleteCharAt(i); upperCaseIt = true; } else { chr = upperCaseIt ? toUpperCase(chr) : toLowerCase(chr); cName.setCharAt(i, chr); upperCaseIt = false; ++i; } } byNameBuilder.put(cName.toString(),c); } byName = byNameBuilder.build(); } /** * It calls the given closure on each row of the underlying table by passing itself * as the only closure parameter * * @param c the self instance of Tuplerator */ public void eachRow(Closure<Void> c) { while (table.advanceRow()) { c.call(this); } table.resetRowPosition(); } /** * It calls the given closure on each row of the underlying table for up to the specified limit, * by passing itself as the only closure parameter * * @param maxRows maximum rows to call the closure on * @param c closure */ public void eachRow(int maxRows, Closure<Void> c) { while (--maxRows >= 0 && table.advanceRow()) { c.call(this); } } public Object getAt(int cidx) { Object cval = table.get(cidx, byIndex[cidx]); if (table.wasNull()) cval = null; return cval; } public Object getAt(String cname) { Integer cidx = byName.get(cname); if (cidx == null) { throw new IllegalArgumentException("No Column named '" + cname + "'"); } return getAt(cidx); } public Object getAt(GString cname) { return getAt(cname.toString()); } @Override public Object getProperty(String name) { return getAt(name); } /** * Sets the table row cursor to the given position * @param num row number to set the row cursor to * @return an instance of self */ public Tuplerator atRow(int num) { table.advanceToRow(num); return this; } /** * Resets the table row cursor * @return an instance of self */ public Tuplerator reset() { table.resetRowPosition(); return this; } /** * Returns the underlying table * @return the underlying table */ public VoltTable getTable() { return table; } }
agpl-3.0
mgherghe/k3po
driver/src/main/java/org/kaazing/k3po/driver/internal/behavior/handler/codec/http/HttpStatusEncoder.java
2014
/** * Copyright 2007-2015, Kaazing 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 org.kaazing.k3po.driver.internal.behavior.handler.codec.http; import static java.lang.String.format; import static java.nio.charset.StandardCharsets.US_ASCII; import org.jboss.netty.channel.Channel; import org.jboss.netty.handler.codec.http.HttpResponseStatus; import org.kaazing.k3po.driver.internal.behavior.handler.codec.ConfigEncoder; import org.kaazing.k3po.driver.internal.behavior.handler.codec.MessageEncoder; import org.kaazing.k3po.driver.internal.netty.bootstrap.http.HttpChannelConfig; public class HttpStatusEncoder implements ConfigEncoder { private final MessageEncoder codeEncoder; private final MessageEncoder reasonEncoder; public HttpStatusEncoder(MessageEncoder codeEncoder, MessageEncoder reasonEncoder) { this.codeEncoder = codeEncoder; this.reasonEncoder = reasonEncoder; } @Override public void encode(Channel channel) throws Exception { HttpChannelConfig httpConfig = (HttpChannelConfig) channel.getConfig(); int code = Integer.parseInt(codeEncoder.encode().toString(US_ASCII)); String reason = reasonEncoder.encode().toString(US_ASCII); HttpResponseStatus status = new HttpResponseStatus(code, reason); httpConfig.setStatus(status); } @Override public String toString() { return format("http:status %s %s", codeEncoder, reasonEncoder); } }
agpl-3.0
evolvedmicrobe/beast-mcmc
src/dr/app/beauti/types/HierarchicalModelType.java
406
package dr.app.beauti.types; /** * @author Marc A. Suchard */ public enum HierarchicalModelType { NORMAL_HPM, LOGNORMAL_HPM; public String toString() { switch (this) { case NORMAL_HPM: return "Normal"; case LOGNORMAL_HPM: return "Lognormal"; default: return ""; } } }
lgpl-2.1
eBay/Eagle
eagle-core/eagle-data-process/eagle-storm-jobrunning-spout/src/main/java/org/apache/eagle/jobrunning/crawler/JobContext.java
1589
/* * 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.eagle.jobrunning.crawler; public class JobContext { public String jobId; public String user; public Long fetchedTime; public JobContext() { } public JobContext(JobContext context) { this.jobId = new String(context.jobId); this.user = new String(context.user); this.fetchedTime = new Long(context.fetchedTime); } public JobContext(String jobId, String user, Long fetchedTime) { this.jobId = jobId; this.user = user; this.fetchedTime = fetchedTime; } @Override public int hashCode() { return jobId.hashCode() ; } @Override public boolean equals(Object obj) { if (obj instanceof JobContext) { JobContext context = (JobContext)obj; if (this.jobId.equals(context.jobId)) { return true; } } return false; } }
apache-2.0
mikekap/buck
src/com/facebook/buck/jvm/java/JavaBinary.java
6767
/* * Copyright 2012-present Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. You may obtain * a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package com.facebook.buck.jvm.java; import static com.facebook.buck.rules.BuildableProperties.Kind.PACKAGING; import com.facebook.buck.io.DirectoryTraverser; import com.facebook.buck.model.BuildTargets; import com.facebook.buck.rules.AbstractBuildRule; import com.facebook.buck.rules.AddToRuleKey; import com.facebook.buck.rules.BinaryBuildRule; import com.facebook.buck.rules.BuildContext; import com.facebook.buck.rules.BuildRuleParams; import com.facebook.buck.rules.BuildRules; import com.facebook.buck.rules.BuildTargetSourcePath; import com.facebook.buck.rules.BuildableContext; import com.facebook.buck.rules.BuildableProperties; import com.facebook.buck.rules.CommandTool; import com.facebook.buck.rules.RuleKeyAppendable; import com.facebook.buck.rules.RuleKeyBuilder; import com.facebook.buck.rules.SourcePath; import com.facebook.buck.rules.SourcePathResolver; import com.facebook.buck.rules.SourcePaths; import com.facebook.buck.rules.Tool; import com.facebook.buck.step.Step; import com.facebook.buck.step.fs.MakeCleanDirectoryStep; import com.facebook.buck.step.fs.MkdirAndSymlinkFileStep; import com.facebook.buck.step.fs.MkdirStep; import com.google.common.base.Preconditions; import com.google.common.collect.FluentIterable; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSetMultimap; import com.google.common.collect.ImmutableSortedSet; import java.nio.file.Path; import java.nio.file.Paths; import javax.annotation.Nullable; @BuildsAnnotationProcessor public class JavaBinary extends AbstractBuildRule implements BinaryBuildRule, HasClasspathEntries, RuleKeyAppendable { private static final BuildableProperties OUTPUT_TYPE = new BuildableProperties(PACKAGING); @AddToRuleKey @Nullable private final String mainClass; @AddToRuleKey @Nullable private final SourcePath manifestFile; private final boolean mergeManifests; @Nullable private final Path metaInfDirectory; @AddToRuleKey private final ImmutableSet<String> blacklist; private final DirectoryTraverser directoryTraverser; private final ImmutableSetMultimap<JavaLibrary, Path> transitiveClasspathEntries; public JavaBinary( BuildRuleParams params, SourcePathResolver resolver, @Nullable String mainClass, @Nullable SourcePath manifestFile, boolean mergeManifests, @Nullable Path metaInfDirectory, ImmutableSet<String> blacklist, DirectoryTraverser directoryTraverser, ImmutableSetMultimap<JavaLibrary, Path> transitiveClasspathEntries) { super(params, resolver); this.mainClass = mainClass; this.manifestFile = manifestFile; this.mergeManifests = mergeManifests; this.metaInfDirectory = metaInfDirectory; this.blacklist = blacklist; this.directoryTraverser = directoryTraverser; this.transitiveClasspathEntries = transitiveClasspathEntries; } @Override public BuildableProperties getProperties() { return OUTPUT_TYPE; } @Override public RuleKeyBuilder appendToRuleKey(RuleKeyBuilder builder) { // Build a sorted set so that metaInfDirectory contents are listed in a canonical order. ImmutableSortedSet.Builder<Path> paths = ImmutableSortedSet.naturalOrder(); BuildRules.addInputsToSortedSet(metaInfDirectory, paths, directoryTraverser); return builder.setReflectively( "metaInfDirectory", FluentIterable.from(paths.build()) .transform(SourcePaths.toSourcePath(getProjectFilesystem()))); } @Override public ImmutableList<Step> getBuildSteps( BuildContext context, BuildableContext buildableContext) { ImmutableList.Builder<Step> commands = ImmutableList.builder(); Path outputDirectory = getOutputDirectory(); Step mkdir = new MkdirStep(getProjectFilesystem(), outputDirectory); commands.add(mkdir); ImmutableSortedSet<Path> includePaths; if (metaInfDirectory != null) { Path stagingRoot = outputDirectory.resolve("meta_inf_staging"); Path stagingTarget = stagingRoot.resolve("META-INF"); MakeCleanDirectoryStep createStagingRoot = new MakeCleanDirectoryStep( getProjectFilesystem(), stagingRoot); commands.add(createStagingRoot); MkdirAndSymlinkFileStep link = new MkdirAndSymlinkFileStep( getProjectFilesystem(), metaInfDirectory, stagingTarget); commands.add(link); includePaths = ImmutableSortedSet.<Path>naturalOrder() .add(stagingRoot) .addAll(getTransitiveClasspathEntries().values()) .build(); } else { includePaths = ImmutableSortedSet.copyOf(getTransitiveClasspathEntries().values()); } Path outputFile = getPathToOutput(); Path manifestPath = manifestFile == null ? null : getResolver().getAbsolutePath(manifestFile); Step jar = new JarDirectoryStep( getProjectFilesystem(), outputFile, includePaths, mainClass, manifestPath, mergeManifests, blacklist); commands.add(jar); buildableContext.recordArtifact(outputFile); return commands.build(); } @Override public ImmutableSetMultimap<JavaLibrary, Path> getTransitiveClasspathEntries() { return transitiveClasspathEntries; } @Override public ImmutableSet<JavaLibrary> getTransitiveClasspathDeps() { return transitiveClasspathEntries.keySet(); } private Path getOutputDirectory() { return BuildTargets.getGenPath(getBuildTarget(), "%s").getParent(); } @Override public Path getPathToOutput() { return Paths.get( String.format( "%s/%s.jar", getOutputDirectory(), getBuildTarget().getShortNameAndFlavorPostfix())); } @Override public Tool getExecutableCommand() { Preconditions.checkState( mainClass != null, "Must specify a main class for %s in order to to run it.", getBuildTarget()); return new CommandTool.Builder() .addArg("java") .addArg("-jar") .addArg(new BuildTargetSourcePath(getBuildTarget())) .build(); } }
apache-2.0
ydai1124/gobblin-1
gobblin-runtime/src/test/java/gobblin/runtime/commit/CommitSequenceTest.java
3431
/* * 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 gobblin.runtime.commit; import java.io.IOException; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.testng.Assert; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import gobblin.commit.CommitSequence; import gobblin.commit.FsRenameCommitStep; import gobblin.configuration.ConfigurationKeys; import gobblin.configuration.State; import gobblin.runtime.JobState.DatasetState; /** * Tests for {@link CommitSequence}. * * @author Ziyang Liu */ @Test(groups = { "gobblin.runtime.commit" }) public class CommitSequenceTest { private static final String ROOT_DIR = "commit-sequence-test"; private FileSystem fs; private CommitSequence sequence; @BeforeClass public void setUp() throws IOException { this.fs = FileSystem.getLocal(new Configuration()); this.fs.delete(new Path(ROOT_DIR), true); Path storeRootDir = new Path(ROOT_DIR, "store"); Path dir1 = new Path(ROOT_DIR, "dir1"); Path dir2 = new Path(ROOT_DIR, "dir2"); this.fs.mkdirs(dir1); this.fs.mkdirs(dir2); Path src1 = new Path(dir1, "file1"); Path src2 = new Path(dir2, "file2"); Path dst1 = new Path(dir2, "file1"); Path dst2 = new Path(dir1, "file2"); this.fs.createNewFile(src1); this.fs.createNewFile(src2); DatasetState ds = new DatasetState("job-name", "job-id"); ds.setDatasetUrn("urn"); ds.setNoJobFailure(); State state = new State(); state.setProp(ConfigurationKeys.STATE_STORE_ROOT_DIR_KEY, storeRootDir.toString()); this.sequence = new CommitSequence.Builder().withJobName("testjob").withDatasetUrn("testurn") .beginStep(FsRenameCommitStep.Builder.class).from(src1).to(dst1).withProps(state).endStep() .beginStep(FsRenameCommitStep.Builder.class).from(src2).to(dst2).withProps(state).endStep() .beginStep(DatasetStateCommitStep.Builder.class).withDatasetUrn("urn").withDatasetState(ds).withProps(state) .endStep().build(); } @AfterClass public void tearDown() throws IOException { this.fs.delete(new Path(ROOT_DIR), true); } @Test public void testExecute() throws IOException { this.sequence.execute(); Assert.assertTrue(this.fs.exists(new Path(ROOT_DIR, "dir1/file2"))); Assert.assertTrue(this.fs.exists(new Path(ROOT_DIR, "dir2/file1"))); Assert.assertTrue(this.fs.exists(new Path(ROOT_DIR, "store/job-name/urn-job-id.jst"))); Assert.assertTrue(this.fs.exists(new Path(ROOT_DIR, "store/job-name/urn-current.jst"))); } }
apache-2.0
dgutierr/uberfire-extensions
uberfire-wires/uberfire-wires-bayesian-network/uberfire-wires-bayesian-network-client/src/main/java/org/uberfire/ext/wires/bayesian/network/client/factory/BaseFactory.java
2954
/* * Copyright 2015 JBoss, by Red Hat, 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.uberfire.ext.wires.bayesian.network.client.factory; import com.ait.lienzo.client.core.shape.Rectangle; import com.ait.lienzo.client.core.shape.Shape; import com.ait.lienzo.client.core.shape.Text; import com.ait.lienzo.shared.core.types.Color; import org.uberfire.ext.wires.core.client.util.ShapesUtils; public class BaseFactory { private static final String defaultFillColor = ShapesUtils.RGB_FILL_SHAPE; private static final String defaultBorderColor = ShapesUtils.RGB_STROKE_SHAPE; protected void setAttributes( final Shape<?> shape, final String fillColor, final double x, final double y, final String borderColor ) { String fill = ( fillColor == null ) ? defaultFillColor : fillColor; String border = ( borderColor == null ) ? defaultBorderColor : borderColor; shape.setX( x ).setY( y ).setStrokeColor( border ).setStrokeWidth( ShapesUtils.RGB_STROKE_WIDTH_SHAPE ).setFillColor( fill ).setDraggable( false ); } protected Rectangle drawComponent( final String color, final int positionX, final int positionY, final int width, final int height, String borderColor, double radius ) { if ( borderColor == null ) { borderColor = Color.rgbToBrowserHexColor( 0, 0, 0 ); } Rectangle component = new Rectangle( width, height ); setAttributes( component, color, positionX, positionY, borderColor ); component.setCornerRadius( radius ); return component; } protected Text drawText( final String description, final int fontSize, final int positionX, final int positionY ) { return new Text( description, "Times", fontSize ).setX( positionX ).setY( positionY ); } }
apache-2.0
siosio/intellij-community
platform/lang-impl/src/com/intellij/codeInsight/template/impl/LiveTemplateLookupActionProvider.java
2424
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.codeInsight.template.impl; import com.intellij.codeInsight.CodeInsightBundle; import com.intellij.codeInsight.lookup.Lookup; import com.intellij.codeInsight.lookup.LookupActionProvider; import com.intellij.codeInsight.lookup.LookupElement; import com.intellij.codeInsight.lookup.LookupElementAction; import com.intellij.icons.AllIcons; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.options.ShowSettingsUtil; import com.intellij.openapi.project.Project; import com.intellij.util.Consumer; import com.intellij.util.PlatformIcons; /** * @author peter */ public class LiveTemplateLookupActionProvider implements LookupActionProvider { @Override public void fillActions(LookupElement element, final Lookup lookup, Consumer<LookupElementAction> consumer) { if (element instanceof LiveTemplateLookupElementImpl) { final TemplateImpl template = ((LiveTemplateLookupElementImpl)element).getTemplate(); final TemplateImpl templateFromSettings = TemplateSettings.getInstance().getTemplate(template.getKey(), template.getGroupName()); if (templateFromSettings != null) { consumer.consume(new LookupElementAction(PlatformIcons.EDIT, CodeInsightBundle.message("action.text.edit.live.template.settings")) { @Override public Result performLookupAction() { final Project project = lookup.getProject(); ApplicationManager.getApplication().invokeLater(() -> { if (project.isDisposed()) return; final LiveTemplatesConfigurable configurable = new LiveTemplatesConfigurable(); ShowSettingsUtil.getInstance().editConfigurable(project, configurable, () -> configurable.getTemplateListPanel().editTemplate(template)); }); return Result.HIDE_LOOKUP; } }); consumer.consume(new LookupElementAction(AllIcons.Actions.Cancel, CodeInsightBundle.message("action.text.disable.live.template", template.getKey())) { @Override public Result performLookupAction() { ApplicationManager.getApplication().invokeLater(() -> templateFromSettings.setDeactivated(true)); return Result.HIDE_LOOKUP; } }); } } } }
apache-2.0
wangcy6/storm_app
frame/kafka-0.11.0/kafka-0.11.0.1-src/connect/file/src/main/java/org/apache/kafka/connect/file/FileStreamSinkConnector.java
2629
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.kafka.connect.file; import org.apache.kafka.common.config.ConfigDef; import org.apache.kafka.common.config.ConfigDef.Importance; import org.apache.kafka.common.config.ConfigDef.Type; import org.apache.kafka.common.utils.AppInfoParser; import org.apache.kafka.connect.connector.Task; import org.apache.kafka.connect.sink.SinkConnector; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * Very simple connector that works with the console. This connector supports both source and * sink modes via its 'mode' setting. */ public class FileStreamSinkConnector extends SinkConnector { public static final String FILE_CONFIG = "file"; private static final ConfigDef CONFIG_DEF = new ConfigDef() .define(FILE_CONFIG, Type.STRING, Importance.HIGH, "Destination filename."); private String filename; @Override public String version() { return AppInfoParser.getVersion(); } @Override public void start(Map<String, String> props) { filename = props.get(FILE_CONFIG); } @Override public Class<? extends Task> taskClass() { return FileStreamSinkTask.class; } @Override public List<Map<String, String>> taskConfigs(int maxTasks) { ArrayList<Map<String, String>> configs = new ArrayList<>(); for (int i = 0; i < maxTasks; i++) { Map<String, String> config = new HashMap<>(); if (filename != null) config.put(FILE_CONFIG, filename); configs.add(config); } return configs; } @Override public void stop() { // Nothing to do since FileStreamSinkConnector has no background monitoring. } @Override public ConfigDef config() { return CONFIG_DEF; } }
apache-2.0
alvin319/CarnotKE
jyhton/installer/src/java/org/python/util/install/driver/NormalVerifier.java
5129
package org.python.util.install.driver; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.io.PrintStream; import java.nio.file.Paths; import java.util.Arrays; import java.util.List; import java.util.StringTokenizer; import org.python.util.install.ChildProcess; import org.python.util.install.FileHelper; public class NormalVerifier implements Verifier { protected static final String AUTOTEST_PY = "autotest.py"; private static final String BIN = "bin"; private static final String JYTHON_UP = "jython up and running!"; private static final String JYTHON = "jython"; private static final String VERIFYING = "verifying"; private File _targetDir; public void setTargetDir(File targetDir) { _targetDir = targetDir; } public File getTargetDir() { return _targetDir; } public void verify() throws DriverException { createTestScriptFile(); // create the test .py script // verify the most simple start of jython works verifyStart(getSimpleCommand()); } /** * Will be overridden in subclass StandaloneVerifier * * @return the command array to start jython with * @throws DriverException * if there was a problem getting the target directory path */ protected String[] getSimpleCommand() throws DriverException { return new String[] { Paths.get(BIN).resolve(JYTHON).toString(), _targetDir.toPath().resolve(AUTOTEST_PY).toString() }; } /** * @return The directory where to create the shell script test command in. * * @throws DriverException */ protected final File getShellScriptTestCommandDir() throws DriverException { return _targetDir.toPath().resolve(BIN).toFile(); } /** * Internal method verifying a jython-starting command by capturing the output * * @param command * * @throws DriverException */ private void verifyStart(String[] command) throws DriverException { ChildProcess p = new ChildProcess(command); p.setDebug(true); p.setCWD(_targetDir.toPath()); System.err.println("Verify start: command=" + Arrays.toString(command) + ", cwd=" + p.getCWD()); int exitValue = p.run(); // if (exitValue != 0) { // throw new DriverException("start of jython failed\n" // + "command: " + Arrays.toString(command) // + "\ncwd: " + p.getCWD() // + "\nexit value: " + exitValue // + "\nstdout: " + p.getStdout() // + "\nstderr: " + p.getStderr()); // } verifyError(p.getStderr()); verifyOutput(p.getStdout()); } /** * Will be overridden in subclass StandaloneVerifier * * @return <code>true</code> if the jython start shell script should be verified (using * different options) */ protected boolean doShellScriptTests() { return true; } private void verifyError(List<String> stderr) throws DriverException { for (String line : stderr) { if (isExpectedError(line)) { feedback(line); } else { throw new DriverException(stderr.toString()); } } } private boolean isExpectedError(String line) { boolean expected = false; if (line.startsWith("*sys-package-mgr*")) { expected = true; } return expected; } private void verifyOutput(List<String> stdout) throws DriverException { boolean started = false; for (String line : stdout) { if (isExpectedOutput(line)) { feedback(line); if (line.startsWith(JYTHON_UP)) { started = true; } } else { throw new DriverException(stdout.toString()); } } if (!started) { throw new DriverException("start of jython failed:\n" + stdout.toString()); } } private boolean isExpectedOutput(String line) { boolean expected = false; if (line.startsWith("[ChildProcess]") || line.startsWith(VERIFYING)) { expected = true; } else if (line.startsWith(JYTHON_UP)) { expected = true; } return expected; } private String getTestScript() { StringBuilder b = new StringBuilder(80); b.append("import sys\n"); b.append("import os\n"); b.append("print '"); b.append(JYTHON_UP); b.append("'\n"); return b.toString(); } private void createTestScriptFile() throws DriverException { File file = new File(getTargetDir(), AUTOTEST_PY); try { FileHelper.write(file, getTestScript()); } catch (IOException ioe) { throw new DriverException(ioe); } } private void feedback(String line) { System.out.println("feedback " + line); } }
apache-2.0
abimarank/product-apim
integration-tests/src/main/java/org/wso2/carbon/apimgt/rest/integration/tests/model/APICorsConfiguration.java
7272
/* * WSO2 API Manager - Publisher API * This specifies a **RESTful API** for WSO2 **API Manager** - Publisher. Please see [full swagger definition](https://raw.githubusercontent.com/wso2/carbon-apimgt/v6.0.4/components/apimgt/org.wso2.carbon.apimgt.rest.api.publisher/src/main/resources/publisher-api.yaml) of the API which is written using [swagger 2.0](http://swagger.io/) specification. * * OpenAPI spec version: v1.0.0 * Contact: architecture@wso2.com * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. */ package org.wso2.carbon.apimgt.rest.integration.tests.model; import java.util.Objects; import com.google.gson.annotations.SerializedName; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.util.ArrayList; import java.util.List; /** * CORS configuration for the API */ @ApiModel(description = "CORS configuration for the API ") @javax.annotation.Generated(value = "io.swagger.codegen.languages.JavaClientCodegen", date = "2017-05-09T06:36:48.873Z") public class APICorsConfiguration { @SerializedName("corsConfigurationEnabled") private Boolean corsConfigurationEnabled = false; @SerializedName("accessControlAllowOrigins") private List<String> accessControlAllowOrigins = new ArrayList<String>(); @SerializedName("accessControlAllowCredentials") private Boolean accessControlAllowCredentials = false; @SerializedName("accessControlAllowHeaders") private List<String> accessControlAllowHeaders = new ArrayList<String>(); @SerializedName("accessControlAllowMethods") private List<String> accessControlAllowMethods = new ArrayList<String>(); public APICorsConfiguration corsConfigurationEnabled(Boolean corsConfigurationEnabled) { this.corsConfigurationEnabled = corsConfigurationEnabled; return this; } /** * Get corsConfigurationEnabled * @return corsConfigurationEnabled **/ @ApiModelProperty(example = "null", value = "") public Boolean getCorsConfigurationEnabled() { return corsConfigurationEnabled; } public void setCorsConfigurationEnabled(Boolean corsConfigurationEnabled) { this.corsConfigurationEnabled = corsConfigurationEnabled; } public APICorsConfiguration accessControlAllowOrigins(List<String> accessControlAllowOrigins) { this.accessControlAllowOrigins = accessControlAllowOrigins; return this; } public APICorsConfiguration addAccessControlAllowOriginsItem(String accessControlAllowOriginsItem) { this.accessControlAllowOrigins.add(accessControlAllowOriginsItem); return this; } /** * Get accessControlAllowOrigins * @return accessControlAllowOrigins **/ @ApiModelProperty(example = "null", value = "") public List<String> getAccessControlAllowOrigins() { return accessControlAllowOrigins; } public void setAccessControlAllowOrigins(List<String> accessControlAllowOrigins) { this.accessControlAllowOrigins = accessControlAllowOrigins; } public APICorsConfiguration accessControlAllowCredentials(Boolean accessControlAllowCredentials) { this.accessControlAllowCredentials = accessControlAllowCredentials; return this; } /** * Get accessControlAllowCredentials * @return accessControlAllowCredentials **/ @ApiModelProperty(example = "null", value = "") public Boolean getAccessControlAllowCredentials() { return accessControlAllowCredentials; } public void setAccessControlAllowCredentials(Boolean accessControlAllowCredentials) { this.accessControlAllowCredentials = accessControlAllowCredentials; } public APICorsConfiguration accessControlAllowHeaders(List<String> accessControlAllowHeaders) { this.accessControlAllowHeaders = accessControlAllowHeaders; return this; } public APICorsConfiguration addAccessControlAllowHeadersItem(String accessControlAllowHeadersItem) { this.accessControlAllowHeaders.add(accessControlAllowHeadersItem); return this; } /** * Get accessControlAllowHeaders * @return accessControlAllowHeaders **/ @ApiModelProperty(example = "null", value = "") public List<String> getAccessControlAllowHeaders() { return accessControlAllowHeaders; } public void setAccessControlAllowHeaders(List<String> accessControlAllowHeaders) { this.accessControlAllowHeaders = accessControlAllowHeaders; } public APICorsConfiguration accessControlAllowMethods(List<String> accessControlAllowMethods) { this.accessControlAllowMethods = accessControlAllowMethods; return this; } public APICorsConfiguration addAccessControlAllowMethodsItem(String accessControlAllowMethodsItem) { this.accessControlAllowMethods.add(accessControlAllowMethodsItem); return this; } /** * Get accessControlAllowMethods * @return accessControlAllowMethods **/ @ApiModelProperty(example = "null", value = "") public List<String> getAccessControlAllowMethods() { return accessControlAllowMethods; } public void setAccessControlAllowMethods(List<String> accessControlAllowMethods) { this.accessControlAllowMethods = accessControlAllowMethods; } @Override public boolean equals(java.lang.Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } APICorsConfiguration apICorsConfiguration = (APICorsConfiguration) o; return Objects.equals(this.corsConfigurationEnabled, apICorsConfiguration.corsConfigurationEnabled) && Objects.equals(this.accessControlAllowOrigins, apICorsConfiguration.accessControlAllowOrigins) && Objects.equals(this.accessControlAllowCredentials, apICorsConfiguration.accessControlAllowCredentials) && Objects.equals(this.accessControlAllowHeaders, apICorsConfiguration.accessControlAllowHeaders) && Objects.equals(this.accessControlAllowMethods, apICorsConfiguration.accessControlAllowMethods); } @Override public int hashCode() { return Objects.hash(corsConfigurationEnabled, accessControlAllowOrigins, accessControlAllowCredentials, accessControlAllowHeaders, accessControlAllowMethods); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class APICorsConfiguration {\n"); sb.append(" corsConfigurationEnabled: ").append(toIndentedString(corsConfigurationEnabled)).append("\n"); sb.append(" accessControlAllowOrigins: ").append(toIndentedString(accessControlAllowOrigins)).append("\n"); sb.append(" accessControlAllowCredentials: ").append(toIndentedString(accessControlAllowCredentials)).append("\n"); sb.append(" accessControlAllowHeaders: ").append(toIndentedString(accessControlAllowHeaders)).append("\n"); sb.append(" accessControlAllowMethods: ").append(toIndentedString(accessControlAllowMethods)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
apache-2.0
nikhilvibhav/camel
core/camel-base-engine/src/main/java/org/apache/camel/impl/engine/DefaultValidatorRegistry.java
2457
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.camel.impl.engine; import org.apache.camel.CamelContext; import org.apache.camel.spi.DataType; import org.apache.camel.spi.Validator; import org.apache.camel.spi.ValidatorRegistry; import org.apache.camel.support.CamelContextHelper; import org.apache.camel.support.service.ServiceHelper; import org.apache.camel.util.ObjectHelper; /** * Default implementation of {@link org.apache.camel.spi.ValidatorRegistry}. */ public class DefaultValidatorRegistry extends AbstractDynamicRegistry<ValidatorKey, Validator> implements ValidatorRegistry<ValidatorKey> { public DefaultValidatorRegistry(CamelContext context) { super(context, CamelContextHelper.getMaximumValidatorCacheSize(context)); } @Override public Validator resolveValidator(ValidatorKey key) { Validator answer = get(key); if (answer == null && ObjectHelper.isNotEmpty(key.getType().getName())) { answer = get(new ValidatorKey(new DataType(key.getType().getModel()))); } return answer; } @Override public boolean isStatic(DataType type) { return isStatic(new ValidatorKey(type)); } @Override public boolean isDynamic(DataType type) { return isDynamic(new ValidatorKey(type)); } @Override public String toString() { return "ValidatorRegistry for " + context.getName() + " [capacity: " + maxCacheSize + "]"; } @Override public Validator put(ValidatorKey key, Validator obj) { // ensure validator is started before its being used ServiceHelper.startService(obj); return super.put(key, obj); } }
apache-2.0
fogbeam/Heceta_nutch
src/plugin/protocol-ftp/src/java/org/apache/nutch/protocol/ftp/FtpRobotRulesParser.java
3708
/** * 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.nutch.protocol.ftp; import java.net.URL; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.io.Text; import org.apache.nutch.crawl.CrawlDatum; import org.apache.nutch.protocol.Protocol; import org.apache.nutch.protocol.ProtocolOutput; import org.apache.nutch.protocol.ProtocolStatus; import org.apache.nutch.protocol.RobotRulesParser; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import crawlercommons.robots.BaseRobotRules; import crawlercommons.robots.SimpleRobotRules; /** * This class is used for parsing robots for urls belonging to FTP protocol. * It extends the generic {@link RobotRulesParser} class and contains * Ftp protocol specific implementation for obtaining the robots file. */ public class FtpRobotRulesParser extends RobotRulesParser { private static final String CONTENT_TYPE = "text/plain"; public static final Logger LOG = LoggerFactory.getLogger(FtpRobotRulesParser.class); FtpRobotRulesParser() { } public FtpRobotRulesParser(Configuration conf) { super(conf); } /** * The hosts for which the caching of robots rules is yet to be done, * it sends a Ftp request to the host corresponding to the {@link URL} * passed, gets robots file, parses the rules and caches the rules object * to avoid re-work in future. * * @param ftp The {@link Protocol} object * @param url URL * * @return robotRules A {@link BaseRobotRules} object for the rules */ public BaseRobotRules getRobotRulesSet(Protocol ftp, URL url) { String protocol = url.getProtocol().toLowerCase(); // normalize to lower case String host = url.getHost().toLowerCase(); // normalize to lower case BaseRobotRules robotRules = (SimpleRobotRules) CACHE.get(protocol + ":" + host); boolean cacheRule = true; if (robotRules == null) { // cache miss if (LOG.isTraceEnabled()) LOG.trace("cache miss " + url); try { Text robotsUrl = new Text(new URL(url, "/robots.txt").toString()); ProtocolOutput output = ((Ftp)ftp).getProtocolOutput(robotsUrl, new CrawlDatum()); ProtocolStatus status = output.getStatus(); if (status.getCode() == ProtocolStatus.SUCCESS) { robotRules = parseRules(url.toString(), output.getContent().getContent(), CONTENT_TYPE, agentNames); } else { robotRules = EMPTY_RULES; // use default rules } } catch (Throwable t) { if (LOG.isInfoEnabled()) { LOG.info("Couldn't get robots.txt for " + url + ": " + t.toString()); } cacheRule = false; robotRules = EMPTY_RULES; } if (cacheRule) CACHE.put(protocol + ":" + host, robotRules); // cache rules for host } return robotRules; } }
apache-2.0
samaitra/ignite
modules/indexing/src/main/java/org/apache/ignite/spi/systemview/view/SqlViewView.java
1673
/* * 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.ignite.spi.systemview.view; import org.apache.ignite.internal.managers.systemview.walker.Order; import org.apache.ignite.internal.processors.query.QueryUtils; import org.apache.ignite.internal.processors.query.h2.sys.view.SqlSystemView; /** * Sql view representation for a {@link SystemView}. */ public class SqlViewView { /** Sql system view. */ private final SqlSystemView view; /** @param view Sql system view. */ public SqlViewView(SqlSystemView view) { this.view = view; } /** View name. */ @Order public String name() { return view.getTableName(); } /** View description. */ @Order(2) public String description() { return view.getDescription(); } /** View schema. */ @Order(1) public String schema() { return QueryUtils.SCHEMA_SYS; } }
apache-2.0
rhusar/undertow
core/src/main/java/io/undertow/protocols/ssl/UndertowSslConnection.java
5435
/* * JBoss, Home of Professional Open Source. * Copyright 2014 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 io.undertow.protocols.ssl; import org.xnio.ChannelListener; import org.xnio.ChannelListeners; import org.xnio.Option; import org.xnio.Options; import io.undertow.connector.ByteBufferPool; import org.xnio.SslClientAuthMode; import org.xnio.StreamConnection; import org.xnio.ssl.SslConnection; import javax.net.ssl.SSLEngine; import javax.net.ssl.SSLSession; import java.io.IOException; import java.net.SocketAddress; import java.util.Set; import java.util.concurrent.Executor; /** * @author Stuart Douglas */ class UndertowSslConnection extends SslConnection { private static final Set<Option<?>> SUPPORTED_OPTIONS = Option.setBuilder().add(Options.SECURE, Options.SSL_CLIENT_AUTH_MODE).create(); private final StreamConnection delegate; private final SslConduit sslConduit; private final ChannelListener.SimpleSetter<SslConnection> handshakeSetter = new ChannelListener.SimpleSetter<>(); private final SSLEngine engine; /** * Construct a new instance. * * @param delegate the underlying connection */ UndertowSslConnection(StreamConnection delegate, SSLEngine engine, ByteBufferPool bufferPool, Executor delegatedTaskExecutor) { super(delegate.getIoThread()); this.delegate = delegate; this.engine = engine; sslConduit = new SslConduit(this, delegate, engine, delegatedTaskExecutor, bufferPool, new HandshakeCallback()); setSourceConduit(sslConduit); setSinkConduit(sslConduit); } @Override public void startHandshake() throws IOException { sslConduit.startHandshake(); } @Override public SSLSession getSslSession() { return sslConduit.getSslSession(); } @Override public ChannelListener.Setter<? extends SslConnection> getHandshakeSetter() { return handshakeSetter; } @Override protected void notifyWriteClosed() { sslConduit.notifyWriteClosed(); } @Override protected void notifyReadClosed() { sslConduit.notifyReadClosed(); } @Override public SocketAddress getPeerAddress() { return delegate.getPeerAddress(); } @Override public SocketAddress getLocalAddress() { return delegate.getLocalAddress(); } public SSLEngine getSSLEngine() { return sslConduit.getSSLEngine(); } SslConduit getSslConduit() { return sslConduit; } /** {@inheritDoc} */ @Override public <T> T setOption(final Option<T> option, final T value) throws IllegalArgumentException, IOException { if (option == Options.SSL_CLIENT_AUTH_MODE) { try { return option.cast(engine.getNeedClientAuth() ? SslClientAuthMode.REQUIRED : engine.getWantClientAuth() ? SslClientAuthMode.REQUESTED : SslClientAuthMode.NOT_REQUESTED); } finally { engine.setWantClientAuth(false); engine.setNeedClientAuth(false); if (value == SslClientAuthMode.REQUESTED) { engine.setWantClientAuth(true); } else if (value == SslClientAuthMode.REQUIRED) { engine.setNeedClientAuth(true); } } } else if (option == Options.SECURE) { throw new IllegalArgumentException(); } else { return delegate.setOption(option, value); } } /** {@inheritDoc} */ @Override public <T> T getOption(final Option<T> option) throws IOException { if (option == Options.SSL_CLIENT_AUTH_MODE) { return option.cast(engine.getNeedClientAuth() ? SslClientAuthMode.REQUIRED : engine.getWantClientAuth() ? SslClientAuthMode.REQUESTED : SslClientAuthMode.NOT_REQUESTED); } else { return option == Options.SECURE ? (T)Boolean.TRUE : delegate.getOption(option); } } /** {@inheritDoc} */ @Override public boolean supportsOption(final Option<?> option) { return SUPPORTED_OPTIONS.contains(option) || delegate.supportsOption(option); } @Override protected boolean readClosed() { return super.readClosed(); } @Override protected boolean writeClosed() { return super.writeClosed(); } protected void closeAction() { sslConduit.close(); } private final class HandshakeCallback implements Runnable { @Override public void run() { final ChannelListener<? super SslConnection> listener = handshakeSetter.get(); if (listener == null) { return; } ChannelListeners.<SslConnection>invokeChannelListener(UndertowSslConnection.this, listener); } } }
apache-2.0
dgutierr/uberfire-extensions
uberfire-wires/uberfire-wires-bpmn/uberfire-wires-bpmn-client/src/main/java/org/uberfire/ext/wires/bpmn/client/commands/impl/BatchCommand.java
2980
/* * Copyright 2015 JBoss, by Red Hat, 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.uberfire.ext.wires.bpmn.client.commands.impl; import java.util.Arrays; import java.util.List; import java.util.Stack; import org.uberfire.commons.validation.PortablePreconditions; import org.uberfire.ext.wires.bpmn.client.commands.Command; import org.uberfire.ext.wires.bpmn.client.commands.ResultType; import org.uberfire.ext.wires.bpmn.client.commands.Results; import org.uberfire.ext.wires.bpmn.client.rules.RuleManager; /** * A batch of Commands to be executed as an atomic unit */ public class BatchCommand implements Command { private List<Command> commands; public BatchCommand( final List<Command> commands ) { this.commands = PortablePreconditions.checkNotNull( "commands", commands ); } public BatchCommand( final Command... commands ) { this.commands = Arrays.asList( PortablePreconditions.checkNotNull( "commands", commands ) ); } @Override public Results apply( final RuleManager ruleManager ) { final Results results = new DefaultResultsImpl(); final Stack<Command> appliedCommands = new Stack<Command>(); for ( Command command : commands ) { results.getMessages().addAll( command.apply( ruleManager ).getMessages() ); if ( results.contains( ResultType.ERROR ) ) { for ( Command undo : appliedCommands ) { undo.undo( ruleManager ); } return results; } else { appliedCommands.add( command ); } } return results; } @Override public Results undo( final RuleManager ruleManager ) { final Results results = new DefaultResultsImpl(); final Stack<Command> appliedCommands = new Stack<Command>(); for ( Command command : commands ) { results.getMessages().addAll( command.undo( ruleManager ).getMessages() ); if ( results.contains( ResultType.ERROR ) ) { for ( Command cmd : appliedCommands ) { cmd.apply( ruleManager ); } return results; } else { appliedCommands.add( command ); } } return results; } }
apache-2.0
jacksonpradolima/pitest
pitest/src/test/java/org/pitest/mutationtest/MutableIncrement.java
735
/* * Copyright 2010 Henry Coles * * 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.pitest.mutationtest; public class MutableIncrement { public static int increment() { int i = 42; i++; return i; } }
apache-2.0
aehlig/bazel
src/test/java/com/google/devtools/build/android/desugar/testdata/InterfaceWithLambda.java
1029
// Copyright 2016 The Bazel Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.devtools.build.android.desugar.testdata; import com.google.common.collect.ImmutableList; import java.util.List; import java.util.stream.Collectors; public interface InterfaceWithLambda { String ZERO = String.valueOf(0); List<String> DIGITS = ImmutableList.of(0, 1) .stream() .map(i -> i == 0 ? ZERO : String.valueOf(i)) .collect(Collectors.toList()); }
apache-2.0
wwjiang007/alluxio
core/common/src/main/java/alluxio/wire/FileSystemCommandOptions.java
1198
/* * The Alluxio Open Foundation licenses this work under the Apache License, version 2.0 * (the "License"). You may not use this work except in compliance with the License, which is * available at www.apache.org/licenses/LICENSE-2.0 * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, * either express or implied, as more fully set forth in the License. * * See the NOTICE file distributed with this work for information regarding copyright ownership. */ package alluxio.wire; /** * Class to represent {@link FileSystemCommand} options. */ public final class FileSystemCommandOptions { private PersistCommandOptions mPersistCommandOptions; /** * Creates a new instance of {@link FileSystemCommandOptions}. */ public FileSystemCommandOptions() {} /** * @return the persist options */ public PersistCommandOptions getPersistOptions() { return mPersistCommandOptions; } /** * Set the persist options. * * @param persistCommandOptions the persist options */ public void setPersistOptions(PersistCommandOptions persistCommandOptions) { mPersistCommandOptions = persistCommandOptions; } }
apache-2.0
sdwilsh/buck
src/com/facebook/buck/cxx/ClangCompiler.java
1330
/* * Copyright 2015-present Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. You may obtain * a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package com.facebook.buck.cxx; import com.facebook.buck.rules.Tool; import com.google.common.collect.ImmutableList; import java.util.Optional; public class ClangCompiler extends DefaultCompiler { public ClangCompiler(Tool tool) { super(tool); } @Override public Optional<ImmutableList<String>> debugCompilationDirFlags(String debugCompilationDir) { return Optional.of( ImmutableList.of("-Xclang", "-fdebug-compilation-dir", "-Xclang", debugCompilationDir)); } @Override public Optional<ImmutableList<String>> getFlagsForColorDiagnostics() { return Optional.of(ImmutableList.of("-fcolor-diagnostics")); } @Override public boolean isArgFileSupported() { return true; } }
apache-2.0
bcsphere/bcexplorer
plugins/org/src/android/org/bcsphere/bluetooth/BCBluetooth.java
15604
/* Copyright 2013-2014, JUMA Technology 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.bcsphere.bluetooth; import java.util.HashMap; import java.util.Iterator; import java.util.Set; import org.apache.cordova.CallbackContext; import org.apache.cordova.CordovaInterface; import org.apache.cordova.CordovaPlugin; import org.apache.cordova.CordovaWebView; import org.apache.cordova.PluginResult; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothDevice; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.SharedPreferences; import android.util.Log; import org.bcsphere.bluetooth.tools.BluetoothDetection; import org.bcsphere.bluetooth.tools.Tools; public class BCBluetooth extends CordovaPlugin { public Context myContext = null; private SharedPreferences sp; private boolean isSetContext = true; private IBluetooth bluetoothAPI = null; private String versionOfAPI; private CallbackContext newadvpacketContext; private CallbackContext disconnectContext; private BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); private static final String TAG = "BCBluetooth"; //classical interface relative data structure public HashMap<String, BluetoothSerialService> classicalServices = new HashMap<String, BluetoothSerialService>(); //when the accept services construct a connection , the service will remove from this map & append into classicalServices map for read/write interface call public HashMap<String, BluetoothSerialService> acceptServices = new HashMap<String, BluetoothSerialService>(); public BCBluetooth() { } @Override public void initialize(CordovaInterface cordova, CordovaWebView webView) { super.initialize(cordova, webView); myContext = this.webView.getContext(); IntentFilter intentFilter = new IntentFilter(); intentFilter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED); intentFilter.addAction(BluetoothDevice.ACTION_FOUND); myContext.registerReceiver(receiver, intentFilter); sp = myContext.getSharedPreferences("VERSION_OF_API", 1); BluetoothDetection.detectionBluetoothAPI(myContext); try { if ((versionOfAPI = sp.getString("API", "no_google")) .equals("google")) { bluetoothAPI = (IBluetooth) Class.forName( "org.bcsphere.bluetooth.BluetoothG43plus") .newInstance(); } else if ((versionOfAPI = sp.getString("API", "no_samsung")) .equals("samsung")) { bluetoothAPI = (IBluetooth) Class.forName( "org.bcsphere.bluetooth.BluetoothSam42").newInstance(); } else if ((versionOfAPI = sp.getString("API", "no_htc")) .equals("htc")) { bluetoothAPI = (IBluetooth) Class.forName( "org.bcsphere.bluetooth.BluetoothHTC41").newInstance(); } } catch (Exception e) { e.printStackTrace(); } } @Override public boolean execute(final String action, final JSONArray json, final CallbackContext callbackContext) throws JSONException { try { if(bluetoothAPI != null){ if (isSetContext) { bluetoothAPI.setContext(myContext); isSetContext = false; } if (action.equals("getCharacteristics")) { bluetoothAPI.getCharacteristics(json, callbackContext); } else if (action.equals("getDescriptors")) { bluetoothAPI.getDescriptors(json, callbackContext); } else if (action.equals("removeServices")) { bluetoothAPI.removeServices(json, callbackContext); } if (action.equals("stopScan")) { bluetoothAPI.stopScan(json, callbackContext); } else if (action.equals("getConnectedDevices")) { bluetoothAPI.getConnectedDevices(json, callbackContext); } cordova.getThreadPool().execute(new Runnable() { @Override public void run() { if (action.equals("startScan")) { bluetoothAPI.startScan(json, callbackContext); } else if (action.equals("connect")) { bluetoothAPI.connect(json, callbackContext); } else if (action.equals("disconnect")) { bluetoothAPI.disconnect(json, callbackContext); } else if (action.equals("getServices")) { bluetoothAPI.getServices(json, callbackContext); } else if (action.equals("writeValue")) { bluetoothAPI.writeValue(json, callbackContext); } else if (action.equals("readValue")) { bluetoothAPI.readValue(json, callbackContext); } else if (action.equals("setNotification")) { bluetoothAPI.setNotification(json, callbackContext); } else if (action.equals("getDeviceAllData")) { bluetoothAPI.getDeviceAllData(json, callbackContext); } else if (action.equals("addServices")) { bluetoothAPI.addServices(json, callbackContext); } else if (action.equals("getRSSI")) { bluetoothAPI.getRSSI(json, callbackContext); } } }); } if (action.equals("addEventListener")) { String eventName = Tools.getData(json, Tools.EVENT_NAME); if (eventName.equals("newadvpacket") ) { newadvpacketContext = callbackContext; }else if(eventName.equals("disconnect")){ disconnectContext = callbackContext; } if(bluetoothAPI != null){ bluetoothAPI.addEventListener(json, callbackContext); } return true; } if (action.equals("getEnvironment")) { JSONObject jo = new JSONObject(); Tools.addProperty(jo, "appID", "com.test.yourappid"); Tools.addProperty(jo, "deviceAddress", "N/A"); Tools.addProperty(jo, "api", versionOfAPI); callbackContext.success(jo); return true; } if (action.equals("openBluetooth")) { if(!bluetoothAdapter.isEnabled()){ bluetoothAdapter.enable(); } Tools.sendSuccessMsg(callbackContext); return true; } if (action.equals("closeBluetooth")) { if(bluetoothAdapter.isEnabled()){ bluetoothAdapter.disable(); } Tools.sendSuccessMsg(callbackContext); return true; } if (action.equals("getBluetoothState")) { Log.i(TAG, "getBluetoothState"); JSONObject obj = new JSONObject(); if (bluetoothAdapter.isEnabled()) { Tools.addProperty(obj, Tools.BLUETOOTH_STATE, Tools.IS_TRUE); callbackContext.success(obj); }else { Tools.addProperty(obj, Tools.BLUETOOTH_STATE, Tools.IS_FALSE); callbackContext.success(obj); } return true; } if(action.equals("startClassicalScan")){ Log.i(TAG,"startClassicalScan"); if(bluetoothAdapter.isEnabled()){ if(bluetoothAdapter.startDiscovery()){ callbackContext.success(); }else{ callbackContext.error("start classical scan error!"); } }else{ callbackContext.error("your bluetooth is not open!"); } } if(action.equals("stopClassicalScan")){ Log.i(TAG,"stopClassicalScan"); if(bluetoothAdapter.isEnabled()){ if(bluetoothAdapter.cancelDiscovery()){ callbackContext.success(); }else{ callbackContext.error("stop classical scan error!"); } }else{ callbackContext.error("your bluetooth is not open!"); } } if(action.equals("rfcommConnect")){ String deviceAddress = Tools.getData(json, Tools.DEVICE_ADDRESS); String securestr = Tools.getData(json, Tools.SECURE); String uuidstr = Tools.getData(json, Tools.UUID); boolean secure = false; if(securestr != null && securestr.equals("true")){ secure = true; } Log.i(TAG,"connect to "+deviceAddress); BluetoothDevice device = bluetoothAdapter.getRemoteDevice(deviceAddress); BluetoothSerialService classicalService = classicalServices.get(deviceAddress); if(device != null && classicalService == null){ classicalService = new BluetoothSerialService(); classicalService.disconnectCallback = disconnectContext; classicalServices.put(deviceAddress, classicalService); } if (device != null) { classicalService.connectCallback = callbackContext; classicalService.connect(device,uuidstr,secure); } else { callbackContext.error("Could not connect to " + deviceAddress); } } if (action.equals("rfcommDisconnect")) { String deviceAddress = Tools.getData(json, Tools.DEVICE_ADDRESS); BluetoothSerialService service = classicalServices.get(deviceAddress); if(service != null){ service.connectCallback = null; service.stop(); classicalServices.remove(deviceAddress); callbackContext.success(); }else{ callbackContext.error("Could not disconnect to " + deviceAddress); } } if(action.equals("rfcommListen")){ String name = Tools.getData(json, Tools.NAME); String uuidstr = Tools.getData(json, Tools.UUID); String securestr = Tools.getData(json, Tools.SECURE); boolean secure = false; if(securestr.equals("true")){ secure = true; } BluetoothSerialService service = new BluetoothSerialService(); service.listen(name, uuidstr, secure, this); acceptServices.put(name+uuidstr, service); } if(action.equals("rfcommUnListen")){ String name = Tools.getData(json, Tools.NAME); String uuidstr = Tools.getData(json, Tools.UUID); BluetoothSerialService service = acceptServices.get(name+uuidstr); if(service != null){ service.stop(); } } if(action.equals("rfcommWrite")){ String deviceAddress = Tools.getData(json, Tools.DEVICE_ADDRESS); BluetoothSerialService service = classicalServices.get(deviceAddress); if(service != null){ String data = Tools.getData(json, Tools.WRITE_VALUE); service.write(Tools.decodeBase64(data)); callbackContext.success(); }else{ callbackContext.error("there is no connection on device:" + deviceAddress); } } if(action.equals("rfcommRead")){ String deviceAddress = Tools.getData(json, Tools.DEVICE_ADDRESS); BluetoothSerialService service = classicalServices.get(deviceAddress); if(service != null){ byte[] data = new byte[2048]; byte[] predata = service.buffer.array(); for(int i = 0;i < service.bufferSize;i++){ data[i] = predata[i]; } JSONObject obj = new JSONObject(); //Tools.addProperty(obj, Tools.DEVICE_ADDRESS, deviceAddress); Tools.addProperty(obj, Tools.VALUE, Tools.encodeBase64(data)); Tools.addProperty(obj, Tools.DATE, Tools.getDateString()); callbackContext.success(obj); service.bufferSize = 0; service.buffer.clear(); }else{ callbackContext.error("there is no connection on device:" + deviceAddress); } } if(action.equals("rfcommSubscribe")){ String deviceAddress = Tools.getData(json, Tools.DEVICE_ADDRESS); BluetoothSerialService service = classicalServices.get(deviceAddress); if(service != null){ service.dataAvailableCallback = callbackContext; }else{ callbackContext.error("there is no connection on device:" + deviceAddress); } } if (action.equals("rfcommUnsubscribe")) { String deviceAddress = Tools.getData(json, Tools.DEVICE_ADDRESS); BluetoothSerialService service = classicalServices.get(deviceAddress); if(service != null){ service.dataAvailableCallback = null; }else{ callbackContext.error("there is no connection on device:" + deviceAddress); } } if (action.equals("getPairedDevices")) { try { Log.i(TAG, "getPairedDevices"); JSONArray ary = new JSONArray(); Set<BluetoothDevice> devices = bluetoothAdapter.getBondedDevices(); Iterator<BluetoothDevice> it = devices.iterator(); while (it.hasNext()) { BluetoothDevice device = (BluetoothDevice) it.next(); JSONObject obj = new JSONObject(); Tools.addProperty(obj, Tools.DEVICE_ADDRESS, device.getAddress()); Tools.addProperty(obj, Tools.DEVICE_NAME, device.getName()); ary.put(obj); } callbackContext.success(ary); } catch (Exception e) { Tools.sendErrorMsg(callbackContext); } catch (java.lang.Error e) { Tools.sendErrorMsg(callbackContext); } } else if (action.equals("createPair")) { Log.i(TAG, "createPair"); String deviceAddress = Tools.getData(json, Tools.DEVICE_ADDRESS); JSONObject obj = new JSONObject(); BluetoothDevice device = bluetoothAdapter.getRemoteDevice(deviceAddress); if (Tools.creatBond(device.getClass(), device)) { Tools.addProperty(obj, Tools.DEVICE_ADDRESS, device.getAddress()); callbackContext.success(obj); }else { Tools.addProperty(obj, Tools.DEVICE_ADDRESS, device.getAddress()); callbackContext.error(obj); } } else if (action.equals("removePair")) { Log.i(TAG, "removePair"); String deviceAddress = Tools.getData(json, Tools.DEVICE_ADDRESS); JSONObject obj = new JSONObject(); BluetoothDevice device = bluetoothAdapter.getRemoteDevice(deviceAddress); if (Tools.removeBond(device.getClass(), device)) { Tools.addProperty(obj, Tools.DEVICE_ADDRESS, device.getAddress()); callbackContext.success(obj); }else { Tools.addProperty(obj, Tools.DEVICE_ADDRESS, device.getAddress()); callbackContext.error(obj); } } } catch (Exception e) { Tools.sendErrorMsg(callbackContext); } catch(Error e){ Tools.sendErrorMsg(callbackContext); } return true; } public BroadcastReceiver receiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { if (intent.getIntExtra(BluetoothAdapter.EXTRA_PREVIOUS_STATE, -1) == 11) { JSONObject joOpen = new JSONObject(); try { joOpen.put("state", "open"); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } webView.sendJavascript("cordova.fireDocumentEvent('bluetoothopen')"); } else if (intent.getIntExtra( BluetoothAdapter.EXTRA_PREVIOUS_STATE, -1) == 13) { JSONObject joClose = new JSONObject(); try { joClose.put("state", "close"); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } webView.sendJavascript("cordova.fireDocumentEvent('bluetoothclose')"); }else if(BluetoothDevice.ACTION_FOUND.equals(intent.getAction())) { // Get the BluetoothDevice object from the Intent BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); System.out.println("new classical bluetooth device found!"+device.getAddress()); // Add the name and address to an array adapter to show in a ListView JSONObject obj = new JSONObject(); Tools.addProperty(obj, Tools.DEVICE_ADDRESS, device.getAddress()); Tools.addProperty(obj, Tools.DEVICE_NAME, device.getName()); Tools.addProperty(obj, Tools.IS_CONNECTED, Tools.IS_FALSE); Tools.addProperty(obj, Tools.TYPE, "Classical"); PluginResult pluginResult = new PluginResult(PluginResult.Status.OK , obj); pluginResult.setKeepCallback(true); newadvpacketContext.sendPluginResult(pluginResult); } } }; }
apache-2.0
jomarko/drools
drools-model/drools-model-compiler/src/test/java/org/drools/modelcompiler/OrTest.java
9484
/* * Copyright 2005 JBoss Inc * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.drools.modelcompiler; import java.util.ArrayList; import java.util.List; import org.assertj.core.api.Assertions; import org.drools.modelcompiler.domain.Address; import org.drools.modelcompiler.domain.Employee; import org.drools.modelcompiler.domain.Person; import org.junit.Test; import org.kie.api.builder.Results; import org.kie.api.runtime.KieSession; import static org.drools.modelcompiler.domain.Employee.createEmployee; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; public class OrTest extends BaseModelTest { public OrTest( RUN_TYPE testRunType ) { super( testRunType ); } @Test public void testOr() { String str = "import " + Person.class.getCanonicalName() + ";" + "rule R when\n" + " $p : Person(name == \"Mark\") or\n" + " ( $mark : Person(name == \"Mark\")\n" + " and\n" + " $p : Person(age > $mark.age) )\n" + " $s: String(this == $p.name)\n" + "then\n" + " System.out.println(\"Found: \" + $s);\n" + "end"; KieSession ksession = getKieSession( str ); ksession.insert( "Mario" ); ksession.insert( new Person( "Mark", 37 ) ); ksession.insert( new Person( "Edson", 35 ) ); ksession.insert( new Person( "Mario", 40 ) ); assertEquals(1, ksession.fireAllRules()); } @Test public void testOrWhenStringFirst() { String str = "import " + Person.class.getCanonicalName() + ";" + "import " + Address.class.getCanonicalName() + ";" + "rule R when\n" + " $s : String(this == \"Go\")\n" + " ( Person(name == \"Mark\") or \n" + " (\n" + " Person(name == \"Mario\") and\n" + " Address(city == \"London\") ) )\n" + "then\n" + " System.out.println(\"Found: \" + $s.getClass());\n" + "end"; KieSession ksession = getKieSession( str ); ksession.insert( "Go" ); ksession.insert( new Person( "Mark", 37 ) ); ksession.insert( new Person( "Mario", 100 ) ); ksession.insert( new Address( "London" ) ); assertEquals(2, ksession.fireAllRules()); } @Test public void testOrWithBetaIndex() { String str = "import " + Person.class.getCanonicalName() + ";" + "rule R when\n" + " $p : Person(name == \"Mark\") or\n" + " ( $mark : Person(name == \"Mark\")\n" + " and\n" + " $p : Person(age == $mark.age) )\n" + " $s: String(this == $p.name)\n" + "then\n" + " System.out.println(\"Found: \" + $s);\n" + "end"; KieSession ksession = getKieSession(str); ksession.insert("Mario"); ksession.insert(new Person("Mark", 37)); ksession.insert(new Person("Edson", 35)); ksession.insert(new Person("Mario", 37)); assertEquals(1, ksession.fireAllRules()); } @Test public void testOrWithBetaIndexOffset() { String str = "import " + Person.class.getCanonicalName() + ";" + "rule R when\n" + " $e : Person(name == \"Edson\")\n" + " $p : Person(name == \"Mark\") or\n" + " ( $mark : Person(name == \"Mark\")\n" + " and\n" + " $p : Person(age == $mark.age) )\n" + " $s: String(this == $p.name)\n" + "then\n" + " System.out.println(\"Found: \" + $s);\n" + "end"; KieSession ksession = getKieSession(str); ksession.insert("Mario"); ksession.insert(new Person("Mark", 37)); ksession.insert(new Person("Edson", 35)); ksession.insert(new Person("Mario", 37)); assertEquals(1, ksession.fireAllRules()); } @Test public void testOrConditional() { final String drl = "import " + Employee.class.getCanonicalName() + ";" + "import " + Address.class.getCanonicalName() + ";" + "global java.util.List list\n" + "\n" + "rule R when\n" + " Employee( $address: address, address.city == 'Big City' )\n" + " or " + " Employee( $address: address, address.city == 'Small City' )\n" + "then\n" + " list.add( $address.getCity() );\n" + "end\n"; KieSession kieSession = getKieSession(drl); List<String> results = new ArrayList<>(); kieSession.setGlobal("list", results); final Employee bruno = createEmployee("Bruno", new Address("Elm", 10, "Small City")); kieSession.insert(bruno); final Employee alice = createEmployee("Alice", new Address("Elm", 10, "Big City")); kieSession.insert(alice); kieSession.fireAllRules(); Assertions.assertThat(results).containsExactlyInAnyOrder("Big City", "Small City"); } @Test public void testOrConstraint() { final String drl = "import " + Employee.class.getCanonicalName() + ";" + "import " + Address.class.getCanonicalName() + ";" + "global java.util.List list\n" + "\n" + "rule R when\n" + " Employee( $address: address, ( address.city == 'Big City' || address.city == 'Small City' ) )\n" + "then\n" + " list.add( $address.getCity() );\n" + "end\n"; KieSession kieSession = getKieSession(drl); List<String> results = new ArrayList<>(); kieSession.setGlobal("list", results); final Employee bruno = createEmployee("Bruno", new Address("Elm", 10, "Small City")); kieSession.insert(bruno); final Employee alice = createEmployee("Alice", new Address("Elm", 10, "Big City")); kieSession.insert(alice); kieSession.fireAllRules(); Assertions.assertThat(results).containsExactlyInAnyOrder("Big City", "Small City"); } @Test public void testOrWithDuplicatedVariables() { String str = "import " + Person.class.getCanonicalName() + ";" + "global java.util.List list\n" + "\n" + "rule R1 when\n" + " Person( $name: name == \"Mark\", $age: age ) or\n" + " Person( $name: name == \"Mario\", $age : age )\n" + "then\n" + " list.add( $name + \" is \" + $age);\n" + "end\n" + "rule R2 when\n" + " $p: Person( name == \"Mark\", $age: age ) or\n" + " $p: Person( name == \"Mario\", $age : age )\n" + "then\n" + " list.add( $p + \" has \" + $age + \" years\");\n" + "end\n"; KieSession ksession = getKieSession( str ); List<String> results = new ArrayList<>(); ksession.setGlobal("list", results); ksession.insert( new Person( "Mark", 37 ) ); ksession.insert( new Person( "Edson", 35 ) ); ksession.insert( new Person( "Mario", 40 ) ); ksession.fireAllRules(); assertEquals(4, results.size()); assertTrue(results.contains("Mark is 37")); assertTrue(results.contains("Mark has 37 years")); assertTrue(results.contains("Mario is 40")); assertTrue(results.contains("Mario has 40 years")); } @Test public void generateErrorForEveryFieldInRHSNotDefinedInLHS() { // JBRULES-3390 final String drl1 = "package org.drools.compiler.integrationtests.operators; \n" + "declare B\n" + " field : int\n" + "end\n" + "declare C\n" + " field : int\n" + "end\n" + "rule R when\n" + "( " + " ( B( $bField : field ) or C( $cField : field ) ) " + ")\n" + "then\n" + " System.out.println($bField);\n" + "end\n"; Results results = getCompilationResults(drl1); assertFalse(results.getMessages().isEmpty()); } private Results getCompilationResults( String drl ) { return createKieBuilder( drl ).getResults(); } }
apache-2.0
GunoH/intellij-community
plugins/maven/src/main/java/org/jetbrains/idea/maven/importing/MavenRootModelAdapter.java
6985
/* * Copyright 2000-2013 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.idea.maven.importing; import com.intellij.openapi.externalSystem.service.project.IdeModifiableModelsProvider; import com.intellij.openapi.module.Module; import com.intellij.openapi.roots.*; import com.intellij.openapi.roots.libraries.Library; import com.intellij.openapi.util.io.FileUtil; import com.intellij.pom.java.LanguageLevel; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.idea.maven.model.MavenArtifact; import org.jetbrains.idea.maven.project.MavenProject; import org.jetbrains.idea.maven.utils.Path; import org.jetbrains.jps.model.JpsElement; import org.jetbrains.jps.model.java.JavaSourceRootType; import org.jetbrains.jps.model.module.JpsModuleSourceRootType; import java.io.File; public class MavenRootModelAdapter implements MavenRootModelAdapterInterface { private final MavenRootModelAdapterInterface myDelegate; public MavenRootModelAdapter(MavenRootModelAdapterInterface delegate) {myDelegate = delegate;} @Override public void init(boolean isNewlyCreatedModule) { myDelegate.init(isNewlyCreatedModule); } @Override public ModifiableRootModel getRootModel() { return myDelegate.getRootModel(); } @Override public String @NotNull [] getSourceRootUrls(boolean includingTests) { return myDelegate.getSourceRootUrls(includingTests); } @Override public Module getModule() { return myDelegate.getModule(); } @Override public void clearSourceFolders() { myDelegate.clearSourceFolders(); } @Override public <P extends JpsElement> void addSourceFolder(String path, JpsModuleSourceRootType<P> rootType) { myDelegate.addSourceFolder(path, rootType); } @Override public void addGeneratedJavaSourceFolder(String path, JavaSourceRootType rootType, boolean ifNotEmpty) { myDelegate.addGeneratedJavaSourceFolder(path, rootType, ifNotEmpty); } @Override public void addGeneratedJavaSourceFolder(String path, JavaSourceRootType rootType) { myDelegate.addGeneratedJavaSourceFolder(path, rootType); } @Override public boolean hasRegisteredSourceSubfolder(@NotNull File f) { return myDelegate.hasRegisteredSourceSubfolder(f); } @Override @Nullable public SourceFolder getSourceFolder(File folder) { return myDelegate.getSourceFolder(folder); } @Override public boolean isAlreadyExcluded(File f) { return myDelegate.isAlreadyExcluded(f); } @Override public void addExcludedFolder(String path) { myDelegate.addExcludedFolder(path); } @Override public void unregisterAll(String path, boolean under, boolean unregisterSources) { myDelegate.unregisterAll(path, under, unregisterSources); } @Override public boolean hasCollision(String sourceRootPath) { return myDelegate.hasCollision(sourceRootPath); } @Override public void useModuleOutput(String production, String test) { myDelegate.useModuleOutput(production, test); } @Override public Path toPath(String path) { return myDelegate.toPath(path); } @Override public void addModuleDependency(@NotNull String moduleName, @NotNull DependencyScope scope, boolean testJar) { myDelegate.addModuleDependency(moduleName, scope, testJar); } @Override @Nullable public Module findModuleByName(String moduleName) { return myDelegate.findModuleByName(moduleName); } @Override public void addSystemDependency(MavenArtifact artifact, DependencyScope scope) { myDelegate.addSystemDependency(artifact, scope); } @Override public LibraryOrderEntry addLibraryDependency(MavenArtifact artifact, DependencyScope scope, IdeModifiableModelsProvider provider, MavenProject project) { return myDelegate.addLibraryDependency(artifact, scope, provider, project); } @Override public Library findLibrary(@NotNull MavenArtifact artifact) { return myDelegate.findLibrary(artifact); } @Override public void setLanguageLevel(LanguageLevel level) { myDelegate.setLanguageLevel(level); } static boolean isChangedByUser(Library library) { String[] classRoots = library.getUrls( OrderRootType.CLASSES); if (classRoots.length != 1) return true; String classes = classRoots[0]; if (!classes.endsWith("!/")) return true; int dotPos = classes.lastIndexOf("/", classes.length() - 2 /* trim ending !/ */); if (dotPos == -1) return true; String pathToJar = classes.substring(0, dotPos); if (MavenRootModelAdapter .hasUserPaths(OrderRootType.SOURCES, library, pathToJar)) { return true; } if (MavenRootModelAdapter .hasUserPaths( JavadocOrderRootType .getInstance(), library, pathToJar)) { return true; } return false; } private static boolean hasUserPaths(OrderRootType rootType, Library library, String pathToJar) { String[] sources = library.getUrls(rootType); for (String each : sources) { if (!FileUtil.startsWith(each, pathToJar)) return true; } return false; } public static boolean isMavenLibrary(@Nullable Library library) { return library != null && MavenArtifact.isMavenLibrary(library.getName()); } public static ProjectModelExternalSource getMavenExternalSource() { return ExternalProjectSystemRegistry.getInstance().getSourceById(ExternalProjectSystemRegistry.MAVEN_EXTERNAL_SOURCE_ID); } @Nullable public static OrderEntry findLibraryEntry(@NotNull Module m, @NotNull MavenArtifact artifact) { String name = artifact.getLibraryName(); for (OrderEntry each : ModuleRootManager.getInstance(m).getOrderEntries()) { if (each instanceof LibraryOrderEntry && name.equals(((LibraryOrderEntry)each).getLibraryName())) { return each; } } return null; } @Nullable public static MavenArtifact findArtifact(@NotNull MavenProject project, @Nullable Library library) { if (library == null) return null; String name = library.getName(); if (!MavenArtifact.isMavenLibrary(name)) return null; for (MavenArtifact each : project.getDependencies()) { if (each.getLibraryName().equals(name)) return each; } return null; } }
apache-2.0
robovm/robovm-studio
java/java-impl/src/com/intellij/psi/formatter/java/AbstractJavaBlock.java
55736
/* * Copyright 2000-2014 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.psi.formatter.java; import com.intellij.formatting.*; import com.intellij.formatting.alignment.AlignmentStrategy; import com.intellij.lang.ASTNode; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.util.TextRange; import com.intellij.openapi.util.text.StringUtil; import com.intellij.psi.*; import com.intellij.psi.codeStyle.CodeStyleSettings; import com.intellij.psi.codeStyle.CommonCodeStyleSettings; import com.intellij.psi.codeStyle.JavaCodeStyleSettings; import com.intellij.psi.formatter.FormatterUtil; import com.intellij.psi.formatter.common.AbstractBlock; import com.intellij.psi.formatter.java.wrap.JavaWrapManager; import com.intellij.psi.formatter.java.wrap.ReservedWrapsProvider; import com.intellij.psi.impl.source.SourceTreeToPsiMap; import com.intellij.psi.impl.source.codeStyle.ShiftIndentInsideHelper; import com.intellij.psi.impl.source.tree.*; import com.intellij.psi.impl.source.tree.injected.InjectedLanguageUtil; import com.intellij.psi.impl.source.tree.java.ClassElement; import com.intellij.psi.jsp.JspElementType; import com.intellij.psi.tree.IElementType; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.text.CharArrayUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.ArrayList; import java.util.List; import java.util.Map; import static com.intellij.psi.formatter.java.JavaFormatterUtil.getWrapType; import static com.intellij.psi.formatter.java.MultipleFieldDeclarationHelper.findLastFieldInGroup; public abstract class AbstractJavaBlock extends AbstractBlock implements JavaBlock, ReservedWrapsProvider { private static final Logger LOG = Logger.getInstance("#com.intellij.psi.formatter.java.AbstractJavaBlock"); @NotNull protected final CommonCodeStyleSettings mySettings; @NotNull protected final JavaCodeStyleSettings myJavaSettings; protected final CommonCodeStyleSettings.IndentOptions myIndentSettings; private final Indent myIndent; protected Indent myChildIndent; protected Alignment myChildAlignment; protected boolean myUseChildAttributes = false; @NotNull protected final AlignmentStrategy myAlignmentStrategy; private boolean myIsAfterClassKeyword = false; protected Alignment myReservedAlignment; protected Alignment myReservedAlignment2; private final JavaWrapManager myWrapManager; private Map<IElementType, Wrap> myPreferredWraps; private AbstractJavaBlock myParentBlock; protected AbstractJavaBlock(@NotNull final ASTNode node, final Wrap wrap, final Alignment alignment, final Indent indent, @NotNull final CommonCodeStyleSettings settings, @NotNull JavaCodeStyleSettings javaSettings) { this(node, wrap, indent, settings, javaSettings, JavaWrapManager.INSTANCE, AlignmentStrategy.wrap(alignment)); } protected AbstractJavaBlock(@NotNull final ASTNode node, final Wrap wrap, @NotNull final AlignmentStrategy alignmentStrategy, final Indent indent, @NotNull final CommonCodeStyleSettings settings, @NotNull JavaCodeStyleSettings javaSettings) { this(node, wrap, indent, settings, javaSettings, JavaWrapManager.INSTANCE, alignmentStrategy); } private AbstractJavaBlock(@NotNull ASTNode ignored, @NotNull CommonCodeStyleSettings commonSettings, @NotNull JavaCodeStyleSettings javaSettings) { super(ignored, null, null); mySettings = commonSettings; myJavaSettings = javaSettings; myIndentSettings = commonSettings.getIndentOptions(); myIndent = null; myWrapManager = JavaWrapManager.INSTANCE; myAlignmentStrategy = AlignmentStrategy.getNullStrategy(); } protected AbstractJavaBlock(@NotNull final ASTNode node, final Wrap wrap, final Indent indent, @NotNull final CommonCodeStyleSettings settings, @NotNull JavaCodeStyleSettings javaSettings, final JavaWrapManager wrapManager, @NotNull final AlignmentStrategy alignmentStrategy) { super(node, wrap, createBlockAlignment(alignmentStrategy, node)); mySettings = settings; myJavaSettings = javaSettings; myIndentSettings = settings.getIndentOptions(); myIndent = indent; myWrapManager = wrapManager; myAlignmentStrategy = alignmentStrategy; } @Nullable private static Alignment createBlockAlignment(@NotNull AlignmentStrategy strategy, @NotNull ASTNode node) { // There is a possible case that 'implements' section is incomplete (e.g. ends with comma). We may want to align lbrace // to the first implemented interface reference then. if (node.getElementType() == JavaElementType.IMPLEMENTS_LIST) { return null; } return strategy.getAlignment(node.getElementType()); } @NotNull public Block createJavaBlock(@NotNull ASTNode child, @NotNull CommonCodeStyleSettings settings, @NotNull JavaCodeStyleSettings javaSettings, @Nullable Indent indent, @Nullable Wrap wrap, Alignment alignment) { return createJavaBlock(child, settings, javaSettings,indent, wrap, AlignmentStrategy.wrap(alignment)); } @NotNull public Block createJavaBlock(@NotNull ASTNode child, @NotNull CommonCodeStyleSettings settings, @NotNull JavaCodeStyleSettings javaSettings, final Indent indent, @Nullable Wrap wrap, @NotNull AlignmentStrategy alignmentStrategy) { return createJavaBlock(child, settings, javaSettings, indent, wrap, alignmentStrategy, -1); } @NotNull private Block createJavaBlock(@NotNull ASTNode child, @NotNull CommonCodeStyleSettings settings, @NotNull JavaCodeStyleSettings javaSettings, @Nullable Indent indent, Wrap wrap, @NotNull AlignmentStrategy alignmentStrategy, int startOffset) { Indent actualIndent = indent == null ? getDefaultSubtreeIndent(child, getJavaIndentOptions(settings)) : indent; final IElementType elementType = child.getElementType(); Alignment alignment = alignmentStrategy.getAlignment(elementType); if (child.getPsi() instanceof PsiWhiteSpace) { String text = child.getText(); int start = CharArrayUtil.shiftForward(text, 0, " \t\n"); int end = CharArrayUtil.shiftBackward(text, text.length() - 1, " \t\n") + 1; LOG.assertTrue(start < end); return new PartialWhitespaceBlock(child, new TextRange(start + child.getStartOffset(), end + child.getStartOffset()), wrap, alignment, actualIndent, settings, javaSettings); } if (child.getPsi() instanceof PsiClass) { return new CodeBlockBlock(child, wrap, alignment, actualIndent, settings, javaSettings); } if (isBlockType(elementType)) { return new BlockContainingJavaBlock(child, wrap, alignment, actualIndent, settings, javaSettings); } if (isStatement(child, child.getTreeParent())) { return new CodeBlockBlock(child, wrap, alignment, actualIndent, settings, javaSettings); } if (isBuildInjectedBlocks() && child instanceof PsiComment && child instanceof PsiLanguageInjectionHost && InjectedLanguageUtil.hasInjections((PsiLanguageInjectionHost)child)) { return new CommentWithInjectionBlock(child, wrap, alignment, indent, settings, javaSettings); } if (child instanceof LeafElement) { final LeafBlock block = new LeafBlock(child, wrap, alignment, actualIndent); block.setStartOffset(startOffset); return block; } else if (isLikeExtendsList(elementType)) { return new ExtendsListBlock(child, wrap, alignmentStrategy, settings, javaSettings); } else if (elementType == JavaElementType.CODE_BLOCK) { return new CodeBlockBlock(child, wrap, alignment, actualIndent, settings, javaSettings); } else if (elementType == JavaElementType.LABELED_STATEMENT) { return new LabeledJavaBlock(child, wrap, alignment, actualIndent, settings, javaSettings); } else if (elementType == JavaDocElementType.DOC_COMMENT) { return new DocCommentBlock(child, wrap, alignment, actualIndent, settings, javaSettings); } else { final SimpleJavaBlock simpleJavaBlock = new SimpleJavaBlock(child, wrap, alignmentStrategy, actualIndent, settings, javaSettings); simpleJavaBlock.setStartOffset(startOffset); return simpleJavaBlock; } } @NotNull public static Block newJavaBlock(@NotNull ASTNode child, @NotNull CommonCodeStyleSettings settings, @NotNull JavaCodeStyleSettings javaSettings) { final Indent indent = getDefaultSubtreeIndent(child, getJavaIndentOptions(settings)); return newJavaBlock(child, settings, javaSettings, indent, null, AlignmentStrategy.getNullStrategy()); } @NotNull public static Block newJavaBlock(@NotNull ASTNode child, @NotNull CommonCodeStyleSettings settings, @NotNull JavaCodeStyleSettings javaSettings, @Nullable Indent indent, @Nullable Wrap wrap, @NotNull AlignmentStrategy strategy) { return new AbstractJavaBlock(child, settings, javaSettings) { @Override protected List<Block> buildChildren() { return null; } }.createJavaBlock(child, settings, javaSettings, indent, wrap, strategy); } @NotNull private static CommonCodeStyleSettings.IndentOptions getJavaIndentOptions(CommonCodeStyleSettings settings) { CommonCodeStyleSettings.IndentOptions indentOptions = settings.getIndentOptions(); assert indentOptions != null : "Java indent options are not initialized"; return indentOptions; } private static boolean isLikeExtendsList(final IElementType elementType) { return elementType == JavaElementType.EXTENDS_LIST || elementType == JavaElementType.IMPLEMENTS_LIST || elementType == JavaElementType.THROWS_LIST; } private static boolean isBlockType(final IElementType elementType) { return elementType == JavaElementType.SWITCH_STATEMENT || elementType == JavaElementType.FOR_STATEMENT || elementType == JavaElementType.WHILE_STATEMENT || elementType == JavaElementType.DO_WHILE_STATEMENT || elementType == JavaElementType.TRY_STATEMENT || elementType == JavaElementType.CATCH_SECTION || elementType == JavaElementType.IF_STATEMENT || elementType == JavaElementType.METHOD || elementType == JavaElementType.ARRAY_INITIALIZER_EXPRESSION || elementType == JavaElementType.ANNOTATION_ARRAY_INITIALIZER || elementType == JavaElementType.CLASS_INITIALIZER || elementType == JavaElementType.SYNCHRONIZED_STATEMENT || elementType == JavaElementType.FOREACH_STATEMENT; } @Nullable private static Indent getDefaultSubtreeIndent(@NotNull ASTNode child, @NotNull CommonCodeStyleSettings.IndentOptions indentOptions) { final ASTNode parent = child.getTreeParent(); final IElementType childNodeType = child.getElementType(); if (childNodeType == JavaElementType.ANNOTATION) { if (parent.getPsi() instanceof PsiArrayInitializerMemberValue) { return Indent.getNormalIndent(); } return Indent.getNoneIndent(); } final ASTNode prevElement = FormatterUtil.getPreviousNonWhitespaceSibling(child); if (prevElement != null && prevElement.getElementType() == JavaElementType.MODIFIER_LIST) { return Indent.getNoneIndent(); } if (childNodeType == JavaDocElementType.DOC_TAG) return Indent.getNoneIndent(); if (childNodeType == JavaDocTokenType.DOC_COMMENT_LEADING_ASTERISKS) return Indent.getSpaceIndent(1); if (child.getPsi() instanceof PsiFile) return Indent.getNoneIndent(); if (parent != null) { final Indent defaultChildIndent = getChildIndent(parent, indentOptions); if (defaultChildIndent != null) return defaultChildIndent; } if (child.getTreeParent() instanceof PsiLambdaExpression && child instanceof PsiCodeBlock) { return Indent.getNoneIndent(); } return null; } @Nullable private static Indent getChildIndent(@NotNull ASTNode parent, @NotNull CommonCodeStyleSettings.IndentOptions indentOptions) { final IElementType parentType = parent.getElementType(); if (parentType == JavaElementType.MODIFIER_LIST) return Indent.getNoneIndent(); if (parentType == JspElementType.JSP_CODE_BLOCK) return Indent.getNormalIndent(); if (parentType == JspElementType.JSP_CLASS_LEVEL_DECLARATION_STATEMENT) return Indent.getNormalIndent(); if (parentType == TokenType.DUMMY_HOLDER) return Indent.getNoneIndent(); if (parentType == JavaElementType.CLASS) return Indent.getNoneIndent(); if (parentType == JavaElementType.IF_STATEMENT) return Indent.getNoneIndent(); if (parentType == JavaElementType.TRY_STATEMENT) return Indent.getNoneIndent(); if (parentType == JavaElementType.CATCH_SECTION) return Indent.getNoneIndent(); if (parentType == JavaElementType.FOR_STATEMENT) return Indent.getNoneIndent(); if (parentType == JavaElementType.FOREACH_STATEMENT) return Indent.getNoneIndent(); if (parentType == JavaElementType.BLOCK_STATEMENT) return Indent.getNoneIndent(); if (parentType == JavaElementType.DO_WHILE_STATEMENT) return Indent.getNoneIndent(); if (parentType == JavaElementType.WHILE_STATEMENT) return Indent.getNoneIndent(); if (parentType == JavaElementType.SWITCH_STATEMENT) return Indent.getNoneIndent(); if (parentType == JavaElementType.METHOD) return Indent.getNoneIndent(); if (parentType == JavaDocElementType.DOC_COMMENT) return Indent.getNoneIndent(); if (parentType == JavaDocElementType.DOC_TAG) return Indent.getNoneIndent(); if (parentType == JavaDocElementType.DOC_INLINE_TAG) return Indent.getNoneIndent(); if (parentType == JavaElementType.IMPORT_LIST) return Indent.getNoneIndent(); if (parentType == JavaElementType.FIELD) return Indent.getContinuationWithoutFirstIndent(indentOptions.USE_RELATIVE_INDENTS); if (parentType == JavaElementType.EXPRESSION_STATEMENT) return Indent.getNoneIndent(); if (SourceTreeToPsiMap.treeElementToPsi(parent) instanceof PsiFile) { return Indent.getNoneIndent(); } return null; } protected static boolean isRBrace(@NotNull final ASTNode child) { return child.getElementType() == JavaTokenType.RBRACE; } @Nullable @Override public Spacing getSpacing(Block child1, @NotNull Block child2) { return JavaSpacePropertyProcessor.getSpacing(getTreeNode(child2), mySettings, myJavaSettings); } @Override public ASTNode getFirstTreeNode() { return myNode; } @Override public Indent getIndent() { return myIndent; } protected static boolean isStatement(final ASTNode child, @Nullable final ASTNode parentNode) { if (parentNode != null) { final IElementType parentType = parentNode.getElementType(); if (parentType == JavaElementType.CODE_BLOCK) return false; final int role = ((CompositeElement)parentNode).getChildRole(child); if (parentType == JavaElementType.IF_STATEMENT) return role == ChildRole.THEN_BRANCH || role == ChildRole.ELSE_BRANCH; if (parentType == JavaElementType.FOR_STATEMENT) return role == ChildRole.LOOP_BODY; if (parentType == JavaElementType.WHILE_STATEMENT) return role == ChildRole.LOOP_BODY; if (parentType == JavaElementType.DO_WHILE_STATEMENT) return role == ChildRole.LOOP_BODY; if (parentType == JavaElementType.FOREACH_STATEMENT) return role == ChildRole.LOOP_BODY; } return false; } @Nullable protected Wrap createChildWrap() { return myWrapManager.createChildBlockWrap(this, getSettings(), this); } @Nullable protected Alignment createChildAlignment() { IElementType nodeType = myNode.getElementType(); if (nodeType == JavaElementType.POLYADIC_EXPRESSION) nodeType = JavaElementType.BINARY_EXPRESSION; if (nodeType == JavaElementType.ASSIGNMENT_EXPRESSION) { if (myNode.getTreeParent() != null && myNode.getTreeParent().getElementType() == JavaElementType.ASSIGNMENT_EXPRESSION && myAlignment != null) { return myAlignment; } return createAlignment(mySettings.ALIGN_MULTILINE_ASSIGNMENT, null); } if (nodeType == JavaElementType.PARENTH_EXPRESSION) { return createAlignment(mySettings.ALIGN_MULTILINE_PARENTHESIZED_EXPRESSION, null); } if (nodeType == JavaElementType.CONDITIONAL_EXPRESSION) { return createAlignment(mySettings.ALIGN_MULTILINE_TERNARY_OPERATION, null); } if (nodeType == JavaElementType.FOR_STATEMENT) { return createAlignment(mySettings.ALIGN_MULTILINE_FOR, null); } if (nodeType == JavaElementType.EXTENDS_LIST || nodeType == JavaElementType.IMPLEMENTS_LIST) { return createAlignment(mySettings.ALIGN_MULTILINE_EXTENDS_LIST, null); } if (nodeType == JavaElementType.THROWS_LIST) { return createAlignment(mySettings.ALIGN_MULTILINE_THROWS_LIST, null); } if (nodeType == JavaElementType.PARAMETER_LIST) { return createAlignment(mySettings.ALIGN_MULTILINE_PARAMETERS, null); } if (nodeType == JavaElementType.RESOURCE_LIST) { return createAlignment(mySettings.ALIGN_MULTILINE_RESOURCES, null); } if (nodeType == JavaElementType.BINARY_EXPRESSION) { Alignment defaultAlignment = null; if (shouldInheritAlignment()) { defaultAlignment = myAlignment; } return createAlignment(mySettings.ALIGN_MULTILINE_BINARY_OPERATION, defaultAlignment); } if (nodeType == JavaElementType.CLASS || nodeType == JavaElementType.METHOD) { return null; } return null; } @Nullable protected Alignment chooseAlignment(@Nullable Alignment alignment, @Nullable Alignment alignment2, @NotNull ASTNode child) { if (isTernaryOperatorToken(child)) { return alignment2; } return alignment; } private boolean isTernaryOperatorToken(@NotNull final ASTNode child) { final IElementType nodeType = myNode.getElementType(); if (nodeType == JavaElementType.CONDITIONAL_EXPRESSION) { IElementType childType = child.getElementType(); return childType == JavaTokenType.QUEST || childType ==JavaTokenType.COLON; } else { return false; } } private boolean shouldInheritAlignment() { if (myNode instanceof PsiPolyadicExpression) { final ASTNode treeParent = myNode.getTreeParent(); if (treeParent instanceof PsiPolyadicExpression) { return JavaFormatterUtil.areSamePriorityBinaryExpressions(myNode, treeParent); } } return false; } @Nullable protected ASTNode processChild(@NotNull final List<Block> result, @NotNull ASTNode child, Alignment defaultAlignment, final Wrap defaultWrap, final Indent childIndent) { return processChild(result, child, AlignmentStrategy.wrap(defaultAlignment), defaultWrap, childIndent, -1); } @Nullable protected ASTNode processChild(@NotNull final List<Block> result, @NotNull ASTNode child, @NotNull AlignmentStrategy alignmentStrategy, @Nullable final Wrap defaultWrap, final Indent childIndent) { return processChild(result, child, alignmentStrategy, defaultWrap, childIndent, -1); } @Nullable protected ASTNode processChild(@NotNull final List<Block> result, @NotNull ASTNode child, @NotNull AlignmentStrategy alignmentStrategy, final Wrap defaultWrap, final Indent childIndent, int childOffset) { final IElementType childType = child.getElementType(); if (childType == JavaTokenType.CLASS_KEYWORD || childType == JavaTokenType.INTERFACE_KEYWORD) { myIsAfterClassKeyword = true; } if (childType == JavaElementType.METHOD_CALL_EXPRESSION) { Alignment alignment = shouldAlignChild(child) ? alignmentStrategy.getAlignment(childType) : null; result.add(createMethodCallExpressionBlock(child, arrangeChildWrap(child, defaultWrap), alignment, childIndent)); } else { IElementType nodeType = myNode.getElementType(); if (nodeType == JavaElementType.POLYADIC_EXPRESSION) nodeType = JavaElementType.BINARY_EXPRESSION; if (childType == JavaTokenType.LBRACE && nodeType == JavaElementType.ARRAY_INITIALIZER_EXPRESSION) { final Wrap wrap = Wrap.createWrap(getWrapType(mySettings.ARRAY_INITIALIZER_WRAP), false); child = processParenthesisBlock(JavaTokenType.LBRACE, JavaTokenType.RBRACE, result, child, WrappingStrategy.createDoNotWrapCommaStrategy(wrap), mySettings.ALIGN_MULTILINE_ARRAY_INITIALIZER_EXPRESSION); } else if (childType == JavaTokenType.LBRACE && nodeType == JavaElementType.ANNOTATION_ARRAY_INITIALIZER) { final Wrap wrap = Wrap.createWrap(getWrapType(mySettings.ARRAY_INITIALIZER_WRAP), false); child = processParenthesisBlock(JavaTokenType.LBRACE, JavaTokenType.RBRACE, result, child, WrappingStrategy.createDoNotWrapCommaStrategy(wrap), mySettings.ALIGN_MULTILINE_ARRAY_INITIALIZER_EXPRESSION); } else if (childType == JavaTokenType.LPARENTH && nodeType == JavaElementType.EXPRESSION_LIST) { final Wrap wrap = Wrap.createWrap(getWrapType(mySettings.CALL_PARAMETERS_WRAP), false); if (mySettings.PREFER_PARAMETERS_WRAP && !isInsideMethodCall(myNode.getPsi())) { wrap.ignoreParentWraps(); } child = processParenthesisBlock(result, child, WrappingStrategy.createDoNotWrapCommaStrategy(wrap), mySettings.ALIGN_MULTILINE_PARAMETERS_IN_CALLS); } else if (childType == JavaTokenType.LPARENTH && nodeType == JavaElementType.PARAMETER_LIST) { ASTNode parent = myNode.getTreeParent(); boolean isLambdaParameterList = parent != null && parent.getElementType() == JavaElementType.LAMBDA_EXPRESSION; Wrap wrapToUse = isLambdaParameterList ? null : getMethodParametersWrap(); WrappingStrategy wrapStrategy = WrappingStrategy.createDoNotWrapCommaStrategy(wrapToUse); child = processParenthesisBlock(result, child, wrapStrategy, mySettings.ALIGN_MULTILINE_PARAMETERS); } else if (childType == JavaTokenType.LPARENTH && nodeType == JavaElementType.RESOURCE_LIST) { Wrap wrap = Wrap.createWrap(getWrapType(mySettings.RESOURCE_LIST_WRAP), false); child = processParenthesisBlock(result, child, WrappingStrategy.createDoNotWrapCommaStrategy(wrap), mySettings.ALIGN_MULTILINE_RESOURCES); } else if (childType == JavaTokenType.LPARENTH && nodeType == JavaElementType.ANNOTATION_PARAMETER_LIST) { Wrap wrap = Wrap.createWrap(getWrapType(myJavaSettings.ANNOTATION_PARAMETER_WRAP), false); child = processParenthesisBlock(result, child, WrappingStrategy.createDoNotWrapCommaStrategy(wrap), myJavaSettings.ALIGN_MULTILINE_ANNOTATION_PARAMETERS); } else if (childType == JavaTokenType.LPARENTH && nodeType == JavaElementType.PARENTH_EXPRESSION) { child = processParenthesisBlock(result, child, WrappingStrategy.DO_NOT_WRAP, mySettings.ALIGN_MULTILINE_PARENTHESIZED_EXPRESSION); } else if (childType == JavaElementType.ENUM_CONSTANT && myNode instanceof ClassElement) { child = processEnumBlock(result, child, ((ClassElement)myNode).findEnumConstantListDelimiterPlace()); } else if (mySettings.TERNARY_OPERATION_SIGNS_ON_NEXT_LINE && isTernaryOperationSign(child)) { child = processTernaryOperationRange(result, child, defaultWrap, childIndent); } else if (childType == JavaElementType.FIELD) { child = processField(result, child, alignmentStrategy, defaultWrap, childIndent); } else if (childType == JavaElementType.LOCAL_VARIABLE || childType == JavaElementType.DECLARATION_STATEMENT && (nodeType == JavaElementType.METHOD || nodeType == JavaElementType.CODE_BLOCK)) { result.add(new SimpleJavaBlock(child, defaultWrap, alignmentStrategy, childIndent, mySettings, myJavaSettings)); } else { Alignment alignment = alignmentStrategy.getAlignment(childType); AlignmentStrategy alignmentStrategyToUse = shouldAlignChild(child) ? AlignmentStrategy.wrap(alignment) : AlignmentStrategy.getNullStrategy(); if (myAlignmentStrategy.getAlignment(nodeType, childType) != null && (nodeType == JavaElementType.IMPLEMENTS_LIST || nodeType == JavaElementType.CLASS)) { alignmentStrategyToUse = myAlignmentStrategy; } Wrap wrap = arrangeChildWrap(child, defaultWrap); Block block = createJavaBlock(child, mySettings, myJavaSettings, childIndent, wrap, alignmentStrategyToUse, childOffset); if (block instanceof AbstractJavaBlock) { final AbstractJavaBlock javaBlock = (AbstractJavaBlock)block; if (nodeType == JavaElementType.METHOD_CALL_EXPRESSION && childType == JavaElementType.REFERENCE_EXPRESSION || nodeType == JavaElementType.REFERENCE_EXPRESSION && childType == JavaElementType.METHOD_CALL_EXPRESSION) { javaBlock.setReservedWrap(getReservedWrap(nodeType), nodeType); javaBlock.setReservedWrap(getReservedWrap(childType), childType); } else if (nodeType == JavaElementType.BINARY_EXPRESSION) { javaBlock.setReservedWrap(defaultWrap, nodeType); } } result.add(block); } } return child; } private boolean isInsideMethodCall(@NotNull PsiElement element) { PsiElement e = element.getParent(); int parentsVisited = 0; while (e != null && !(e instanceof PsiStatement) && parentsVisited < 5) { if (e instanceof PsiExpressionList) { return true; } e = e.getParent(); parentsVisited++; } return false; } @NotNull private Wrap getMethodParametersWrap() { Wrap preferredWrap = getModifierListWrap(); if (preferredWrap == null) { return Wrap.createWrap(getWrapType(mySettings.METHOD_PARAMETERS_WRAP), false); } else { return Wrap.createChildWrap(preferredWrap, getWrapType(mySettings.METHOD_PARAMETERS_WRAP), false); } } @Nullable private Wrap getModifierListWrap() { AbstractJavaBlock parentBlock = getParentBlock(); if (parentBlock != null) { return parentBlock.getReservedWrap(JavaElementType.MODIFIER_LIST); } return null; } private ASTNode processField(@NotNull final List<Block> result, ASTNode child, @NotNull final AlignmentStrategy alignmentStrategy, final Wrap defaultWrap, final Indent childIndent) { ASTNode lastFieldInGroup = findLastFieldInGroup(child); if (lastFieldInGroup == child) { result.add(createJavaBlock(child, getSettings(), myJavaSettings, childIndent, arrangeChildWrap(child, defaultWrap), alignmentStrategy)); return child; } else { final ArrayList<Block> localResult = new ArrayList<Block>(); while (child != null) { if (!FormatterUtil.containsWhiteSpacesOnly(child)) { localResult.add(createJavaBlock( child, getSettings(), myJavaSettings, Indent.getContinuationWithoutFirstIndent(myIndentSettings.USE_RELATIVE_INDENTS), arrangeChildWrap(child, defaultWrap), alignmentStrategy ) ); } if (child == lastFieldInGroup) break; child = child.getTreeNext(); } if (!localResult.isEmpty()) { result.add(new SyntheticCodeBlock(localResult, null, getSettings(), myJavaSettings, childIndent, null)); } return lastFieldInGroup; } } @Nullable private ASTNode processTernaryOperationRange(@NotNull final List<Block> result, @NotNull final ASTNode child, final Wrap defaultWrap, final Indent childIndent) { final ArrayList<Block> localResult = new ArrayList<Block>(); final Wrap wrap = arrangeChildWrap(child, defaultWrap); final Alignment alignment = myReservedAlignment; final Alignment alignment2 = myReservedAlignment2; localResult.add(new LeafBlock(child, wrap, chooseAlignment(alignment, alignment2, child), childIndent)); ASTNode current = child.getTreeNext(); while (current != null) { if (!FormatterUtil.containsWhiteSpacesOnly(current) && current.getTextLength() > 0) { if (isTernaryOperationSign(current)) break; current = processChild(localResult, current, chooseAlignment(alignment, alignment2, current), defaultWrap, childIndent); } if (current != null) { current = current.getTreeNext(); } } result.add(new SyntheticCodeBlock(localResult, chooseAlignment(alignment, alignment2, child), getSettings(), myJavaSettings, null, wrap)); if (current == null) { return null; } return current.getTreePrev(); } private boolean isTernaryOperationSign(@NotNull final ASTNode child) { if (myNode.getElementType() != JavaElementType.CONDITIONAL_EXPRESSION) return false; final int role = ((CompositeElement)child.getTreeParent()).getChildRole(child); return role == ChildRole.OPERATION_SIGN || role == ChildRole.COLON; } @NotNull private Block createMethodCallExpressionBlock(@NotNull ASTNode node, Wrap blockWrap, Alignment alignment, Indent indent) { final ArrayList<ASTNode> nodes = new ArrayList<ASTNode>(); collectNodes(nodes, node); return new ChainMethodCallsBlockBuilder(alignment, blockWrap, indent, mySettings, myJavaSettings).build(nodes); } private static void collectNodes(@NotNull List<ASTNode> nodes, @NotNull ASTNode node) { ASTNode child = node.getFirstChildNode(); while (child != null) { if (!FormatterUtil.containsWhiteSpacesOnly(child)) { if (child.getElementType() == JavaElementType.METHOD_CALL_EXPRESSION || child.getElementType() == JavaElementType .REFERENCE_EXPRESSION) { collectNodes(nodes, child); } else { nodes.add(child); } } child = child.getTreeNext(); } } private boolean shouldAlignChild(@NotNull final ASTNode child) { int role = getChildRole(child); final IElementType nodeType = myNode.getElementType(); if (nodeType == JavaElementType.FOR_STATEMENT) { if (role == ChildRole.FOR_INITIALIZATION || role == ChildRole.CONDITION || role == ChildRole.FOR_UPDATE) { return true; } return false; } else if (nodeType == JavaElementType.EXTENDS_LIST || nodeType == JavaElementType.IMPLEMENTS_LIST) { if (role == ChildRole.REFERENCE_IN_LIST || role == ChildRole.IMPLEMENTS_KEYWORD) { return true; } return false; } else if (nodeType == JavaElementType.THROWS_LIST) { if (role == ChildRole.REFERENCE_IN_LIST) { return true; } return false; } else if (nodeType == JavaElementType.CLASS) { if (role == ChildRole.CLASS_OR_INTERFACE_KEYWORD) return true; if (myIsAfterClassKeyword) return false; if (role == ChildRole.MODIFIER_LIST) return true; return false; } else if (JavaElementType.FIELD == nodeType) { return shouldAlignFieldInColumns(child); } else if (nodeType == JavaElementType.METHOD) { if (role == ChildRole.MODIFIER_LIST) return true; if (role == ChildRole.TYPE_PARAMETER_LIST) return true; if (role == ChildRole.TYPE) return true; if (role == ChildRole.NAME) return true; if (role == ChildRole.THROWS_LIST && mySettings.ALIGN_THROWS_KEYWORD) return true; return false; } else if (nodeType == JavaElementType.ASSIGNMENT_EXPRESSION) { if (role == ChildRole.LOPERAND) return true; if (role == ChildRole.ROPERAND && child.getElementType() == JavaElementType.ASSIGNMENT_EXPRESSION) { return true; } return false; } else if (child.getElementType() == JavaTokenType.END_OF_LINE_COMMENT) { ASTNode previous = child.getTreePrev(); // There is a special case - comment block that is located at the very start of the line. We don't reformat such a blocks, // hence, no alignment should be applied to them in order to avoid subsequent blocks aligned with the same alignment to // be located at the left editor edge as well. CharSequence prevChars; if (previous != null && previous.getElementType() == TokenType.WHITE_SPACE && (prevChars = previous.getChars()).length() > 0 && prevChars.charAt(prevChars.length() - 1) == '\n') { return false; } return true; } else if (nodeType == JavaElementType.MODIFIER_LIST) { // There is a possible case that modifier list contains from more than one elements, e.g. 'private final'. It's also possible // that the list is aligned. We want to apply alignment rule only to the first element then. ASTNode previous = child.getTreePrev(); if (previous == null || previous.getTreeParent() != myNode) { return true; } return false; } else { return true; } } private static int getChildRole(@NotNull ASTNode child) { return ((CompositeElement)child.getTreeParent()).getChildRole(child); } /** * Encapsulates alignment retrieval logic for variable declaration use-case assuming that given node is a child node * of basic variable declaration node. * * @param child variable declaration child node which alignment is to be defined * @return alignment to use for the given node * @see CodeStyleSettings#ALIGN_GROUP_FIELD_DECLARATIONS */ @Nullable private boolean shouldAlignFieldInColumns(@NotNull ASTNode child) { // The whole idea of variable declarations alignment is that complete declaration blocks which children are to be aligned hold // reference to the same AlignmentStrategy object, hence, reuse the same Alignment objects. So, there is no point in checking // if it's necessary to align sub-blocks if shared strategy is not defined. if (!mySettings.ALIGN_GROUP_FIELD_DECLARATIONS) { return false; } IElementType childType = child.getElementType(); // We don't want to align subsequent identifiers in single-line declarations like 'int i1, i2, i3'. I.e. only 'i1' // should be aligned then. ASTNode previousNode = FormatterUtil.getPreviousNonWhitespaceSibling(child); if (childType == JavaTokenType.IDENTIFIER && (previousNode == null || previousNode.getElementType() == JavaTokenType.COMMA)) { return false; } return true; } @Nullable public static Alignment createAlignment(final boolean alignOption, @Nullable final Alignment defaultAlignment) { return alignOption ? createAlignmentOrDefault(null, defaultAlignment) : defaultAlignment; } @Nullable public static Alignment createAlignment(Alignment base, final boolean alignOption, @Nullable final Alignment defaultAlignment) { return alignOption ? createAlignmentOrDefault(base, defaultAlignment) : defaultAlignment; } @Nullable protected Wrap arrangeChildWrap(final ASTNode child, Wrap defaultWrap) { return myWrapManager.arrangeChildWrap(child, myNode, mySettings, myJavaSettings, defaultWrap, this); } @NotNull private ASTNode processParenthesisBlock(@NotNull List<Block> result, @NotNull ASTNode child, @NotNull WrappingStrategy wrappingStrategy, final boolean doAlign) { myUseChildAttributes = true; final IElementType from = JavaTokenType.LPARENTH; final IElementType to = JavaTokenType.RPARENTH; return processParenthesisBlock(from, to, result, child, wrappingStrategy, doAlign); } @NotNull private ASTNode processParenthesisBlock(@NotNull IElementType from, @Nullable final IElementType to, @NotNull final List<Block> result, @NotNull ASTNode child, @NotNull final WrappingStrategy wrappingStrategy, final boolean doAlign) { final Indent externalIndent = Indent.getNoneIndent(); final Indent internalIndent = Indent.getContinuationWithoutFirstIndent(myIndentSettings.USE_RELATIVE_INDENTS); final Indent internalIndentEnforcedToChildren = Indent.getIndent(Indent.Type.CONTINUATION, myIndentSettings.USE_RELATIVE_INDENTS, true); AlignmentStrategy alignmentStrategy = AlignmentStrategy.wrap(createAlignment(doAlign, null), JavaTokenType.COMMA); setChildIndent(internalIndent); setChildAlignment(alignmentStrategy.getAlignment(null)); boolean methodParametersBlock = true; ASTNode lBracketParent = child.getTreeParent(); if (lBracketParent != null) { ASTNode methodCandidate = lBracketParent.getTreeParent(); methodParametersBlock = methodCandidate != null && (methodCandidate.getElementType() == JavaElementType.METHOD || methodCandidate.getElementType() == JavaElementType.METHOD_CALL_EXPRESSION); } Alignment bracketAlignment = methodParametersBlock && mySettings.ALIGN_MULTILINE_METHOD_BRACKETS ? Alignment.createAlignment() : null; AlignmentStrategy anonymousClassStrategy = doAlign ? alignmentStrategy : AlignmentStrategy.wrap(Alignment.createAlignment(), false, JavaTokenType.NEW_KEYWORD, JavaElementType.NEW_EXPRESSION, JavaTokenType.RBRACE); setChildIndent(internalIndent); setChildAlignment(alignmentStrategy.getAlignment(null)); boolean isAfterIncomplete = false; ASTNode prev = child; boolean afterAnonymousClass = false; final boolean enforceIndent = shouldEnforceIndentToChildren(); while (child != null) { isAfterIncomplete = isAfterIncomplete || child.getElementType() == TokenType.ERROR_ELEMENT || child.getElementType() == JavaElementType.EMPTY_EXPRESSION; if (!FormatterUtil.containsWhiteSpacesOnly(child) && child.getTextLength() > 0) { if (child.getElementType() == from) { result.add(createJavaBlock(child, mySettings, myJavaSettings, externalIndent, null, bracketAlignment)); } else if (child.getElementType() == to) { result.add(createJavaBlock(child, mySettings, myJavaSettings, isAfterIncomplete && !afterAnonymousClass ? internalIndent : externalIndent, null, isAfterIncomplete ? alignmentStrategy.getAlignment(null) : bracketAlignment) ); return child; } else { final IElementType elementType = child.getElementType(); Indent indentToUse = enforceIndent ? internalIndentEnforcedToChildren : internalIndent; AlignmentStrategy alignmentStrategyToUse = canUseAnonymousClassAlignment(child) ? anonymousClassStrategy : alignmentStrategy; processChild(result, child, alignmentStrategyToUse.getAlignment(elementType), wrappingStrategy.getWrap(elementType), indentToUse); if (to == null) {//process only one statement return child; } } isAfterIncomplete = false; if (child.getElementType() != JavaTokenType.COMMA) { afterAnonymousClass = isAnonymousClass(child); } } prev = child; child = child.getTreeNext(); } return prev; } private static boolean canUseAnonymousClassAlignment(@NotNull ASTNode child) { // The general idea is to handle situations like below: // test(new Runnable() { // public void run() { // } // }, new Runnable() { // public void run() { // } // } // ); // I.e. we want to align subsequent anonymous class argument to the previous one if it's not preceded by another argument // at the same line, e.g.: // test("this is a long argument", new Runnable() { // public void run() { // } // }, new Runnable() { // public void run() { // } // } // ); if (!isAnonymousClass(child)) { return false; } for (ASTNode node = child.getTreePrev(); node != null; node = node.getTreePrev()) { if (node.getElementType() == TokenType.WHITE_SPACE) { if (StringUtil.countNewLines(node.getChars()) > 0) { return false; } } else if (node.getElementType() == JavaTokenType.LPARENTH) { // First method call argument. return true; } else if (node.getElementType() != JavaTokenType.COMMA && !isAnonymousClass(node)) { return false; } } return true; } private boolean shouldEnforceIndentToChildren() { if (myNode.getElementType() != JavaElementType.EXPRESSION_LIST) { return false; } ASTNode parent = myNode.getTreeParent(); if (parent == null || parent.getElementType() != JavaElementType.METHOD_CALL_EXPRESSION) { return false; } PsiExpression[] arguments = ((PsiExpressionList)myNode.getPsi()).getExpressions(); return JavaFormatterUtil.hasMultilineArguments(arguments) && JavaFormatterUtil.isMultilineExceptArguments(arguments); } private static boolean isAnonymousClass(@Nullable ASTNode node) { if (node == null || node.getElementType() != JavaElementType.NEW_EXPRESSION) { return false; } ASTNode lastChild = node.getLastChildNode(); return lastChild != null && lastChild.getElementType() == JavaElementType.ANONYMOUS_CLASS; } @Nullable private ASTNode processEnumBlock(@NotNull List<Block> result, @Nullable ASTNode child, ASTNode last) { final WrappingStrategy wrappingStrategy = WrappingStrategy.createDoNotWrapCommaStrategy(Wrap .createWrap(getWrapType(mySettings.ENUM_CONSTANTS_WRAP), true)); while (child != null) { if (!FormatterUtil.containsWhiteSpacesOnly(child) && child.getTextLength() > 0) { result.add(createJavaBlock(child, mySettings, myJavaSettings, Indent.getNormalIndent(), wrappingStrategy.getWrap(child.getElementType()), AlignmentStrategy.getNullStrategy())); if (child == last) return child; } child = child.getTreeNext(); } return null; } private void setChildAlignment(final Alignment alignment) { myChildAlignment = alignment; } private void setChildIndent(final Indent internalIndent) { myChildIndent = internalIndent; } @Nullable private static Alignment createAlignmentOrDefault(@Nullable Alignment base, @Nullable final Alignment defaultAlignment) { if (defaultAlignment == null) { return base == null ? Alignment.createAlignment() : Alignment.createChildAlignment(base); } return defaultAlignment; } private int getBraceStyle() { final PsiElement psiNode = SourceTreeToPsiMap.treeElementToPsi(myNode); if (psiNode instanceof PsiClass) { return mySettings.CLASS_BRACE_STYLE; } if (psiNode instanceof PsiMethod || psiNode instanceof PsiCodeBlock && psiNode.getParent() != null && psiNode.getParent() instanceof PsiMethod) { return mySettings.METHOD_BRACE_STYLE; } return mySettings.BRACE_STYLE; } protected Indent getCodeBlockInternalIndent(final int baseChildrenIndent) { return getCodeBlockInternalIndent(baseChildrenIndent, false); } protected Indent getCodeBlockInternalIndent(final int baseChildrenIndent, boolean enforceParentIndent) { if (isTopLevelClass() && mySettings.DO_NOT_INDENT_TOP_LEVEL_CLASS_MEMBERS) { return Indent.getNoneIndent(); } final int braceStyle = getBraceStyle(); return braceStyle == CommonCodeStyleSettings.NEXT_LINE_SHIFTED ? createNormalIndent(baseChildrenIndent - 1, enforceParentIndent) : createNormalIndent(baseChildrenIndent, enforceParentIndent); } protected static Indent createNormalIndent(final int baseChildrenIndent) { return createNormalIndent(baseChildrenIndent, false); } protected static Indent createNormalIndent(final int baseChildrenIndent, boolean enforceIndentToChildren) { if (baseChildrenIndent == 1) { return Indent.getIndent(Indent.Type.NORMAL, false, enforceIndentToChildren); } else if (baseChildrenIndent <= 0) { return Indent.getNoneIndent(); } else { LOG.assertTrue(false); return Indent.getIndent(Indent.Type.NORMAL, false, enforceIndentToChildren); } } private boolean isTopLevelClass() { return myNode.getElementType() == JavaElementType.CLASS && SourceTreeToPsiMap.treeElementToPsi(myNode.getTreeParent()) instanceof PsiFile; } protected Indent getCodeBlockExternalIndent() { final int braceStyle = getBraceStyle(); if (braceStyle == CommonCodeStyleSettings.END_OF_LINE || braceStyle == CommonCodeStyleSettings.NEXT_LINE || braceStyle == CommonCodeStyleSettings.NEXT_LINE_IF_WRAPPED) { return Indent.getNoneIndent(); } return Indent.getNormalIndent(); } protected Indent getCodeBlockChildExternalIndent(final int newChildIndex) { final int braceStyle = getBraceStyle(); if (!isAfterCodeBlock(newChildIndex)) { return Indent.getNormalIndent(); } if (braceStyle == CommonCodeStyleSettings.NEXT_LINE || braceStyle == CommonCodeStyleSettings.NEXT_LINE_IF_WRAPPED || braceStyle == CommonCodeStyleSettings.END_OF_LINE) { return Indent.getNoneIndent(); } return Indent.getNormalIndent(); } private boolean isAfterCodeBlock(final int newChildIndex) { if (newChildIndex == 0) return false; Block blockBefore = getSubBlocks().get(newChildIndex - 1); return blockBefore instanceof CodeBlockBlock; } /** * <b>Note:</b> this method is considered to be a legacy heritage and is assumed to be removed as soon as formatting processing * is refactored * * @param elementType target element type * @return <code>null</code> all the time */ @Nullable @Override public Wrap getReservedWrap(IElementType elementType) { return myPreferredWraps != null ? myPreferredWraps.get(elementType) : null; } /** * Defines contract for associating operation type and particular wrap instance. I.e. given wrap object <b>may</b> be returned * from subsequent {@link #getReservedWrap(IElementType)} call if given operation type is used as an argument there. * <p/> * Default implementation ({@link AbstractJavaBlock#setReservedWrap(Wrap, IElementType)}) does nothing. * <p/> * <b>Note:</b> this method is considered to be a legacy heritage and is assumed to be removed as soon as formatting processing * is refactored * * @param reservedWrap reserved wrap instance * @param operationType target operation type to associate with the given wrap instance */ public void setReservedWrap(final Wrap reservedWrap, final IElementType operationType) { if (myPreferredWraps == null) { myPreferredWraps = ContainerUtil.newHashMap(); } myPreferredWraps.put(operationType, reservedWrap); } @Nullable protected static ASTNode getTreeNode(final Block child2) { if (child2 instanceof JavaBlock) { return ((JavaBlock)child2).getFirstTreeNode(); } if (child2 instanceof LeafBlock) { return ((LeafBlock)child2).getTreeNode(); } return null; } @Override @NotNull public ChildAttributes getChildAttributes(final int newChildIndex) { if (myUseChildAttributes) { return new ChildAttributes(myChildIndent, myChildAlignment); } if (isAfter(newChildIndex, new IElementType[]{JavaDocElementType.DOC_COMMENT})) { return new ChildAttributes(Indent.getNoneIndent(), myChildAlignment); } return super.getChildAttributes(newChildIndex); } @Override @Nullable protected Indent getChildIndent() { return getChildIndent(myNode, myIndentSettings); } @NotNull public CommonCodeStyleSettings getSettings() { return mySettings; } protected boolean isAfter(final int newChildIndex, @NotNull final IElementType[] elementTypes) { if (newChildIndex == 0) return false; final Block previousBlock = getSubBlocks().get(newChildIndex - 1); if (!(previousBlock instanceof AbstractBlock)) return false; final IElementType previousElementType = ((AbstractBlock)previousBlock).getNode().getElementType(); for (IElementType elementType : elementTypes) { if (previousElementType == elementType) return true; } return false; } @Nullable protected Alignment getUsedAlignment(final int newChildIndex) { final List<Block> subBlocks = getSubBlocks(); for (int i = 0; i < newChildIndex; i++) { if (i >= subBlocks.size()) return null; final Block block = subBlocks.get(i); final Alignment alignment = block.getAlignment(); if (alignment != null) return alignment; } return null; } @Override public boolean isLeaf() { return ShiftIndentInsideHelper.mayShiftIndentInside(myNode); } @Nullable protected ASTNode composeCodeBlock(@NotNull final List<Block> result, ASTNode child, final Indent indent, final int childrenIndent, @Nullable final Wrap childWrap) { final ArrayList<Block> localResult = new ArrayList<Block>(); processChild(localResult, child, AlignmentStrategy.getNullStrategy(), null, Indent.getNoneIndent()); child = child.getTreeNext(); ChildAlignmentStrategyProvider alignmentStrategyProvider = getStrategyProvider(); while (child != null) { if (FormatterUtil.containsWhiteSpacesOnly(child)) { child = child.getTreeNext(); continue; } Indent childIndent = getIndentForCodeBlock(child, childrenIndent); AlignmentStrategy alignmentStrategyToUse = alignmentStrategyProvider.getNextChildStrategy(child); final boolean isRBrace = isRBrace(child); child = processChild(localResult, child, alignmentStrategyToUse, childWrap, childIndent); if (isRBrace) { result.add(createCodeBlockBlock(localResult, indent, childrenIndent)); return child; } if (child != null) { child = child.getTreeNext(); } } result.add(createCodeBlockBlock(localResult, indent, childrenIndent)); return null; } private ChildAlignmentStrategyProvider getStrategyProvider() { if (mySettings.ALIGN_GROUP_FIELD_DECLARATIONS && myNode.getElementType() == JavaElementType.CLASS) { return new SubsequentFieldAligner(mySettings); } ASTNode parent = myNode.getTreeParent(); IElementType parentType = parent != null ? parent.getElementType() : null; if (mySettings.ALIGN_CONSECUTIVE_VARIABLE_DECLARATIONS && parentType == JavaElementType.METHOD) { return new SubsequentVariablesAligner(); } return ChildAlignmentStrategyProvider.NULL_STRATEGY_PROVIDER; } private Indent getIndentForCodeBlock(ASTNode child, int childrenIndent) { if (child.getElementType() == JavaElementType.CODE_BLOCK && (getBraceStyle() == CommonCodeStyleSettings.NEXT_LINE_SHIFTED || getBraceStyle() == CommonCodeStyleSettings.NEXT_LINE_SHIFTED2)) { return Indent.getNormalIndent(); } return isRBrace(child) ? Indent.getNoneIndent() : getCodeBlockInternalIndent(childrenIndent, false); } public AbstractJavaBlock getParentBlock() { return myParentBlock; } public void setParentBlock(@NotNull AbstractJavaBlock parentBlock) { myParentBlock = parentBlock; } @NotNull public SyntheticCodeBlock createCodeBlockBlock(final List<Block> localResult, final Indent indent, final int childrenIndent) { final SyntheticCodeBlock result = new SyntheticCodeBlock(localResult, null, getSettings(), myJavaSettings, indent, null); result.setChildAttributes(new ChildAttributes(getCodeBlockInternalIndent(childrenIndent), null)); return result; } }
apache-2.0
marsorp/blog
presto166/presto-main/src/main/java/com/facebook/presto/sql/relational/SqlToRowExpressionTranslator.java
28699
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.facebook.presto.sql.relational; import com.facebook.presto.Session; import com.facebook.presto.metadata.FunctionKind; import com.facebook.presto.metadata.FunctionRegistry; import com.facebook.presto.metadata.Signature; import com.facebook.presto.spi.type.DecimalParseResult; import com.facebook.presto.spi.type.Decimals; import com.facebook.presto.spi.type.TimeZoneKey; import com.facebook.presto.spi.type.Type; import com.facebook.presto.spi.type.TypeManager; import com.facebook.presto.spi.type.TypeSignature; import com.facebook.presto.sql.relational.optimizer.ExpressionOptimizer; import com.facebook.presto.sql.tree.ArithmeticBinaryExpression; import com.facebook.presto.sql.tree.ArithmeticUnaryExpression; import com.facebook.presto.sql.tree.ArrayConstructor; import com.facebook.presto.sql.tree.AstVisitor; import com.facebook.presto.sql.tree.BetweenPredicate; import com.facebook.presto.sql.tree.BinaryLiteral; import com.facebook.presto.sql.tree.BooleanLiteral; import com.facebook.presto.sql.tree.Cast; import com.facebook.presto.sql.tree.CharLiteral; import com.facebook.presto.sql.tree.CoalesceExpression; import com.facebook.presto.sql.tree.ComparisonExpression; import com.facebook.presto.sql.tree.DecimalLiteral; import com.facebook.presto.sql.tree.DereferenceExpression; import com.facebook.presto.sql.tree.DoubleLiteral; import com.facebook.presto.sql.tree.Expression; import com.facebook.presto.sql.tree.FieldReference; import com.facebook.presto.sql.tree.FunctionCall; import com.facebook.presto.sql.tree.GenericLiteral; import com.facebook.presto.sql.tree.IfExpression; import com.facebook.presto.sql.tree.InListExpression; import com.facebook.presto.sql.tree.InPredicate; import com.facebook.presto.sql.tree.IntervalLiteral; import com.facebook.presto.sql.tree.IsNotNullPredicate; import com.facebook.presto.sql.tree.IsNullPredicate; import com.facebook.presto.sql.tree.LambdaArgumentDeclaration; import com.facebook.presto.sql.tree.LambdaExpression; import com.facebook.presto.sql.tree.LikePredicate; import com.facebook.presto.sql.tree.LogicalBinaryExpression; import com.facebook.presto.sql.tree.LongLiteral; import com.facebook.presto.sql.tree.NotExpression; import com.facebook.presto.sql.tree.NullIfExpression; import com.facebook.presto.sql.tree.NullLiteral; import com.facebook.presto.sql.tree.Row; import com.facebook.presto.sql.tree.SearchedCaseExpression; import com.facebook.presto.sql.tree.SimpleCaseExpression; import com.facebook.presto.sql.tree.StringLiteral; import com.facebook.presto.sql.tree.SubscriptExpression; import com.facebook.presto.sql.tree.SymbolReference; import com.facebook.presto.sql.tree.TimeLiteral; import com.facebook.presto.sql.tree.TimestampLiteral; import com.facebook.presto.sql.tree.TryExpression; import com.facebook.presto.sql.tree.WhenClause; import com.facebook.presto.type.RowType; import com.facebook.presto.type.RowType.RowField; import com.facebook.presto.type.UnknownType; import com.google.common.collect.ImmutableList; import com.google.common.collect.Lists; import java.util.IdentityHashMap; import java.util.List; import static com.facebook.presto.metadata.FunctionKind.SCALAR; import static com.facebook.presto.spi.type.BigintType.BIGINT; import static com.facebook.presto.spi.type.BooleanType.BOOLEAN; import static com.facebook.presto.spi.type.CharType.createCharType; import static com.facebook.presto.spi.type.DoubleType.DOUBLE; import static com.facebook.presto.spi.type.IntegerType.INTEGER; import static com.facebook.presto.spi.type.TimeWithTimeZoneType.TIME_WITH_TIME_ZONE; import static com.facebook.presto.spi.type.TimestampWithTimeZoneType.TIMESTAMP_WITH_TIME_ZONE; import static com.facebook.presto.spi.type.TypeSignature.parseTypeSignature; import static com.facebook.presto.spi.type.VarbinaryType.VARBINARY; import static com.facebook.presto.spi.type.VarcharType.VARCHAR; import static com.facebook.presto.spi.type.VarcharType.createVarcharType; import static com.facebook.presto.sql.relational.Expressions.call; import static com.facebook.presto.sql.relational.Expressions.constant; import static com.facebook.presto.sql.relational.Expressions.constantNull; import static com.facebook.presto.sql.relational.Expressions.field; import static com.facebook.presto.sql.relational.Signatures.arithmeticExpressionSignature; import static com.facebook.presto.sql.relational.Signatures.arithmeticNegationSignature; import static com.facebook.presto.sql.relational.Signatures.arrayConstructorSignature; import static com.facebook.presto.sql.relational.Signatures.betweenSignature; import static com.facebook.presto.sql.relational.Signatures.castSignature; import static com.facebook.presto.sql.relational.Signatures.coalesceSignature; import static com.facebook.presto.sql.relational.Signatures.comparisonExpressionSignature; import static com.facebook.presto.sql.relational.Signatures.dereferenceSignature; import static com.facebook.presto.sql.relational.Signatures.likePatternSignature; import static com.facebook.presto.sql.relational.Signatures.likeSignature; import static com.facebook.presto.sql.relational.Signatures.logicalExpressionSignature; import static com.facebook.presto.sql.relational.Signatures.nullIfSignature; import static com.facebook.presto.sql.relational.Signatures.rowConstructorSignature; import static com.facebook.presto.sql.relational.Signatures.subscriptSignature; import static com.facebook.presto.sql.relational.Signatures.switchSignature; import static com.facebook.presto.sql.relational.Signatures.tryCastSignature; import static com.facebook.presto.sql.relational.Signatures.whenSignature; import static com.facebook.presto.type.JsonType.JSON; import static com.facebook.presto.type.LikePatternType.LIKE_PATTERN; import static com.facebook.presto.util.DateTimeUtils.parseDayTimeInterval; import static com.facebook.presto.util.DateTimeUtils.parseTimeWithTimeZone; import static com.facebook.presto.util.DateTimeUtils.parseTimeWithoutTimeZone; import static com.facebook.presto.util.DateTimeUtils.parseTimestampWithTimeZone; import static com.facebook.presto.util.DateTimeUtils.parseTimestampWithoutTimeZone; import static com.facebook.presto.util.DateTimeUtils.parseYearMonthInterval; import static com.facebook.presto.util.ImmutableCollectors.toImmutableList; import static com.facebook.presto.util.Types.checkType; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkState; import static io.airlift.slice.SliceUtf8.countCodePoints; import static io.airlift.slice.Slices.utf8Slice; import static java.util.Objects.requireNonNull; public final class SqlToRowExpressionTranslator { private SqlToRowExpressionTranslator() {} public static RowExpression translate( Expression expression, FunctionKind functionKind, IdentityHashMap<Expression, Type> types, FunctionRegistry functionRegistry, TypeManager typeManager, Session session, boolean optimize) { RowExpression result = new Visitor(functionKind, types, typeManager, session.getTimeZoneKey()).process(expression, null); requireNonNull(result, "translated expression is null"); if (optimize) { ExpressionOptimizer optimizer = new ExpressionOptimizer(functionRegistry, typeManager, session); return optimizer.optimize(result); } return result; } private static class Visitor extends AstVisitor<RowExpression, Void> { private final FunctionKind functionKind; private final IdentityHashMap<Expression, Type> types; private final TypeManager typeManager; private final TimeZoneKey timeZoneKey; private Visitor(FunctionKind functionKind, IdentityHashMap<Expression, Type> types, TypeManager typeManager, TimeZoneKey timeZoneKey) { this.functionKind = functionKind; this.types = types; this.typeManager = typeManager; this.timeZoneKey = timeZoneKey; } @Override protected RowExpression visitExpression(Expression node, Void context) { throw new UnsupportedOperationException("not yet implemented: expression translator for " + node.getClass().getName()); } @Override protected RowExpression visitFieldReference(FieldReference node, Void context) { return field(node.getFieldIndex(), types.get(node)); } @Override protected RowExpression visitNullLiteral(NullLiteral node, Void context) { return constantNull(UnknownType.UNKNOWN); } @Override protected RowExpression visitBooleanLiteral(BooleanLiteral node, Void context) { return constant(node.getValue(), BOOLEAN); } @Override protected RowExpression visitLongLiteral(LongLiteral node, Void context) { if (node.getValue() >= Integer.MIN_VALUE && node.getValue() <= Integer.MAX_VALUE) { return constant(node.getValue(), INTEGER); } return constant(node.getValue(), BIGINT); } @Override protected RowExpression visitDoubleLiteral(DoubleLiteral node, Void context) { return constant(node.getValue(), DOUBLE); } @Override protected RowExpression visitDecimalLiteral(DecimalLiteral node, Void context) { DecimalParseResult parseResult = Decimals.parse(node.getValue()); return constant(parseResult.getObject(), parseResult.getType()); } @Override protected RowExpression visitStringLiteral(StringLiteral node, Void context) { return constant(node.getSlice(), createVarcharType(countCodePoints(node.getSlice()))); } @Override protected RowExpression visitCharLiteral(CharLiteral node, Void context) { return constant(node.getSlice(), createCharType(node.getValue().length())); } @Override protected RowExpression visitBinaryLiteral(BinaryLiteral node, Void context) { return constant(node.getValue(), VARBINARY); } @Override protected RowExpression visitGenericLiteral(GenericLiteral node, Void context) { Type type = typeManager.getType(parseTypeSignature(node.getType())); if (type == null) { throw new IllegalArgumentException("Unsupported type: " + node.getType()); } if (JSON.equals(type)) { return call( new Signature("json_parse", SCALAR, types.get(node).getTypeSignature(), VARCHAR.getTypeSignature()), types.get(node), constant(utf8Slice(node.getValue()), VARCHAR)); } return call( castSignature(types.get(node), VARCHAR), types.get(node), constant(utf8Slice(node.getValue()), VARCHAR)); } @Override protected RowExpression visitTimeLiteral(TimeLiteral node, Void context) { long value; if (types.get(node).equals(TIME_WITH_TIME_ZONE)) { value = parseTimeWithTimeZone(node.getValue()); } else { // parse in time zone of client value = parseTimeWithoutTimeZone(timeZoneKey, node.getValue()); } return constant(value, types.get(node)); } @Override protected RowExpression visitTimestampLiteral(TimestampLiteral node, Void context) { long value; if (types.get(node).equals(TIMESTAMP_WITH_TIME_ZONE)) { value = parseTimestampWithTimeZone(timeZoneKey, node.getValue()); } else { // parse in time zone of client value = parseTimestampWithoutTimeZone(timeZoneKey, node.getValue()); } return constant(value, types.get(node)); } @Override protected RowExpression visitIntervalLiteral(IntervalLiteral node, Void context) { long value; if (node.isYearToMonth()) { value = node.getSign().multiplier() * parseYearMonthInterval(node.getValue(), node.getStartField(), node.getEndField()); } else { value = node.getSign().multiplier() * parseDayTimeInterval(node.getValue(), node.getStartField(), node.getEndField()); } return constant(value, types.get(node)); } @Override protected RowExpression visitComparisonExpression(ComparisonExpression node, Void context) { RowExpression left = process(node.getLeft(), context); RowExpression right = process(node.getRight(), context); return call( comparisonExpressionSignature(node.getType(), left.getType(), right.getType()), BOOLEAN, left, right); } @Override protected RowExpression visitFunctionCall(FunctionCall node, Void context) { List<RowExpression> arguments = node.getArguments().stream() .map(value -> process(value, context)) .collect(toImmutableList()); List<TypeSignature> argumentTypes = arguments.stream() .map(RowExpression::getType) .map(Type::getTypeSignature) .collect(toImmutableList()); Signature signature = new Signature(node.getName().getSuffix(), functionKind, types.get(node).getTypeSignature(), argumentTypes); return call(signature, types.get(node), arguments); } @Override protected RowExpression visitSymbolReference(SymbolReference node, Void context) { return new VariableReferenceExpression(node.getName(), types.get(node)); } @Override protected RowExpression visitLambdaExpression(LambdaExpression node, Void context) { RowExpression body = process(node.getBody(), context); Type type = types.get(node); List<Type> typeParameters = type.getTypeParameters(); List<Type> argumentTypes = typeParameters.subList(0, typeParameters.size() - 1); List<String> argumentNames = node.getArguments().stream() .map(LambdaArgumentDeclaration::getName) .collect(toImmutableList()); return new LambdaDefinitionExpression(argumentTypes, argumentNames, body); } @Override protected RowExpression visitArithmeticBinary(ArithmeticBinaryExpression node, Void context) { RowExpression left = process(node.getLeft(), context); RowExpression right = process(node.getRight(), context); return call( arithmeticExpressionSignature(node.getType(), types.get(node), left.getType(), right.getType()), types.get(node), left, right); } @Override protected RowExpression visitArithmeticUnary(ArithmeticUnaryExpression node, Void context) { RowExpression expression = process(node.getValue(), context); switch (node.getSign()) { case PLUS: return expression; case MINUS: return call( arithmeticNegationSignature(types.get(node), expression.getType()), types.get(node), expression); } throw new UnsupportedOperationException("Unsupported unary operator: " + node.getSign()); } @Override protected RowExpression visitLogicalBinaryExpression(LogicalBinaryExpression node, Void context) { return call( logicalExpressionSignature(node.getType()), BOOLEAN, process(node.getLeft(), context), process(node.getRight(), context)); } @Override protected RowExpression visitCast(Cast node, Void context) { RowExpression value = process(node.getExpression(), context); if (node.isTypeOnly()) { return changeType(value, types.get(node)); } if (node.isSafe()) { return call(tryCastSignature(types.get(node), value.getType()), types.get(node), value); } return call(castSignature(types.get(node), value.getType()), types.get(node), value); } private static RowExpression changeType(RowExpression value, Type targetType) { ChangeTypeVisitor visitor = new ChangeTypeVisitor(targetType); return value.accept(visitor, null); } private static class ChangeTypeVisitor implements RowExpressionVisitor<Void, RowExpression> { private final Type targetType; private ChangeTypeVisitor(Type targetType) { this.targetType = targetType; } @Override public RowExpression visitCall(CallExpression call, Void context) { return new CallExpression(call.getSignature(), targetType, call.getArguments()); } @Override public RowExpression visitInputReference(InputReferenceExpression reference, Void context) { return new InputReferenceExpression(reference.getField(), targetType); } @Override public RowExpression visitConstant(ConstantExpression literal, Void context) { return new ConstantExpression(literal.getValue(), targetType); } @Override public RowExpression visitLambda(LambdaDefinitionExpression lambda, Void context) { throw new UnsupportedOperationException(); } @Override public RowExpression visitVariableReference(VariableReferenceExpression reference, Void context) { return new VariableReferenceExpression(reference.getName(), targetType); } } @Override protected RowExpression visitCoalesceExpression(CoalesceExpression node, Void context) { List<RowExpression> arguments = node.getOperands().stream() .map(value -> process(value, context)) .collect(toImmutableList()); List<Type> argumentTypes = arguments.stream().map(RowExpression::getType).collect(toImmutableList()); return call(coalesceSignature(types.get(node), argumentTypes), types.get(node), arguments); } @Override protected RowExpression visitSimpleCaseExpression(SimpleCaseExpression node, Void context) { ImmutableList.Builder<RowExpression> arguments = ImmutableList.builder(); arguments.add(process(node.getOperand(), context)); for (WhenClause clause : node.getWhenClauses()) { arguments.add(call(whenSignature(types.get(clause)), types.get(clause), process(clause.getOperand(), context), process(clause.getResult(), context))); } Type returnType = types.get(node); arguments.add(node.getDefaultValue() .map((value) -> process(value, context)) .orElse(constantNull(returnType))); return call(switchSignature(returnType), returnType, arguments.build()); } @Override protected RowExpression visitSearchedCaseExpression(SearchedCaseExpression node, Void context) { /* Translates an expression like: case when cond1 then value1 when cond2 then value2 when cond3 then value3 else value4 end To: IF(cond1, value1, IF(cond2, value2, If(cond3, value3, value4))) */ RowExpression expression = node.getDefaultValue() .map((value) -> process(value, context)) .orElse(constantNull(types.get(node))); for (WhenClause clause : Lists.reverse(node.getWhenClauses())) { expression = call( Signatures.ifSignature(types.get(node)), types.get(node), process(clause.getOperand(), context), process(clause.getResult(), context), expression); } return expression; } @Override protected RowExpression visitDereferenceExpression(DereferenceExpression node, Void context) { RowType rowType = checkType(types.get(node.getBase()), RowType.class, "type"); List<RowField> fields = rowType.getFields(); int index = -1; for (int i = 0; i < fields.size(); i++) { RowField field = fields.get(i); if (field.getName().isPresent() && field.getName().get().equalsIgnoreCase(node.getFieldName())) { checkArgument(index < 0, "Ambiguous field %s in type %s", field, rowType.getDisplayName()); index = i; } } checkState(index >= 0, "could not find field name: %s", node.getFieldName()); Type returnType = types.get(node); return call(dereferenceSignature(returnType, rowType), returnType, process(node.getBase(), context), constant(index, INTEGER)); } @Override protected RowExpression visitIfExpression(IfExpression node, Void context) { ImmutableList.Builder<RowExpression> arguments = ImmutableList.builder(); arguments.add(process(node.getCondition(), context)) .add(process(node.getTrueValue(), context)); if (node.getFalseValue().isPresent()) { arguments.add(process(node.getFalseValue().get(), context)); } else { arguments.add(constantNull(types.get(node))); } return call(Signatures.ifSignature(types.get(node)), types.get(node), arguments.build()); } @Override protected RowExpression visitTryExpression(TryExpression node, Void context) { return call(Signatures.trySignature(types.get(node)), types.get(node), process(node.getInnerExpression(), context)); } @Override protected RowExpression visitInPredicate(InPredicate node, Void context) { ImmutableList.Builder<RowExpression> arguments = ImmutableList.builder(); arguments.add(process(node.getValue(), context)); InListExpression values = (InListExpression) node.getValueList(); for (Expression value : values.getValues()) { arguments.add(process(value, context)); } return call(Signatures.inSignature(), BOOLEAN, arguments.build()); } @Override protected RowExpression visitIsNotNullPredicate(IsNotNullPredicate node, Void context) { RowExpression expression = process(node.getValue(), context); return call( Signatures.notSignature(), BOOLEAN, call(Signatures.isNullSignature(expression.getType()), BOOLEAN, ImmutableList.of(expression))); } @Override protected RowExpression visitIsNullPredicate(IsNullPredicate node, Void context) { RowExpression expression = process(node.getValue(), context); return call(Signatures.isNullSignature(expression.getType()), BOOLEAN, expression); } @Override protected RowExpression visitNotExpression(NotExpression node, Void context) { return call(Signatures.notSignature(), BOOLEAN, process(node.getValue(), context)); } @Override protected RowExpression visitNullIfExpression(NullIfExpression node, Void context) { RowExpression first = process(node.getFirst(), context); RowExpression second = process(node.getSecond(), context); return call( nullIfSignature(types.get(node), first.getType(), second.getType()), types.get(node), first, second); } @Override protected RowExpression visitBetweenPredicate(BetweenPredicate node, Void context) { RowExpression value = process(node.getValue(), context); RowExpression min = process(node.getMin(), context); RowExpression max = process(node.getMax(), context); return call( betweenSignature(value.getType(), min.getType(), max.getType()), BOOLEAN, value, min, max); } @Override protected RowExpression visitLikePredicate(LikePredicate node, Void context) { RowExpression value = process(node.getValue(), context); RowExpression pattern = process(node.getPattern(), context); if (node.getEscape() != null) { RowExpression escape = process(node.getEscape(), context); return call(likeSignature(), BOOLEAN, value, call(likePatternSignature(), LIKE_PATTERN, pattern, escape)); } return call(likeSignature(), BOOLEAN, value, call(castSignature(LIKE_PATTERN, VARCHAR), LIKE_PATTERN, pattern)); } @Override protected RowExpression visitSubscriptExpression(SubscriptExpression node, Void context) { RowExpression base = process(node.getBase(), context); RowExpression index = process(node.getIndex(), context); return call( subscriptSignature(types.get(node), base.getType(), index.getType()), types.get(node), base, index); } @Override protected RowExpression visitArrayConstructor(ArrayConstructor node, Void context) { List<RowExpression> arguments = node.getValues().stream() .map(value -> process(value, context)) .collect(toImmutableList()); List<Type> argumentTypes = arguments.stream() .map(RowExpression::getType) .collect(toImmutableList()); return call(arrayConstructorSignature(types.get(node), argumentTypes), types.get(node), arguments); } @Override protected RowExpression visitRow(Row node, Void context) { List<RowExpression> arguments = node.getItems().stream() .map(value -> process(value, context)) .collect(toImmutableList()); Type returnType = types.get(node); List<Type> argumentTypes = node.getItems().stream() .map(value -> types.get(value)) .collect(toImmutableList()); return call(rowConstructorSignature(returnType, argumentTypes), returnType, arguments); } } }
apache-2.0
sebbrudzinski/motech
platform/mds/mds/src/test/java/org/motechproject/mds/builder/impl/EntityMetadataBuilderTest.java
22796
package org.motechproject.mds.builder.impl; import javassist.CannotCompileException; import javassist.ClassPool; import javassist.CtClass; import javassist.CtField; import javassist.NotFoundException; import org.apache.commons.lang.reflect.FieldUtils; import org.joda.time.DateTime; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; import org.motechproject.mds.annotations.internal.samples.AnotherSample; import org.motechproject.mds.builder.EntityMetadataBuilder; import org.motechproject.mds.builder.Sample; import org.motechproject.mds.builder.SampleWithIncrementStrategy; import org.motechproject.mds.domain.ClassData; import org.motechproject.mds.domain.EntityType; import org.motechproject.mds.domain.OneToManyRelationship; import org.motechproject.mds.domain.OneToOneRelationship; import org.motechproject.mds.dto.EntityDto; import org.motechproject.mds.dto.FieldBasicDto; import org.motechproject.mds.dto.FieldDto; import org.motechproject.mds.dto.LookupDto; import org.motechproject.mds.dto.LookupFieldDto; import org.motechproject.mds.dto.LookupFieldType; import org.motechproject.mds.dto.MetadataDto; import org.motechproject.mds.dto.SchemaHolder; import org.motechproject.mds.dto.TypeDto; import org.motechproject.mds.javassist.MotechClassPool; import org.powermock.api.mockito.PowerMockito; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import javax.jdo.annotations.IdGeneratorStrategy; import javax.jdo.annotations.IdentityType; import javax.jdo.annotations.PersistenceModifier; import javax.jdo.metadata.ClassMetadata; import javax.jdo.metadata.ClassPersistenceModifier; import javax.jdo.metadata.CollectionMetadata; import javax.jdo.metadata.FieldMetadata; import javax.jdo.metadata.ForeignKeyMetadata; import javax.jdo.metadata.IndexMetadata; import javax.jdo.metadata.InheritanceMetadata; import javax.jdo.metadata.JDOMetadata; import javax.jdo.metadata.PackageMetadata; import javax.jdo.metadata.UniqueMetadata; import java.util.ArrayList; import java.util.List; import static java.util.Arrays.asList; import static java.util.Collections.singletonList; import static org.mockito.Matchers.anyBoolean; import static org.mockito.Matchers.anyString; import static org.mockito.Matchers.eq; import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyZeroInteractions; import static org.mockito.Mockito.when; import static org.mockito.MockitoAnnotations.initMocks; import static org.motechproject.mds.testutil.FieldTestHelper.fieldDto; import static org.motechproject.mds.util.Constants.MetadataKeys.RELATED_CLASS; import static org.motechproject.mds.util.Constants.MetadataKeys.RELATED_FIELD; import static org.motechproject.mds.util.Constants.Util.CREATION_DATE_DISPLAY_FIELD_NAME; import static org.motechproject.mds.util.Constants.Util.CREATION_DATE_FIELD_NAME; import static org.motechproject.mds.util.Constants.Util.CREATOR_DISPLAY_FIELD_NAME; import static org.motechproject.mds.util.Constants.Util.CREATOR_FIELD_NAME; import static org.motechproject.mds.util.Constants.Util.DATANUCLEUS; import static org.motechproject.mds.util.Constants.Util.MODIFICATION_DATE_DISPLAY_FIELD_NAME; import static org.motechproject.mds.util.Constants.Util.MODIFICATION_DATE_FIELD_NAME; import static org.motechproject.mds.util.Constants.Util.MODIFIED_BY_DISPLAY_FIELD_NAME; import static org.motechproject.mds.util.Constants.Util.MODIFIED_BY_FIELD_NAME; import static org.motechproject.mds.util.Constants.Util.OWNER_DISPLAY_FIELD_NAME; import static org.motechproject.mds.util.Constants.Util.OWNER_FIELD_NAME; import static org.motechproject.mds.util.Constants.Util.VALUE_GENERATOR; @RunWith(PowerMockRunner.class) @PrepareForTest({MotechClassPool.class, FieldUtils.class}) public class EntityMetadataBuilderTest { private static final String PACKAGE = "org.motechproject.mds.entity"; private static final String ENTITY_NAME = "Sample"; private static final String MODULE = "MrS"; private static final String NAMESPACE = "arrio"; private static final String TABLE_NAME = ""; private static final String CLASS_NAME = String.format("%s.%s", PACKAGE, ENTITY_NAME); private static final String TABLE_NAME_1 = String.format("MDS_%s", ENTITY_NAME).toUpperCase(); private static final String TABLE_NAME_2 = String.format("%s_%s", MODULE, ENTITY_NAME).toUpperCase(); private static final String TABLE_NAME_3 = String.format("%s_%s_%s", MODULE, NAMESPACE, ENTITY_NAME).toUpperCase(); private EntityMetadataBuilder entityMetadataBuilder = new EntityMetadataBuilderImpl(); @Mock private EntityDto entity; @Mock private FieldDto idField; @Mock private JDOMetadata jdoMetadata; @Mock private PackageMetadata packageMetadata; @Mock private ClassMetadata classMetadata; @Mock private FieldMetadata idMetadata; @Mock private InheritanceMetadata inheritanceMetadata; @Mock private IndexMetadata indexMetadata; @Mock private SchemaHolder schemaHolder; @Before public void setUp() { initMocks(this); when(entity.getClassName()).thenReturn(CLASS_NAME); when(classMetadata.newFieldMetadata("id")).thenReturn(idMetadata); when(idMetadata.getName()).thenReturn("id"); when(classMetadata.newInheritanceMetadata()).thenReturn(inheritanceMetadata); when(schemaHolder.getFieldByName(entity, "id")).thenReturn(idField); when(entity.isBaseEntity()).thenReturn(true); } @Test public void shouldAddEntityMetadata() throws Exception { when(entity.getName()).thenReturn(ENTITY_NAME); when(entity.getModule()).thenReturn(MODULE); when(entity.getNamespace()).thenReturn(NAMESPACE); when(entity.getTableName()).thenReturn(TABLE_NAME); when(jdoMetadata.newPackageMetadata(PACKAGE)).thenReturn(packageMetadata); when(packageMetadata.newClassMetadata(ENTITY_NAME)).thenReturn(classMetadata); entityMetadataBuilder.addEntityMetadata(jdoMetadata, entity, Sample.class, schemaHolder); verify(jdoMetadata).newPackageMetadata(PACKAGE); verify(packageMetadata).newClassMetadata(ENTITY_NAME); verify(classMetadata).setTable(TABLE_NAME_3); verifyCommonClassMetadata(); } @Test public void shouldAddToAnExistingPackage() { when(entity.getName()).thenReturn(ENTITY_NAME); when(entity.getTableName()).thenReturn(TABLE_NAME); when(jdoMetadata.getPackages()).thenReturn(new PackageMetadata[]{packageMetadata}); when(packageMetadata.getName()).thenReturn(PACKAGE); when(packageMetadata.newClassMetadata(ENTITY_NAME)).thenReturn(classMetadata); entityMetadataBuilder.addEntityMetadata(jdoMetadata, entity, Sample.class, schemaHolder); verify(jdoMetadata, never()).newPackageMetadata(PACKAGE); verify(jdoMetadata).getPackages(); verify(packageMetadata).newClassMetadata(ENTITY_NAME); verify(classMetadata).setTable(TABLE_NAME_1); verifyCommonClassMetadata(); } @Test public void shouldSetAppropriateTableName() throws Exception { when(entity.getName()).thenReturn(ENTITY_NAME); when(entity.getTableName()).thenReturn(TABLE_NAME); when(jdoMetadata.newPackageMetadata(anyString())).thenReturn(packageMetadata); when(packageMetadata.newClassMetadata(anyString())).thenReturn(classMetadata); entityMetadataBuilder.addEntityMetadata(jdoMetadata, entity, Sample.class, schemaHolder); verify(classMetadata).setTable(TABLE_NAME_1); when(entity.getModule()).thenReturn(MODULE); entityMetadataBuilder.addEntityMetadata(jdoMetadata, entity, Sample.class, schemaHolder); verify(classMetadata).setTable(TABLE_NAME_2); when(entity.getNamespace()).thenReturn(NAMESPACE); entityMetadataBuilder.addEntityMetadata(jdoMetadata, entity, Sample.class, schemaHolder); verify(classMetadata).setTable(TABLE_NAME_3); } @Test public void shouldAddBaseEntityMetadata() throws Exception { CtField ctField = mock(CtField.class); CtClass ctClass = mock(CtClass.class); CtClass superClass = mock(CtClass.class); ClassData classData = mock(ClassData.class); ClassPool pool = mock(ClassPool.class); PowerMockito.mockStatic(MotechClassPool.class); PowerMockito.when(MotechClassPool.getDefault()).thenReturn(pool); when(classData.getClassName()).thenReturn(CLASS_NAME); when(classData.getModule()).thenReturn(MODULE); when(classData.getNamespace()).thenReturn(NAMESPACE); when(entity.getTableName()).thenReturn(TABLE_NAME); when(pool.getOrNull(CLASS_NAME)).thenReturn(ctClass); when(ctClass.getField("id")).thenReturn(ctField); when(ctClass.getSuperclass()).thenReturn(superClass); when(superClass.getName()).thenReturn(Object.class.getName()); when(jdoMetadata.newPackageMetadata(PACKAGE)).thenReturn(packageMetadata); when(packageMetadata.newClassMetadata(ENTITY_NAME)).thenReturn(classMetadata); entityMetadataBuilder.addBaseMetadata(jdoMetadata, classData, EntityType.STANDARD, Sample.class); verify(jdoMetadata).newPackageMetadata(PACKAGE); verify(packageMetadata).newClassMetadata(ENTITY_NAME); verify(classMetadata).setTable(TABLE_NAME_3); verifyCommonClassMetadata(); } @Test public void shouldAddOneToManyRelationshipMetadata() { FieldDto oneToManyField = fieldDto("oneToManyName", OneToManyRelationship.class); oneToManyField.addMetadata(new MetadataDto(RELATED_CLASS, "org.motechproject.test.MyClass")); FieldMetadata fmd = mock(FieldMetadata.class); CollectionMetadata collMd = mock(CollectionMetadata.class); when(entity.getName()).thenReturn(ENTITY_NAME); when(entity.getId()).thenReturn(2L); when(schemaHolder.getFields(entity)).thenReturn(singletonList(oneToManyField)); when(entity.getTableName()).thenReturn(TABLE_NAME); when(jdoMetadata.newPackageMetadata(PACKAGE)).thenReturn(packageMetadata); when(packageMetadata.newClassMetadata(ENTITY_NAME)).thenReturn(classMetadata); when(classMetadata.newFieldMetadata("oneToManyName")).thenReturn(fmd); when(fmd.getCollectionMetadata()).thenReturn(collMd); when(fmd.getName()).thenReturn("oneToManyName"); entityMetadataBuilder.addEntityMetadata(jdoMetadata, entity, Sample.class, schemaHolder); verifyCommonClassMetadata(); verify(fmd).setDefaultFetchGroup(true); verify(collMd).setEmbeddedElement(false); verify(collMd).setSerializedElement(false); verify(collMd).setElementType("org.motechproject.test.MyClass"); } @Test public void shouldAddOneToOneRelationshipMetadata() throws NotFoundException, CannotCompileException { final String relClassName = "org.motechproject.test.MyClass"; final String relFieldName = "myField"; FieldDto oneToOneField = fieldDto("oneToOneName", OneToOneRelationship.class); oneToOneField.addMetadata(new MetadataDto(RELATED_CLASS, relClassName)); oneToOneField.addMetadata(new MetadataDto(RELATED_FIELD, relFieldName)); FieldMetadata fmd = mock(FieldMetadata.class); when(fmd.getName()).thenReturn("oneToOneName"); ForeignKeyMetadata fkmd = mock(ForeignKeyMetadata.class); when(entity.getName()).thenReturn(ENTITY_NAME); when(entity.getId()).thenReturn(3L); when(schemaHolder.getFields(entity)).thenReturn(singletonList(oneToOneField)); when(entity.getTableName()).thenReturn(TABLE_NAME); when(jdoMetadata.newPackageMetadata(PACKAGE)).thenReturn(packageMetadata); when(packageMetadata.newClassMetadata(ENTITY_NAME)).thenReturn(classMetadata); when(classMetadata.newFieldMetadata("oneToOneName")).thenReturn(fmd); when(fmd.newForeignKeyMetadata()).thenReturn(fkmd); /* We simulate configuration for the bi-directional relationship (the related class has got a field that links back to the main class) */ CtClass myClass = mock(CtClass.class); CtClass relatedClass = mock(CtClass.class); CtField myField = mock(CtField.class); CtField relatedField = mock(CtField.class); when(myClass.getName()).thenReturn(relClassName); when(myClass.getDeclaredFields()).thenReturn(new CtField[]{myField}); when(myField.getType()).thenReturn(relatedClass); when(myField.getName()).thenReturn(relFieldName); when(relatedClass.getDeclaredFields()).thenReturn(new CtField[]{relatedField}); when(relatedClass.getName()).thenReturn(CLASS_NAME); entityMetadataBuilder.addEntityMetadata(jdoMetadata, entity, Sample.class, schemaHolder); verifyCommonClassMetadata(); verify(fmd).setDefaultFetchGroup(true); verify(fmd).setPersistenceModifier(PersistenceModifier.PERSISTENT); verify(fkmd).setName("fk_Sample_oneToOneName_3"); } @Test public void shouldSetIndexOnMetadataLookupField() throws Exception { FieldDto lookupField = fieldDto("lookupField", String.class); LookupDto lookup = new LookupDto(); lookup.setLookupName("A lookup"); lookup.setLookupFields(singletonList(new LookupFieldDto("lookupField", LookupFieldType.VALUE))); lookup.setIndexRequired(true); lookupField.setLookups(singletonList(lookup)); FieldMetadata fmd = mock(FieldMetadata.class); when(entity.getName()).thenReturn(ENTITY_NAME); when(entity.getId()).thenReturn(14L); when(schemaHolder.getFields(entity)).thenReturn(singletonList(lookupField)); when(entity.getTableName()).thenReturn(TABLE_NAME); when(jdoMetadata.newPackageMetadata(PACKAGE)).thenReturn(packageMetadata); when(packageMetadata.newClassMetadata(ENTITY_NAME)).thenReturn(classMetadata); when(classMetadata.newFieldMetadata("lookupField")).thenReturn(fmd); when(fmd.newIndexMetadata()).thenReturn(indexMetadata); PowerMockito.mockStatic(FieldUtils.class); when(FieldUtils.getDeclaredField(eq(Sample.class), anyString(), eq(true))).thenReturn(Sample.class.getDeclaredField("notInDefFg")); entityMetadataBuilder.addEntityMetadata(jdoMetadata, entity, Sample.class, schemaHolder); verifyCommonClassMetadata(); verify(fmd).newIndexMetadata(); verify(indexMetadata).setName("lkp_idx_" + ENTITY_NAME + "_lookupField_14"); } @Test public void shouldAddObjectValueGeneratorToAppropriateFields() throws Exception { when(entity.getName()).thenReturn(ENTITY_NAME); when(entity.getTableName()).thenReturn(TABLE_NAME); when(jdoMetadata.newPackageMetadata(anyString())).thenReturn(packageMetadata); when(packageMetadata.newClassMetadata(anyString())).thenReturn(classMetadata); List<FieldDto> fields = new ArrayList<>(); // for these fields the appropriate generator should be added fields.add(fieldDto(1L, CREATOR_FIELD_NAME, String.class.getName(), CREATOR_DISPLAY_FIELD_NAME, null)); fields.add(fieldDto(2L, OWNER_FIELD_NAME, String.class.getName(), OWNER_DISPLAY_FIELD_NAME, null)); fields.add(fieldDto(3L, CREATION_DATE_FIELD_NAME, DateTime.class.getName(), CREATION_DATE_DISPLAY_FIELD_NAME, null)); fields.add(fieldDto(4L, MODIFIED_BY_FIELD_NAME, String.class.getName(), MODIFIED_BY_DISPLAY_FIELD_NAME, null)); fields.add(fieldDto(5L, MODIFICATION_DATE_FIELD_NAME, DateTime.class.getName(), MODIFICATION_DATE_DISPLAY_FIELD_NAME, null)); doReturn(fields).when(schemaHolder).getFields(CLASS_NAME); final List<FieldMetadata> list = new ArrayList<>(); doAnswer(new Answer() { @Override public Object answer(InvocationOnMock invocation) throws Throwable { // we create a mock ... FieldMetadata metadata = mock(FieldMetadata.class); // ... and it should return correct name doReturn(invocation.getArguments()[0]).when(metadata).getName(); // Because we want to check that appropriate methods was executed // we added metadata to list and later we will verify conditions list.add(metadata); // in the end we have to return the mock return metadata; } }).when(classMetadata).newFieldMetadata(anyString()); PowerMockito.mockStatic(FieldUtils.class); when(FieldUtils.getDeclaredField(eq(Sample.class), anyString(), eq(true))).thenReturn(Sample.class.getDeclaredField("notInDefFg")); entityMetadataBuilder.addEntityMetadata(jdoMetadata, entity, Sample.class, schemaHolder); for (FieldMetadata metadata : list) { String name = metadata.getName(); // the id field should not have set object value generator metadata int invocations = "id".equalsIgnoreCase(name) ? 0 : 1; verify(classMetadata).newFieldMetadata(name); verify(metadata, times(invocations)).setPersistenceModifier(PersistenceModifier.PERSISTENT); verify(metadata, times(invocations)).setDefaultFetchGroup(true); verify(metadata, times(invocations)).newExtensionMetadata(DATANUCLEUS, VALUE_GENERATOR, "ovg." + name); } } @Test public void shouldNotSetDefaultInheritanceStrategyIfUserDefinedOwn() { when(entity.getName()).thenReturn(ENTITY_NAME); when(entity.getTableName()).thenReturn(TABLE_NAME); when(jdoMetadata.newPackageMetadata(anyString())).thenReturn(packageMetadata); when(packageMetadata.newClassMetadata(anyString())).thenReturn(classMetadata); entityMetadataBuilder.addEntityMetadata(jdoMetadata, entity, AnotherSample.class, schemaHolder); verifyZeroInteractions(inheritanceMetadata); } @Test public void shouldNotSetDefaultFetchGroupIfSpecified() { when(entity.getName()).thenReturn(ENTITY_NAME); when(entity.getTableName()).thenReturn(TABLE_NAME); when(jdoMetadata.newPackageMetadata(anyString())).thenReturn(packageMetadata); when(packageMetadata.newClassMetadata(anyString())).thenReturn(classMetadata); FieldDto field = fieldDto("notInDefFg", OneToOneRelationship.class); when(schemaHolder.getFields(CLASS_NAME)).thenReturn(singletonList(field)); FieldMetadata fmd = mock(FieldMetadata.class); when(fmd.getName()).thenReturn("notInDefFg"); when(classMetadata.newFieldMetadata("notInDefFg")).thenReturn(fmd); entityMetadataBuilder.addEntityMetadata(jdoMetadata, entity, Sample.class, schemaHolder); verify(fmd, never()).setDefaultFetchGroup(anyBoolean()); } @Test public void shouldMarkEudeFieldsAsUnique() { when(entity.getName()).thenReturn(ENTITY_NAME); when(jdoMetadata.newPackageMetadata(anyString())).thenReturn(packageMetadata); when(packageMetadata.newClassMetadata(anyString())).thenReturn(classMetadata); FieldDto eudeField = mock(FieldDto.class); FieldBasicDto eudeBasic = mock(FieldBasicDto.class); when(eudeField.getBasic()).thenReturn(eudeBasic); when(eudeBasic.getName()).thenReturn("uniqueField"); when(eudeField.isReadOnly()).thenReturn(false); when(eudeBasic.isUnique()).thenReturn(true); when(eudeField.getType()).thenReturn(TypeDto.STRING); FieldDto ddeField = mock(FieldDto.class); FieldBasicDto ddeBasic = mock(FieldBasicDto.class); when(ddeField.getBasic()).thenReturn(ddeBasic); when(ddeBasic.getName()).thenReturn("uniqueField2"); when(ddeField.isReadOnly()).thenReturn(true); when(ddeBasic.isUnique()).thenReturn(true); when(ddeField.getType()).thenReturn(TypeDto.STRING); when(schemaHolder.getFields(entity)).thenReturn(asList(ddeField, eudeField)); FieldMetadata fmdEude = mock(FieldMetadata.class); when(fmdEude.getName()).thenReturn("uniqueField"); when(classMetadata.newFieldMetadata("uniqueField")).thenReturn(fmdEude); FieldMetadata fmdDde = mock(FieldMetadata.class); when(fmdDde.getName()).thenReturn("uniqueField2"); when(classMetadata.newFieldMetadata("uniqueField2")).thenReturn(fmdDde); UniqueMetadata umd = mock(UniqueMetadata.class); when(fmdEude.newUniqueMetadata()).thenReturn(umd); entityMetadataBuilder.addEntityMetadata(jdoMetadata, entity, Sample.class, schemaHolder); verify(fmdDde, never()).newUniqueMetadata(); verify(fmdDde, never()).setUnique(anyBoolean()); verify(fmdEude).newUniqueMetadata(); verify(umd).setName("unq_Sample_uniqueField"); } @Test public void shouldSetIncrementStrategy() { when(entity.getName()).thenReturn(ENTITY_NAME); when(entity.getModule()).thenReturn(MODULE); when(entity.getNamespace()).thenReturn(NAMESPACE); when(entity.getTableName()).thenReturn(TABLE_NAME); when(jdoMetadata.newPackageMetadata(PACKAGE)).thenReturn(packageMetadata); when(packageMetadata.newClassMetadata(ENTITY_NAME)).thenReturn(classMetadata); entityMetadataBuilder.addEntityMetadata(jdoMetadata, entity, SampleWithIncrementStrategy.class, schemaHolder); verify(jdoMetadata).newPackageMetadata(PACKAGE); verify(packageMetadata).newClassMetadata(ENTITY_NAME); verify(classMetadata).setTable(TABLE_NAME_3); verifyCommonClassMetadata(IdGeneratorStrategy.INCREMENT); } private void verifyCommonClassMetadata() { verifyCommonClassMetadata(IdGeneratorStrategy.NATIVE); } private void verifyCommonClassMetadata(IdGeneratorStrategy expextedStrategy) { verify(classMetadata).setDetachable(true); verify(classMetadata).setIdentityType(IdentityType.APPLICATION); verify(classMetadata).setPersistenceModifier(ClassPersistenceModifier.PERSISTENCE_CAPABLE); verify(idMetadata).setPrimaryKey(true); verify(idMetadata).setValueStrategy(expextedStrategy); verify(inheritanceMetadata).setCustomStrategy("complete-table"); } }
bsd-3-clause
Skywalker-11/spongycastle
core/src/test/java/org/spongycastle/crypto/test/SHA256DigestTest.java
1536
package org.spongycastle.crypto.test; import org.spongycastle.crypto.Digest; import org.spongycastle.crypto.digests.SHA256Digest; /** * standard vector test for SHA-256 from FIPS Draft 180-2. * * Note, the first two vectors are _not_ from the draft, the last three are. */ public class SHA256DigestTest extends DigestTest { private static String[] messages = { "", "a", "abc", "abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq" }; private static String[] digests = { "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", "ca978112ca1bbdcafac231b39a23dc4da786eff8147c4e72b9807785afee48bb", "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad", "248d6a61d20638b8e5c026930c3e6039a33ce45964ff2167f6ecedd419db06c1" }; // 1 million 'a' static private String million_a_digest = "cdc76e5c9914fb9281a1c7e284d73e67f1809a48a497200e046d39ccc7112cd0"; SHA256DigestTest() { super(new SHA256Digest(), messages, digests); } public void performTest() { super.performTest(); millionATest(million_a_digest); } protected Digest cloneDigest(Digest digest) { return new SHA256Digest((SHA256Digest)digest); } protected Digest cloneDigest(byte[] encodedState) { return new SHA256Digest(encodedState); } public static void main( String[] args) { runTest(new SHA256DigestTest()); } }
mit
afuechsel/openhab2
addons/binding/org.openhab.binding.dsmr/src/main/java/org/openhab/binding/dsmr/internal/device/DSMRSerialAutoDevice.java
9975
/** * Copyright (c) 2010-2019 Contributors to the openHAB project * * See the NOTICE file(s) distributed with this work for additional * information. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License 2.0 which is available at * http://www.eclipse.org/legal/epl-2.0 * * SPDX-License-Identifier: EPL-2.0 */ package org.openhab.binding.dsmr.internal.device; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; import org.eclipse.jdt.annotation.NonNullByDefault; import org.eclipse.jdt.annotation.Nullable; import org.eclipse.smarthome.io.transport.serial.SerialPortManager; import org.openhab.binding.dsmr.internal.device.connector.DSMRConnectorErrorEvent; import org.openhab.binding.dsmr.internal.device.connector.DSMRSerialConnector; import org.openhab.binding.dsmr.internal.device.connector.DSMRSerialSettings; import org.openhab.binding.dsmr.internal.device.p1telegram.P1Telegram; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * DSMR Serial device that auto discovers the serial port speed. * * @author M. Volaart - Initial contribution * @author Hilbrand Bouwkamp - New class. Simplified states and contains code specific to discover the serial port * settings automatically. */ @NonNullByDefault public class DSMRSerialAutoDevice implements DSMRDevice, DSMREventListener { /** * Enum to keep track of the internal state of {@link DSMRSerialAutoDevice}. */ enum DeviceState { /** * Discovers the settings of the serial port. */ DISCOVER_SETTINGS, /** * Device is receiving telegram data from the serial port. */ NORMAL, /** * Communication with serial port isn't working. */ ERROR } /** * When switching baudrate ignore any errors received with the given time frame. Switching baudrate causes errors * and should not be interpreted as reading errors. */ private static final long SWITCHING_BAUDRATE_TIMEOUT_NANOS = TimeUnit.SECONDS.toNanos(5); /** * This factor is multiplied with the {@link #baudrateSwitchTimeoutSeconds} and used as the duration the discovery * of the baudrate may take. */ private static final int DISCOVER_TIMEOUT_FACTOR = 4; /* * Februari 2017 * Due to the Dutch Smart Meter program where every residence is provided * a smart for free and the smart meters are DSMR V4 or higher * we assume the majority of meters communicate with HIGH_SPEED_SETTINGS * For older meters this means initializing is taking probably 1 minute */ private static final DSMRSerialSettings DEFAULT_PORT_SETTINGS = DSMRSerialSettings.HIGH_SPEED_SETTINGS; private final Logger logger = LoggerFactory.getLogger(DSMRSerialAutoDevice.class); /** * DSMR Connector to the serial port */ private final DSMRSerialConnector dsmrConnector; private final ScheduledExecutorService scheduler; private final DSMRTelegramListener telegramListener; /** * Time in seconds in which period valid data is expected during discovery. If exceeded without success the baudrate * is switched */ private final int baudrateSwitchTimeoutSeconds; /** * Serial port connection settings */ private DSMRSerialSettings portSettings = DEFAULT_PORT_SETTINGS; /** * Keeps track of the state this instance is in. */ private DeviceState state = DeviceState.NORMAL; /** * Timer for handling discovery of a single setting. */ private @Nullable ScheduledFuture<?> halfTimeTimer; /** * Timer for handling end of discovery. */ private @Nullable ScheduledFuture<?> endTimeTimer; /** * The listener of the class handling the connector events */ private DSMREventListener parentListener; /** * Time in nanos the last time the baudrate was switched. This is used during discovery ignore errors retrieved * after switching baudrate for the period set in {@link #SWITCHING_BAUDRATE_TIMEOUT_NANOS}. */ private long lastSwitchedBaudrateNanos; /** * Creates a new {@link DSMRSerialAutoDevice} * * @param serialPortManager the manager to get a new serial port connecting from * @param serialPortName the port name (e.g. /dev/ttyUSB0 or COM1) * @param listener the parent {@link DSMREventListener} * @param scheduler the scheduler to use with the baudrate switching timers * @param baudrateSwitchTimeoutSeconds timeout period for when to try other baudrate settings and end the discovery * of the baudrate */ public DSMRSerialAutoDevice(SerialPortManager serialPortManager, String serialPortName, DSMREventListener listener, ScheduledExecutorService scheduler, int baudrateSwitchTimeoutSeconds) { this.parentListener = listener; this.scheduler = scheduler; this.baudrateSwitchTimeoutSeconds = baudrateSwitchTimeoutSeconds; telegramListener = new DSMRTelegramListener(listener); dsmrConnector = new DSMRSerialConnector(serialPortManager, serialPortName, telegramListener); logger.debug("Initialized port '{}'", serialPortName); } @Override public void start() { stopDiscover(DeviceState.DISCOVER_SETTINGS); portSettings = DEFAULT_PORT_SETTINGS; telegramListener.setDsmrEventListener(this); dsmrConnector.open(portSettings); restartHalfTimer(); endTimeTimer = scheduler.schedule(this::endTimeScheduledCall, baudrateSwitchTimeoutSeconds * DISCOVER_TIMEOUT_FACTOR, TimeUnit.SECONDS); } @Override public void restart() { if (state == DeviceState.ERROR) { stop(); start(); } else if (state == DeviceState.NORMAL) { dsmrConnector.restart(portSettings); } } @Override public synchronized void stop() { dsmrConnector.close(); stopDiscover(state); logger.trace("stopped with state:{}", state); } /** * Handle if telegrams are received. * * @param telegram the details of the received telegram */ @Override public void handleTelegramReceived(P1Telegram telegram) { if (!telegram.getCosemObjects().isEmpty()) { stopDiscover(DeviceState.NORMAL); parentListener.handleTelegramReceived(telegram); logger.info("Start receiving telegrams on port {} with settings: {}", dsmrConnector.getPortName(), portSettings); } } /** * Event handler for DSMR Port events. * * @param portEvent {@link DSMRConnectorErrorEvent} to handle */ @Override public void handleErrorEvent(DSMRConnectorErrorEvent portEvent) { logger.trace("Received portEvent {}", portEvent.getEventDetails()); if (portEvent == DSMRConnectorErrorEvent.READ_ERROR) { switchBaudrate(); } else { logger.debug("Error during discovery of port settings: {}, current state:{}.", portEvent.getEventDetails(), state); stopDiscover(DeviceState.ERROR); parentListener.handleErrorEvent(portEvent); } } /** * @param lenientMode the lenientMode to set */ @Override public void setLenientMode(boolean lenientMode) { telegramListener.setLenientMode(lenientMode); } /** * @return Returns the state of the instance. Used for testing only. */ DeviceState getState() { return state; } /** * Switches the baudrate on the serial port. */ private void switchBaudrate() { if (lastSwitchedBaudrateNanos + SWITCHING_BAUDRATE_TIMEOUT_NANOS > System.nanoTime()) { // Ignore switching baudrate if this is called within the timeout after a previous switch. return; } lastSwitchedBaudrateNanos = System.nanoTime(); if (state == DeviceState.DISCOVER_SETTINGS) { restartHalfTimer(); logger.debug( "Discover port settings is running for half time now and still nothing discovered, switching baudrate and retrying"); portSettings = portSettings == DSMRSerialSettings.HIGH_SPEED_SETTINGS ? DSMRSerialSettings.LOW_SPEED_SETTINGS : DSMRSerialSettings.HIGH_SPEED_SETTINGS; dsmrConnector.setSerialPortParams(portSettings); } } /** * Stops the discovery process as triggered by the end timer. It will only act if the discovery process was still * running. */ private void endTimeScheduledCall() { if (state == DeviceState.DISCOVER_SETTINGS) { stopDiscover(DeviceState.ERROR); parentListener.handleErrorEvent(DSMRConnectorErrorEvent.DONT_EXISTS); } } /** * Stops the discovery of port speed process and sets the state with which it should be stopped. * * @param state the state with which the process was stopped. */ private void stopDiscover(DeviceState state) { telegramListener.setDsmrEventListener(parentListener); logger.debug("Stop discovery of port settings."); if (halfTimeTimer != null) { halfTimeTimer.cancel(true); halfTimeTimer = null; } if (endTimeTimer != null) { endTimeTimer.cancel(true); endTimeTimer = null; } this.state = state; } /** * Method to (re)start the switching baudrate timer. */ private void restartHalfTimer() { if (halfTimeTimer != null) { halfTimeTimer.cancel(true); } halfTimeTimer = scheduler.schedule(this::switchBaudrate, baudrateSwitchTimeoutSeconds, TimeUnit.SECONDS); } }
epl-1.0
johannrichard/openhab2-addons
addons/binding/org.openhab.binding.yamahareceiver/src/main/java/org/openhab/binding/yamahareceiver/internal/state/ZoneControlState.java
1158
/** * Copyright (c) 2010-2018 by the respective copyright holders. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ package org.openhab.binding.yamahareceiver.internal.state; import static org.openhab.binding.yamahareceiver.YamahaReceiverBindingConstants.VALUE_EMPTY; /** * The state of a specific zone of a Yamaha receiver. * * @author David Graeff <david.graeff@web.de> * */ public class ZoneControlState { public boolean power = false; // User visible name of the input channel for the current zone public String inputName = VALUE_EMPTY; // The ID of the input channel that is used as xml tags (for example NET_RADIO, HDMI_1). // This may differ from what the AVR returns in Input/Input_Sel ("NET RADIO", "HDMI1") public String inputID = VALUE_EMPTY; public String surroundProgram = VALUE_EMPTY; public float volumeDB = 0.0f; // volume in dB public boolean mute = false; public int dialogueLevel = 0; }
epl-1.0
aogorek/openhab2-addons
addons/binding/org.openhab.binding.nikohomecontrol/src/main/java/org/openhab/binding/nikohomecontrol/internal/protocol/NhcMessageBase.java
1148
/** * Copyright (c) 2010-2018 by the respective copyright holders. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ package org.openhab.binding.nikohomecontrol.internal.protocol; /** * Class {@link NhcMessageBase} used as base class for output from gson for cmd or event feedback from Niko Home * Control. This class only contains the common base fields required for the deserializer * {@link NikoHomeControlMessageDeserializer} to select the specific formats implemented in {@link NhcMessageMap}, * {@link NhcMessageListMap}, {@link NhcMessageCmd}. * <p> * * @author Mark Herwege - Initial Contribution */ abstract class NhcMessageBase { private String cmd; private String event; String getCmd() { return this.cmd; } void setCmd(String cmd) { this.cmd = cmd; } String getEvent() { return this.event; } void setEvent(String event) { this.event = event; } }
epl-1.0
YouDiSN/OpenJDK-Research
jdk9/jdk/test/sun/tools/jhsdb/HeapDumpTest.java
4479
/* * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ /* * @test * @bug 8163346 * @summary Test hashing of extended characters in Serviceability Agent. * @library /test/lib * @library /lib/testlibrary * @compile -encoding utf8 HeapDumpTest.java * @run main/timeout=240 HeapDumpTest */ import static jdk.testlibrary.Asserts.assertTrue; import java.io.IOException; import java.io.File; import java.util.List; import java.util.Arrays; import jdk.testlibrary.JDKToolLauncher; import jdk.testlibrary.OutputAnalyzer; import jdk.testlibrary.ProcessTools; import jdk.test.lib.apps.LingeredApp; import jdk.test.lib.Platform; public class HeapDumpTest { private static LingeredAppWithExtendedChars theApp = null; /** * * @param vmArgs - tool arguments to launch jhsdb * @return exit code of tool */ public static void launch(String expectedMessage, List<String> toolArgs) throws IOException { System.out.println("Starting LingeredApp"); try { theApp = new LingeredAppWithExtendedChars(); LingeredApp.startApp(Arrays.asList("-Xmx256m"), theApp); System.out.println(theApp.\u00CB); System.out.println("Starting " + toolArgs.get(0) + " against " + theApp.getPid()); JDKToolLauncher launcher = JDKToolLauncher.createUsingTestJDK("jhsdb"); for (String cmd : toolArgs) { launcher.addToolArg(cmd); } launcher.addToolArg("--pid=" + Long.toString(theApp.getPid())); ProcessBuilder processBuilder = new ProcessBuilder(launcher.getCommand()); processBuilder.redirectError(ProcessBuilder.Redirect.INHERIT); OutputAnalyzer output = ProcessTools.executeProcess(processBuilder); System.out.println("stdout:"); System.out.println(output.getStdout()); System.out.println("stderr:"); System.out.println(output.getStderr()); output.shouldContain(expectedMessage); output.shouldHaveExitValue(0); } catch (Exception ex) { throw new RuntimeException("Test ERROR " + ex, ex); } finally { LingeredApp.stopApp(theApp); } } public static void launch(String expectedMessage, String... toolArgs) throws IOException { launch(expectedMessage, Arrays.asList(toolArgs)); } public static void testHeapDump() throws IOException { File dump = new File("jhsdb.jmap.heap." + System.currentTimeMillis() + ".hprof"); if (dump.exists()) { dump.delete(); } launch("heap written to", "jmap", "--binaryheap", "--dumpfile=" + dump.getAbsolutePath()); assertTrue(dump.exists() && dump.isFile(), "Could not create dump file " + dump.getAbsolutePath()); dump.delete(); } public static void main(String[] args) throws Exception { if (!Platform.shouldSAAttach()) { // Silently skip the test if we don't have enough permissions to attach System.err.println("Error! Insufficient permissions to attach - test skipped."); return; } testHeapDump(); // The test throws RuntimeException on error. // IOException is thrown if LingeredApp can't start because of some bad // environment condition System.out.println("Test PASSED"); } }
gpl-2.0
erpcya/adempierePOS
base/src/org/compiere/model/MInOutLineMA.java
4940
/****************************************************************************** * Product: Adempiere ERP & CRM Smart Business Solution * * Copyright (C) 1999-2006 ComPiere, Inc. All Rights Reserved. * * This program is free software; you can redistribute it and/or modify it * * under the terms version 2 of the GNU General Public License as published * * by the Free Software Foundation. This program is distributed in the hope * * that it will be useful, but WITHOUT ANY WARRANTY; without even the implied * * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * * See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * * with this program; if not, write to the Free Software Foundation, Inc., * * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. * * For the text or an alternative of this public license, you may reach us * * ComPiere, Inc., 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA * * or via info@compiere.org or http://www.compiere.org/license.html * *****************************************************************************/ package org.compiere.model; import java.math.BigDecimal; import java.sql.ResultSet; import java.util.List; import java.util.Properties; import org.compiere.util.DB; /** * Shipment Material Allocation * * @author Jorg Janke * @version $Id: MInOutLineMA.java,v 1.3 2006/07/30 00:51:02 jjanke Exp $ */ public class MInOutLineMA extends X_M_InOutLineMA { /** * */ private static final long serialVersionUID = -3229418883339488380L; /** * Get Material Allocations for Line * @param ctx context * @param M_InOutLine_ID line * @param trxName trx * @return allocations */ public static MInOutLineMA[] get (Properties ctx, int M_InOutLine_ID, String trxName) { Query query = MTable.get(ctx, MInOutLineMA.Table_Name) .createQuery(I_M_InOutLineMA.COLUMNNAME_M_InOutLine_ID+"=?", trxName); query.setParameters(M_InOutLine_ID); List<MInOutLineMA> list = query.list(); MInOutLineMA[] retValue = new MInOutLineMA[list.size ()]; list.toArray (retValue); return retValue; } // get /** * Delete all Material Allocation for InOut * @param M_InOut_ID shipment * @param trxName transaction * @return number of rows deleted or -1 for error */ public static int deleteInOutMA (int M_InOut_ID, String trxName) { String sql = "DELETE FROM M_InOutLineMA ma WHERE EXISTS " + "(SELECT * FROM M_InOutLine l WHERE l.M_InOutLine_ID=ma.M_InOutLine_ID" + " AND M_InOut_ID=" + M_InOut_ID + ")"; return DB.executeUpdate(sql, trxName); } // deleteInOutMA /** * Delete all Material Allocation for InOutLine * @param M_InOutLine_ID Shipment Line * @param trxName transaction * @return number of rows deleted or -1 for error */ public static int deleteInOutLineMA (int M_InOutLine_ID, String trxName) { String sql = "DELETE FROM M_InOutLineMA ma WHERE ma.M_InOutLine_ID=?"; return DB.executeUpdate(sql, M_InOutLine_ID, trxName); } // deleteInOutLineMA // /** Logger */ // private static CLogger s_log = CLogger.getCLogger (MInOutLineMA.class); /************************************************************************** * Standard Constructor * @param ctx context * @param M_InOutLineMA_ID ignored * @param trxName trx */ public MInOutLineMA (Properties ctx, int M_InOutLineMA_ID, String trxName) { super (ctx, M_InOutLineMA_ID, trxName); if (M_InOutLineMA_ID != 0) throw new IllegalArgumentException("Multi-Key"); } // MInOutLineMA /** * Load Constructor * @param ctx context * @param rs result set * @param trxName trx */ public MInOutLineMA (Properties ctx, ResultSet rs, String trxName) { super (ctx, rs, trxName); } // MInOutLineMA /** * Parent Constructor * @param parent parent * @param M_AttributeSetInstance_ID asi * @param MovementQty qty */ public MInOutLineMA (MInOutLine parent, int M_AttributeSetInstance_ID, BigDecimal MovementQty) { this (parent.getCtx(), 0, parent.get_TrxName()); setClientOrg(parent); setM_InOutLine_ID(parent.getM_InOutLine_ID()); // setM_AttributeSetInstance_ID(M_AttributeSetInstance_ID); setMovementQty(MovementQty); } // MInOutLineMA /** * String Representation * @return info */ public String toString () { StringBuffer sb = new StringBuffer ("MInOutLineMA["); sb.append("M_InOutLine_ID=").append(getM_InOutLine_ID()) .append(",M_AttributeSetInstance_ID=").append(getM_AttributeSetInstance_ID()) .append(", Qty=").append(getMovementQty()) .append ("]"); return sb.toString (); } // toString } // MInOutLineMA
gpl-2.0
dgault/bioformats
components/bio-formats-plugins/src/loci/plugins/util/WindowTools.java
6353
/* * #%L * Bio-Formats Plugins for ImageJ: a collection of ImageJ plugins including the * Bio-Formats Importer, Bio-Formats Exporter, Bio-Formats Macro Extensions, * Data Browser and Stack Slicer. * %% * Copyright (C) 2006 - 2015 Open Microscopy Environment: * - Board of Regents of the University of Wisconsin-Madison * - Glencoe Software, Inc. * - University of Dundee * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 2 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public * License along with this program. If not, see * <http://www.gnu.org/licenses/gpl-2.0.html>. * #L% */ package loci.plugins.util; import ij.IJ; import ij.ImageJ; import ij.gui.GenericDialog; import java.awt.BorderLayout; import java.awt.Checkbox; import java.awt.Choice; import java.awt.Component; import java.awt.Container; import java.awt.Dimension; import java.awt.Frame; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Panel; import java.awt.Point; import java.awt.Rectangle; import java.awt.ScrollPane; import java.awt.TextField; import java.awt.Toolkit; import java.awt.Window; import java.util.List; import java.util.StringTokenizer; import loci.common.DebugTools; import loci.plugins.BF; /** * Utility methods for managing ImageJ dialogs and windows. */ public final class WindowTools { // -- Constructor -- private WindowTools() { } // -- Utility methods -- /** Adds AWT scroll bars to the given container. */ public static void addScrollBars(Container pane) { GridBagLayout layout = (GridBagLayout) pane.getLayout(); // extract components int count = pane.getComponentCount(); Component[] c = new Component[count]; GridBagConstraints[] gbc = new GridBagConstraints[count]; for (int i=0; i<count; i++) { c[i] = pane.getComponent(i); gbc[i] = layout.getConstraints(c[i]); } // clear components pane.removeAll(); layout.invalidateLayout(pane); // create new container panel Panel newPane = new Panel(); GridBagLayout newLayout = new GridBagLayout(); newPane.setLayout(newLayout); for (int i=0; i<count; i++) { newLayout.setConstraints(c[i], gbc[i]); newPane.add(c[i]); } // HACK - get preferred size for container panel // NB: don't know a better way: // - newPane.getPreferredSize() doesn't work // - newLayout.preferredLayoutSize(newPane) doesn't work Frame f = new Frame(); f.setLayout(new BorderLayout()); f.add(newPane, BorderLayout.CENTER); f.pack(); final Dimension size = newPane.getSize(); f.remove(newPane); f.dispose(); // compute best size for scrollable viewport size.width += 25; size.height += 15; Dimension screen = Toolkit.getDefaultToolkit().getScreenSize(); int maxWidth = 7 * screen.width / 8; int maxHeight = 3 * screen.height / 4; if (size.width > maxWidth) size.width = maxWidth; if (size.height > maxHeight) size.height = maxHeight; // create scroll pane ScrollPane scroll = new ScrollPane() { @Override public Dimension getPreferredSize() { return size; } }; scroll.add(newPane); // add scroll pane to original container GridBagConstraints constraints = new GridBagConstraints(); constraints.gridwidth = GridBagConstraints.REMAINDER; constraints.fill = GridBagConstraints.BOTH; constraints.weightx = 1.0; constraints.weighty = 1.0; layout.setConstraints(scroll, constraints); pane.add(scroll); } /** * Places the given window at a nice location on screen, either centered * below the ImageJ window if there is one, or else centered on screen. */ public static void placeWindow(Window w) { Dimension size = w.getSize(); Dimension screen = Toolkit.getDefaultToolkit().getScreenSize(); ImageJ ij = IJ.getInstance(); Point p = new Point(); if (ij == null) { // center config window on screen p.x = (screen.width - size.width) / 2; p.y = (screen.height - size.height) / 2; } else { // place config window below ImageJ window Rectangle ijBounds = ij.getBounds(); p.x = ijBounds.x + (ijBounds.width - size.width) / 2; p.y = ijBounds.y + ijBounds.height + 5; } // nudge config window away from screen edges final int pad = 10; if (p.x < pad) p.x = pad; else if (p.x + size.width + pad > screen.width) { p.x = screen.width - size.width - pad; } if (p.y < pad) p.y = pad; else if (p.y + size.height + pad > screen.height) { p.y = screen.height - size.height - pad; } w.setLocation(p); } /** Reports the given exception with stack trace in an ImageJ error dialog. */ public static void reportException(Throwable t) { reportException(t, false, null); } /** Reports the given exception with stack trace in an ImageJ error dialog. */ public static void reportException(Throwable t, boolean quiet) { reportException(t, quiet, null); } /** Reports the given exception with stack trace in an ImageJ error dialog. */ public static void reportException(Throwable t, boolean quiet, String msg) { if (quiet) return; BF.status(quiet, ""); if (t != null) { String s = DebugTools.getStackTrace(t); StringTokenizer st = new StringTokenizer(s, "\n\r"); while (st.hasMoreTokens()) IJ.log(st.nextToken()); } if (msg != null) IJ.error("Bio-Formats Importer", msg); } @SuppressWarnings("unchecked") public static List<TextField> getNumericFields(GenericDialog gd) { return gd.getNumericFields(); } @SuppressWarnings("unchecked") public static List<Checkbox> getCheckboxes(GenericDialog gd) { return gd.getCheckboxes(); } @SuppressWarnings("unchecked") public static List<Choice> getChoices(GenericDialog gd) { return gd.getChoices(); } }
gpl-2.0
HossainKhademian/Studio3
plugins/com.aptana.core/src/com/aptana/core/internal/resources/Messages.java
969
/** * Aptana Studio * Copyright (c) 2005-2011 by Appcelerator, Inc. All Rights Reserved. * Licensed under the terms of the GNU Public License (GPL) v3 (with exceptions). * Please see the license.html included with this distribution for details. * Any modifications to this file must keep this entire header intact. */ package com.aptana.core.internal.resources; import org.eclipse.osgi.util.NLS; /** * * @author Ingo Muschenetz * */ public final class Messages extends NLS { private static final String BUNDLE_NAME = "com.aptana.core.internal.resources.messages"; //$NON-NLS-1$ private Messages() { } static { // initialize resource bundle NLS.initializeMessages(BUNDLE_NAME, Messages.class); } /** * MarkerManager_MarkerIDIsDefined */ public static String MarkerManager_MarkerIDIsDefined; /** * UniformResourceMarker_UniformResourceMarketInfoNull */ public static String UniformResourceMarker_UniformResourceMarketInfoNull; }
gpl-3.0
Lobz/reforged-pixel-dungeon
src/com/shatteredpixel/shatteredpixeldungeon/scenes/InterlevelScene.java
7657
/* * Pixel Dungeon * Copyright (C) 2012-2014 Oleg Dolya * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> */ package com.shatteredpixel.shatteredpixeldungeon.scenes; import com.shatteredpixel.shatteredpixeldungeon.Assets; import com.shatteredpixel.shatteredpixeldungeon.Dungeon; import com.shatteredpixel.shatteredpixeldungeon.Statistics; import com.shatteredpixel.shatteredpixeldungeon.actors.Actor; import com.shatteredpixel.shatteredpixeldungeon.items.Generator; import com.shatteredpixel.shatteredpixeldungeon.levels.Level; import com.shatteredpixel.shatteredpixeldungeon.windows.WndError; import com.shatteredpixel.shatteredpixeldungeon.windows.WndStory; import com.watabou.noosa.BitmapText; import com.watabou.noosa.Camera; import com.watabou.noosa.Game; import com.watabou.noosa.audio.Music; import com.watabou.noosa.audio.Sample; import java.io.FileNotFoundException; import java.io.IOException; public class InterlevelScene extends PixelScene { private static final float TIME_TO_FADE = 0.3f; private static final String TXT_DESCENDING = "Descending..."; private static final String TXT_ASCENDING = "Ascending..."; private static final String TXT_LOADING = "Loading..."; private static final String TXT_RESURRECTING= "Resurrecting..."; private static final String TXT_RETURNING = "Returning..."; private static final String TXT_FALLING = "Falling..."; private static final String ERR_FILE_NOT_FOUND = "Save file not found. If this error persists after restarting, " + "it may mean this save game is corrupted. Sorry about that."; private static final String ERR_IO = "Cannot read save file. If this error persists after restarting, " + "it may mean this save game is corrupted. Sorry about that."; public static enum Mode { DESCEND, ASCEND, CONTINUE, RESURRECT, RETURN, FALL }; public static Mode mode; public static int returnDepth; public static int returnPos; public static boolean noStory = false; public static boolean fallIntoPit; private enum Phase { FADE_IN, STATIC, FADE_OUT }; private Phase phase; private float timeLeft; private BitmapText message; private Thread thread; private Exception error = null; @Override public void create() { super.create(); String text = ""; switch (mode) { case DESCEND: text = TXT_DESCENDING; break; case ASCEND: text = TXT_ASCENDING; break; case CONTINUE: text = TXT_LOADING; break; case RESURRECT: text = TXT_RESURRECTING; break; case RETURN: text = TXT_RETURNING; break; case FALL: text = TXT_FALLING; break; } message = PixelScene.createText( text, 9 ); message.measure(); message.x = (Camera.main.width - message.width()) / 2; message.y = (Camera.main.height - message.height()) / 2; add( message ); phase = Phase.FADE_IN; timeLeft = TIME_TO_FADE; thread = new Thread() { @Override public void run() { try { Generator.reset(); switch (mode) { case DESCEND: descend(); break; case ASCEND: ascend(); break; case CONTINUE: restore(); break; case RESURRECT: resurrect(); break; case RETURN: returnTo(); break; case FALL: fall(); break; } if ((Dungeon.depth % 5) == 0) { Sample.INSTANCE.load( Assets.SND_BOSS ); } } catch (Exception e) { error = e; } if (phase == Phase.STATIC && error == null) { phase = Phase.FADE_OUT; timeLeft = TIME_TO_FADE; } } }; thread.start(); } @Override public void update() { super.update(); float p = timeLeft / TIME_TO_FADE; switch (phase) { case FADE_IN: message.alpha( 1 - p ); if ((timeLeft -= Game.elapsed) <= 0) { if (!thread.isAlive() && error == null) { phase = Phase.FADE_OUT; timeLeft = TIME_TO_FADE; } else { phase = Phase.STATIC; } } break; case FADE_OUT: message.alpha( p ); if (mode == Mode.CONTINUE || (mode == Mode.DESCEND && Dungeon.depth == 1)) { Music.INSTANCE.volume( p ); } if ((timeLeft -= Game.elapsed) <= 0) { Game.switchScene( GameScene.class ); } break; case STATIC: if (error != null) { String errorMsg; if (error instanceof FileNotFoundException) errorMsg = ERR_FILE_NOT_FOUND; else if (error instanceof IOException) errorMsg = ERR_IO; else throw new RuntimeException("fatal error occured while moving between floors", error); add( new WndError( errorMsg ) { public void onBackPressed() { super.onBackPressed(); Game.switchScene( StartScene.class ); }; } ); error = null; } break; } } private void descend() throws IOException { Actor.fixTime(); if (Dungeon.hero == null) { Dungeon.init(); if (noStory) { Dungeon.chapters.add( WndStory.ID_SEWERS ); noStory = false; } } else { Dungeon.saveLevel(); } Level level; if (Dungeon.depth >= Statistics.deepestFloor) { level = Dungeon.newLevel(); } else { Dungeon.depth++; level = Dungeon.loadLevel( Dungeon.hero.heroClass ); } Dungeon.switchLevel( level, level.entrance ); } private void fall() throws IOException { Actor.fixTime(); Dungeon.saveLevel(); Level level; if (Dungeon.depth >= Statistics.deepestFloor) { level = Dungeon.newLevel(); } else { Dungeon.depth++; level = Dungeon.loadLevel( Dungeon.hero.heroClass ); } Dungeon.switchLevel( level, fallIntoPit ? level.pitCell() : level.randomRespawnCell() ); } private void ascend() throws IOException { Actor.fixTime(); Dungeon.saveLevel(); Dungeon.depth--; Level level = Dungeon.loadLevel( Dungeon.hero.heroClass ); Dungeon.switchLevel( level, level.exit ); } private void returnTo() throws IOException { Actor.fixTime(); Dungeon.saveLevel(); Dungeon.depth = returnDepth; Level level = Dungeon.loadLevel( Dungeon.hero.heroClass ); Dungeon.switchLevel( level, Level.resizingNeeded ? level.adjustPos( returnPos ) : returnPos ); } private void restore() throws IOException { Actor.fixTime(); Dungeon.loadGame( StartScene.curClass ); if (Dungeon.depth == -1) { Dungeon.depth = Statistics.deepestFloor; Dungeon.switchLevel( Dungeon.loadLevel( StartScene.curClass ), -1 ); } else { Level level = Dungeon.loadLevel( StartScene.curClass ); Dungeon.switchLevel( level, Level.resizingNeeded ? level.adjustPos( Dungeon.hero.pos ) : Dungeon.hero.pos ); } } private void resurrect() throws IOException { Actor.fixTime(); if (Dungeon.level.locked) { Dungeon.hero.resurrect( Dungeon.depth ); Dungeon.depth--; Level level = Dungeon.newLevel(); Dungeon.switchLevel( level, level.entrance ); } else { Dungeon.hero.resurrect( -1 ); Dungeon.resetLevel(); } } @Override protected void onBackPressed() { //Do nothing } }
gpl-3.0
bhutchinson/kfs
kfs-cg/src/main/java/org/kuali/kfs/module/cg/service/impl/ContractsAndGrantsBillingServiceImpl.java
2589
/* * The Kuali Financial System, a comprehensive financial management system for higher education. * * Copyright 2005-2014 The Kuali Foundation * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.kuali.kfs.module.cg.service.impl; import java.util.ArrayList; import java.util.List; import org.kuali.kfs.module.cg.CGPropertyConstants; import org.kuali.kfs.module.cg.service.ContractsAndGrantsBillingService; /** * Service with methods related to the Contracts & Grants Billing (CGB) enhancement. */ public class ContractsAndGrantsBillingServiceImpl implements ContractsAndGrantsBillingService { @Override public List<String> getAgencyContractsGrantsBillingSectionIds() { List<String> contractsGrantsSectionIds = new ArrayList<String>(); contractsGrantsSectionIds.add(CGPropertyConstants.SectionId.AGENCY_ADDRESS_SECTION_ID); contractsGrantsSectionIds.add(CGPropertyConstants.SectionId.AGENCY_ADDRESSES_SECTION_ID); contractsGrantsSectionIds.add(CGPropertyConstants.SectionId.AGENCY_COLLECTIONS_MAINTENANCE_SECTION_ID); contractsGrantsSectionIds.add(CGPropertyConstants.SectionId.AGENCY_CONTRACTS_AND_GRANTS_SECTION_ID); contractsGrantsSectionIds.add(CGPropertyConstants.SectionId.AGENCY_CUSTOMER_SECTION_ID); return contractsGrantsSectionIds; } @Override public List<String> getAwardContractsGrantsBillingSectionIds() { List<String> contractsGrantsSectionIds = new ArrayList<String>(); contractsGrantsSectionIds.add(CGPropertyConstants.SectionId.AWARD_FUND_MANAGERS_SECTION_ID); contractsGrantsSectionIds.add(CGPropertyConstants.SectionId.AWARD_INVOICING_SECTION_ID); contractsGrantsSectionIds.add(CGPropertyConstants.SectionId.AWARD_MILESTONE_SCHEDULE_SECTION_ID); contractsGrantsSectionIds.add(CGPropertyConstants.SectionId.AWARD_PREDETERMINED_BILLING_SCHEDULE_SECTION_ID); return contractsGrantsSectionIds; } }
agpl-3.0
elkafoury/tux
src/org/herac/tuxguitar/gui/util/MidiTickUtil.java
2150
package org.herac.tuxguitar.gui.util; import org.herac.tuxguitar.gui.TuxGuitar; import org.herac.tuxguitar.player.base.MidiRepeatController; import org.herac.tuxguitar.song.managers.TGSongManager; import org.herac.tuxguitar.song.models.TGMeasureHeader; public class MidiTickUtil { public static long getStart(long tick){ long startPoint = getStartPoint(); long start = startPoint; long length = 0; TGSongManager manager = TuxGuitar.instance().getSongManager(); MidiRepeatController controller = new MidiRepeatController(manager.getSong(), getSHeader() , getEHeader() ); while(!controller.finished()){ TGMeasureHeader header = manager.getSong().getMeasureHeader(controller.getIndex()); controller.process(); if(controller.shouldPlay()){ start += length; length = header.getLength(); //verifico si es el compas correcto if(tick >= start && tick < (start + length )){ return header.getStart() + (tick - start); } } } return ( tick < startPoint ? startPoint : start ); } public static long getTick(long start){ long startPoint = getStartPoint(); long tick = startPoint; long length = 0; TGSongManager manager = TuxGuitar.instance().getSongManager(); MidiRepeatController controller = new MidiRepeatController(manager.getSong(), getSHeader() , getEHeader() ); while(!controller.finished()){ TGMeasureHeader header = manager.getSong().getMeasureHeader(controller.getIndex()); controller.process(); if(controller.shouldPlay()){ tick += length; length = header.getLength(); //verifico si es el compas correcto if(start >= header.getStart() && start < (header.getStart() + length )){ return tick; } } } return ( start < startPoint ? startPoint : tick ); } private static long getStartPoint(){ TuxGuitar.instance().getPlayer().updateLoop( false ); return TuxGuitar.instance().getPlayer().getLoopSPosition(); } public static int getSHeader() { return TuxGuitar.instance().getPlayer().getLoopSHeader(); } public static int getEHeader() { return TuxGuitar.instance().getPlayer().getLoopEHeader(); } }
lgpl-2.1
gytis/narayana
txframework/src/main/java/org/jboss/narayana/txframework/api/exception/TXFrameworkException.java
1829
/* * JBoss, Home of Professional Open Source. * Copyright 2012, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.narayana.txframework.api.exception; /** * @deprecated The TXFramework API will be removed. The org.jboss.narayana.compensations API should be used instead. * The new API is superior for these reasons: * <p/> * i) offers a higher level API; * ii) The API very closely matches that of JTA, making it easier for developers to learn, * iii) It works for non-distributed transactions as well as distributed transactions. * iv) It is CDI based so only needs a CDI container to run, rather than a full Java EE server. * <p/> */ @Deprecated public class TXFrameworkException extends Exception { public TXFrameworkException(String message) { super(message); } public TXFrameworkException(String message, Throwable cause) { super(message, cause); } }
lgpl-2.1
gytis/narayana
qa/tests/src/org/jboss/jbossts/qa/RawResources02Clients2/Client085.java
4881
/* * JBoss, Home of Professional Open Source * Copyright 2007, Red Hat Middleware LLC, and individual contributors * as indicated by the @author tags. * See the copyright.txt in the distribution for a * full listing of individual contributors. * This copyrighted material is made available to anyone wishing to use, * modify, copy, or redistribute it subject to the terms and conditions * of the GNU Lesser General Public License, v. 2.1. * This program is distributed in the hope that it will be useful, but WITHOUT A * 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, * v.2.1 along with this distribution; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. * * (C) 2005-2006, * @author JBoss Inc. */ // // Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003 // // Arjuna Technologies Ltd., // Newcastle upon Tyne, // Tyne and Wear, // UK. // package org.jboss.jbossts.qa.RawResources02Clients2; /* * Copyright (C) 1999-2001 by HP Bluestone Software, Inc. All rights Reserved. * * HP Arjuna Labs, * Newcastle upon Tyne, * Tyne and Wear, * UK. * * $Id: Client085.java,v 1.3 2003/07/07 13:43:32 jcoleman Exp $ */ /* * Try to get around the differences between Ansi CPP and * K&R cpp with concatenation. */ /* * Copyright (C) 1999-2001 by HP Bluestone Software, Inc. All rights Reserved. * * HP Arjuna Labs, * Newcastle upon Tyne, * Tyne and Wear, * UK. * * $Id: Client085.java,v 1.3 2003/07/07 13:43:32 jcoleman Exp $ */ import org.jboss.jbossts.qa.RawResources02.*; import org.jboss.jbossts.qa.Utils.OAInterface; import org.jboss.jbossts.qa.Utils.ORBInterface; import org.jboss.jbossts.qa.Utils.OTS; import org.jboss.jbossts.qa.Utils.ServerIORStore; import org.omg.CORBA.TRANSACTION_ROLLEDBACK; public class Client085 { public static void main(String[] args) { try { ORBInterface.initORB(args, null); OAInterface.initOA(); String serviceIOR1 = ServerIORStore.loadIOR(args[args.length - 2]); Service service1 = ServiceHelper.narrow(ORBInterface.orb().string_to_object(serviceIOR1)); String serviceIOR2 = ServerIORStore.loadIOR(args[args.length - 1]); Service service2 = ServiceHelper.narrow(ORBInterface.orb().string_to_object(serviceIOR2)); ResourceBehavior[] resourceBehaviors1 = new ResourceBehavior[1]; resourceBehaviors1[0] = new ResourceBehavior(); resourceBehaviors1[0].prepare_behavior = PrepareBehavior.PrepareBehaviorReturnVoteRollback; resourceBehaviors1[0].rollback_behavior = RollbackBehavior.RollbackBehaviorReturn; resourceBehaviors1[0].commit_behavior = CommitBehavior.CommitBehaviorReturn; resourceBehaviors1[0].commitonephase_behavior = CommitOnePhaseBehavior.CommitOnePhaseBehaviorReturn; ResourceBehavior[] resourceBehaviors2 = new ResourceBehavior[1]; resourceBehaviors2[0] = new ResourceBehavior(); resourceBehaviors2[0].prepare_behavior = PrepareBehavior.PrepareBehaviorReturnVoteReadOnly; resourceBehaviors2[0].rollback_behavior = RollbackBehavior.RollbackBehaviorReturn; resourceBehaviors2[0].commit_behavior = CommitBehavior.CommitBehaviorReturn; resourceBehaviors2[0].commitonephase_behavior = CommitOnePhaseBehavior.CommitOnePhaseBehaviorReturn; boolean correct = true; OTS.current().begin(); service1.oper(resourceBehaviors1, OTS.current().get_control()); service2.oper(resourceBehaviors2, OTS.current().get_control()); try { OTS.current().commit(true); System.err.println("Commit succeeded when it shouldn't"); correct = false; } catch (TRANSACTION_ROLLEDBACK transactionRolledback) { } correct = correct && service1.is_correct() && service2.is_correct(); if (!correct) { System.err.println("service1.is_correct() or service2.is_correct() returned false"); } ResourceTrace resourceTrace1 = service1.get_resource_trace(0); ResourceTrace resourceTrace2 = service2.get_resource_trace(0); correct = correct && (resourceTrace1 == ResourceTrace.ResourceTracePrepareRollback); correct = correct && ((resourceTrace2 == ResourceTrace.ResourceTracePrepare) || (resourceTrace2 == ResourceTrace.ResourceTraceRollback)); if (correct) { System.out.println("Passed"); } else { System.out.println("Failed"); } } catch (Exception exception) { System.err.println("Client085.main: " + exception); exception.printStackTrace(System.err); System.out.println("Failed"); } try { OAInterface.shutdownOA(); ORBInterface.shutdownORB(); } catch (Exception exception) { System.err.println("Client085.main: " + exception); exception.printStackTrace(System.err); } } }
lgpl-2.1
curvejumper/pi4j
pi4j-core/src/main/java/com/pi4j/io/gpio/GpioPinPwm.java
1511
package com.pi4j.io.gpio; /* * #%L * ********************************************************************** * ORGANIZATION : Pi4J * PROJECT : Pi4J :: Java Library (Core) * FILENAME : GpioPinPwm.java * * This file is part of the Pi4J project. More information about * this project can be found here: http://www.pi4j.com/ * ********************************************************************** * %% * Copyright (C) 2012 - 2015 Pi4J * %% * This program 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. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-3.0.html>. * #L% */ /** * Gpio input pin interface. This interface is extension of {@link GpioPin} interface * with reading pwm values. * * @author Robert Savage (<a * href="http://www.savagehomeautomation.com">http://www.savagehomeautomation.com</a>) */ @SuppressWarnings("unused") public interface GpioPinPwm extends GpioPin { int getPwm(); }
lgpl-3.0
lukecwik/incubator-beam
sdks/java/extensions/ml/src/test/java/org/apache/beam/sdk/extensions/ml/DLPInspectTextTest.java
3694
/* * 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.extensions.ml; import static org.junit.Assert.assertThrows; import java.util.List; import org.apache.beam.sdk.testing.TestPipeline; import org.apache.beam.sdk.transforms.Create; import org.apache.beam.sdk.transforms.View; import org.apache.beam.sdk.values.PCollectionView; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; @RunWith(JUnit4.class) public class DLPInspectTextTest { @Rule public TestPipeline testPipeline = TestPipeline.create(); private static final Integer BATCH_SIZE_SMALL = 200; private static final String DELIMITER = ";"; private static final String TEMPLATE_NAME = "test_template"; private static final String PROJECT_ID = "test_id"; @Test public void throwsExceptionWhenDeidentifyConfigAndTemplatesAreEmpty() { assertThrows( "Either inspectTemplateName or inspectConfig must be supplied!", IllegalArgumentException.class, () -> DLPInspectText.newBuilder() .setProjectId(PROJECT_ID) .setBatchSizeBytes(BATCH_SIZE_SMALL) .setColumnDelimiter(DELIMITER) .build()); } @Test public void throwsExceptionWhenDelimiterIsNullAndHeadersAreSet() { PCollectionView<List<String>> header = testPipeline.apply(Create.of("header")).apply(View.asList()); assertThrows( "Column delimiter should be set if headers are present.", IllegalArgumentException.class, () -> DLPInspectText.newBuilder() .setProjectId(PROJECT_ID) .setBatchSizeBytes(BATCH_SIZE_SMALL) .setInspectTemplateName(TEMPLATE_NAME) .setHeaderColumns(header) .build()); testPipeline.run().waitUntilFinish(); } @Test public void throwsExceptionWhenBatchSizeIsTooLarge() { assertThrows( String.format( "Batch size is too large! It should be smaller or equal than %d.", DLPInspectText.DLP_PAYLOAD_LIMIT_BYTES), IllegalArgumentException.class, () -> DLPInspectText.newBuilder() .setProjectId(PROJECT_ID) .setBatchSizeBytes(Integer.MAX_VALUE) .setInspectTemplateName(TEMPLATE_NAME) .setColumnDelimiter(DELIMITER) .build()); } @Test public void throwsExceptionWhenDelimiterIsSetAndHeadersAreNot() { assertThrows( "Column headers should be supplied when delimiter is present.", IllegalArgumentException.class, () -> DLPInspectText.newBuilder() .setProjectId(PROJECT_ID) .setBatchSizeBytes(BATCH_SIZE_SMALL) .setInspectTemplateName(TEMPLATE_NAME) .setColumnDelimiter(DELIMITER) .build()); } }
apache-2.0
nmcl/scratch
graalvm/transactions/fork/narayana/XTS/localjunit/unit/src/test/java/com/arjuna/wsas/tests/DemoHLS.java
4846
/* * JBoss, Home of Professional Open Source * Copyright 2006, Red Hat Middleware LLC, and individual contributors * as indicated by the @author tags. * See the copyright.txt in the distribution for a full listing * of individual contributors. * This copyrighted material is made available to anyone wishing to use, * modify, copy, or redistribute it subject to the terms and conditions * of the GNU Lesser General Public License, v. 2.1. * This program is distributed in the hope that it will be useful, but WITHOUT A * 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, * v.2.1 along with this distribution; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. * * (C) 2005-2006, * @author JBoss Inc. */ /* * Copyright (C) 2002, * * Arjuna Technologies Limited, * Newcastle upon Tyne, * Tyne and Wear, * UK. * * $Id: DemoHLS.java,v 1.2 2005/05/19 12:13:19 nmcl Exp $ */ package com.arjuna.wsas.tests; import com.arjuna.mw.wsas.context.Context; import com.arjuna.mw.wsas.UserActivityFactory; import com.arjuna.mw.wsas.common.GlobalId; import com.arjuna.mw.wsas.activity.Outcome; import com.arjuna.mw.wsas.activity.HLS; import com.arjuna.mw.wsas.completionstatus.CompletionStatus; import com.arjuna.mw.wsas.exceptions.*; import java.util.*; /** * @author Mark Little (mark.little@arjuna.com) * @version $Id: DemoHLS.java,v 1.2 2005/05/19 12:13:19 nmcl Exp $ * @since 1.0. */ public class DemoHLS implements HLS { private Stack<GlobalId> _id; public DemoHLS() { _id = new Stack<GlobalId>(); } /** * An activity has begun and is active on the current thread. */ public void begun () throws SystemException { try { GlobalId activityId = UserActivityFactory.userActivity().activityId(); _id.push(activityId); System.out.println("DemoHLS.begun "+activityId); } catch (Exception ex) { ex.printStackTrace(); } } /** * The current activity is completing with the specified completion status. * * @return The result of terminating the relationship of this HLS and * the current activity. */ public Outcome complete (CompletionStatus cs) throws SystemException { try { System.out.println("DemoHLS.complete ( "+cs+" ) " + UserActivityFactory.userActivity().activityId()); } catch (Exception ex) { ex.printStackTrace(); } return null; } /** * The activity has been suspended. How does the HLS know which activity * has been suspended? It must remember what its notion of current is. */ public void suspended () throws SystemException { System.out.println("DemoHLS.suspended"); } /** * The activity has been resumed on the current thread. */ public void resumed () throws SystemException { System.out.println("DemoHLS.resumed"); } /** * The activity has completed and is no longer active on the current * thread. */ public void completed () throws SystemException { try { System.out.println("DemoHLS.completed "+ UserActivityFactory.userActivity().activityId()); } catch (Exception ex) { ex.printStackTrace(); } if (!_id.isEmpty()) { _id.pop(); } } /** * The HLS name. */ public String identity () throws SystemException { return "DemoHLS"; } /** * The activity service maintains a priority ordered list of HLS * implementations. If an HLS wishes to be ordered based on priority * then it can return a non-negative value: the higher the value, * the higher the priority and hence the earlier in the list of HLSes * it will appear (and be used in). * * @return a positive value for the priority for this HLS, or zero/negative * if the order is not important. */ public int priority () throws SystemException { return 0; } /** * Return the context augmentation for this HLS, if any on the current * activity. * * @return a context object or null if no augmentation is necessary. */ public Context context () throws SystemException { if (_id.isEmpty()) { throw new SystemException("request for context when inactive"); } try { System.out.println("DemoHLS.context "+ UserActivityFactory.userActivity().activityId()); } catch (Exception ex) { ex.printStackTrace(); } return new DemoSOAPContextImple(identity() + "_" + _id.size()); } }
apache-2.0
nvoron23/Kylin
metadata/src/main/java/org/apache/kylin/metadata/tool/HiveSourceTableLoader.java
6633
/* * 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.kylin.metadata.tool; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.collect.Sets; import org.apache.hadoop.hive.metastore.api.FieldSchema; import org.apache.hadoop.hive.metastore.api.Table; import org.apache.kylin.common.KylinConfig; import org.apache.kylin.common.util.HadoopUtil; import org.apache.kylin.common.util.HiveClient; import org.apache.kylin.metadata.MetadataConstants; import org.apache.kylin.metadata.MetadataManager; import org.apache.kylin.metadata.model.ColumnDesc; import org.apache.kylin.metadata.model.TableDesc; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.util.*; /** * Management class to sync hive table metadata with command See main method for * how to use the class * * @author jianliu */ public class HiveSourceTableLoader { @SuppressWarnings("unused") private static final Logger logger = LoggerFactory.getLogger(HiveSourceTableLoader.class); public static final String OUTPUT_SURFIX = "json"; public static final String TABLE_FOLDER_NAME = "table"; public static final String TABLE_EXD_FOLDER_NAME = "table_exd"; public static Set<String> reloadHiveTables(String[] hiveTables, KylinConfig config) throws IOException { Map<String, Set<String>> db2tables = Maps.newHashMap(); for (String table : hiveTables) { String[] parts = HadoopUtil.parseHiveTableName(table); Set<String> set = db2tables.get(parts[0]); if (set == null) { set = Sets.newHashSet(); db2tables.put(parts[0], set); } set.add(parts[1]); } // extract from hive Set<String> loadedTables = Sets.newHashSet(); for (String database : db2tables.keySet()) { List<String> loaded = extractHiveTables(database, db2tables.get(database), config); loadedTables.addAll(loaded); } return loadedTables; } private static List<String> extractHiveTables(String database, Set<String> tables, KylinConfig config) throws IOException { List<String> loadedTables = Lists.newArrayList(); MetadataManager metaMgr = MetadataManager.getInstance(KylinConfig.getInstanceFromEnv()); for (String tableName : tables) { Table table = null; HiveClient hiveClient = new HiveClient(); List<FieldSchema> partitionFields = null; List<FieldSchema> fields = null; try { table = hiveClient.getHiveTable(database, tableName); partitionFields = table.getPartitionKeys(); fields = hiveClient.getHiveTableFields(database, tableName); } catch (Exception e) { e.printStackTrace(); throw new IOException(e); } if (fields != null && partitionFields != null && partitionFields.size() > 0) { fields.addAll(partitionFields); } long tableSize = hiveClient.getFileSizeForTable(table); long tableFileNum = hiveClient.getFileNumberForTable(table); TableDesc tableDesc = metaMgr.getTableDesc(database + "." + tableName); if (tableDesc == null) { tableDesc = new TableDesc(); tableDesc.setDatabase(database.toUpperCase()); tableDesc.setName(tableName.toUpperCase()); tableDesc.setUuid(UUID.randomUUID().toString()); tableDesc.setLastModified(0); } int columnNumber = fields.size(); List<ColumnDesc> columns = new ArrayList<ColumnDesc>(columnNumber); for (int i = 0; i < columnNumber; i++) { FieldSchema field = fields.get(i); ColumnDesc cdesc = new ColumnDesc(); cdesc.setName(field.getName().toUpperCase()); cdesc.setDatatype(field.getType()); cdesc.setId(String.valueOf(i + 1)); columns.add(cdesc); } tableDesc.setColumns(columns.toArray(new ColumnDesc[columnNumber])); StringBuffer partitionColumnString = new StringBuffer(); for (int i = 0, n = partitionFields.size(); i < n; i++) { if (i > 0) partitionColumnString.append(", "); partitionColumnString.append(partitionFields.get(i).getName().toUpperCase()); } Map<String, String> map = metaMgr.getTableDescExd(tableDesc.getIdentity()); if (map == null) { map = Maps.newHashMap(); } map.put(MetadataConstants.TABLE_EXD_TABLENAME, table.getTableName()); map.put(MetadataConstants.TABLE_EXD_LOCATION, table.getSd().getLocation()); map.put(MetadataConstants.TABLE_EXD_IF, table.getSd().getInputFormat()); map.put(MetadataConstants.TABLE_EXD_OF, table.getSd().getOutputFormat()); map.put(MetadataConstants.TABLE_EXD_OWNER, table.getOwner()); map.put(MetadataConstants.TABLE_EXD_LAT, String.valueOf(table.getLastAccessTime())); map.put(MetadataConstants.TABLE_EXD_PC, partitionColumnString.toString()); map.put(MetadataConstants.TABLE_EXD_TFS, String.valueOf(tableSize)); map.put(MetadataConstants.TABLE_EXD_TNF, String.valueOf(tableFileNum)); map.put(MetadataConstants.TABLE_EXD_PARTITIONED, Boolean.valueOf(partitionFields != null && partitionFields.size() > 0).toString()); metaMgr.saveSourceTable(tableDesc); metaMgr.saveTableExd(tableDesc.getIdentity(), map); loadedTables.add(tableDesc.getIdentity()); } return loadedTables; } }
apache-2.0
LegNeato/buck
test/com/facebook/buck/io/ConfiguredBuckOutIntegrationTest.java
6709
/* * Copyright 2016-present Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. You may obtain * a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package com.facebook.buck.io; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; import static org.junit.Assume.assumeThat; import com.facebook.buck.io.file.MorePaths; import com.facebook.buck.testutil.ProcessResult; import com.facebook.buck.testutil.TemporaryPaths; import com.facebook.buck.testutil.integration.ProjectWorkspace; import com.facebook.buck.testutil.integration.TestDataHelper; import com.facebook.buck.util.environment.Platform; import com.google.common.base.Splitter; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import org.hamcrest.Matchers; import org.junit.Before; import org.junit.Rule; import org.junit.Test; public class ConfiguredBuckOutIntegrationTest { private ProjectWorkspace workspace; @Rule public TemporaryPaths tmp = new TemporaryPaths(); @Before public void setUp() throws IOException { workspace = TestDataHelper.createProjectWorkspaceForScenario(this, "configured_buck_out", tmp); workspace.setUp(); } @Test public void outputPathsUseConfiguredBuckOut() throws IOException { String buckOut = "new-buck-out"; Path output = workspace.buildAndReturnOutput("-c", "project.buck_out=" + buckOut, "//:dummy"); assertTrue(Files.exists(output)); assertThat(workspace.getDestPath().relativize(output).toString(), Matchers.startsWith(buckOut)); } @Test public void configuredBuckOutAffectsRuleKey() throws IOException { String out = workspace .runBuckCommand("targets", "--show-rulekey", "//:dummy") .assertSuccess() .getStdout(); String ruleKey = Splitter.on(' ').splitToList(out).get(1); String configuredOut = workspace .runBuckCommand( "targets", "--show-rulekey", "-c", "project.buck_out=something", "//:dummy") .assertSuccess() .getStdout(); String configuredRuleKey = Splitter.on(' ').splitToList(configuredOut).get(1); assertThat(ruleKey, Matchers.not(Matchers.equalTo(configuredRuleKey))); } @Test public void buckOutCompatSymlink() throws IOException { assumeThat(Platform.detect(), Matchers.not(Matchers.is(Platform.WINDOWS))); ProcessResult result = workspace.runBuckBuild( "-c", "project.buck_out=something", "-c", "project.buck_out_compat_link=true", "//:dummy"); result.assertSuccess(); assertThat( Files.readSymbolicLink(workspace.resolve("buck-out/gen")), Matchers.equalTo(workspace.getDestPath().getFileSystem().getPath("../something/gen"))); } @Test public void verifyTogglingConfiguredBuckOut() throws IOException { assumeThat(Platform.detect(), Matchers.not(Matchers.is(Platform.WINDOWS))); workspace .runBuckBuild( "-c", "project.buck_out=something", "-c", "project.buck_out_compat_link=true", "//:dummy") .assertSuccess(); workspace.runBuckBuild("//:dummy").assertSuccess(); workspace .runBuckBuild( "-c", "project.buck_out=something", "-c", "project.buck_out_compat_link=true", "//:dummy") .assertSuccess(); } @Test public void verifyNoopBuildWithCompatSymlink() throws IOException { assumeThat(Platform.detect(), Matchers.not(Matchers.is(Platform.WINDOWS))); // Do an initial build. workspace .runBuckBuild( "-c", "project.buck_out=something", "-c", "project.buck_out_compat_link=true", "//:dummy") .assertSuccess(); workspace.getBuildLog().assertTargetBuiltLocally("//:dummy"); // Run another build immediately after and verify everything was up to date. workspace .runBuckBuild( "-c", "project.buck_out=something", "-c", "project.buck_out_compat_link=true", "//:dummy") .assertSuccess(); workspace.getBuildLog().assertTargetHadMatchingRuleKey("//:dummy"); } @Test public void targetsShowOutput() throws IOException { String output = workspace .runBuckCommand( "targets", "--show-output", "-c", "project.buck_out=something", "//:dummy") .assertSuccess() .getStdout() .trim(); output = Splitter.on(' ').splitToList(output).get(1); assertThat(MorePaths.pathWithUnixSeparators(output), Matchers.startsWith("something/")); } @Test public void targetsShowOutputCompatSymlink() throws IOException { assumeThat(Platform.detect(), Matchers.not(Matchers.is(Platform.WINDOWS))); String output = workspace .runBuckCommand( "targets", "--show-output", "-c", "project.buck_out=something", "-c", "project.buck_out_compat_link=true", "//:dummy") .assertSuccess() .getStdout() .trim(); output = Splitter.on(' ').splitToList(output).get(1); assertThat(MorePaths.pathWithUnixSeparators(output), Matchers.startsWith("buck-out/gen/")); } @Test public void buildShowOutput() throws IOException { Path output = workspace.buildAndReturnOutput("-c", "project.buck_out=something", "//:dummy"); assertThat( MorePaths.pathWithUnixSeparators(workspace.getDestPath().relativize(output)), Matchers.startsWith("something/")); } @Test public void buildShowOutputCompatSymlink() throws IOException { assumeThat(Platform.detect(), Matchers.not(Matchers.is(Platform.WINDOWS))); Path output = workspace.buildAndReturnOutput( "-c", "project.buck_out=something", "-c", "project.buck_out_compat_link=true", "//:dummy"); assertThat( MorePaths.pathWithUnixSeparators(workspace.getDestPath().relativize(output)), Matchers.startsWith("buck-out/gen/")); } }
apache-2.0
0x6e6562/astyanax
src/main/java/com/netflix/astyanax/thrift/model/ThriftCounterColumnListImpl.java
3953
/******************************************************************************* * Copyright 2011 Netflix * * 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.netflix.astyanax.thrift.model; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.Map; import com.google.common.collect.Maps; import com.netflix.astyanax.Serializer; import com.netflix.astyanax.model.AbstractColumnList; import com.netflix.astyanax.model.Column; public class ThriftCounterColumnListImpl<C> extends AbstractColumnList<C> { private final List<org.apache.cassandra.thrift.CounterColumn> columns; private Map<C, org.apache.cassandra.thrift.CounterColumn> lookup; private final Serializer<C> colSer; public ThriftCounterColumnListImpl(List<org.apache.cassandra.thrift.CounterColumn> columns, Serializer<C> colSer) { this.columns = columns; this.colSer = colSer; } @Override public Iterator<Column<C>> iterator() { class IteratorImpl implements Iterator<Column<C>> { Iterator<org.apache.cassandra.thrift.CounterColumn> base; public IteratorImpl(Iterator<org.apache.cassandra.thrift.CounterColumn> base) { this.base = base; } @Override public boolean hasNext() { return base.hasNext(); } @Override public Column<C> next() { org.apache.cassandra.thrift.CounterColumn c = base.next(); return new ThriftCounterColumnImpl<C>(colSer.fromBytes(c.getName()), c); } @Override public void remove() { throw new UnsupportedOperationException("Iterator is immutable"); } } return new IteratorImpl(columns.iterator()); } @Override public Column<C> getColumnByName(C columnName) { constructMap(); org.apache.cassandra.thrift.CounterColumn c = lookup.get(columnName); if (c == null) { return null; } return new ThriftCounterColumnImpl<C>(colSer.fromBytes(c.getName()), c); } @Override public Column<C> getColumnByIndex(int idx) { org.apache.cassandra.thrift.CounterColumn c = columns.get(idx); return new ThriftCounterColumnImpl<C>(colSer.fromBytes(c.getName()), c); } @Override public <C2> Column<C2> getSuperColumn(C columnName, Serializer<C2> colSer) { throw new UnsupportedOperationException("Call getCounter"); } @Override public <C2> Column<C2> getSuperColumn(int idx, Serializer<C2> colSer) { throw new UnsupportedOperationException("Call getCounter"); } @Override public boolean isEmpty() { return columns.isEmpty(); } @Override public int size() { return columns.size(); } @Override public boolean isSuperColumn() { return false; } @Override public Collection<C> getColumnNames() { constructMap(); return lookup.keySet(); } private void constructMap() { if (lookup == null) { lookup = Maps.newHashMap(); for (org.apache.cassandra.thrift.CounterColumn column : columns) { lookup.put(colSer.fromBytes(column.getName()), column); } } } }
apache-2.0
facebook/presto
presto-main/src/test/java/com/facebook/presto/operator/unnest/TestUnnestOperator.java
26599
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.facebook.presto.operator.unnest; import com.facebook.presto.Session; import com.facebook.presto.block.BlockAssertions.Encoding; import com.facebook.presto.common.Page; import com.facebook.presto.common.type.ArrayType; import com.facebook.presto.common.type.RowType; import com.facebook.presto.common.type.Type; import com.facebook.presto.metadata.MetadataManager; import com.facebook.presto.operator.DriverContext; import com.facebook.presto.operator.Operator; import com.facebook.presto.operator.OperatorFactory; import com.facebook.presto.operator.PageAssertions; import com.facebook.presto.spi.plan.PlanNodeId; import com.facebook.presto.testing.MaterializedResult; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import java.util.ArrayList; import java.util.List; import java.util.concurrent.ExecutorService; import java.util.concurrent.ScheduledExecutorService; import java.util.stream.Collectors; import java.util.stream.IntStream; import static com.facebook.airlift.concurrent.Threads.daemonThreadsNamed; import static com.facebook.presto.RowPagesBuilder.rowPagesBuilder; import static com.facebook.presto.SessionTestUtils.TEST_SESSION; import static com.facebook.presto.block.BlockAssertions.Encoding.DICTIONARY; import static com.facebook.presto.block.BlockAssertions.Encoding.RUN_LENGTH; import static com.facebook.presto.block.BlockAssertions.createMapType; import static com.facebook.presto.common.type.BigintType.BIGINT; import static com.facebook.presto.common.type.BooleanType.BOOLEAN; import static com.facebook.presto.common.type.DecimalType.createDecimalType; import static com.facebook.presto.common.type.Decimals.MAX_SHORT_PRECISION; import static com.facebook.presto.common.type.DoubleType.DOUBLE; import static com.facebook.presto.common.type.IntegerType.INTEGER; import static com.facebook.presto.common.type.RowType.withDefaultFieldNames; import static com.facebook.presto.common.type.SmallintType.SMALLINT; import static com.facebook.presto.common.type.TypeSignature.parseTypeSignature; import static com.facebook.presto.common.type.VarcharType.VARCHAR; import static com.facebook.presto.metadata.MetadataManager.createTestMetadataManager; import static com.facebook.presto.operator.OperatorAssertion.assertOperatorEquals; import static com.facebook.presto.operator.PageAssertions.assertPageEquals; import static com.facebook.presto.operator.unnest.TestUnnesterUtil.buildExpectedPage; import static com.facebook.presto.operator.unnest.TestUnnesterUtil.buildOutputTypes; import static com.facebook.presto.operator.unnest.TestUnnesterUtil.calculateMaxCardinalities; import static com.facebook.presto.operator.unnest.TestUnnesterUtil.mergePages; import static com.facebook.presto.testing.MaterializedResult.resultBuilder; import static com.facebook.presto.testing.TestingSession.testSessionBuilder; import static com.facebook.presto.testing.TestingTaskContext.createTaskContext; import static com.facebook.presto.tpch.TpchMetadata.TINY_SCHEMA_NAME; import static com.facebook.presto.util.StructuralTestUtil.arrayBlockOf; import static com.facebook.presto.util.StructuralTestUtil.mapBlockOf; import static java.lang.Double.NEGATIVE_INFINITY; import static java.lang.Double.NaN; import static java.lang.Double.POSITIVE_INFINITY; import static java.util.concurrent.Executors.newCachedThreadPool; import static java.util.concurrent.Executors.newScheduledThreadPool; import static org.testng.Assert.assertTrue; @Test(singleThreaded = true) public class TestUnnestOperator { private static final int PAGE_COUNT = 10; private static final int POSITION_COUNT = 500; private static final ExecutorService EXECUTOR = newCachedThreadPool(daemonThreadsNamed("test-EXECUTOR-%s")); private static final ScheduledExecutorService SCHEDULER = newScheduledThreadPool(1, daemonThreadsNamed("test-%s")); private ExecutorService executor; private ScheduledExecutorService scheduledExecutor; private DriverContext driverContext; @BeforeMethod public void setUp() { executor = newCachedThreadPool(daemonThreadsNamed("test-executor-%s")); scheduledExecutor = newScheduledThreadPool(2, daemonThreadsNamed("test-scheduledExecutor-%s")); driverContext = createTaskContext(executor, scheduledExecutor, TEST_SESSION) .addPipelineContext(0, true, true, false) .addDriverContext(); } @AfterMethod public void tearDown() { executor.shutdownNow(); scheduledExecutor.shutdownNow(); } @Test public void testUnnest() { MetadataManager metadata = createTestMetadataManager(); Type arrayType = metadata.getType(parseTypeSignature("array(bigint)")); Type mapType = metadata.getType(parseTypeSignature("map(bigint,bigint)")); List<Page> input = rowPagesBuilder(BIGINT, arrayType, mapType) .row(1L, arrayBlockOf(BIGINT, 2, 3), mapBlockOf(BIGINT, BIGINT, ImmutableMap.of(4, 5))) .row(2L, arrayBlockOf(BIGINT, 99), null) .row(3L, null, null) .pageBreak() .row(6L, arrayBlockOf(BIGINT, 7, 8), mapBlockOf(BIGINT, BIGINT, ImmutableMap.of(9, 10, 11, 12))) .build(); OperatorFactory operatorFactory = new UnnestOperator.UnnestOperatorFactory( 0, new PlanNodeId("test"), ImmutableList.of(0), ImmutableList.of(BIGINT), ImmutableList.of(1, 2), ImmutableList.of(arrayType, mapType), false); MaterializedResult expected = resultBuilder(driverContext.getSession(), BIGINT, BIGINT, BIGINT, BIGINT) .row(1L, 2L, 4L, 5L) .row(1L, 3L, null, null) .row(2L, 99L, null, null) .row(6L, 7L, 9L, 10L) .row(6L, 8L, 11L, 12L) .build(); assertOperatorEquals(operatorFactory, driverContext, input, expected); } @Test public void testUnnestWithArray() { MetadataManager metadata = createTestMetadataManager(); Type arrayType = metadata.getType(parseTypeSignature("array(array(bigint))")); Type mapType = metadata.getType(parseTypeSignature("map(array(bigint),array(bigint))")); List<Page> input = rowPagesBuilder(BIGINT, arrayType, mapType) .row( 1L, arrayBlockOf(new ArrayType(BIGINT), ImmutableList.of(2, 4), ImmutableList.of(3, 6)), mapBlockOf(new ArrayType(BIGINT), new ArrayType(BIGINT), ImmutableMap.of(ImmutableList.of(4, 8), ImmutableList.of(5, 10)))) .row(2L, arrayBlockOf(new ArrayType(BIGINT), ImmutableList.of(99, 198)), null) .row(3L, null, null) .pageBreak() .row( 6, arrayBlockOf(new ArrayType(BIGINT), ImmutableList.of(7, 14), ImmutableList.of(8, 16)), mapBlockOf(new ArrayType(BIGINT), new ArrayType(BIGINT), ImmutableMap.of(ImmutableList.of(9, 18), ImmutableList.of(10, 20), ImmutableList.of(11, 22), ImmutableList.of(12, 24)))) .build(); OperatorFactory operatorFactory = new UnnestOperator.UnnestOperatorFactory( 0, new PlanNodeId("test"), ImmutableList.of(0), ImmutableList.of(BIGINT), ImmutableList.of(1, 2), ImmutableList.of(arrayType, mapType), false); MaterializedResult expected = resultBuilder(driverContext.getSession(), BIGINT, new ArrayType(BIGINT), new ArrayType(BIGINT), new ArrayType(BIGINT)) .row(1L, ImmutableList.of(2L, 4L), ImmutableList.of(4L, 8L), ImmutableList.of(5L, 10L)) .row(1L, ImmutableList.of(3L, 6L), null, null) .row(2L, ImmutableList.of(99L, 198L), null, null) .row(6L, ImmutableList.of(7L, 14L), ImmutableList.of(9L, 18L), ImmutableList.of(10L, 20L)) .row(6L, ImmutableList.of(8L, 16L), ImmutableList.of(11L, 22L), ImmutableList.of(12L, 24L)) .build(); assertOperatorEquals(operatorFactory, driverContext, input, expected); } @Test public void testUnnestWithOrdinality() { MetadataManager metadata = createTestMetadataManager(); Type arrayType = metadata.getType(parseTypeSignature("array(bigint)")); Type mapType = metadata.getType(parseTypeSignature("map(bigint,bigint)")); List<Page> input = rowPagesBuilder(BIGINT, arrayType, mapType) .row(1L, arrayBlockOf(BIGINT, 2, 3), mapBlockOf(BIGINT, BIGINT, ImmutableMap.of(4, 5))) .row(2L, arrayBlockOf(BIGINT, 99), null) .row(3L, null, null) .pageBreak() .row(6L, arrayBlockOf(BIGINT, 7, 8), mapBlockOf(BIGINT, BIGINT, ImmutableMap.of(9, 10, 11, 12))) .build(); OperatorFactory operatorFactory = new UnnestOperator.UnnestOperatorFactory( 0, new PlanNodeId("test"), ImmutableList.of(0), ImmutableList.of(BIGINT), ImmutableList.of(1, 2), ImmutableList.of(arrayType, mapType), true); MaterializedResult expected = resultBuilder(driverContext.getSession(), BIGINT, BIGINT, BIGINT, BIGINT, BIGINT) .row(1L, 2L, 4L, 5L, 1L) .row(1L, 3L, null, null, 2L) .row(2L, 99L, null, null, 1L) .row(6L, 7L, 9L, 10L, 1L) .row(6L, 8L, 11L, 12L, 2L) .build(); assertOperatorEquals(operatorFactory, driverContext, input, expected); } @Test public void testUnnestNonNumericDoubles() { MetadataManager metadata = createTestMetadataManager(); Type arrayType = metadata.getType(parseTypeSignature("array(double)")); Type mapType = metadata.getType(parseTypeSignature("map(bigint,double)")); List<Page> input = rowPagesBuilder(BIGINT, arrayType, mapType) .row(1L, arrayBlockOf(DOUBLE, NEGATIVE_INFINITY, POSITIVE_INFINITY, NaN), mapBlockOf(BIGINT, DOUBLE, ImmutableMap.of(1, NEGATIVE_INFINITY, 2, POSITIVE_INFINITY, 3, NaN))) .build(); OperatorFactory operatorFactory = new UnnestOperator.UnnestOperatorFactory( 0, new PlanNodeId("test"), ImmutableList.of(0), ImmutableList.of(BIGINT), ImmutableList.of(1, 2), ImmutableList.of(arrayType, mapType), false); MaterializedResult expected = resultBuilder(driverContext.getSession(), BIGINT, DOUBLE, BIGINT, DOUBLE) .row(1L, NEGATIVE_INFINITY, 1L, NEGATIVE_INFINITY) .row(1L, POSITIVE_INFINITY, 2L, POSITIVE_INFINITY) .row(1L, NaN, 3L, NaN) .build(); assertOperatorEquals(operatorFactory, driverContext, input, expected); } @Test public void testUnnestWithArrayOfRows() { MetadataManager metadata = createTestMetadataManager(); Type arrayOfRowType = metadata.getType(parseTypeSignature("array(row(bigint, double, varchar))")); Type elementType = RowType.anonymous(ImmutableList.of(BIGINT, DOUBLE, VARCHAR)); List<Page> input = rowPagesBuilder(BIGINT, arrayOfRowType) .row(1, arrayBlockOf(elementType, ImmutableList.of(2, 4.2, "abc"), ImmutableList.of(3, 6.6, "def"))) .row(2, arrayBlockOf(elementType, ImmutableList.of(99, 3.14, "pi"), null)) .row(3, null) .pageBreak() .row(6, arrayBlockOf(elementType, null, ImmutableList.of(8, 1.111, "tt"))) .build(); OperatorFactory operatorFactory = new UnnestOperator.UnnestOperatorFactory( 0, new PlanNodeId("test"), ImmutableList.of(0), ImmutableList.of(BIGINT), ImmutableList.of(1), ImmutableList.of(arrayOfRowType), false); MaterializedResult expected = resultBuilder(driverContext.getSession(), BIGINT, BIGINT, DOUBLE, VARCHAR) .row(1L, 2L, 4.2, "abc") .row(1L, 3L, 6.6, "def") .row(2L, 99L, 3.14, "pi") .row(2L, null, null, null) .row(6L, null, null, null) .row(6L, 8L, 1.111, "tt") .build(); assertOperatorEquals(operatorFactory, driverContext, input, expected); } @Test public void testUnnestSingleArrayUnnester() { List<Type> replicatedTypes = ImmutableList.of(BIGINT); List<Type> unnestTypes = ImmutableList.of(new ArrayType(BIGINT)); List<Type> types = new ArrayList<>(replicatedTypes); types.addAll(unnestTypes); testUnnest(replicatedTypes, unnestTypes, types); replicatedTypes = ImmutableList.of(VARCHAR); unnestTypes = ImmutableList.of(new ArrayType(VARCHAR)); types = new ArrayList<>(replicatedTypes); types.addAll(unnestTypes); testUnnest(replicatedTypes, unnestTypes, types); replicatedTypes = ImmutableList.of(VARCHAR); unnestTypes = ImmutableList.of(new ArrayType(new ArrayType(BIGINT))); types = new ArrayList<>(replicatedTypes); types.addAll(unnestTypes); testUnnest(replicatedTypes, unnestTypes, types); } @Test public void testUnnestSingleMapUnnester() { List<Type> replicatedTypes = ImmutableList.of(BIGINT); List<Type> unnestTypes = ImmutableList.of(createMapType(BIGINT, BIGINT)); List<Type> types = new ArrayList<>(replicatedTypes); types.addAll(unnestTypes); testUnnest(replicatedTypes, unnestTypes, types); replicatedTypes = ImmutableList.of(VARCHAR); unnestTypes = ImmutableList.of(createMapType(VARCHAR, VARCHAR)); types = new ArrayList<>(replicatedTypes); types.addAll(unnestTypes); testUnnest(replicatedTypes, unnestTypes, types); replicatedTypes = ImmutableList.of(VARCHAR); unnestTypes = ImmutableList.of(createMapType(VARCHAR, new ArrayType(BIGINT))); types = new ArrayList<>(replicatedTypes); types.addAll(unnestTypes); testUnnest(replicatedTypes, unnestTypes, types); } @Test public void testUnnestSingleArrayOfRowUnnester() { List<Type> replicatedTypes = ImmutableList.of(BIGINT); List<Type> unnestTypes = ImmutableList.of(new ArrayType(withDefaultFieldNames(ImmutableList.of(BIGINT, BIGINT, BIGINT)))); List<Type> types = new ArrayList<>(replicatedTypes); types.addAll(unnestTypes); testUnnest(replicatedTypes, unnestTypes, types); replicatedTypes = ImmutableList.of(VARCHAR); unnestTypes = ImmutableList.of(new ArrayType(withDefaultFieldNames(ImmutableList.of(VARCHAR, VARCHAR, VARCHAR)))); types = new ArrayList<>(replicatedTypes); types.addAll(unnestTypes); testUnnest(replicatedTypes, unnestTypes, types); replicatedTypes = ImmutableList.of(VARCHAR); unnestTypes = ImmutableList.of( new ArrayType(withDefaultFieldNames(ImmutableList.of(VARCHAR, new ArrayType(BIGINT), createMapType(VARCHAR, VARCHAR))))); types = new ArrayList<>(replicatedTypes); types.addAll(unnestTypes); testUnnest(replicatedTypes, unnestTypes, types); } @Test public void testUnnestTwoArrayUnnesters() { List<Type> replicatedTypes = ImmutableList.of(BOOLEAN); List<Type> unnestTypes = ImmutableList.of(new ArrayType(BOOLEAN), new ArrayType(BOOLEAN)); List<Type> types = new ArrayList<>(replicatedTypes); types.addAll(unnestTypes); testUnnest(replicatedTypes, unnestTypes, types); replicatedTypes = ImmutableList.of(SMALLINT); unnestTypes = ImmutableList.of(new ArrayType(SMALLINT), new ArrayType(SMALLINT)); types = new ArrayList<>(replicatedTypes); types.addAll(unnestTypes); testUnnest(replicatedTypes, unnestTypes, types); replicatedTypes = ImmutableList.of(INTEGER); unnestTypes = ImmutableList.of(new ArrayType(INTEGER), new ArrayType(INTEGER)); types = new ArrayList<>(replicatedTypes); types.addAll(unnestTypes); testUnnest(replicatedTypes, unnestTypes, types); replicatedTypes = ImmutableList.of(BIGINT); unnestTypes = ImmutableList.of(new ArrayType(BIGINT), new ArrayType(BIGINT)); types = new ArrayList<>(replicatedTypes); types.addAll(unnestTypes); testUnnest(replicatedTypes, unnestTypes, types); replicatedTypes = ImmutableList.of(createDecimalType(MAX_SHORT_PRECISION + 1)); unnestTypes = ImmutableList.of( new ArrayType(createDecimalType(MAX_SHORT_PRECISION + 1)), new ArrayType(createDecimalType(MAX_SHORT_PRECISION + 1))); types = new ArrayList<>(replicatedTypes); types.addAll(unnestTypes); testUnnest(replicatedTypes, unnestTypes, types); replicatedTypes = ImmutableList.of(VARCHAR); unnestTypes = ImmutableList.of(new ArrayType(VARCHAR), new ArrayType(VARCHAR)); types = new ArrayList<>(replicatedTypes); types.addAll(unnestTypes); testUnnest(replicatedTypes, unnestTypes, types); replicatedTypes = ImmutableList.of(BIGINT); unnestTypes = ImmutableList.of(new ArrayType(new ArrayType(BIGINT)), new ArrayType(new ArrayType(VARCHAR))); types = new ArrayList<>(replicatedTypes); types.addAll(unnestTypes); testUnnest(replicatedTypes, unnestTypes, types); replicatedTypes = ImmutableList.of(BIGINT); unnestTypes = ImmutableList.of(new ArrayType(createMapType(BIGINT, BIGINT)), new ArrayType(createMapType(BIGINT, BIGINT))); types = new ArrayList<>(replicatedTypes); types.addAll(unnestTypes); testUnnest(replicatedTypes, unnestTypes, types); } @Test public void testUnnestTwoMapUnnesters() { List<Type> replicatedTypes = ImmutableList.of(BIGINT); List<Type> unnestTypes = ImmutableList.of(createMapType(BIGINT, BIGINT), createMapType(VARCHAR, VARCHAR)); List<Type> types = new ArrayList<>(replicatedTypes); types.addAll(unnestTypes); testUnnest(replicatedTypes, unnestTypes, types); } @Test public void testUnnestTwoArrayOfRowUnnesters() { List<Type> replicatedTypes = ImmutableList.of(BIGINT); List<Type> unnestTypes = ImmutableList.of( new ArrayType(withDefaultFieldNames(ImmutableList.of(INTEGER, INTEGER))), new ArrayType(withDefaultFieldNames(ImmutableList.of(INTEGER, INTEGER)))); List<Type> types = new ArrayList<>(replicatedTypes); types.addAll(unnestTypes); testUnnest(replicatedTypes, unnestTypes, types); } @Test public void testUnnestMultipleUnnesters() { List<Type> replicatedTypes = ImmutableList.of(BIGINT); List<Type> unnestTypes = ImmutableList.of( new ArrayType(BIGINT), createMapType(VARCHAR, VARCHAR), new ArrayType(withDefaultFieldNames(ImmutableList.of(BIGINT, BIGINT, BIGINT))), new ArrayType(withDefaultFieldNames(ImmutableList.of(VARCHAR, VARCHAR, VARCHAR)))); List<Type> types = new ArrayList<>(replicatedTypes); types.addAll(unnestTypes); testUnnest(replicatedTypes, unnestTypes, types); } protected void testUnnest(List<Type> replicatedTypes, List<Type> unnestTypes, List<Type> types) { testUnnest(replicatedTypes, unnestTypes, types, 0.0f, 0.0f, false, ImmutableList.of()); testUnnest(replicatedTypes, unnestTypes, types, 0.0f, 0.2f, false, ImmutableList.of()); testUnnest(replicatedTypes, unnestTypes, types, 0.2f, 0.2f, false, ImmutableList.of()); testUnnest(replicatedTypes, unnestTypes, types, 0.0f, 0.0f, true, ImmutableList.of()); testUnnest(replicatedTypes, unnestTypes, types, 0.0f, 0.2f, true, ImmutableList.of()); testUnnest(replicatedTypes, unnestTypes, types, 0.2f, 0.2f, true, ImmutableList.of()); testUnnest(replicatedTypes, unnestTypes, types, 0.0f, 0.0f, false, ImmutableList.of(DICTIONARY)); testUnnest(replicatedTypes, unnestTypes, types, 0.0f, 0.0f, false, ImmutableList.of(RUN_LENGTH)); testUnnest(replicatedTypes, unnestTypes, types, 0.0f, 0.0f, false, ImmutableList.of(DICTIONARY, DICTIONARY)); testUnnest(replicatedTypes, unnestTypes, types, 0.0f, 0.0f, false, ImmutableList.of(RUN_LENGTH, DICTIONARY)); testUnnest(replicatedTypes, unnestTypes, types, 0.0f, 0.2f, false, ImmutableList.of(DICTIONARY)); testUnnest(replicatedTypes, unnestTypes, types, 0.0f, 0.2f, false, ImmutableList.of(RUN_LENGTH)); testUnnest(replicatedTypes, unnestTypes, types, 0.0f, 0.2f, false, ImmutableList.of(DICTIONARY, DICTIONARY)); testUnnest(replicatedTypes, unnestTypes, types, 0.0f, 0.2f, false, ImmutableList.of(RUN_LENGTH, DICTIONARY)); testUnnest(replicatedTypes, unnestTypes, types, 0.2f, 0.2f, false, ImmutableList.of(DICTIONARY)); testUnnest(replicatedTypes, unnestTypes, types, 0.2f, 0.2f, false, ImmutableList.of(RUN_LENGTH)); testUnnest(replicatedTypes, unnestTypes, types, 0.2f, 0.2f, false, ImmutableList.of(DICTIONARY, DICTIONARY)); testUnnest(replicatedTypes, unnestTypes, types, 0.2f, 0.2f, false, ImmutableList.of(RUN_LENGTH, DICTIONARY)); testUnnest(replicatedTypes, unnestTypes, types, 0.0f, 0.0f, true, ImmutableList.of(DICTIONARY)); testUnnest(replicatedTypes, unnestTypes, types, 0.0f, 0.0f, true, ImmutableList.of(RUN_LENGTH)); testUnnest(replicatedTypes, unnestTypes, types, 0.0f, 0.0f, true, ImmutableList.of(DICTIONARY, DICTIONARY)); testUnnest(replicatedTypes, unnestTypes, types, 0.0f, 0.0f, true, ImmutableList.of(RUN_LENGTH, DICTIONARY)); testUnnest(replicatedTypes, unnestTypes, types, 0.0f, 0.2f, true, ImmutableList.of(DICTIONARY)); testUnnest(replicatedTypes, unnestTypes, types, 0.0f, 0.2f, true, ImmutableList.of(RUN_LENGTH)); testUnnest(replicatedTypes, unnestTypes, types, 0.0f, 0.2f, true, ImmutableList.of(DICTIONARY, DICTIONARY)); testUnnest(replicatedTypes, unnestTypes, types, 0.0f, 0.2f, true, ImmutableList.of(RUN_LENGTH, DICTIONARY)); testUnnest(replicatedTypes, unnestTypes, types, 0.2f, 0.2f, true, ImmutableList.of(DICTIONARY)); testUnnest(replicatedTypes, unnestTypes, types, 0.2f, 0.2f, true, ImmutableList.of(RUN_LENGTH)); testUnnest(replicatedTypes, unnestTypes, types, 0.2f, 0.2f, true, ImmutableList.of(DICTIONARY, DICTIONARY)); testUnnest(replicatedTypes, unnestTypes, types, 0.2f, 0.2f, true, ImmutableList.of(RUN_LENGTH, DICTIONARY)); } protected void testUnnest( List<Type> replicatedTypes, List<Type> unnestTypes, List<Type> types, float primitiveNullRate, float nestedNullRate, boolean useBlockView, List<Encoding> wrappings) { List<Page> inputPages = new ArrayList<>(); for (int i = 0; i < PAGE_COUNT; i++) { Page inputPage = PageAssertions.createPageWithRandomData(types, POSITION_COUNT, false, false, primitiveNullRate, nestedNullRate, useBlockView, wrappings); inputPages.add(inputPage); } testUnnest(inputPages, replicatedTypes, unnestTypes, false, false); testUnnest(inputPages, replicatedTypes, unnestTypes, true, false); testUnnest(inputPages, replicatedTypes, unnestTypes, false, true); testUnnest(inputPages, replicatedTypes, unnestTypes, true, true); } private void testUnnest(List<Page> inputPages, List<Type> replicatedTypes, List<Type> unnestTypes, boolean withOrdinality, boolean legacyUnnest) { List<Integer> replicatedChannels = IntStream.range(0, replicatedTypes.size()).boxed().collect(Collectors.toList()); List<Integer> unnestChannels = IntStream.range(replicatedTypes.size(), replicatedTypes.size() + unnestTypes.size()).boxed().collect(Collectors.toList()); OperatorFactory operatorFactory = new UnnestOperator.UnnestOperatorFactory( 0, new PlanNodeId("test"), replicatedChannels, replicatedTypes, unnestChannels, unnestTypes, withOrdinality); Operator unnestOperator = ((UnnestOperator.UnnestOperatorFactory) operatorFactory).createOperator(createDriverContext(), legacyUnnest); for (Page inputPage : inputPages) { int[] maxCardinalities = calculateMaxCardinalities(inputPage, replicatedTypes, unnestTypes); List<Type> outputTypes = buildOutputTypes(replicatedTypes, unnestTypes, withOrdinality, legacyUnnest); Page expectedPage = buildExpectedPage(inputPage, replicatedTypes, unnestTypes, outputTypes, maxCardinalities, withOrdinality, legacyUnnest); unnestOperator.addInput(inputPage); List<Page> outputPages = new ArrayList<>(); while (true) { Page outputPage = unnestOperator.getOutput(); if (outputPage == null) { break; } assertTrue(outputPage.getPositionCount() <= 1000); outputPages.add(outputPage); } Page mergedOutputPage = mergePages(outputTypes, outputPages); assertPageEquals(outputTypes, mergedOutputPage, expectedPage); } } private DriverContext createDriverContext() { Session testSession = testSessionBuilder() .setCatalog("tpch") .setSchema(TINY_SCHEMA_NAME) .build(); return createTaskContext(EXECUTOR, SCHEDULER, testSession) .addPipelineContext(0, true, true, false) .addDriverContext(); } }
apache-2.0
mirego/j2objc
xalan/third_party/android/platform/external/apache-xml/src/main/java/org/apache/xml/serializer/dom3/DOMErrorImpl.java
4503
/* * 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. */ /* * $Id: $ */ package org.apache.xml.serializer.dom3; import org.w3c.dom.DOMError; import org.w3c.dom.DOMLocator; /** * Implementation of the DOM Level 3 DOMError interface. * * <p>See also the <a href='http://www.w3.org/TR/2004/REC-DOM-Level-3-Core-20040407/core.html#ERROR-Interfaces-DOMError'>DOMError Interface definition from Document Object Model (DOM) Level 3 Core Specification</a>. * * @xsl.usage internal */ public final class DOMErrorImpl implements DOMError { /** private data members */ // The DOMError Severity private short fSeverity = DOMError.SEVERITY_WARNING; // The Error message private String fMessage = null; // A String indicating which related data is expected in relatedData. private String fType; // The platform related exception private Exception fException = null; // private Object fRelatedData; // The location of the exception private DOMLocatorImpl fLocation = new DOMLocatorImpl(); // // Constructors // /** * Default constructor. */ DOMErrorImpl () { } /** * @param severity * @param message * @param type */ public DOMErrorImpl(short severity, String message, String type) { fSeverity = severity; fMessage = message; fType = type; } /** * @param severity * @param message * @param type * @param exception */ public DOMErrorImpl(short severity, String message, String type, Exception exception) { fSeverity = severity; fMessage = message; fType = type; fException = exception; } /** * @param severity * @param message * @param type * @param exception * @param relatedData * @param location */ public DOMErrorImpl(short severity, String message, String type, Exception exception, Object relatedData, DOMLocatorImpl location) { fSeverity = severity; fMessage = message; fType = type; fException = exception; fRelatedData = relatedData; fLocation = location; } /** * The severity of the error, either <code>SEVERITY_WARNING</code>, * <code>SEVERITY_ERROR</code>, or <code>SEVERITY_FATAL_ERROR</code>. * * @return A short containing the DOMError severity */ public short getSeverity() { return fSeverity; } /** * The DOMError message string. * * @return String */ public String getMessage() { return fMessage; } /** * The location of the DOMError. * * @return A DOMLocator object containing the DOMError location. */ public DOMLocator getLocation() { return fLocation; } /** * The related platform dependent exception if any. * * @return A java.lang.Exception */ public Object getRelatedException(){ return fException; } /** * Returns a String indicating which related data is expected in relatedData. * * @return A String */ public String getType(){ return fType; } /** * The related DOMError.type dependent data if any. * * @return java.lang.Object */ public Object getRelatedData(){ return fRelatedData; } public void reset(){ fSeverity = DOMError.SEVERITY_WARNING; fException = null; fMessage = null; fType = null; fRelatedData = null; fLocation = null; } }// class DOMErrorImpl
apache-2.0
bojanv55/AxonFramework
test/src/test/java/org/axonframework/test/saga/NonTransientResource.java
76
package org.axonframework.test.saga; public class NonTransientResource { }
apache-2.0
googleapis/google-api-java-client-services
clients/google-api-services-dfareporting/v3.4/1.29.2/com/google/api/services/dfareporting/model/CreativeClickThroughUrl.java
4569
/* * 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.dfareporting.model; /** * Click-through URL * * <p> This is the Java data model class that specifies how to parse/serialize into the JSON that is * transmitted over HTTP when working with the DCM/DFA Reporting And Trafficking API. For a detailed * explanation see: * <a href="https://developers.google.com/api-client-library/java/google-http-java-client/json">https://developers.google.com/api-client-library/java/google-http-java-client/json</a> * </p> * * @author Google, Inc. */ @SuppressWarnings("javadoc") public final class CreativeClickThroughUrl extends com.google.api.client.json.GenericJson { /** * Read-only convenience field representing the actual URL that will be used for this click- * through. The URL is computed as follows: - If landingPageId is specified then that landing * page's URL is assigned to this field. - Otherwise, the customClickThroughUrl is assigned to * this field. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String computedClickThroughUrl; /** * Custom click-through URL. Applicable if the landingPageId field is left unset. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String customClickThroughUrl; /** * ID of the landing page for the click-through URL. * The value may be {@code null}. */ @com.google.api.client.util.Key @com.google.api.client.json.JsonString private java.lang.Long landingPageId; /** * Read-only convenience field representing the actual URL that will be used for this click- * through. The URL is computed as follows: - If landingPageId is specified then that landing * page's URL is assigned to this field. - Otherwise, the customClickThroughUrl is assigned to * this field. * @return value or {@code null} for none */ public java.lang.String getComputedClickThroughUrl() { return computedClickThroughUrl; } /** * Read-only convenience field representing the actual URL that will be used for this click- * through. The URL is computed as follows: - If landingPageId is specified then that landing * page's URL is assigned to this field. - Otherwise, the customClickThroughUrl is assigned to * this field. * @param computedClickThroughUrl computedClickThroughUrl or {@code null} for none */ public CreativeClickThroughUrl setComputedClickThroughUrl(java.lang.String computedClickThroughUrl) { this.computedClickThroughUrl = computedClickThroughUrl; return this; } /** * Custom click-through URL. Applicable if the landingPageId field is left unset. * @return value or {@code null} for none */ public java.lang.String getCustomClickThroughUrl() { return customClickThroughUrl; } /** * Custom click-through URL. Applicable if the landingPageId field is left unset. * @param customClickThroughUrl customClickThroughUrl or {@code null} for none */ public CreativeClickThroughUrl setCustomClickThroughUrl(java.lang.String customClickThroughUrl) { this.customClickThroughUrl = customClickThroughUrl; return this; } /** * ID of the landing page for the click-through URL. * @return value or {@code null} for none */ public java.lang.Long getLandingPageId() { return landingPageId; } /** * ID of the landing page for the click-through URL. * @param landingPageId landingPageId or {@code null} for none */ public CreativeClickThroughUrl setLandingPageId(java.lang.Long landingPageId) { this.landingPageId = landingPageId; return this; } @Override public CreativeClickThroughUrl set(String fieldName, Object value) { return (CreativeClickThroughUrl) super.set(fieldName, value); } @Override public CreativeClickThroughUrl clone() { return (CreativeClickThroughUrl) super.clone(); } }
apache-2.0
Crespo911/encog-java-core
src/main/java/org/encog/neural/pattern/FeedForwardPattern.java
3936
/* * Encog(tm) Core v3.3 - Java Version * http://www.heatonresearch.com/encog/ * https://github.com/encog/encog-java-core * Copyright 2008-2014 Heaton 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. * * For more information on Heaton Research copyrights, licenses * and trademarks visit: * http://www.heatonresearch.com/copyright */ package org.encog.neural.pattern; import java.util.ArrayList; import java.util.List; import org.encog.engine.network.activation.ActivationFunction; import org.encog.ml.MLMethod; import org.encog.neural.networks.BasicNetwork; import org.encog.neural.networks.layers.BasicLayer; import org.encog.neural.networks.layers.Layer; /** * Used to create feedforward neural networks. A feedforward network has an * input and output layers separated by zero or more hidden layers. The * feedforward neural network is one of the most common neural network patterns. * * @author jheaton * */ public class FeedForwardPattern implements NeuralNetworkPattern { /** * The number of input neurons. */ private int inputNeurons; /** * The number of output neurons. */ private int outputNeurons; /** * The activation function. */ private ActivationFunction activationHidden; /** * The activation function. */ private ActivationFunction activationOutput; /** * The number of hidden neurons. */ private final List<Integer> hidden = new ArrayList<Integer>(); /** * Add a hidden layer, with the specified number of neurons. * * @param count * The number of neurons to add. */ public void addHiddenLayer(final int count) { this.hidden.add(count); } /** * Clear out any hidden neurons. */ public void clear() { this.hidden.clear(); } /** * Generate the feedforward neural network. * * @return The feedforward neural network. */ public MLMethod generate() { if( this.activationOutput==null ) this.activationOutput = this.activationHidden; final Layer input = new BasicLayer(null, true, this.inputNeurons); final BasicNetwork result = new BasicNetwork(); result.addLayer(input); for (final Integer count : this.hidden) { final Layer hidden = new BasicLayer(this.activationHidden, true, count); result.addLayer(hidden); } final Layer output = new BasicLayer(this.activationOutput, false, this.outputNeurons); result.addLayer(output); result.getStructure().finalizeStructure(); result.reset(); return result; } /** * Set the activation function to use on each of the layers. * * @param activation * The activation function. */ public void setActivationFunction(final ActivationFunction activation) { this.activationHidden = activation; } /** * Set the number of input neurons. * * @param count * Neuron count. */ public void setInputNeurons(final int count) { this.inputNeurons = count; } /** * Set the number of output neurons. * * @param count * Neuron count. */ public void setOutputNeurons(final int count) { this.outputNeurons = count; } /** * @return the activationOutput */ public ActivationFunction getActivationOutput() { return activationOutput; } /** * @param activationOutput the activationOutput to set */ public void setActivationOutput(ActivationFunction activationOutput) { this.activationOutput = activationOutput; } }
apache-2.0
twitter-forks/bazel
src/main/java/net/starlark/java/syntax/ForStatement.java
2418
// Copyright 2014 The Bazel Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package net.starlark.java.syntax; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableList; /** Syntax node for a for loop statement, {@code for vars in iterable: ...}. */ public final class ForStatement extends Statement { private final int forOffset; private final Expression vars; private final Expression iterable; private final ImmutableList<Statement> body; // non-empty if well formed /** Constructs a for loop statement. */ ForStatement( FileLocations locs, int forOffset, Expression vars, Expression iterable, ImmutableList<Statement> body) { super(locs); this.forOffset = forOffset; this.vars = Preconditions.checkNotNull(vars); this.iterable = Preconditions.checkNotNull(iterable); this.body = body; } /** * Returns variables assigned by each iteration. May be a compound target such as {@code (a[b], * c.d)}. */ public Expression getVars() { return vars; } /** Returns the iterable value. */ // TODO(adonovan): rename to getIterable. public Expression getCollection() { return iterable; } /** Returns the statements of the loop body. Non-empty if parsing succeeded. */ public ImmutableList<Statement> getBody() { return body; } @Override public int getStartOffset() { return forOffset; } @Override public int getEndOffset() { return body.isEmpty() ? iterable.getEndOffset() // wrong, but tree is ill formed : body.get(body.size() - 1).getEndOffset(); } @Override public String toString() { return "for " + vars + " in " + iterable + ": ...\n"; } @Override public void accept(NodeVisitor visitor) { visitor.visit(this); } @Override public Kind kind() { return Kind.FOR; } }
apache-2.0
hgl888/Pedometer
src/main/java/de/j4velin/pedometer/util/ColorPreview.java
1251
package de.j4velin.pedometer.util; import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.util.AttributeSet; import android.view.View; public class ColorPreview extends View { private Paint paint = new Paint(); private int color; public ColorPreview(Context context) { super(context); } public ColorPreview(Context context, AttributeSet attrs) { super(context, attrs); } public ColorPreview(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); } public void setColor(final int c) { color = c; invalidate(); } @Override protected void onDraw(final Canvas canvas) { super.onDraw(canvas); paint.setColor(color); paint.setStyle(Paint.Style.FILL); canvas.drawCircle(canvas.getWidth() / 2, canvas.getHeight() / 2, canvas.getHeight() / 2, paint); paint.setColor(Color.BLACK); paint.setStyle(Paint.Style.STROKE); paint.setStrokeWidth(2); canvas.drawCircle(canvas.getWidth() / 2, canvas.getHeight() / 2, canvas.getHeight() / 2 - 1, paint); } }
apache-2.0
wsargent/playframework
documentation/manual/working/javaGuide/main/xml/code/javaguide/xml/JavaXmlRequests.java
1900
/* * Copyright (C) 2009-2017 Lightbend Inc. <https://www.lightbend.com> */ package javaguide.xml; import org.w3c.dom.Document; import play.libs.XPath; import play.mvc.BodyParser; import play.mvc.Controller; import play.mvc.Result; public class JavaXmlRequests extends Controller { //#xml-hello public Result sayHello() { Document dom = request().body().asXml(); if (dom == null) { return badRequest("Expecting Xml data"); } else { String name = XPath.selectText("//name", dom); if (name == null) { return badRequest("Missing parameter [name]"); } else { return ok("Hello " + name); } } } //#xml-hello //#xml-hello-bodyparser @BodyParser.Of(BodyParser.Xml.class) public Result sayHelloBP() { Document dom = request().body().asXml(); if (dom == null) { return badRequest("Expecting Xml data"); } else { String name = XPath.selectText("//name", dom); if (name == null) { return badRequest("Missing parameter [name]"); } else { return ok("Hello " + name); } } } //#xml-hello-bodyparser //#xml-reply @BodyParser.Of(BodyParser.Xml.class) public Result replyHello() { Document dom = request().body().asXml(); if (dom == null) { return badRequest("Expecting Xml data"); } else { String name = XPath.selectText("//name", dom); if (name == null) { return badRequest("<message \"status\"=\"KO\">Missing parameter [name]</message>").as("application/xml"); } else { return ok("<message \"status\"=\"OK\">Hello " + name + "</message>").as("application/xml"); } } } //#xml-reply }
apache-2.0
pjain1/druid
indexing-hadoop/src/test/java/org/apache/druid/indexer/HdfsClasspathSetupTest.java
8361
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.druid.indexer; import com.google.common.util.concurrent.Futures; import com.google.common.util.concurrent.ListenableFuture; import com.google.common.util.concurrent.ListeningExecutorService; import com.google.common.util.concurrent.MoreExecutors; import org.apache.commons.io.IOUtils; import org.apache.druid.common.utils.UUIDUtils; import org.apache.druid.java.util.common.FileUtils; import org.apache.druid.java.util.common.IOE; import org.apache.druid.java.util.common.StringUtils; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.Path; import org.apache.hadoop.hdfs.DistributedFileSystem; import org.apache.hadoop.hdfs.MiniDFSCluster; import org.apache.hadoop.mapreduce.Job; import org.apache.hadoop.mapreduce.MRJobConfig; import org.junit.After; import org.junit.AfterClass; import org.junit.Assert; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import java.io.ByteArrayInputStream; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.StandardCopyOption; import java.util.ArrayList; import java.util.List; import java.util.concurrent.Callable; import java.util.concurrent.CyclicBarrier; import java.util.concurrent.ExecutionException; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; public class HdfsClasspathSetupTest { private static MiniDFSCluster miniCluster; private static File hdfsTmpDir; private static Configuration conf; private static String dummyJarString = "This is a test jar file."; private File dummyJarFile; private Path finalClasspath; private Path intermediatePath; @Rule public final TemporaryFolder tempFolder = new TemporaryFolder(); @BeforeClass public static void setupStatic() throws IOException { hdfsTmpDir = File.createTempFile("hdfsClasspathSetupTest", "dir"); if (!hdfsTmpDir.delete()) { throw new IOE("Unable to delete hdfsTmpDir [%s]", hdfsTmpDir.getAbsolutePath()); } conf = new Configuration(true); conf.set(MiniDFSCluster.HDFS_MINIDFS_BASEDIR, hdfsTmpDir.getAbsolutePath()); miniCluster = new MiniDFSCluster.Builder(conf).build(); } @Before public void setUp() throws IOException { // intermedatePath and finalClasspath are relative to hdfsTmpDir directory. intermediatePath = new Path(StringUtils.format("/tmp/classpath/%s", UUIDUtils.generateUuid())); finalClasspath = new Path(StringUtils.format("/tmp/intermediate/%s", UUIDUtils.generateUuid())); dummyJarFile = tempFolder.newFile("dummy-test.jar"); Files.copy( new ByteArrayInputStream(StringUtils.toUtf8(dummyJarString)), dummyJarFile.toPath(), StandardCopyOption.REPLACE_EXISTING ); } @AfterClass public static void tearDownStatic() throws IOException { if (miniCluster != null) { miniCluster.shutdown(true); } FileUtils.deleteDirectory(hdfsTmpDir); } @After public void tearDown() throws IOException { dummyJarFile.delete(); Assert.assertFalse(dummyJarFile.exists()); miniCluster.getFileSystem().delete(finalClasspath, true); Assert.assertFalse(miniCluster.getFileSystem().exists(finalClasspath)); miniCluster.getFileSystem().delete(intermediatePath, true); Assert.assertFalse(miniCluster.getFileSystem().exists(intermediatePath)); } @Test public void testAddSnapshotJarToClasspath() throws IOException { Job job = Job.getInstance(conf, "test-job"); DistributedFileSystem fs = miniCluster.getFileSystem(); Path intermediatePath = new Path("/tmp/classpath"); JobHelper.addSnapshotJarToClassPath(dummyJarFile, intermediatePath, fs, job); Path expectedJarPath = new Path(intermediatePath, dummyJarFile.getName()); // check file gets uploaded to HDFS Assert.assertTrue(fs.exists(expectedJarPath)); // check file gets added to the classpath Assert.assertEquals(expectedJarPath.toString(), job.getConfiguration().get(MRJobConfig.CLASSPATH_FILES)); Assert.assertEquals(dummyJarString, StringUtils.fromUtf8(IOUtils.toByteArray(fs.open(expectedJarPath)))); } @Test public void testAddNonSnapshotJarToClasspath() throws IOException { Job job = Job.getInstance(conf, "test-job"); DistributedFileSystem fs = miniCluster.getFileSystem(); JobHelper.addJarToClassPath(dummyJarFile, finalClasspath, intermediatePath, fs, job); Path expectedJarPath = new Path(finalClasspath, dummyJarFile.getName()); // check file gets uploaded to final HDFS path Assert.assertTrue(fs.exists(expectedJarPath)); // check that the intermediate file gets deleted Assert.assertFalse(fs.exists(new Path(intermediatePath, dummyJarFile.getName()))); // check file gets added to the classpath Assert.assertEquals(expectedJarPath.toString(), job.getConfiguration().get(MRJobConfig.CLASSPATH_FILES)); Assert.assertEquals(dummyJarString, StringUtils.fromUtf8(IOUtils.toByteArray(fs.open(expectedJarPath)))); } @Test public void testIsSnapshot() { Assert.assertTrue(JobHelper.isSnapshot(new File("test-SNAPSHOT.jar"))); Assert.assertTrue(JobHelper.isSnapshot(new File("test-SNAPSHOT-selfcontained.jar"))); Assert.assertFalse(JobHelper.isSnapshot(new File("test.jar"))); Assert.assertFalse(JobHelper.isSnapshot(new File("test-selfcontained.jar"))); Assert.assertFalse(JobHelper.isSnapshot(new File("iAmNotSNAPSHOT.jar"))); Assert.assertFalse(JobHelper.isSnapshot(new File("iAmNotSNAPSHOT-selfcontained.jar"))); } @Test public void testConcurrentUpload() throws IOException, InterruptedException, ExecutionException, TimeoutException { final int concurrency = 10; ListeningExecutorService pool = MoreExecutors.listeningDecorator(Executors.newFixedThreadPool(concurrency)); // barrier ensures that all jobs try to add files to classpath at same time. final CyclicBarrier barrier = new CyclicBarrier(concurrency); final DistributedFileSystem fs = miniCluster.getFileSystem(); final Path expectedJarPath = new Path(finalClasspath, dummyJarFile.getName()); List<ListenableFuture<Boolean>> futures = new ArrayList<>(); for (int i = 0; i < concurrency; i++) { futures.add( pool.submit( new Callable() { @Override public Boolean call() throws Exception { int id = barrier.await(); Job job = Job.getInstance(conf, "test-job-" + id); Path intermediatePathForJob = new Path(intermediatePath, "job-" + id); JobHelper.addJarToClassPath(dummyJarFile, finalClasspath, intermediatePathForJob, fs, job); // check file gets uploaded to final HDFS path Assert.assertTrue(fs.exists(expectedJarPath)); // check that the intermediate file is not present Assert.assertFalse(fs.exists(new Path(intermediatePathForJob, dummyJarFile.getName()))); // check file gets added to the classpath Assert.assertEquals( expectedJarPath.toString(), job.getConfiguration().get(MRJobConfig.CLASSPATH_FILES) ); return true; } } ) ); } Futures.allAsList(futures).get(30, TimeUnit.SECONDS); pool.shutdownNow(); } }
apache-2.0
cdapio/twill
twill-core/src/main/java/org/apache/twill/internal/ZKMessages.java
4170
/* * 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.twill.internal; import com.google.common.util.concurrent.FutureCallback; import com.google.common.util.concurrent.Futures; import com.google.common.util.concurrent.ListenableFuture; import com.google.common.util.concurrent.SettableFuture; import org.apache.twill.internal.state.Message; import org.apache.twill.internal.state.MessageCodec; import org.apache.twill.zookeeper.ZKClient; import org.apache.twill.zookeeper.ZKOperations; import org.apache.zookeeper.CreateMode; /** * Helper class to send messages to remote instances using Apache Zookeeper watch mechanism. */ public final class ZKMessages { /** * Creates a message node in zookeeper. The message node created is a PERSISTENT_SEQUENTIAL node. * * @param zkClient The ZooKeeper client for interacting with ZooKeeper. * @param messagePathPrefix ZooKeeper path prefix for the message node. * @param message The {@link Message} object for the content of the message node. * @param completionResult Object to set to the result future when the message is processed. * @param <V> Type of the completion result. * @return A {@link ListenableFuture} that will be completed when the message is consumed, which indicated * by deletion of the node. If there is exception during the process, it will be reflected * to the future returned. */ public static <V> ListenableFuture<V> sendMessage(final ZKClient zkClient, String messagePathPrefix, Message message, final V completionResult) { SettableFuture<V> result = SettableFuture.create(); sendMessage(zkClient, messagePathPrefix, message, result, completionResult); return result; } /** * Creates a message node in zookeeper. The message node created is a PERSISTENT_SEQUENTIAL node. * * @param zkClient The ZooKeeper client for interacting with ZooKeeper. * @param messagePathPrefix ZooKeeper path prefix for the message node. * @param message The {@link Message} object for the content of the message node. * @param completion A {@link SettableFuture} to reflect the result of message process completion. * @param completionResult Object to set to the result future when the message is processed. * @param <V> Type of the completion result. */ public static <V> void sendMessage(final ZKClient zkClient, String messagePathPrefix, Message message, final SettableFuture<V> completion, final V completionResult) { // Creates a message and watch for its deletion for completion. Futures.addCallback(zkClient.create(messagePathPrefix, MessageCodec.encode(message), CreateMode.PERSISTENT_SEQUENTIAL), new FutureCallback<String>() { @Override public void onSuccess(String path) { Futures.addCallback(ZKOperations.watchDeleted(zkClient, path), new FutureCallback<String>() { @Override public void onSuccess(String result) { completion.set(completionResult); } @Override public void onFailure(Throwable t) { completion.setException(t); } }); } @Override public void onFailure(Throwable t) { completion.setException(t); } }); } private ZKMessages() { } }
apache-2.0
johan/closure-compiler
src/com/google/javascript/jscomp/DiagnosticGroupWarningsGuard.java
1568
/* * Copyright 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.javascript.jscomp; import com.google.javascript.jscomp.CheckLevel; /** * Sets the level for a particular DiagnosticGroup. * @author nicksantos@google.com (Nick Santos) */ public class DiagnosticGroupWarningsGuard extends WarningsGuard { private final DiagnosticGroup group; private final CheckLevel level; public DiagnosticGroupWarningsGuard( DiagnosticGroup group, CheckLevel level) { this.group = group; this.level = level; } @Override public CheckLevel level(JSError error) { return group.matches(error) ? level : null; } @Override public boolean disables(DiagnosticGroup otherGroup) { return !level.isOn() && group.isSubGroup(otherGroup); } @Override public boolean enables(DiagnosticGroup otherGroup) { if (level.isOn()) { for (DiagnosticType type : otherGroup.getTypes()) { if (group.matches(type)) { return true; } } } return false; } }
apache-2.0
GJL/flink
flink-end-to-end-tests/flink-streaming-kafka-test-base/src/main/java/org/apache/flink/streaming/kafka/test/base/KafkaExampleUtil.java
2183
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.flink.streaming.kafka.test.base; import org.apache.flink.api.common.restartstrategy.RestartStrategies; import org.apache.flink.api.java.utils.ParameterTool; import org.apache.flink.streaming.api.TimeCharacteristic; import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment; /** * The util class for kafka example. */ public class KafkaExampleUtil { public static StreamExecutionEnvironment prepareExecutionEnv(ParameterTool parameterTool) throws Exception { if (parameterTool.getNumberOfParameters() < 5) { System.out.println("Missing parameters!\n" + "Usage: Kafka --input-topic <topic> --output-topic <topic> " + "--bootstrap.servers <kafka brokers> " + "--group.id <some id>"); throw new Exception("Missing parameters!\n" + "Usage: Kafka --input-topic <topic> --output-topic <topic> " + "--bootstrap.servers <kafka brokers> " + "--group.id <some id>"); } StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(); env.getConfig().setRestartStrategy(RestartStrategies.fixedDelayRestart(4, 10000)); env.enableCheckpointing(5000); // create a checkpoint every 5 seconds env.getConfig().setGlobalJobParameters(parameterTool); // make parameters available in the web interface env.setStreamTimeCharacteristic(TimeCharacteristic.EventTime); return env; } }
apache-2.0
googleapis/google-api-java-client-services
clients/google-api-services-content/v2/1.29.2/com/google/api/services/content/model/OrdersSetLineItemMetadataResponse.java
3052
/* * 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.content.model; /** * Model definition for OrdersSetLineItemMetadataResponse. * * <p> This is the Java data model class that specifies how to parse/serialize into the JSON that is * transmitted over HTTP when working with the Content API for Shopping. For a detailed explanation * see: * <a href="https://developers.google.com/api-client-library/java/google-http-java-client/json">https://developers.google.com/api-client-library/java/google-http-java-client/json</a> * </p> * * @author Google, Inc. */ @SuppressWarnings("javadoc") public final class OrdersSetLineItemMetadataResponse extends com.google.api.client.json.GenericJson { /** * The status of the execution. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String executionStatus; /** * Identifies what kind of resource this is. Value: the fixed string * "content#ordersSetLineItemMetadataResponse". * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String kind; /** * The status of the execution. * @return value or {@code null} for none */ public java.lang.String getExecutionStatus() { return executionStatus; } /** * The status of the execution. * @param executionStatus executionStatus or {@code null} for none */ public OrdersSetLineItemMetadataResponse setExecutionStatus(java.lang.String executionStatus) { this.executionStatus = executionStatus; return this; } /** * Identifies what kind of resource this is. Value: the fixed string * "content#ordersSetLineItemMetadataResponse". * @return value or {@code null} for none */ public java.lang.String getKind() { return kind; } /** * Identifies what kind of resource this is. Value: the fixed string * "content#ordersSetLineItemMetadataResponse". * @param kind kind or {@code null} for none */ public OrdersSetLineItemMetadataResponse setKind(java.lang.String kind) { this.kind = kind; return this; } @Override public OrdersSetLineItemMetadataResponse set(String fieldName, Object value) { return (OrdersSetLineItemMetadataResponse) super.set(fieldName, value); } @Override public OrdersSetLineItemMetadataResponse clone() { return (OrdersSetLineItemMetadataResponse) super.clone(); } }
apache-2.0
jiangchaoting/spring
src/main/java/org/mybatis/spring/SqlSessionTemplate.java
13876
/** * 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.mybatis.spring; import static java.lang.reflect.Proxy.newProxyInstance; import static org.apache.ibatis.reflection.ExceptionUtil.unwrapThrowable; import static org.mybatis.spring.SqlSessionUtils.closeSqlSession; import static org.mybatis.spring.SqlSessionUtils.getSqlSession; import static org.mybatis.spring.SqlSessionUtils.isSqlSessionTransactional; import static org.springframework.util.Assert.notNull; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.sql.Connection; import java.util.List; import java.util.Map; import org.apache.ibatis.cursor.Cursor; import org.apache.ibatis.exceptions.PersistenceException; import org.apache.ibatis.executor.BatchResult; import org.apache.ibatis.session.Configuration; import org.apache.ibatis.session.ExecutorType; import org.apache.ibatis.session.ResultHandler; import org.apache.ibatis.session.RowBounds; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.springframework.beans.factory.DisposableBean; import org.springframework.dao.support.PersistenceExceptionTranslator; /** * Thread safe, Spring managed, {@code SqlSession} that works with Spring * transaction management to ensure that that the actual SqlSession used is the * one associated with the current Spring transaction. In addition, it manages * the session life-cycle, including closing, committing or rolling back the * session as necessary based on the Spring transaction configuration. * <p> * The template needs a SqlSessionFactory to create SqlSessions, passed as a * constructor argument. It also can be constructed indicating the executor type * to be used, if not, the default executor type, defined in the session factory * will be used. * <p> * This template converts MyBatis PersistenceExceptions into unchecked * DataAccessExceptions, using, by default, a {@code MyBatisExceptionTranslator}. * <p> * Because SqlSessionTemplate is thread safe, a single instance can be shared * by all DAOs; there should also be a small memory savings by doing this. This * pattern can be used in Spring configuration files as follows: * * <pre class="code"> * {@code * <bean id="sqlSessionTemplate" class="org.mybatis.spring.SqlSessionTemplate"> * <constructor-arg ref="sqlSessionFactory" /> * </bean> * } * </pre> * * @author Putthibong Boonbong * @author Hunter Presnall * @author Eduardo Macarron * * @see SqlSessionFactory * @see MyBatisExceptionTranslator * @version $Id$ */ public class SqlSessionTemplate implements SqlSession, DisposableBean { private final SqlSessionFactory sqlSessionFactory; private final ExecutorType executorType; private final SqlSession sqlSessionProxy; private final PersistenceExceptionTranslator exceptionTranslator; /** * Constructs a Spring managed SqlSession with the {@code SqlSessionFactory} * provided as an argument. * * @param sqlSessionFactory */ public SqlSessionTemplate(SqlSessionFactory sqlSessionFactory) { this(sqlSessionFactory, sqlSessionFactory.getConfiguration().getDefaultExecutorType()); } /** * Constructs a Spring managed SqlSession with the {@code SqlSessionFactory} * provided as an argument and the given {@code ExecutorType} * {@code ExecutorType} cannot be changed once the {@code SqlSessionTemplate} * is constructed. * * @param sqlSessionFactory * @param executorType */ public SqlSessionTemplate(SqlSessionFactory sqlSessionFactory, ExecutorType executorType) { this(sqlSessionFactory, executorType, new MyBatisExceptionTranslator( sqlSessionFactory.getConfiguration().getEnvironment().getDataSource(), true)); } /** * Constructs a Spring managed {@code SqlSession} with the given * {@code SqlSessionFactory} and {@code ExecutorType}. * A custom {@code SQLExceptionTranslator} can be provided as an * argument so any {@code PersistenceException} thrown by MyBatis * can be custom translated to a {@code RuntimeException} * The {@code SQLExceptionTranslator} can also be null and thus no * exception translation will be done and MyBatis exceptions will be * thrown * * @param sqlSessionFactory * @param executorType * @param exceptionTranslator */ public SqlSessionTemplate(SqlSessionFactory sqlSessionFactory, ExecutorType executorType, PersistenceExceptionTranslator exceptionTranslator) { notNull(sqlSessionFactory, "Property 'sqlSessionFactory' is required"); notNull(executorType, "Property 'executorType' is required"); this.sqlSessionFactory = sqlSessionFactory; this.executorType = executorType; this.exceptionTranslator = exceptionTranslator; this.sqlSessionProxy = (SqlSession) newProxyInstance( SqlSessionFactory.class.getClassLoader(), new Class[] { SqlSession.class }, new SqlSessionInterceptor()); } public SqlSessionFactory getSqlSessionFactory() { return this.sqlSessionFactory; } public ExecutorType getExecutorType() { return this.executorType; } public PersistenceExceptionTranslator getPersistenceExceptionTranslator() { return this.exceptionTranslator; } /** * {@inheritDoc} */ @Override public <T> T selectOne(String statement) { return this.sqlSessionProxy.<T> selectOne(statement); } /** * {@inheritDoc} */ @Override public <T> T selectOne(String statement, Object parameter) { return this.sqlSessionProxy.<T> selectOne(statement, parameter); } /** * {@inheritDoc} */ @Override public <K, V> Map<K, V> selectMap(String statement, String mapKey) { return this.sqlSessionProxy.<K, V> selectMap(statement, mapKey); } /** * {@inheritDoc} */ @Override public <K, V> Map<K, V> selectMap(String statement, Object parameter, String mapKey) { return this.sqlSessionProxy.<K, V> selectMap(statement, parameter, mapKey); } /** * {@inheritDoc} */ @Override public <K, V> Map<K, V> selectMap(String statement, Object parameter, String mapKey, RowBounds rowBounds) { return this.sqlSessionProxy.<K, V> selectMap(statement, parameter, mapKey, rowBounds); } /** * {@inheritDoc} */ @Override public <T> Cursor<T> selectCursor(String statement) { return this.sqlSessionProxy.selectCursor(statement); } /** * {@inheritDoc} */ @Override public <T> Cursor<T> selectCursor(String statement, Object parameter) { return this.sqlSessionProxy.selectCursor(statement, parameter); } /** * {@inheritDoc} */ @Override public <T> Cursor<T> selectCursor(String statement, Object parameter, RowBounds rowBounds) { return this.sqlSessionProxy.selectCursor(statement, parameter, rowBounds); } /** * {@inheritDoc} */ @Override public <E> List<E> selectList(String statement) { return this.sqlSessionProxy.<E> selectList(statement); } /** * {@inheritDoc} */ @Override public <E> List<E> selectList(String statement, Object parameter) { return this.sqlSessionProxy.<E> selectList(statement, parameter); } /** * {@inheritDoc} */ @Override public <E> List<E> selectList(String statement, Object parameter, RowBounds rowBounds) { return this.sqlSessionProxy.<E> selectList(statement, parameter, rowBounds); } /** * {@inheritDoc} */ @Override public void select(String statement, ResultHandler handler) { this.sqlSessionProxy.select(statement, handler); } /** * {@inheritDoc} */ @Override public void select(String statement, Object parameter, ResultHandler handler) { this.sqlSessionProxy.select(statement, parameter, handler); } /** * {@inheritDoc} */ @Override public void select(String statement, Object parameter, RowBounds rowBounds, ResultHandler handler) { this.sqlSessionProxy.select(statement, parameter, rowBounds, handler); } /** * {@inheritDoc} */ @Override public int insert(String statement) { return this.sqlSessionProxy.insert(statement); } /** * {@inheritDoc} */ @Override public int insert(String statement, Object parameter) { return this.sqlSessionProxy.insert(statement, parameter); } /** * {@inheritDoc} */ @Override public int update(String statement) { return this.sqlSessionProxy.update(statement); } /** * {@inheritDoc} */ @Override public int update(String statement, Object parameter) { return this.sqlSessionProxy.update(statement, parameter); } /** * {@inheritDoc} */ @Override public int delete(String statement) { return this.sqlSessionProxy.delete(statement); } /** * {@inheritDoc} */ @Override public int delete(String statement, Object parameter) { return this.sqlSessionProxy.delete(statement, parameter); } /** * {@inheritDoc} */ @Override public <T> T getMapper(Class<T> type) { return getConfiguration().getMapper(type, this); } /** * {@inheritDoc} */ @Override public void commit() { throw new UnsupportedOperationException("Manual commit is not allowed over a Spring managed SqlSession"); } /** * {@inheritDoc} */ @Override public void commit(boolean force) { throw new UnsupportedOperationException("Manual commit is not allowed over a Spring managed SqlSession"); } /** * {@inheritDoc} */ @Override public void rollback() { throw new UnsupportedOperationException("Manual rollback is not allowed over a Spring managed SqlSession"); } /** * {@inheritDoc} */ @Override public void rollback(boolean force) { throw new UnsupportedOperationException("Manual rollback is not allowed over a Spring managed SqlSession"); } /** * {@inheritDoc} */ @Override public void close() { throw new UnsupportedOperationException("Manual close is not allowed over a Spring managed SqlSession"); } /** * {@inheritDoc} */ @Override public void clearCache() { this.sqlSessionProxy.clearCache(); } /** * {@inheritDoc} * */ @Override public Configuration getConfiguration() { return this.sqlSessionFactory.getConfiguration(); } /** * {@inheritDoc} */ @Override public Connection getConnection() { return this.sqlSessionProxy.getConnection(); } /** * {@inheritDoc} * * @since 1.0.2 * */ @Override public List<BatchResult> flushStatements() { return this.sqlSessionProxy.flushStatements(); } /** * Allow gently dispose bean: * <pre> * {@code * * <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate"> * <constructor-arg index="0" ref="sqlSessionFactory" /> * </bean> * } *</pre> * * The implementation of {@link DisposableBean} forces spring context to use {@link DisposableBean#destroy()} method instead of {@link SqlSessionTemplate#close()} to shutdown gently. * * @see SqlSessionTemplate#close() * @see org.springframework.beans.factory.support.DisposableBeanAdapter#inferDestroyMethodIfNecessary * @see org.springframework.beans.factory.support.DisposableBeanAdapter#CLOSE_METHOD_NAME */ @Override public void destroy() throws Exception { //This method forces spring disposer to avoid call of SqlSessionTemplate.close() which gives UnsupportedOperationException } /** * Proxy needed to route MyBatis method calls to the proper SqlSession got * from Spring's Transaction Manager * It also unwraps exceptions thrown by {@code Method#invoke(Object, Object...)} to * pass a {@code PersistenceException} to the {@code PersistenceExceptionTranslator}. */ private class SqlSessionInterceptor implements InvocationHandler { @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { SqlSession sqlSession = getSqlSession( SqlSessionTemplate.this.sqlSessionFactory, SqlSessionTemplate.this.executorType, SqlSessionTemplate.this.exceptionTranslator); try { Object result = method.invoke(sqlSession, args); if (!isSqlSessionTransactional(sqlSession, SqlSessionTemplate.this.sqlSessionFactory)) { // force commit even on non-dirty sessions because some databases require // a commit/rollback before calling close() sqlSession.commit(true); } return result; } catch (Throwable t) { Throwable unwrapped = unwrapThrowable(t); if (SqlSessionTemplate.this.exceptionTranslator != null && unwrapped instanceof PersistenceException) { // release the connection to avoid a deadlock if the translator is no loaded. See issue #22 closeSqlSession(sqlSession, SqlSessionTemplate.this.sqlSessionFactory); sqlSession = null; Throwable translated = SqlSessionTemplate.this.exceptionTranslator.translateExceptionIfPossible((PersistenceException) unwrapped); if (translated != null) { unwrapped = translated; } } throw unwrapped; } finally { if (sqlSession != null) { closeSqlSession(sqlSession, SqlSessionTemplate.this.sqlSessionFactory); } } } } }
apache-2.0
panchenko/pgjdbc
pgjdbc/src/test/java/org/postgresql/test/jdbc4/jdbc41/SchemaTest.java
7435
/* * Copyright (c) 2010, PostgreSQL Global Development Group * See the LICENSE file in the project root for more information. */ package org.postgresql.test.jdbc4.jdbc41; import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; import org.postgresql.test.TestUtil; import org.junit.After; import org.junit.Before; import org.junit.Test; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.sql.Statement; import java.sql.Types; import java.util.Properties; public class SchemaTest { private Connection _conn; private boolean dropUserSchema; @Before public void setUp() throws Exception { _conn = TestUtil.openDB(); Statement stmt = _conn.createStatement(); try { stmt.execute("CREATE SCHEMA " + TestUtil.getUser()); dropUserSchema = true; } catch (SQLException e) { /* assume schema existed */ } stmt.execute("CREATE SCHEMA schema1"); stmt.execute("CREATE SCHEMA schema2"); stmt.execute("CREATE SCHEMA \"schema 3\""); stmt.execute("CREATE SCHEMA \"schema \"\"4\""); stmt.execute("CREATE SCHEMA \"schema '5\""); stmt.execute("CREATE SCHEMA \"schema ,6\""); stmt.execute("CREATE SCHEMA \"UpperCase\""); TestUtil.createTable(_conn, "schema1.table1", "id integer"); TestUtil.createTable(_conn, "schema2.table2", "id integer"); TestUtil.createTable(_conn, "\"UpperCase\".table3", "id integer"); TestUtil.createTable(_conn, "schema1.sptest", "id integer"); TestUtil.createTable(_conn, "schema2.sptest", "id varchar"); } @After public void tearDown() throws SQLException { _conn.setAutoCommit(true); _conn.setSchema(null); Statement stmt = _conn.createStatement(); if (dropUserSchema) { stmt.execute("DROP SCHEMA " + TestUtil.getUser() + " CASCADE"); } stmt.execute("DROP SCHEMA schema1 CASCADE"); stmt.execute("DROP SCHEMA schema2 CASCADE"); stmt.execute("DROP SCHEMA \"schema 3\" CASCADE"); stmt.execute("DROP SCHEMA \"schema \"\"4\" CASCADE"); stmt.execute("DROP SCHEMA \"schema '5\" CASCADE"); stmt.execute("DROP SCHEMA \"schema ,6\""); stmt.execute("DROP SCHEMA \"UpperCase\" CASCADE"); TestUtil.closeDB(_conn); } /** * Test that what you set is what you get */ @Test public void testGetSetSchema() throws SQLException { _conn.setSchema("schema1"); assertEquals("schema1", _conn.getSchema()); _conn.setSchema("schema2"); assertEquals("schema2", _conn.getSchema()); _conn.setSchema("schema 3"); assertEquals("schema 3", _conn.getSchema()); _conn.setSchema("schema \"4"); assertEquals("schema \"4", _conn.getSchema()); _conn.setSchema("schema '5"); assertEquals("schema '5", _conn.getSchema()); _conn.setSchema("UpperCase"); assertEquals("UpperCase", _conn.getSchema()); } /** * Test that setting the schema allows to access objects of this schema without prefix, hide * objects from other schemas but doesn't prevent to prefix-access to them. */ @Test public void testUsingSchema() throws SQLException { Statement stmt = _conn.createStatement(); try { try { _conn.setSchema("schema1"); stmt.executeQuery(TestUtil.selectSQL("table1", "*")); stmt.executeQuery(TestUtil.selectSQL("schema2.table2", "*")); try { stmt.executeQuery(TestUtil.selectSQL("table2", "*")); fail("Objects of schema2 should not be visible without prefix"); } catch (SQLException e) { // expected } _conn.setSchema("schema2"); stmt.executeQuery(TestUtil.selectSQL("table2", "*")); stmt.executeQuery(TestUtil.selectSQL("schema1.table1", "*")); try { stmt.executeQuery(TestUtil.selectSQL("table1", "*")); fail("Objects of schema1 should not be visible without prefix"); } catch (SQLException e) { // expected } _conn.setSchema("UpperCase"); stmt.executeQuery(TestUtil.selectSQL("table3", "*")); stmt.executeQuery(TestUtil.selectSQL("schema1.table1", "*")); try { stmt.executeQuery(TestUtil.selectSQL("table1", "*")); fail("Objects of schema1 should not be visible without prefix"); } catch (SQLException e) { // expected } } catch (SQLException e) { fail("Could not find expected schema elements: " + e.getMessage()); } } finally { try { stmt.close(); } catch (SQLException e) { } } } /** * Test that get schema returns the schema with the highest priority in the search path */ @Test public void testMultipleSearchPath() throws SQLException { execute("SET search_path TO schema1,schema2"); assertEquals("schema1", _conn.getSchema()); execute("SET search_path TO \"schema ,6\",schema2"); assertEquals("schema ,6", _conn.getSchema()); } @Test public void testSchemaInProperties() throws Exception { Properties properties = new Properties(); properties.setProperty("currentSchema", "schema1"); Connection conn = TestUtil.openDB(properties); try { assertEquals("schema1", conn.getSchema()); Statement stmt = conn.createStatement(); stmt.executeQuery(TestUtil.selectSQL("table1", "*")); stmt.executeQuery(TestUtil.selectSQL("schema2.table2", "*")); try { stmt.executeQuery(TestUtil.selectSQL("table2", "*")); fail("Objects of schema2 should not be visible without prefix"); } catch (SQLException e) { // expected } } finally { TestUtil.closeDB(conn); } } @Test public void testSchemaPath$User() throws Exception { execute("SET search_path TO \"$user\",public,schema2"); assertEquals(TestUtil.getUser(), _conn.getSchema()); } private void execute(String sql) throws SQLException { Statement stmt = _conn.createStatement(); try { stmt.execute(sql); } finally { try { stmt.close(); } catch (SQLException e) { } } } @Test public void testSearchPathPreparedStatementAutoCommitFalse() throws SQLException { _conn.setAutoCommit(false); testSearchPathPreparedStatement(); } @Test public void testSearchPathPreparedStatementAutoCommitTrue() throws SQLException { testSearchPathPreparedStatement(); } @Test public void testSearchPathPreparedStatement() throws SQLException { execute("set search_path to schema1,public"); PreparedStatement ps = _conn.prepareStatement("select * from sptest"); for (int i = 0; i < 10; i++) { ps.execute(); } assertColType(ps, "sptest should point to schema1.sptest, thus column type should be INT", Types.INTEGER); ps.close(); execute("set search_path to schema2,public"); ps = _conn.prepareStatement("select * from sptest"); assertColType(ps, "sptest should point to schema2.sptest, thus column type should be VARCHAR", Types.VARCHAR); ps.close(); } private void assertColType(PreparedStatement ps, String message, int expected) throws SQLException { ResultSet rs = ps.executeQuery(); ResultSetMetaData md = rs.getMetaData(); int columnType = md.getColumnType(1); assertEquals(message, expected, columnType); rs.close(); } }
bsd-2-clause
ric2b/Vivaldi-browser
chromium/chrome/android/java/src/org/chromium/chrome/browser/browserservices/ui/splashscreen/trustedwebactivity/TwaSplashController.java
8032
// Copyright 2019 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package org.chromium.chrome.browser.browserservices.ui.splashscreen.trustedwebactivity; import static android.view.ViewGroup.LayoutParams.MATCH_PARENT; import static androidx.browser.trusted.TrustedWebActivityIntentBuilder.EXTRA_SPLASH_SCREEN_PARAMS; import android.app.Activity; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.Color; import android.graphics.Matrix; import android.os.Bundle; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import androidx.browser.customtabs.TrustedWebUtils; import androidx.browser.trusted.TrustedWebActivityIntentBuilder; import androidx.browser.trusted.splashscreens.SplashScreenParamKey; import org.chromium.base.IntentUtils; import org.chromium.chrome.browser.browserservices.intents.BrowserServicesIntentDataProvider; import org.chromium.chrome.browser.browserservices.ui.splashscreen.SplashController; import org.chromium.chrome.browser.browserservices.ui.splashscreen.SplashDelegate; import org.chromium.chrome.browser.customtabs.TranslucentCustomTabActivity; import org.chromium.chrome.browser.tab.Tab; import org.chromium.ui.base.ActivityWindowAndroid; import org.chromium.ui.util.ColorUtils; import javax.inject.Inject; /** * Orchestrates the flow of showing and removing splash screens for apps based on Trusted Web * Activities. * * The flow is as follows: * - TWA client app verifies conditions for showing splash screen. If the checks pass, it shows the * splash screen immediately. * - The client passes the URI to a file with the splash image to * {@link androidx.browser.customtabs.CustomTabsService}. The image is decoded and put into * {@link SplashImageHolder}. * - The client then launches a TWA, at which point the Bitmap is already available. * - ChromeLauncherActivity calls {@link #handleIntent}, which starts * {@link TranslucentCustomTabActivity} - a CustomTabActivity with translucent style. The * translucency is necessary in order to avoid a flash that might be seen when starting the activity * before the splash screen is attached. * - {@link TranslucentCustomTabActivity} creates an instance of {@link TwaSplashController} which * immediately displays the splash screen in an ImageView on top of the rest of view hierarchy. * - It also immediately removes the translucency. See comment in {@link SplashController} for more * details. * - It waits for the page to load, and removes the splash image once first paint (or a failure) * occurs. * * Lifecycle: this class is resolved only once when CustomTabActivity is launched, and is * gc-ed when it finishes its job. * If these lifecycle assumptions change, consider whether @ActivityScope needs to be added. */ public class TwaSplashController implements SplashDelegate { // TODO(pshmakov): move this to AndroidX. private static final String KEY_SHOWN_IN_CLIENT = "androidx.browser.trusted.KEY_SPLASH_SCREEN_SHOWN_IN_CLIENT"; private final SplashController mSplashController; private final Activity mActivity; private final SplashImageHolder mSplashImageCache; private final BrowserServicesIntentDataProvider mIntentDataProvider; @Inject public TwaSplashController(SplashController splashController, Activity activity, ActivityWindowAndroid activityWindowAndroid, SplashImageHolder splashImageCache, BrowserServicesIntentDataProvider intentDataProvider) { mSplashController = splashController; mActivity = activity; mSplashImageCache = splashImageCache; mIntentDataProvider = intentDataProvider; long splashHideAnimationDurationMs = IntentUtils.safeGetInt(getSplashScreenParamsFromIntent(), SplashScreenParamKey.KEY_FADE_OUT_DURATION_MS, 0); mSplashController.setConfig(this, splashHideAnimationDurationMs); } @Override public View buildSplashView() { Bitmap bitmap = mSplashImageCache.takeImage(mIntentDataProvider.getSession()); if (bitmap == null) { return null; } ImageView splashView = new ImageView(mActivity); splashView.setLayoutParams(new ViewGroup.LayoutParams(MATCH_PARENT, MATCH_PARENT)); splashView.setImageBitmap(bitmap); applyCustomizationsToSplashScreenView(splashView); return splashView; } @Override public void onSplashHidden(Tab tab, long startTimestamp, long endTimestamp) {} @Override public boolean shouldWaitForSubsequentPageLoadToHideSplash() { return false; } private void applyCustomizationsToSplashScreenView(ImageView imageView) { Bundle params = getSplashScreenParamsFromIntent(); int backgroundColor = IntentUtils.safeGetInt( params, SplashScreenParamKey.KEY_BACKGROUND_COLOR, Color.WHITE); imageView.setBackgroundColor(ColorUtils.getOpaqueColor(backgroundColor)); int scaleTypeOrdinal = IntentUtils.safeGetInt(params, SplashScreenParamKey.KEY_SCALE_TYPE, -1); ImageView.ScaleType[] scaleTypes = ImageView.ScaleType.values(); ImageView.ScaleType scaleType; if (scaleTypeOrdinal < 0 || scaleTypeOrdinal >= scaleTypes.length) { scaleType = ImageView.ScaleType.CENTER; } else { scaleType = scaleTypes[scaleTypeOrdinal]; } imageView.setScaleType(scaleType); if (scaleType != ImageView.ScaleType.MATRIX) return; float[] matrixValues = IntentUtils.safeGetFloatArray( params, SplashScreenParamKey.KEY_IMAGE_TRANSFORMATION_MATRIX); if (matrixValues == null || matrixValues.length != 9) return; Matrix matrix = new Matrix(); matrix.setValues(matrixValues); imageView.setImageMatrix(matrix); } private Bundle getSplashScreenParamsFromIntent() { return mIntentDataProvider.getIntent().getBundleExtra(EXTRA_SPLASH_SCREEN_PARAMS); } /** * Returns true if the intent corresponds to a TWA with a splash screen. */ public static boolean intentIsForTwaWithSplashScreen(Intent intent) { boolean isTrustedWebActivity = IntentUtils.safeGetBooleanExtra( intent, TrustedWebUtils.EXTRA_LAUNCH_AS_TRUSTED_WEB_ACTIVITY, false); boolean requestsSplashScreen = IntentUtils.safeGetParcelableExtra(intent, EXTRA_SPLASH_SCREEN_PARAMS) != null; return isTrustedWebActivity && requestsSplashScreen; } /** * Handles the intent if it should launch a TWA with splash screen. * @param activity Activity, from which to start the next one. * @param intent Incoming intent. * @return Whether the intent was handled. */ public static boolean handleIntent(Activity activity, Intent intent) { if (!intentIsForTwaWithSplashScreen(intent)) return false; Bundle params = IntentUtils.safeGetBundleExtra( intent, TrustedWebActivityIntentBuilder.EXTRA_SPLASH_SCREEN_PARAMS); boolean shownInClient = IntentUtils.safeGetBoolean(params, KEY_SHOWN_IN_CLIENT, true); // shownInClient is "true" by default for the following reasons: // - For compatibility with older clients which don't use this bundle key. // - Because getting "false" when it should be "true" leads to more severe visual glitches, // than vice versa. if (shownInClient) { // If splash screen was shown in client, we must launch a translucent activity to // ensure smooth transition. intent.setClassName(activity, TranslucentCustomTabActivity.class.getName()); } intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION); activity.startActivity(intent); activity.overridePendingTransition(0, 0); return true; } }
bsd-3-clause
xiaopengs/iBooks
src/com/greenlemonmobile/app/ebook/books/parser/ZipWrapper.java
433
package com.greenlemonmobile.app.ebook.books.parser; import java.io.IOException; import java.io.InputStream; import java.util.Enumeration; import java.util.zip.ZipEntry; public interface ZipWrapper { ZipEntry getEntry(String entryName); InputStream getInputStream(ZipEntry entry) throws IOException; Enumeration<? extends ZipEntry> entries(); void close() throws IOException; }
mit
yy1300326388/iBooks
src/com/greenlemonmobile/app/ebook/books/imagezoom/graphics/IBitmapDrawable.java
253
package com.greenlemonmobile.app.ebook.books.imagezoom.graphics; import android.graphics.Bitmap; /** * Base interface used in the {@link ImageViewTouchBase} view * @author alessandro * */ public interface IBitmapDrawable { Bitmap getBitmap(); }
mit
yaqiyang/autorest
src/generator/AutoRest.Java.Azure.Tests/src/main/java/fixtures/azurespecials/implementation/AutoRestAzureSpecialParametersTestClientImpl.java
10599
/** * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for * license information. * * Code generated by Microsoft (R) AutoRest Code Generator. * Changes may cause incorrect behavior and will be lost if the code is * regenerated. */ package fixtures.azurespecials.implementation; import com.microsoft.azure.AzureClient; import com.microsoft.azure.AzureServiceClient; import com.microsoft.azure.RestClient; import com.microsoft.rest.credentials.ServiceClientCredentials; import fixtures.azurespecials.ApiVersionDefaults; import fixtures.azurespecials.ApiVersionLocals; import fixtures.azurespecials.AutoRestAzureSpecialParametersTestClient; import fixtures.azurespecials.Headers; import fixtures.azurespecials.Odatas; import fixtures.azurespecials.SkipUrlEncodings; import fixtures.azurespecials.SubscriptionInCredentials; import fixtures.azurespecials.SubscriptionInMethods; import fixtures.azurespecials.XMsClientRequestIds; /** * Initializes a new instance of the AutoRestAzureSpecialParametersTestClientImpl class. */ public final class AutoRestAzureSpecialParametersTestClientImpl extends AzureServiceClient implements AutoRestAzureSpecialParametersTestClient { /** the {@link AzureClient} used for long running operations. */ private AzureClient azureClient; /** * Gets the {@link AzureClient} used for long running operations. * @return the azure client; */ public AzureClient getAzureClient() { return this.azureClient; } /** The subscription id, which appears in the path, always modeled in credentials. The value is always '1234-5678-9012-3456'. */ private String subscriptionId; /** * Gets The subscription id, which appears in the path, always modeled in credentials. The value is always '1234-5678-9012-3456'. * * @return the subscriptionId value. */ public String subscriptionId() { return this.subscriptionId; } /** * Sets The subscription id, which appears in the path, always modeled in credentials. The value is always '1234-5678-9012-3456'. * * @param subscriptionId the subscriptionId value. * @return the service client itself */ public AutoRestAzureSpecialParametersTestClientImpl withSubscriptionId(String subscriptionId) { this.subscriptionId = subscriptionId; return this; } /** The api version, which appears in the query, the value is always '2015-07-01-preview'. */ private String apiVersion; /** * Gets The api version, which appears in the query, the value is always '2015-07-01-preview'. * * @return the apiVersion value. */ public String apiVersion() { return this.apiVersion; } /** Gets or sets the preferred language for the response. */ private String acceptLanguage; /** * Gets Gets or sets the preferred language for the response. * * @return the acceptLanguage value. */ public String acceptLanguage() { return this.acceptLanguage; } /** * Sets Gets or sets the preferred language for the response. * * @param acceptLanguage the acceptLanguage value. * @return the service client itself */ public AutoRestAzureSpecialParametersTestClientImpl withAcceptLanguage(String acceptLanguage) { this.acceptLanguage = acceptLanguage; return this; } /** Gets or sets the retry timeout in seconds for Long Running Operations. Default value is 30. */ private int longRunningOperationRetryTimeout; /** * Gets Gets or sets the retry timeout in seconds for Long Running Operations. Default value is 30. * * @return the longRunningOperationRetryTimeout value. */ public int longRunningOperationRetryTimeout() { return this.longRunningOperationRetryTimeout; } /** * Sets Gets or sets the retry timeout in seconds for Long Running Operations. Default value is 30. * * @param longRunningOperationRetryTimeout the longRunningOperationRetryTimeout value. * @return the service client itself */ public AutoRestAzureSpecialParametersTestClientImpl withLongRunningOperationRetryTimeout(int longRunningOperationRetryTimeout) { this.longRunningOperationRetryTimeout = longRunningOperationRetryTimeout; return this; } /** When set to true a unique x-ms-client-request-id value is generated and included in each request. Default is true. */ private boolean generateClientRequestId; /** * Gets When set to true a unique x-ms-client-request-id value is generated and included in each request. Default is true. * * @return the generateClientRequestId value. */ public boolean generateClientRequestId() { return this.generateClientRequestId; } /** * Sets When set to true a unique x-ms-client-request-id value is generated and included in each request. Default is true. * * @param generateClientRequestId the generateClientRequestId value. * @return the service client itself */ public AutoRestAzureSpecialParametersTestClientImpl withGenerateClientRequestId(boolean generateClientRequestId) { this.generateClientRequestId = generateClientRequestId; return this; } /** * The XMsClientRequestIds object to access its operations. */ private XMsClientRequestIds xMsClientRequestIds; /** * Gets the XMsClientRequestIds object to access its operations. * @return the XMsClientRequestIds object. */ public XMsClientRequestIds xMsClientRequestIds() { return this.xMsClientRequestIds; } /** * The SubscriptionInCredentials object to access its operations. */ private SubscriptionInCredentials subscriptionInCredentials; /** * Gets the SubscriptionInCredentials object to access its operations. * @return the SubscriptionInCredentials object. */ public SubscriptionInCredentials subscriptionInCredentials() { return this.subscriptionInCredentials; } /** * The SubscriptionInMethods object to access its operations. */ private SubscriptionInMethods subscriptionInMethods; /** * Gets the SubscriptionInMethods object to access its operations. * @return the SubscriptionInMethods object. */ public SubscriptionInMethods subscriptionInMethods() { return this.subscriptionInMethods; } /** * The ApiVersionDefaults object to access its operations. */ private ApiVersionDefaults apiVersionDefaults; /** * Gets the ApiVersionDefaults object to access its operations. * @return the ApiVersionDefaults object. */ public ApiVersionDefaults apiVersionDefaults() { return this.apiVersionDefaults; } /** * The ApiVersionLocals object to access its operations. */ private ApiVersionLocals apiVersionLocals; /** * Gets the ApiVersionLocals object to access its operations. * @return the ApiVersionLocals object. */ public ApiVersionLocals apiVersionLocals() { return this.apiVersionLocals; } /** * The SkipUrlEncodings object to access its operations. */ private SkipUrlEncodings skipUrlEncodings; /** * Gets the SkipUrlEncodings object to access its operations. * @return the SkipUrlEncodings object. */ public SkipUrlEncodings skipUrlEncodings() { return this.skipUrlEncodings; } /** * The Odatas object to access its operations. */ private Odatas odatas; /** * Gets the Odatas object to access its operations. * @return the Odatas object. */ public Odatas odatas() { return this.odatas; } /** * The Headers object to access its operations. */ private Headers headers; /** * Gets the Headers object to access its operations. * @return the Headers object. */ public Headers headers() { return this.headers; } /** * Initializes an instance of AutoRestAzureSpecialParametersTestClient client. * * @param credentials the management credentials for Azure */ public AutoRestAzureSpecialParametersTestClientImpl(ServiceClientCredentials credentials) { this("http://localhost", credentials); } /** * Initializes an instance of AutoRestAzureSpecialParametersTestClient client. * * @param baseUrl the base URL of the host * @param credentials the management credentials for Azure */ public AutoRestAzureSpecialParametersTestClientImpl(String baseUrl, ServiceClientCredentials credentials) { this(new RestClient.Builder() .withBaseUrl(baseUrl) .withCredentials(credentials) .build()); } /** * Initializes an instance of AutoRestAzureSpecialParametersTestClient client. * * @param restClient the REST client to connect to Azure. */ public AutoRestAzureSpecialParametersTestClientImpl(RestClient restClient) { super(restClient); initialize(); } protected void initialize() { this.apiVersion = "2015-07-01-preview"; this.acceptLanguage = "en-US"; this.longRunningOperationRetryTimeout = 30; this.generateClientRequestId = true; this.xMsClientRequestIds = new XMsClientRequestIdsImpl(restClient().retrofit(), this); this.subscriptionInCredentials = new SubscriptionInCredentialsImpl(restClient().retrofit(), this); this.subscriptionInMethods = new SubscriptionInMethodsImpl(restClient().retrofit(), this); this.apiVersionDefaults = new ApiVersionDefaultsImpl(restClient().retrofit(), this); this.apiVersionLocals = new ApiVersionLocalsImpl(restClient().retrofit(), this); this.skipUrlEncodings = new SkipUrlEncodingsImpl(restClient().retrofit(), this); this.odatas = new OdatasImpl(restClient().retrofit(), this); this.headers = new HeadersImpl(restClient().retrofit(), this); this.azureClient = new AzureClient(this); } /** * Gets the User-Agent header for the client. * * @return the user agent string. */ @Override public String userAgent() { return String.format("Azure-SDK-For-Java/%s (%s)", getClass().getPackage().getImplementationVersion(), "AutoRestAzureSpecialParametersTestClient, 2015-07-01-preview"); } }
mit
shitikanth/jabref
src/jmh/java/org/jabref/benchmarks/Benchmarks.java
5418
package org.jabref.benchmarks; import java.io.IOException; import java.io.StringReader; import java.util.List; import java.util.Random; import java.util.stream.Collectors; import org.jabref.Globals; import org.jabref.logic.exporter.BibtexDatabaseWriter; import org.jabref.logic.exporter.SavePreferences; import org.jabref.logic.exporter.StringSaveSession; import org.jabref.logic.formatter.bibtexfields.HtmlToLatexFormatter; import org.jabref.logic.importer.ParseException; import org.jabref.logic.importer.ParserResult; import org.jabref.logic.importer.fileformat.BibtexParser; import org.jabref.logic.layout.format.HTMLChars; import org.jabref.logic.layout.format.LatexToUnicodeFormatter; import org.jabref.logic.search.SearchQuery; import org.jabref.model.Defaults; import org.jabref.model.database.BibDatabase; import org.jabref.model.database.BibDatabaseContext; import org.jabref.model.database.BibDatabaseMode; import org.jabref.model.database.BibDatabaseModeDetection; import org.jabref.model.entry.BibEntry; import org.jabref.model.groups.GroupHierarchyType; import org.jabref.model.groups.KeywordGroup; import org.jabref.model.groups.WordKeywordGroup; import org.jabref.model.metadata.MetaData; import org.jabref.preferences.JabRefPreferences; import org.openjdk.jmh.Main; import org.openjdk.jmh.annotations.Benchmark; import org.openjdk.jmh.annotations.Scope; import org.openjdk.jmh.annotations.Setup; import org.openjdk.jmh.annotations.State; import org.openjdk.jmh.runner.RunnerException; @State(Scope.Thread) public class Benchmarks { private String bibtexString; private final BibDatabase database = new BibDatabase(); private String latexConversionString; private String htmlConversionString; @Setup public void init() throws Exception { Globals.prefs = JabRefPreferences.getInstance(); Random randomizer = new Random(); for (int i = 0; i < 1000; i++) { BibEntry entry = new BibEntry(); entry.setCiteKey("id" + i); entry.setField("title", "This is my title " + i); entry.setField("author", "Firstname Lastname and FirstnameA LastnameA and FirstnameB LastnameB" + i); entry.setField("journal", "Journal Title " + i); entry.setField("keyword", "testkeyword"); entry.setField("year", "1" + i); entry.setField("rnd", "2" + randomizer.nextInt()); database.insertEntry(entry); } BibtexDatabaseWriter<StringSaveSession> databaseWriter = new BibtexDatabaseWriter<>(StringSaveSession::new); StringSaveSession saveSession = databaseWriter.savePartOfDatabase( new BibDatabaseContext(database, new MetaData(), new Defaults()), database.getEntries(), new SavePreferences()); bibtexString = saveSession.getStringValue(); latexConversionString = "{A} \\textbf{bold} approach {\\it to} ${{\\Sigma}}{\\Delta}$ modulator \\textsuperscript{2} \\$"; htmlConversionString = "<b>&Ouml;sterreich</b> &#8211; &amp; characters &#x2aa2; <i>italic</i>"; } @Benchmark public ParserResult parse() throws IOException { BibtexParser parser = new BibtexParser(Globals.prefs.getImportFormatPreferences()); return parser.parse(new StringReader(bibtexString)); } @Benchmark public String write() throws Exception { BibtexDatabaseWriter<StringSaveSession> databaseWriter = new BibtexDatabaseWriter<>(StringSaveSession::new); StringSaveSession saveSession = databaseWriter.savePartOfDatabase( new BibDatabaseContext(database, new MetaData(), new Defaults()), database.getEntries(), new SavePreferences()); return saveSession.getStringValue(); } @Benchmark public List<BibEntry> search() { // FIXME: Reuse SearchWorker here SearchQuery searchQuery = new SearchQuery("Journal Title 500", false, false); return database.getEntries().stream().filter(searchQuery::isMatch).collect(Collectors.toList()); } @Benchmark public List<BibEntry> parallelSearch() { // FIXME: Reuse SearchWorker here SearchQuery searchQuery = new SearchQuery("Journal Title 500", false, false); return database.getEntries().parallelStream().filter(searchQuery::isMatch).collect(Collectors.toList()); } @Benchmark public BibDatabaseMode inferBibDatabaseMode() { return BibDatabaseModeDetection.inferMode(database); } @Benchmark public String latexToUnicodeConversion() { LatexToUnicodeFormatter f = new LatexToUnicodeFormatter(); return f.format(latexConversionString); } @Benchmark public String latexToHTMLConversion() { HTMLChars f = new HTMLChars(); return f.format(latexConversionString); } @Benchmark public String htmlToLatexConversion() { HtmlToLatexFormatter f = new HtmlToLatexFormatter(); return f.format(htmlConversionString); } @Benchmark public boolean keywordGroupContains() throws ParseException { KeywordGroup group = new WordKeywordGroup("testGroup", GroupHierarchyType.INDEPENDENT, "keyword", "testkeyword", false, ',', false); return group.containsAll(database.getEntries()); } public static void main(String[] args) throws IOException, RunnerException { Main.main(args); } }
mit
Snickermicker/smarthome
bundles/core/org.eclipse.smarthome.core/src/main/java/org/eclipse/smarthome/core/library/items/DimmerItem.java
3066
/** * Copyright (c) 2014,2019 Contributors to the Eclipse Foundation * * See the NOTICE file(s) distributed with this work for additional * information regarding copyright ownership. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License 2.0 which is available at * http://www.eclipse.org/legal/epl-2.0 * * SPDX-License-Identifier: EPL-2.0 */ package org.eclipse.smarthome.core.library.items; import java.util.ArrayList; import java.util.Collections; import java.util.List; import org.eclipse.jdt.annotation.NonNullByDefault; import org.eclipse.smarthome.core.library.CoreItemFactory; import org.eclipse.smarthome.core.library.types.IncreaseDecreaseType; import org.eclipse.smarthome.core.library.types.OnOffType; import org.eclipse.smarthome.core.library.types.PercentType; import org.eclipse.smarthome.core.types.Command; import org.eclipse.smarthome.core.types.RefreshType; import org.eclipse.smarthome.core.types.State; import org.eclipse.smarthome.core.types.UnDefType; /** * A DimmerItem can be used as a switch (ON/OFF), but it also accepts percent values * to reflect the dimmed state. * * @author Kai Kreuzer - Initial contribution and API * @author Markus Rathgeb - Support more types for getStateAs * */ @NonNullByDefault public class DimmerItem extends SwitchItem { private static List<Class<? extends State>> acceptedDataTypes = new ArrayList<Class<? extends State>>(); private static List<Class<? extends Command>> acceptedCommandTypes = new ArrayList<Class<? extends Command>>(); static { acceptedDataTypes.add(PercentType.class); acceptedDataTypes.add(OnOffType.class); acceptedDataTypes.add(UnDefType.class); acceptedCommandTypes.add(PercentType.class); acceptedCommandTypes.add(OnOffType.class); acceptedCommandTypes.add(IncreaseDecreaseType.class); acceptedCommandTypes.add(RefreshType.class); } public DimmerItem(String name) { super(CoreItemFactory.DIMMER, name); } /* package */ DimmerItem(String type, String name) { super(type, name); } public void send(PercentType command) { internalSend(command); } @Override public List<Class<? extends State>> getAcceptedDataTypes() { return Collections.unmodifiableList(acceptedDataTypes); } @Override public List<Class<? extends Command>> getAcceptedCommandTypes() { return Collections.unmodifiableList(acceptedCommandTypes); } @Override public void setState(State state) { if (isAcceptedState(acceptedDataTypes, state)) { // try conversion State convertedState = state.as(PercentType.class); if (convertedState != null) { applyState(convertedState); } else { applyState(state); } } else { logSetTypeError(state); } } }
epl-1.0
bramalingam/openmicroscopy
components/server/test/ome/server/itests/ImmutabilityTest.java
1831
/* * ome.server.itests.ImmutabilityTest * * Copyright 2006 University of Dundee. All rights reserved. * Use is subject to license terms supplied in LICENSE.txt */ package ome.server.itests; // Java imports // Third-party libraries import org.testng.annotations.Test; // Application-internal dependencies import ome.model.core.Image; import ome.model.meta.Event; import ome.parameters.Filter; import ome.parameters.Parameters; /** * * @author Josh Moore &nbsp;&nbsp;&nbsp;&nbsp; <a * href="mailto:josh.moore@gmx.de">josh.moore@gmx.de</a> * @version 1.0 <small> (<b>Internal version:</b> $Rev$ $Date$) </small> * @since 1.0 */ public class ImmutabilityTest extends AbstractManagedContextTest { @Test public void testCreationEventWillBeSilentlyUnchanged() throws Exception { loginRoot(); Image i = new_Image("immutable creation"); i = iUpdate.saveAndReturnObject(i); Event oldEvent = i.getDetails().getCreationEvent(); Event newEvent = iQuery.findByQuery( "select e from Event e where id != :id", new Parameters( new Filter().page(0, 1)).addId(oldEvent.getId())); i.getDetails().setCreationEvent(newEvent); // This fails because it gets silently copied to our new instance. See: // http://trac.openmicroscopy.org.uk/ome/ticket/346 // i = iUpdate.saveAndReturnObject(i); // assertEquals( i.getDetails().getCreationEvent().getId(), // oldEvent.getId()); // Saving and reacquiring to be sure. iUpdate.saveObject(i); // unfortunately still not working properly i = iQuery.refresh(i); i = iQuery.get(i.getClass(), i.getId()); assertEquals(i.getDetails().getCreationEvent().getId(), oldEvent .getId()); } }
gpl-2.0
jballanc/openmicroscopy
components/insight/SRC/org/openmicroscopy/shoola/agents/editor/uiComponents/CustomLabel.java
2450
/* * uiComponents.CustomLabel * *------------------------------------------------------------------------------ * Copyright (C) 2006-2008 University of Dundee. All rights reserved. * * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * *------------------------------------------------------------------------------ */ package org.openmicroscopy.shoola.agents.editor.uiComponents; //Java imports import javax.swing.Icon; import javax.swing.JLabel; //Third-party libraries //Application-internal dependencies /** * A Custom Label, which should be used by the UI instead of using * JLabel. Sets the font to CUSTOM FONT. * * This font is also used by many other Custom UI components in this * package, making it easy to change the font in many components in * one place (here!). * * @author William Moore &nbsp;&nbsp;&nbsp;&nbsp; * <a href="mailto:will@lifesci.dundee.ac.uk">will@lifesci.dundee.ac.uk</a> * @version 3.0 * <small> * (<b>Internal version:</b> $Revision: $Date: $) * </small> * @since OME3.0 */ public class CustomLabel extends JLabel { private int fontSize; /** * Simply delegates to JLabel superclass. */ public CustomLabel() { super(); setFont(); } /** * Simply delegates to JLabel superclass. */ public CustomLabel(Icon image) { super(image); setFont(); } /** * Simply delegates to JLabel superclass. */ public CustomLabel(String text) { super(text); setFont(); } /** * Simply delegates to JLabel superclass. */ public CustomLabel(String text, int fontSize) { super(text); this.fontSize = fontSize; setFont(); } private void setFont() { if (fontSize == 0) setFont(new CustomFont()); else { setFont(CustomFont.getFontBySize(fontSize)); } } }
gpl-2.0
JohnTsaiAndroid/iBeebo
app/src/main/java/org/zarroboogs/weibo/hot/bean/hotweibo/TopicStruct.java
718
package org.zarroboogs.weibo.hot.bean.hotweibo; import org.json.*; public class TopicStruct { private String topicTitle; private String topicUrl; public TopicStruct () { } public TopicStruct (JSONObject json) { this.topicTitle = json.optString("topic_title"); this.topicUrl = json.optString("topic_url"); } public String getTopicTitle() { return this.topicTitle; } public void setTopicTitle(String topicTitle) { this.topicTitle = topicTitle; } public String getTopicUrl() { return this.topicUrl; } public void setTopicUrl(String topicUrl) { this.topicUrl = topicUrl; } }
gpl-3.0
jvanz/core
qadevOOo/tests/java/mod/_streams/uno/DataInputStream.java
6006
/* * This file is part of the LibreOffice project. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * This file incorporates work covered by the following license notice: * * 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 . */ package mod._streams.uno; import com.sun.star.io.XActiveDataSink; import com.sun.star.io.XActiveDataSource; import com.sun.star.io.XDataOutputStream; import com.sun.star.io.XInputStream; import com.sun.star.io.XOutputStream; import com.sun.star.lang.XMultiServiceFactory; import com.sun.star.uno.UnoRuntime; import com.sun.star.uno.XInterface; import java.io.PrintWriter; import java.util.ArrayList; import lib.TestCase; import lib.TestEnvironment; import lib.TestParameters; /** * Test for object which is represented by service * <code>com.sun.star.io.DataInputStream</code>. * <ul> * <li> <code>com::sun::star::io::XInputStream</code></li> * <li> <code>com::sun::star::io::XDataInputStream</code></li> * <li> <code>com::sun::star::io::XConnectable</code></li> * <li> <code>com::sun::star::io::XActiveDataSink</code></li> * </ul> * @see com.sun.star.io.DataInputStream * @see com.sun.star.io.XInputStream * @see com.sun.star.io.XDataInputStream * @see com.sun.star.io.XConnectable * @see com.sun.star.io.XActiveDataSink * @see ifc.io._XInputStream * @see ifc.io._XDataInputStream * @see ifc.io._XConnectable * @see ifc.io._XActiveDataSink */ public class DataInputStream extends TestCase { /** * Creates a TestEnvironment for the interfaces to be tested. * Creates <code>com.sun.star.io.DataInputStream</code> object, * connects it to <code>com.sun.star.io.DataOutputStream</code> * through <code>com.sun.star.io.Pipe</code>. All of possible data * types are written into <code>DataOutputStream</code>. * Object relations created : * <ul> * <li> <code>'StreamData'</code> for * {@link ifc.io._XDataInputStream}(the data that should be written into * the stream) </li> * <li> <code>'ByteData'</code> for * {@link ifc.io._XInputStream}(the data that should be written into * the stream) </li> * <li> <code>'StreamWriter'</code> for * {@link ifc.io._XDataInputStream} * {@link ifc.io._XInputStream}(a stream to write data to) </li> * <li> <code>'Connectable'</code> for * {@link ifc.io._XConnectable}(another object that can be connected) </li> * <li> <code>'InputStream'</code> for * {@link ifc.io._XActiveDataSink}(an input stream to set and get) </li> * </ul> */ @Override protected TestEnvironment createTestEnvironment(TestParameters Param, PrintWriter log) throws Exception { Object oInterface = null; XMultiServiceFactory xMSF = Param.getMSF(); oInterface = xMSF.createInstance("com.sun.star.io.DataInputStream"); XInterface oObj = (XInterface) oInterface; // creating and connecting DataOutputStream to the // DataInputStream created through the Pipe XActiveDataSink xDataSink = UnoRuntime.queryInterface(XActiveDataSink.class, oObj); XInterface oPipe = (XInterface) xMSF.createInstance("com.sun.star.io.Pipe"); XInputStream xPipeInput = UnoRuntime.queryInterface(XInputStream.class, oPipe); XOutputStream xPipeOutput = UnoRuntime.queryInterface(XOutputStream.class, oPipe); XInterface oDataOutput = (XInterface) xMSF.createInstance("com.sun.star.io.DataOutputStream"); XDataOutputStream xDataOutput = UnoRuntime.queryInterface(XDataOutputStream.class, oDataOutput) ; XActiveDataSource xDataSource = UnoRuntime.queryInterface(XActiveDataSource.class, oDataOutput) ; xDataSource.setOutputStream(xPipeOutput) ; xDataSink.setInputStream(xPipeInput) ; // all data types for writing to an XDataInputStream ArrayList<Object> data = new ArrayList<Object>() ; data.add(Boolean.TRUE) ; data.add(Byte.valueOf((byte)123)) ; data.add(new Character((char)1234)) ; data.add(Short.valueOf((short)1234)) ; data.add(Integer.valueOf(123456)) ; data.add(new Float(1.234)) ; data.add(new Double(1.23456)) ; data.add("DataInputStream") ; // information for writing to the pipe byte[] byteData = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 } ; // creating a connectable object for XConnectable interface XInterface xConnect = (XInterface)xMSF.createInstance( "com.sun.star.io.DataInputStream") ; // creating an input stream to set in XActiveDataSink XInterface oDataInput = (XInterface) xMSF.createInstance( "com.sun.star.io.Pipe" ); log.println("creating a new environment for object"); TestEnvironment tEnv = new TestEnvironment( oObj ); // adding sequence of data that must be read // by XDataInputStream interface methods tEnv.addObjRelation("StreamData", data) ; // add a writer tEnv.addObjRelation("StreamWriter", xDataOutput); // add a connectable tEnv.addObjRelation("Connectable", xConnect); // add an inputStream tEnv.addObjRelation("InputStream", oDataInput); tEnv.addObjRelation("ByteData", byteData); return tEnv; } // finish method getTestEnvironment }
gpl-3.0
walster001/Essentials
EssentialsAntiBuild/src/com/earth2me/essentials/antibuild/EssentialsAntiBuild.java
1783
package com.earth2me.essentials.antibuild; import java.util.EnumMap; import java.util.List; import java.util.Map; import org.bukkit.plugin.Plugin; import org.bukkit.plugin.PluginManager; import org.bukkit.plugin.java.JavaPlugin; public class EssentialsAntiBuild extends JavaPlugin implements IAntiBuild { private final transient Map<AntiBuildConfig, Boolean> settingsBoolean = new EnumMap<AntiBuildConfig, Boolean>(AntiBuildConfig.class); private final transient Map<AntiBuildConfig, List<Integer>> settingsList = new EnumMap<AntiBuildConfig, List<Integer>>(AntiBuildConfig.class); private transient EssentialsConnect ess = null; @Override public void onEnable() { final PluginManager pm = this.getServer().getPluginManager(); final Plugin essPlugin = pm.getPlugin("Essentials"); if (essPlugin == null || !essPlugin.isEnabled()) { return; } ess = new EssentialsConnect(essPlugin, this); final EssentialsAntiBuildListener blockListener = new EssentialsAntiBuildListener(this); pm.registerEvents(blockListener, this); } @Override public boolean checkProtectionItems(final AntiBuildConfig list, final int id) { final List<Integer> itemList = settingsList.get(list); return itemList != null && !itemList.isEmpty() && itemList.contains(id); } @Override public EssentialsConnect getEssentialsConnect() { return ess; } @Override public Map<AntiBuildConfig, Boolean> getSettingsBoolean() { return settingsBoolean; } @Override public Map<AntiBuildConfig, List<Integer>> getSettingsList() { return settingsList; } @Override public boolean getSettingBool(final AntiBuildConfig protectConfig) { final Boolean bool = settingsBoolean.get(protectConfig); return bool == null ? protectConfig.getDefaultValueBoolean() : bool; } }
gpl-3.0
aloubyansky/wildfly-core
testsuite/manualmode/src/test/java/org/jboss/as/test/manualmode/secman/PermissionsDeploymentTestCase.java
7442
/* * JBoss, Home of Professional Open Source. * Copyright 2012, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. * */ package org.jboss.as.test.manualmode.secman; import org.jboss.as.controller.PathAddress; import org.jboss.as.controller.client.ModelControllerClient; import org.jboss.as.controller.descriptions.ModelDescriptionConstants; import org.jboss.as.test.manualmode.deployment.AbstractDeploymentScannerBasedTestCase; import org.jboss.as.test.shared.TestSuiteEnvironment; import org.jboss.as.test.shared.TimeoutUtil; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.asset.StringAsset; import org.jboss.shrinkwrap.api.exporter.ZipExporter; import org.jboss.shrinkwrap.api.spec.JavaArchive; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import org.junit.runner.RunWith; import org.wildfly.core.testrunner.ServerControl; import org.wildfly.core.testrunner.ServerController; import org.wildfly.core.testrunner.WildflyTestRunner; import javax.inject.Inject; import java.io.File; /** * Tests the processing of {@code permissions.xml} in deployments * * @author Jaikiran Pai */ @RunWith(WildflyTestRunner.class) @ServerControl(manual = true) public class PermissionsDeploymentTestCase extends AbstractDeploymentScannerBasedTestCase { private static final String SYS_PROP_SERVER_BOOTSTRAP_MAX_THREADS = "-Dorg.jboss.server.bootstrap.maxThreads=1"; @Rule public TemporaryFolder tempDir = new TemporaryFolder(); @Inject private ServerController container; private ModelControllerClient modelControllerClient; @Before public void before() throws Exception { modelControllerClient = TestSuiteEnvironment.getModelControllerClient(); } @After public void after() throws Exception { modelControllerClient.close(); } @Override protected File getDeployDir() { return this.tempDir.getRoot(); } /** * Tests that when the server is booted with {@code org.jboss.server.bootstrap.maxThreads} system property * set (to whatever value), the deployment unit processors relevant for dealing with processing of {@code permissions.xml}, * in deployments, do run and process the deployment * <p> * NOTE: This test just tests that the deployment unit processor(s) process the deployment unit for the {@code permissions.xml} * and it's not in the scope of this test to verify that the permissions configured in that file are indeed applied correctly * to the deployment unit * * @throws Exception * @see <a href="https://issues.jboss.org/browse/WFLY-6657">WFLY-6657</a> */ @Test public void testWithConfiguredMaxBootThreads() throws Exception { // Test-runner's ServerController/Server uses prop jvm.args to control what args are passed // to the server process VM. So, we add the system property controlling the max boot threads, // here final String existingJvmArgs = System.getProperty("jvm.args"); if (existingJvmArgs == null) { System.setProperty("jvm.args", SYS_PROP_SERVER_BOOTSTRAP_MAX_THREADS); } else { System.setProperty("jvm.args", existingJvmArgs + " " + SYS_PROP_SERVER_BOOTSTRAP_MAX_THREADS); } // start the container container.start(); try { addDeploymentScanner(modelControllerClient,1000, false, true); this.testInvalidPermissionsXmlDeployment("test-permissions-xml-with-configured-max-boot-threads.jar"); } finally { removeDeploymentScanner(modelControllerClient); container.stop(); if (existingJvmArgs == null) { System.clearProperty("jvm.args"); } else { System.setProperty("jvm.args", existingJvmArgs); } } } /** * Tests that when the server is booted *without* the {@code org.jboss.server.bootstrap.maxThreads} system property * set, the deployment unit processors relevant for dealing with processing of {@code permissions.xml}, * in deployments, do run and process the deployment * <p> * NOTE: This test just tests that the deployment unit processor(s) process the deployment unit for the {@code permissions.xml} * and it's not in the scope of this test to verify that the permissions configured in that file are indeed applied correctly * to the deployment unit * * @throws Exception * @see <a href="https://issues.jboss.org/browse/WFLY-6657">WFLY-6657</a> */ @Test public void testWithoutConfiguredMaxBootThreads() throws Exception { container.start(); try { addDeploymentScanner(modelControllerClient,1000, false, true); this.testInvalidPermissionsXmlDeployment("test-permissions-xml-without-max-boot-threads.jar"); } finally { removeDeploymentScanner(modelControllerClient); container.stop(); } } private void testInvalidPermissionsXmlDeployment(final String deploymentName) throws Exception { final JavaArchive jar = ShrinkWrap.create(JavaArchive.class); // add an empty (a.k.a invalid content) in permissions.xml jar.addAsManifestResource(new StringAsset(""), "permissions.xml"); // "deploy" it by placing it in the deployment directory jar.as(ZipExporter.class).exportTo(new File(getDeployDir(), deploymentName)); final PathAddress deploymentPathAddr = PathAddress.pathAddress(ModelDescriptionConstants.DEPLOYMENT, deploymentName); // wait for the deployment to be picked up and completed (either with success or failure) waitForDeploymentToFinish(deploymentPathAddr); // the deployment is expected to fail due to a parsing error in the permissions.xml Assert.assertEquals("Deployment was expected to fail", "FAILED", deploymentState(modelControllerClient, deploymentPathAddr)); } private void waitForDeploymentToFinish(final PathAddress deploymentPathAddr) throws Exception { // Wait until deployed ... long timeout = System.currentTimeMillis() + TimeoutUtil.adjust(30000); while (!exists(modelControllerClient, deploymentPathAddr) && System.currentTimeMillis() < timeout) { Thread.sleep(100); } Assert.assertTrue(exists(modelControllerClient, deploymentPathAddr)); } }
lgpl-2.1
lucee/unoffical-Lucee-no-jre
source/java/core/src/lucee/runtime/type/comparator/SortRegisterComparator.java
2517
/** * * Copyright (c) 2014, the Railo Company Ltd. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library. If not, see <http://www.gnu.org/licenses/>. * **/ package lucee.runtime.type.comparator; import java.util.Comparator; import lucee.commons.lang.ComparatorUtil; import lucee.runtime.PageContext; import lucee.runtime.engine.ThreadLocalPageContext; import lucee.runtime.exp.PageException; import lucee.runtime.op.Caster; /** * Implementation of a Comparator, compares to Softregister Objects */ public final class SortRegisterComparator implements ExceptionComparator { private boolean isAsc; private PageException pageException=null; private boolean ignoreCase; private final Comparator comparator; /** * constructor of the class * @param isAsc is ascending or descending * @param ignoreCase do ignore case */ public SortRegisterComparator(PageContext pc,boolean isAsc, boolean ignoreCase, boolean localeSensitive) { this.isAsc=isAsc; this.ignoreCase=ignoreCase; comparator = ComparatorUtil.toComparator( ignoreCase?ComparatorUtil.SORT_TYPE_TEXT_NO_CASE:ComparatorUtil.SORT_TYPE_TEXT , isAsc, localeSensitive?ThreadLocalPageContext.getLocale(pc):null, null); } /** * @return Returns the expressionException. */ public PageException getPageException() { return pageException; } @Override public int compare(Object oLeft, Object oRight) { try { if(pageException!=null) return 0; else if(isAsc) return compareObjects(oLeft, oRight); else return compareObjects(oRight, oLeft); } catch (PageException e) { pageException=e; return 0; } } private int compareObjects(Object oLeft, Object oRight) throws PageException { String strLeft=Caster.toString(((SortRegister)oLeft).getValue()); String strRight=Caster.toString(((SortRegister)oRight).getValue()); return comparator.compare(strLeft, strRight); } }
lgpl-2.1
jomarko/kie-wb-common
kie-wb-common-services/kie-wb-common-compiler/kie-wb-common-compiler-service/src/test/java/org/kie/workbench/common/services/backend/compiler/BaseCompilerTest.java
2464
/* * 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.services.backend.compiler; import java.io.File; import java.io.Serializable; import org.junit.AfterClass; import org.junit.BeforeClass; import org.kie.workbench.common.services.backend.compiler.impl.WorkspaceCompilationInfo; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.uberfire.java.nio.file.Files; import org.uberfire.java.nio.file.Path; import org.uberfire.java.nio.file.Paths; public class BaseCompilerTest implements Serializable { protected static Path tmpRoot; protected String mavenRepoPath; protected static Logger logger = LoggerFactory.getLogger(BaseCompilerTest.class); protected String alternateSettingsAbsPath; protected WorkspaceCompilationInfo info; protected AFCompiler compiler; @BeforeClass public static void setup() { System.setProperty("org.uberfire.nio.git.daemon.enabled", "false"); System.setProperty("org.uberfire.nio.git.ssh.enabled", "false"); } public BaseCompilerTest(String prjName) { try { mavenRepoPath = TestUtilMaven.getMavenRepo(); tmpRoot = Files.createTempDirectory("repo"); alternateSettingsAbsPath = new File("src/test/settings.xml").getAbsolutePath(); Path tmp = Files.createDirectories(Paths.get(tmpRoot.toString(), "dummy")); TestUtil.copyTree(Paths.get(prjName), tmp); info = new WorkspaceCompilationInfo(Paths.get(tmp.toUri())); } catch (Exception e) { logger.error(e.getMessage()); } } @AfterClass public static void tearDown() { System.clearProperty("org.uberfire.nio.git.daemon.enabled"); System.clearProperty("org.uberfire.nio.git.ssh.enabled"); if (tmpRoot != null) { TestUtil.rm(tmpRoot.toFile()); } } }
apache-2.0
Subasinghe/ode
bpel-ql/src/main/java/org/apache/ode/ql/tree/nodes/Equality.java
1136
/* * 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.ode.ql.tree.nodes; public class Equality extends IdentifierToValueCMP { private static final long serialVersionUID = 8151616227509392901L; /** * @param identifier * @param value */ public Equality(Identifier identifier, Value value) { super(identifier, value); } }
apache-2.0
romankagan/DDBWorkbench
platform/analysis-impl/src/com/intellij/packageDependencies/ForwardDependenciesBuilder.java
6335
/* * Copyright 2000-2009 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.packageDependencies; import com.intellij.analysis.AnalysisScope; import com.intellij.analysis.AnalysisScopeBundle; import com.intellij.lang.injection.InjectedLanguageManager; import com.intellij.openapi.progress.ProcessCanceledException; import com.intellij.openapi.progress.ProgressIndicator; import com.intellij.openapi.progress.ProgressManager; import com.intellij.openapi.project.Project; import com.intellij.openapi.roots.ProjectFileIndex; import com.intellij.openapi.roots.ProjectRootManager; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.*; import org.jetbrains.annotations.NotNull; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; public class ForwardDependenciesBuilder extends DependenciesBuilder { private final Map<PsiFile, Set<PsiFile>> myDirectDependencies = new HashMap<PsiFile, Set<PsiFile>>(); public ForwardDependenciesBuilder(@NotNull Project project, @NotNull AnalysisScope scope) { super(project, scope); } public ForwardDependenciesBuilder(final Project project, final AnalysisScope scope, final AnalysisScope scopeOfInterest) { super(project, scope, scopeOfInterest); } public ForwardDependenciesBuilder(final Project project, final AnalysisScope scope, final int transitive) { super(project, scope); myTransitive = transitive; } @Override public String getRootNodeNameInUsageView(){ return AnalysisScopeBundle.message("forward.dependencies.usage.view.root.node.text"); } @Override public String getInitialUsagesPosition(){ return AnalysisScopeBundle.message("forward.dependencies.usage.view.initial.text"); } @Override public boolean isBackward(){ return false; } @Override public void analyze() { final PsiManager psiManager = PsiManager.getInstance(getProject()); psiManager.startBatchFilesProcessingMode(); final ProjectFileIndex fileIndex = ProjectRootManager.getInstance(getProject()).getFileIndex(); try { getScope().accept(new PsiRecursiveElementVisitor() { @Override public void visitFile(final PsiFile file) { visit(file, fileIndex, psiManager, 0); } }); } finally { psiManager.finishBatchFilesProcessingMode(); } } private void visit(final PsiFile file, final ProjectFileIndex fileIndex, final PsiManager psiManager, int depth) { final FileViewProvider viewProvider = file.getViewProvider(); if (viewProvider.getBaseLanguage() != file.getLanguage()) return; if (getScopeOfInterest() != null && !getScopeOfInterest().contains(file)) return; ProgressIndicator indicator = ProgressManager.getInstance().getProgressIndicator(); final VirtualFile virtualFile = file.getVirtualFile(); if (indicator != null) { if (indicator.isCanceled()) { throw new ProcessCanceledException(); } indicator.setText(AnalysisScopeBundle.message("package.dependencies.progress.text")); if (virtualFile != null) { indicator.setText2(getRelativeToProjectPath(virtualFile)); } if ( myTotalFileCount > 0) { indicator.setFraction(((double)++ myFileCount) / myTotalFileCount); } } final boolean isInLibrary = virtualFile == null || fileIndex.isInLibrarySource(virtualFile) || fileIndex.isInLibraryClasses(virtualFile); final Set<PsiFile> collectedDeps = new HashSet<PsiFile>(); final HashSet<PsiFile> processed = new HashSet<PsiFile>(); collectedDeps.add(file); do { if (depth++ > getTransitiveBorder()) return; for (PsiFile psiFile : new HashSet<PsiFile>(collectedDeps)) { final VirtualFile vFile = psiFile.getVirtualFile(); if (vFile != null) { if (indicator != null) { indicator.setText2(getRelativeToProjectPath(vFile)); } if (!isInLibrary && (fileIndex.isInLibraryClasses(vFile) || fileIndex.isInLibrarySource(vFile))) { processed.add(psiFile); } } final Set<PsiFile> found = new HashSet<PsiFile>(); if (!processed.contains(psiFile)) { processed.add(psiFile); analyzeFileDependencies(psiFile, new DependencyProcessor() { @Override public void process(PsiElement place, PsiElement dependency) { PsiFile dependencyFile = dependency.getContainingFile(); if (dependencyFile != null) { if (viewProvider == dependencyFile.getViewProvider()) return; if (dependencyFile.isPhysical()) { final VirtualFile virtualFile = dependencyFile.getVirtualFile(); if (virtualFile != null && (fileIndex.isInContent(virtualFile) || fileIndex.isInLibraryClasses(virtualFile) || fileIndex.isInLibrarySource(virtualFile))) { found.add(dependencyFile); } } } } }); Set<PsiFile> deps = getDependencies().get(file); if (deps == null) { deps = new HashSet<PsiFile>(); getDependencies().put(file, deps); } deps.addAll(found); getDirectDependencies().put(psiFile, new HashSet<PsiFile>(found)); collectedDeps.addAll(found); psiManager.dropResolveCaches(); InjectedLanguageManager.getInstance(file.getProject()).dropFileCaches(file); } } collectedDeps.removeAll(processed); } while (isTransitive() && !collectedDeps.isEmpty()); } @Override public Map<PsiFile, Set<PsiFile>> getDirectDependencies() { return myDirectDependencies; } }
apache-2.0
ruhan1/pnc
common/src/main/java/org/jboss/pnc/common/util/ResultWrapper.java
1569
/** * JBoss, Home of Professional Open Source. * Copyright 2014 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jboss.pnc.common.util; /** * Simple wrapper class which contains a result and an exception. * This can be useful for example when performing asynchronous operations * which do not immediately return, but could throw an exception. * * @param <R> The result of the operation * @param <E> The exception (if any) thrown during the operation. */ public class ResultWrapper<R, E extends Exception> { private E exception; private R result; public ResultWrapper(R result) { this.result = result; } public ResultWrapper(R result, E exception) { this.result = result; this.exception = exception; } /** Returns null if no exception was thrown */ /** * @return */ public E getException() { return exception; } public R getResult() { return result; } }
apache-2.0
wmedvede/uberfire-extensions
uberfire-widgets/uberfire-widgets-commons/src/main/java/org/uberfire/ext/widgets/common/client/colorpicker/dialog/DialogClosedHandler.java
849
/* * Copyright 2015 JBoss by Red Hat. * * 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.uberfire.ext.widgets.common.client.colorpicker.dialog; import com.google.gwt.event.shared.EventHandler; public interface DialogClosedHandler extends EventHandler { void dialogClosed(DialogClosedEvent event); }
apache-2.0
nwnpallewela/devstudio-tooling-esb
plugins/org.wso2.developerstudio.eclipse.gmf.esb.edit/src/org/wso2/developerstudio/eclipse/gmf/esb/provider/LogMediatorInputConnectorItemProvider.java
2890
/** * <copyright> * </copyright> * * $Id$ */ package org.wso2.developerstudio.eclipse.gmf.esb.provider; import java.util.Collection; import java.util.List; import org.eclipse.emf.common.notify.AdapterFactory; import org.eclipse.emf.common.notify.Notification; import org.eclipse.emf.edit.provider.IEditingDomainItemProvider; import org.eclipse.emf.edit.provider.IItemLabelProvider; import org.eclipse.emf.edit.provider.IItemPropertyDescriptor; import org.eclipse.emf.edit.provider.IItemPropertySource; import org.eclipse.emf.edit.provider.IStructuredItemContentProvider; import org.eclipse.emf.edit.provider.ITreeItemContentProvider; /** * This is the item provider adapter for a {@link org.wso2.developerstudio.eclipse.gmf.esb.LogMediatorInputConnector} object. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public class LogMediatorInputConnectorItemProvider extends InputConnectorItemProvider { /** * This constructs an instance from a factory and a notifier. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public LogMediatorInputConnectorItemProvider(AdapterFactory adapterFactory) { super(adapterFactory); } /** * This returns the property descriptors for the adapted class. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public List<IItemPropertyDescriptor> getPropertyDescriptors(Object object) { if (itemPropertyDescriptors == null) { super.getPropertyDescriptors(object); } return itemPropertyDescriptors; } /** * This returns LogMediatorInputConnector.gif. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public Object getImage(Object object) { return overlayImage(object, getResourceLocator().getImage("full/obj16/LogMediatorInputConnector")); } /** * This returns the label text for the adapted class. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public String getText(Object object) { return getString("_UI_LogMediatorInputConnector_type"); } /** * This handles model notifications by calling {@link #updateChildren} to update any cached * children and by creating a viewer notification, which it passes to {@link #fireNotifyChanged}. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void notifyChanged(Notification notification) { updateChildren(notification); super.notifyChanged(notification); } /** * This adds {@link org.eclipse.emf.edit.command.CommandParameter}s describing the children * that can be created under this object. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override protected void collectNewChildDescriptors(Collection<Object> newChildDescriptors, Object object) { super.collectNewChildDescriptors(newChildDescriptors, object); } }
apache-2.0
steveloughran/hadoop
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-common/src/main/java/org/apache/hadoop/yarn/server/api/protocolrecords/impl/pb/GetTimelineCollectorContextRequestPBImpl.java
3988
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.yarn.server.api.protocolrecords.impl.pb; import org.apache.hadoop.thirdparty.protobuf.TextFormat; import org.apache.hadoop.yarn.api.records.ApplicationId; import org.apache.hadoop.yarn.api.records.impl.pb.ApplicationIdPBImpl; import org.apache.hadoop.yarn.proto.YarnProtos; import org.apache.hadoop.yarn.proto.YarnServerCommonServiceProtos.GetTimelineCollectorContextRequestProtoOrBuilder; import org.apache.hadoop.yarn.proto.YarnServerCommonServiceProtos.GetTimelineCollectorContextRequestProto; import org.apache.hadoop.yarn.server.api.protocolrecords.GetTimelineCollectorContextRequest; public class GetTimelineCollectorContextRequestPBImpl extends GetTimelineCollectorContextRequest { private GetTimelineCollectorContextRequestProto proto = GetTimelineCollectorContextRequestProto.getDefaultInstance(); private GetTimelineCollectorContextRequestProto.Builder builder = null; private boolean viaProto = false; private ApplicationId appId = null; public GetTimelineCollectorContextRequestPBImpl() { builder = GetTimelineCollectorContextRequestProto.newBuilder(); } public GetTimelineCollectorContextRequestPBImpl( GetTimelineCollectorContextRequestProto proto) { this.proto = proto; viaProto = true; } public GetTimelineCollectorContextRequestProto getProto() { mergeLocalToProto(); proto = viaProto ? proto : builder.build(); viaProto = true; return proto; } @Override public int hashCode() { return getProto().hashCode(); } @Override public boolean equals(Object other) { if (other == null) { return false; } if (other.getClass().isAssignableFrom(this.getClass())) { return this.getProto().equals(this.getClass().cast(other).getProto()); } return false; } @Override public String toString() { return TextFormat.shortDebugString(getProto()); } private void mergeLocalToBuilder() { if (appId != null) { builder.setAppId(convertToProtoFormat(this.appId)); } } private void mergeLocalToProto() { if (viaProto) { maybeInitBuilder(); } mergeLocalToBuilder(); proto = builder.build(); viaProto = true; } private void maybeInitBuilder() { if (viaProto || builder == null) { builder = GetTimelineCollectorContextRequestProto.newBuilder(proto); } viaProto = false; } @Override public ApplicationId getApplicationId() { if (this.appId != null) { return this.appId; } GetTimelineCollectorContextRequestProtoOrBuilder p = viaProto ? proto : builder; if (!p.hasAppId()) { return null; } this.appId = convertFromProtoFormat(p.getAppId()); return this.appId; } @Override public void setApplicationId(ApplicationId id) { maybeInitBuilder(); if (id == null) { builder.clearAppId(); } this.appId = id; } private ApplicationIdPBImpl convertFromProtoFormat( YarnProtos.ApplicationIdProto p) { return new ApplicationIdPBImpl(p); } private YarnProtos.ApplicationIdProto convertToProtoFormat(ApplicationId t) { return ((ApplicationIdPBImpl)t).getProto(); } }
apache-2.0
kdwink/intellij-community
platform/lang-impl/src/com/intellij/codeInsight/template/impl/TemplateImplUtil.java
1752
/* * Copyright 2000-2015 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.codeInsight.template.impl; import com.intellij.psi.tree.IElementType; import com.intellij.util.containers.hash.LinkedHashMap; /** * @author Maxim.Mossienko */ public class TemplateImplUtil { public static LinkedHashMap<String, Variable> parseVariables(CharSequence text) { LinkedHashMap<String, Variable> variables = new LinkedHashMap<String, Variable>(); TemplateTextLexer lexer = new TemplateTextLexer(); lexer.start(text); while (true) { IElementType tokenType = lexer.getTokenType(); if (tokenType == null) break; int start = lexer.getTokenStart(); int end = lexer.getTokenEnd(); String token = text.subSequence(start, end).toString(); if (tokenType == TemplateTokenType.VARIABLE) { String name = token.substring(1, token.length() - 1); if (!variables.containsKey(name)) { variables.put(name, new Variable(name, "", "", true)); } } lexer.advance(); } return variables; } public static boolean isValidVariableName(String varName) { return parseVariables("$" + varName + "$").containsKey(varName); } }
apache-2.0
strapdata/elassandra
server/src/test/java/org/elasticsearch/common/io/stream/StreamTests.java
16395
/* * Licensed to Elasticsearch under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch licenses this file to you under * the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.elasticsearch.common.io.stream; import org.apache.lucene.util.BytesRef; import org.elasticsearch.common.CheckedBiConsumer; import org.elasticsearch.common.CheckedFunction; import org.elasticsearch.common.bytes.BytesArray; import org.elasticsearch.common.bytes.BytesReference; import org.elasticsearch.common.collect.Tuple; import org.elasticsearch.test.ESTestCase; import java.io.ByteArrayInputStream; import java.io.EOFException; import java.io.IOException; import java.time.Instant; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Objects; import java.util.Set; import java.util.function.Supplier; import java.util.stream.Collectors; import java.util.stream.IntStream; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.hasToString; import static org.hamcrest.Matchers.iterableWithSize; public class StreamTests extends ESTestCase { public void testBooleanSerialization() throws IOException { final BytesStreamOutput output = new BytesStreamOutput(); output.writeBoolean(false); output.writeBoolean(true); final BytesReference bytesReference = output.bytes(); final BytesRef bytesRef = bytesReference.toBytesRef(); assertThat(bytesRef.length, equalTo(2)); final byte[] bytes = bytesRef.bytes; assertThat(bytes[0], equalTo((byte) 0)); assertThat(bytes[1], equalTo((byte) 1)); final StreamInput input = bytesReference.streamInput(); assertFalse(input.readBoolean()); assertTrue(input.readBoolean()); final Set<Byte> set = IntStream.range(Byte.MIN_VALUE, Byte.MAX_VALUE).mapToObj(v -> (byte) v).collect(Collectors.toSet()); set.remove((byte) 0); set.remove((byte) 1); final byte[] corruptBytes = new byte[]{randomFrom(set)}; final BytesReference corrupt = new BytesArray(corruptBytes); final IllegalStateException e = expectThrows(IllegalStateException.class, () -> corrupt.streamInput().readBoolean()); final String message = String.format(Locale.ROOT, "unexpected byte [0x%02x]", corruptBytes[0]); assertThat(e, hasToString(containsString(message))); } public void testOptionalBooleanSerialization() throws IOException { final BytesStreamOutput output = new BytesStreamOutput(); output.writeOptionalBoolean(false); output.writeOptionalBoolean(true); output.writeOptionalBoolean(null); final BytesReference bytesReference = output.bytes(); final BytesRef bytesRef = bytesReference.toBytesRef(); assertThat(bytesRef.length, equalTo(3)); final byte[] bytes = bytesRef.bytes; assertThat(bytes[0], equalTo((byte) 0)); assertThat(bytes[1], equalTo((byte) 1)); assertThat(bytes[2], equalTo((byte) 2)); final StreamInput input = bytesReference.streamInput(); final Boolean maybeFalse = input.readOptionalBoolean(); assertNotNull(maybeFalse); assertFalse(maybeFalse); final Boolean maybeTrue = input.readOptionalBoolean(); assertNotNull(maybeTrue); assertTrue(maybeTrue); assertNull(input.readOptionalBoolean()); final Set<Byte> set = IntStream.range(Byte.MIN_VALUE, Byte.MAX_VALUE).mapToObj(v -> (byte) v).collect(Collectors.toSet()); set.remove((byte) 0); set.remove((byte) 1); set.remove((byte) 2); final byte[] corruptBytes = new byte[]{randomFrom(set)}; final BytesReference corrupt = new BytesArray(corruptBytes); final IllegalStateException e = expectThrows(IllegalStateException.class, () -> corrupt.streamInput().readOptionalBoolean()); final String message = String.format(Locale.ROOT, "unexpected byte [0x%02x]", corruptBytes[0]); assertThat(e, hasToString(containsString(message))); } public void testRandomVLongSerialization() throws IOException { for (int i = 0; i < 1024; i++) { long write = randomLong(); BytesStreamOutput out = new BytesStreamOutput(); out.writeZLong(write); long read = out.bytes().streamInput().readZLong(); assertEquals(write, read); } } public void testSpecificVLongSerialization() throws IOException { List<Tuple<Long, byte[]>> values = Arrays.asList( new Tuple<>(0L, new byte[]{0}), new Tuple<>(-1L, new byte[]{1}), new Tuple<>(1L, new byte[]{2}), new Tuple<>(-2L, new byte[]{3}), new Tuple<>(2L, new byte[]{4}), new Tuple<>(Long.MIN_VALUE, new byte[]{-1, -1, -1, -1, -1, -1, -1, -1, -1, 1}), new Tuple<>(Long.MAX_VALUE, new byte[]{-2, -1, -1, -1, -1, -1, -1, -1, -1, 1}) ); for (Tuple<Long, byte[]> value : values) { BytesStreamOutput out = new BytesStreamOutput(); out.writeZLong(value.v1()); assertArrayEquals(Long.toString(value.v1()), value.v2(), BytesReference.toBytes(out.bytes())); BytesReference bytes = new BytesArray(value.v2()); assertEquals(Arrays.toString(value.v2()), (long) value.v1(), bytes.streamInput().readZLong()); } } public void testLinkedHashMap() throws IOException { int size = randomIntBetween(1, 1024); boolean accessOrder = randomBoolean(); List<Tuple<String, Integer>> list = new ArrayList<>(size); LinkedHashMap<String, Integer> write = new LinkedHashMap<>(size, 0.75f, accessOrder); for (int i = 0; i < size; i++) { int value = randomInt(); list.add(new Tuple<>(Integer.toString(i), value)); write.put(Integer.toString(i), value); } if (accessOrder) { // randomize access order Collections.shuffle(list, random()); for (Tuple<String, Integer> entry : list) { // touch the entries to set the access order write.get(entry.v1()); } } BytesStreamOutput out = new BytesStreamOutput(); out.writeGenericValue(write); LinkedHashMap<String, Integer> read = (LinkedHashMap<String, Integer>) out.bytes().streamInput().readGenericValue(); assertEquals(size, read.size()); int index = 0; for (Map.Entry<String, Integer> entry : read.entrySet()) { assertEquals(list.get(index).v1(), entry.getKey()); assertEquals(list.get(index).v2(), entry.getValue()); index++; } } public void testFilterStreamInputDelegatesAvailable() throws IOException { final int length = randomIntBetween(1, 1024); StreamInput delegate = StreamInput.wrap(new byte[length]); FilterStreamInput filterInputStream = new FilterStreamInput(delegate) { }; assertEquals(filterInputStream.available(), length); // read some bytes final int bytesToRead = randomIntBetween(1, length); filterInputStream.readBytes(new byte[bytesToRead], 0, bytesToRead); assertEquals(filterInputStream.available(), length - bytesToRead); } public void testInputStreamStreamInputDelegatesAvailable() throws IOException { final int length = randomIntBetween(1, 1024); ByteArrayInputStream is = new ByteArrayInputStream(new byte[length]); InputStreamStreamInput streamInput = new InputStreamStreamInput(is); assertEquals(streamInput.available(), length); // read some bytes final int bytesToRead = randomIntBetween(1, length); streamInput.readBytes(new byte[bytesToRead], 0, bytesToRead); assertEquals(streamInput.available(), length - bytesToRead); } public void testReadArraySize() throws IOException { BytesStreamOutput stream = new BytesStreamOutput(); byte[] array = new byte[randomIntBetween(1, 10)]; for (int i = 0; i < array.length; i++) { array[i] = randomByte(); } stream.writeByteArray(array); InputStreamStreamInput streamInput = new InputStreamStreamInput(StreamInput.wrap(BytesReference.toBytes(stream.bytes())), array .length - 1); expectThrows(EOFException.class, streamInput::readByteArray); streamInput = new InputStreamStreamInput(StreamInput.wrap(BytesReference.toBytes(stream.bytes())), BytesReference.toBytes(stream .bytes()).length); assertArrayEquals(array, streamInput.readByteArray()); } public void testWritableArrays() throws IOException { final String[] strings = generateRandomStringArray(10, 10, false, true); WriteableString[] sourceArray = Arrays.stream(strings).<WriteableString>map(WriteableString::new).toArray(WriteableString[]::new); WriteableString[] targetArray; BytesStreamOutput out = new BytesStreamOutput(); if (randomBoolean()) { if (randomBoolean()) { sourceArray = null; } out.writeOptionalArray(sourceArray); targetArray = out.bytes().streamInput().readOptionalArray(WriteableString::new, WriteableString[]::new); } else { out.writeArray(sourceArray); targetArray = out.bytes().streamInput().readArray(WriteableString::new, WriteableString[]::new); } assertThat(targetArray, equalTo(sourceArray)); } public void testArrays() throws IOException { final String[] strings; final String[] deserialized; Writeable.Writer<String> writer = StreamOutput::writeString; Writeable.Reader<String> reader = StreamInput::readString; BytesStreamOutput out = new BytesStreamOutput(); if (randomBoolean()) { if (randomBoolean()) { strings = null; } else { strings = generateRandomStringArray(10, 10, false, true); } out.writeOptionalArray(writer, strings); deserialized = out.bytes().streamInput().readOptionalArray(reader, String[]::new); } else { strings = generateRandomStringArray(10, 10, false, true); out.writeArray(writer, strings); deserialized = out.bytes().streamInput().readArray(reader, String[]::new); } assertThat(deserialized, equalTo(strings)); } public void testCollection() throws IOException { class FooBar implements Writeable { private final int foo; private final int bar; private FooBar(final int foo, final int bar) { this.foo = foo; this.bar = bar; } private FooBar(final StreamInput in) throws IOException { this.foo = in.readInt(); this.bar = in.readInt(); } @Override public void writeTo(final StreamOutput out) throws IOException { out.writeInt(foo); out.writeInt(bar); } @Override public boolean equals(final Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; final FooBar that = (FooBar) o; return foo == that.foo && bar == that.bar; } @Override public int hashCode() { return Objects.hash(foo, bar); } } runWriteReadCollectionTest( () -> new FooBar(randomInt(), randomInt()), StreamOutput::writeCollection, in -> in.readList(FooBar::new)); } public void testStringCollection() throws IOException { runWriteReadCollectionTest(() -> randomUnicodeOfLength(16), StreamOutput::writeStringCollection, StreamInput::readStringList); } private <T> void runWriteReadCollectionTest( final Supplier<T> supplier, final CheckedBiConsumer<StreamOutput, Collection<T>, IOException> writer, final CheckedFunction<StreamInput, Collection<T>, IOException> reader) throws IOException { final int length = randomIntBetween(0, 10); final Collection<T> collection = new ArrayList<>(length); for (int i = 0; i < length; i++) { collection.add(supplier.get()); } try (BytesStreamOutput out = new BytesStreamOutput()) { writer.accept(out, collection); try (StreamInput in = out.bytes().streamInput()) { assertThat(collection, equalTo(reader.apply(in))); } } } public void testSetOfLongs() throws IOException { final int size = randomIntBetween(0, 6); final Set<Long> sourceSet = new HashSet<>(size); for (int i = 0; i < size; i++) { sourceSet.add(randomLongBetween(i * 1000, (i + 1) * 1000 - 1)); } assertThat(sourceSet, iterableWithSize(size)); final BytesStreamOutput out = new BytesStreamOutput(); out.writeCollection(sourceSet, StreamOutput::writeLong); final Set<Long> targetSet = out.bytes().streamInput().readSet(StreamInput::readLong); assertThat(targetSet, equalTo(sourceSet)); } public void testInstantSerialization() throws IOException { final Instant instant = Instant.now(); try (BytesStreamOutput out = new BytesStreamOutput()) { out.writeInstant(instant); try (StreamInput in = out.bytes().streamInput()) { final Instant serialized = in.readInstant(); assertEquals(instant, serialized); } } } public void testOptionalInstantSerialization() throws IOException { final Instant instant = Instant.now(); try (BytesStreamOutput out = new BytesStreamOutput()) { out.writeOptionalInstant(instant); try (StreamInput in = out.bytes().streamInput()) { final Instant serialized = in.readOptionalInstant(); assertEquals(instant, serialized); } } final Instant missing = null; try (BytesStreamOutput out = new BytesStreamOutput()) { out.writeOptionalInstant(missing); try (StreamInput in = out.bytes().streamInput()) { final Instant serialized = in.readOptionalInstant(); assertEquals(missing, serialized); } } } static final class WriteableString implements Writeable { final String string; WriteableString(String string) { this.string = string; } WriteableString(StreamInput in) throws IOException { this(in.readString()); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } WriteableString that = (WriteableString) o; return string.equals(that.string); } @Override public int hashCode() { return string.hashCode(); } @Override public void writeTo(StreamOutput out) throws IOException { out.writeString(string); } } }
apache-2.0
bbrouwer/spring-boot
spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/session/RedisSessionConfiguration.java
2669
/* * Copyright 2012-2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.boot.autoconfigure.session; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.condition.ConditionalOnBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.context.annotation.Conditional; import org.springframework.context.annotation.Configuration; import org.springframework.data.redis.connection.RedisConnectionFactory; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.session.SessionRepository; import org.springframework.session.data.redis.RedisOperationsSessionRepository; import org.springframework.session.data.redis.config.annotation.web.http.RedisHttpSessionConfiguration; /** * Redis backed session configuration. * * @author Andy Wilkinson * @author Tommy Ludwig * @author Eddú Meléndez * @author Stephane Nicoll * @author Vedran Pavic */ @Configuration @ConditionalOnClass({ RedisTemplate.class, RedisOperationsSessionRepository.class }) @ConditionalOnMissingBean(SessionRepository.class) @ConditionalOnBean(RedisConnectionFactory.class) @Conditional(SessionCondition.class) @EnableConfigurationProperties(RedisSessionProperties.class) class RedisSessionConfiguration { @Configuration public static class SpringBootRedisHttpSessionConfiguration extends RedisHttpSessionConfiguration { private SessionProperties sessionProperties; @Autowired public void customize(SessionProperties sessionProperties, RedisSessionProperties redisSessionProperties) { this.sessionProperties = sessionProperties; Integer timeout = this.sessionProperties.getTimeout(); if (timeout != null) { setMaxInactiveIntervalInSeconds(timeout); } setRedisNamespace(redisSessionProperties.getNamespace()); setRedisFlushMode(redisSessionProperties.getFlushMode()); } } }
apache-2.0
fredji97/samza
samza-core/src/main/java/org/apache/samza/operators/spec/StatefulOperatorSpec.java
1163
/* * 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.samza.operators.spec; import java.util.Collection; /** * Spec for stateful operators. */ public interface StatefulOperatorSpec { /** * Get the store descriptors for stores required by this operator. * * @return store descriptors for this operator's stores */ Collection<StoreDescriptor> getStoreDescriptors(); }
apache-2.0
milleruntime/accumulo
core/src/main/java/org/apache/accumulo/core/client/lexicoder/Encoder.java
1095
/* * 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.core.client.lexicoder; /** * An encoder represents a typed object that can be encoded/decoded to/from a byte array. * * @since 1.6.0 */ public interface Encoder<T> { byte[] encode(T object); T decode(byte[] bytes) throws IllegalArgumentException; }
apache-2.0
kutala/activiti-in-action-codes
bpmn20-example/src/test/java/me/kafeitu/activiti/chapter15/leave/LeaveWebServiceBusinessTest.java
2672
package me.kafeitu.activiti.chapter15.leave; import me.kafeitu.activiti.chapter15.leave.ws.LeaveWebService; import org.apache.cxf.interceptor.LoggingInInterceptor; import org.apache.cxf.interceptor.LoggingOutInterceptor; import org.apache.cxf.jaxws.JaxWsProxyFactoryBean; import org.junit.After; import org.junit.Before; import org.junit.Test; import javax.xml.namespace.QName; import javax.xml.ws.Service; import java.net.MalformedURLException; import java.net.URL; import java.text.ParseException; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; /** * 测试请假流程的Webservice基础功能 * @author: Henry Yan */ public class LeaveWebServiceBusinessTest { /** * 发布并启动WebService */ @Before public void before() { LeaveWebserviceUtil.startServer(); } /** * 需要总经理审批 * @throws ParseException */ @Test public void testTrue() throws ParseException, MalformedURLException { /* // CXF方式 JaxWsProxyFactoryBean factory = new JaxWsProxyFactoryBean(); factory.getInInterceptors().add(new LoggingInInterceptor()); factory.getOutInterceptors().add(new LoggingOutInterceptor()); factory.setServiceClass(LeaveWebService.class); factory.setAddress(LeaveWebserviceUtil.WEBSERVICE_URL); LeaveWebService leaveWebService = (LeaveWebService) factory.create();*/ // 标准方式 URL url = new URL(LeaveWebserviceUtil.WEBSERVICE_WSDL_URL); QName qname = new QName(LeaveWebserviceUtil.WEBSERVICE_URI, "LeaveWebService"); Service service = Service.create(url, qname); LeaveWebService leaveWebService = service.getPort(LeaveWebService.class); boolean audit = leaveWebService.generalManagerAudit("2013-01-01 09:00", "2013-01-05 17:30"); assertTrue(audit); } /** * 不需要总经理审批 * @throws ParseException */ @Test public void testFalse() throws ParseException { JaxWsProxyFactoryBean factory = new JaxWsProxyFactoryBean(); factory.getInInterceptors().add(new LoggingInInterceptor()); factory.getOutInterceptors().add(new LoggingOutInterceptor()); factory.setServiceClass(LeaveWebService.class); factory.setAddress(LeaveWebserviceUtil.WEBSERVICE_URL); LeaveWebService leaveWebService = (LeaveWebService) factory.create(); boolean audit = leaveWebService.generalManagerAudit("2013-01-01 09:00", "2013-01-04 17:30"); assertFalse(audit); } @After public void after() { LeaveWebserviceUtil.stopServer(); } }
apache-2.0
onders86/camel
platforms/camel-catalog-provider-springboot/src/main/java/org/apache/camel/catalog/springboot/SpringBootRuntimeProvider.java
4859
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.camel.catalog.springboot; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.List; import org.apache.camel.catalog.CamelCatalog; import org.apache.camel.catalog.CatalogHelper; import org.apache.camel.catalog.RuntimeProvider; /** * A Spring Boot based {@link RuntimeProvider} which only includes the supported Camel components, data formats, and languages * which can be installed in Spring Boot using the starter dependencies. */ public class SpringBootRuntimeProvider implements RuntimeProvider { private static final String COMPONENT_DIR = "org/apache/camel/catalog/springboot/components"; private static final String DATAFORMAT_DIR = "org/apache/camel/catalog/springboot/dataformats"; private static final String LANGUAGE_DIR = "org/apache/camel/catalog/springboot/languages"; private static final String OTHER_DIR = "org/apache/camel/catalog/springboot/others"; private static final String COMPONENTS_CATALOG = "org/apache/camel/catalog/springboot/components.properties"; private static final String DATA_FORMATS_CATALOG = "org/apache/camel/catalog/springboot/dataformats.properties"; private static final String LANGUAGE_CATALOG = "org/apache/camel/catalog/springboot/languages.properties"; private static final String OTHER_CATALOG = "org/apache/camel/catalog/springboot/others.properties"; private CamelCatalog camelCatalog; @Override public CamelCatalog getCamelCatalog() { return camelCatalog; } @Override public void setCamelCatalog(CamelCatalog camelCatalog) { this.camelCatalog = camelCatalog; } @Override public String getProviderName() { return "springboot"; } @Override public String getProviderGroupId() { return "org.apache.camel"; } @Override public String getProviderArtifactId() { return "camel-catalog-provider-springboot"; } @Override public String getComponentJSonSchemaDirectory() { return COMPONENT_DIR; } @Override public String getDataFormatJSonSchemaDirectory() { return DATAFORMAT_DIR; } @Override public String getLanguageJSonSchemaDirectory() { return LANGUAGE_DIR; } @Override public String getOtherJSonSchemaDirectory() { return OTHER_DIR; } @Override public List<String> findComponentNames() { List<String> names = new ArrayList<>(); InputStream is = camelCatalog.getVersionManager().getResourceAsStream(COMPONENTS_CATALOG); if (is != null) { try { CatalogHelper.loadLines(is, names); } catch (IOException e) { // ignore } } return names; } @Override public List<String> findDataFormatNames() { List<String> names = new ArrayList<>(); InputStream is = camelCatalog.getVersionManager().getResourceAsStream(DATA_FORMATS_CATALOG); if (is != null) { try { CatalogHelper.loadLines(is, names); } catch (IOException e) { // ignore } } return names; } @Override public List<String> findLanguageNames() { List<String> names = new ArrayList<>(); InputStream is = camelCatalog.getVersionManager().getResourceAsStream(LANGUAGE_CATALOG); if (is != null) { try { CatalogHelper.loadLines(is, names); } catch (IOException e) { // ignore } } return names; } @Override public List<String> findOtherNames() { List<String> names = new ArrayList<>(); InputStream is = camelCatalog.getVersionManager().getResourceAsStream(OTHER_CATALOG); if (is != null) { try { CatalogHelper.loadLines(is, names); } catch (IOException e) { // ignore } } return names; } }
apache-2.0
alanfgates/hive
standalone-metastore/metastore-server/src/main/java/org/apache/hadoop/hive/metastore/events/PreReadDatabaseEvent.java
1483
/* * 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.hive.metastore.events; import org.apache.hadoop.classification.InterfaceAudience; import org.apache.hadoop.classification.InterfaceStability; import org.apache.hadoop.hive.metastore.IHMSHandler; import org.apache.hadoop.hive.metastore.api.Database; /** * Database read event */ @InterfaceAudience.Public @InterfaceStability.Stable public class PreReadDatabaseEvent extends PreEventContext { private final Database db; public PreReadDatabaseEvent(Database db, IHMSHandler handler) { super(PreEventType.READ_DATABASE, handler); this.db = db; } /** * @return the db */ public Database getDatabase() { return db; } }
apache-2.0
eugene-chow/keycloak
examples/demo-template/third-party-cdi/src/main/java/org/keycloak/example/oauth/DatabaseClient.java
4047
package org.keycloak.example.oauth; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient; import org.jboss.logging.Logger; import org.keycloak.KeycloakSecurityContext; import org.keycloak.adapters.AdapterUtils; import org.keycloak.servlet.ServletOAuthClient; import org.keycloak.util.JsonSerialization; import org.keycloak.util.UriUtils; import javax.enterprise.context.ApplicationScoped; import javax.faces.application.FacesMessage; import javax.faces.context.FacesContext; import javax.inject.Inject; import javax.inject.Named; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.List; /** * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a> * @author <a href="mailto:mposolda@redhat.com">Marek Posolda</a> * @version $Revision: 1 $ */ @ApplicationScoped @Named("databaseClient") public class DatabaseClient { @Inject @ServletRequestQualifier private HttpServletRequest request; @Inject private HttpServletResponse response; @Inject private FacesContext facesContext; @Inject private ServletOAuthClient oauthClient; @Inject private UserData userData; private static final Logger logger = Logger.getLogger(DatabaseClient.class); public void retrieveAccessToken() { try { oauthClient.redirectRelative("client.jsf", request, response); } catch (IOException e) { throw new RuntimeException(e); } } static class TypedList extends ArrayList<String> {} public void sendCustomersRequest() { List<String> customers = sendRequestToDBApplication(getBaseUrl() + "/database/customers"); userData.setCustomers(customers); } public void sendProductsRequest() { List<String> products = sendRequestToDBApplication(getBaseUrl() + "/database/products"); userData.setProducts(products); } protected List<String> sendRequestToDBApplication(String dbUri) { HttpClient client = new DefaultHttpClient(); HttpGet get = new HttpGet(dbUri); try { if (userData.isHasAccessToken()) { get.addHeader("Authorization", "Bearer " + userData.getAccessToken()); } HttpResponse response = client.execute(get); switch (response.getStatusLine().getStatusCode()) { case 200: HttpEntity entity = response.getEntity(); InputStream is = entity.getContent(); try { return JsonSerialization.readValue(is, TypedList.class); } finally { is.close(); } case 401: facesContext.addMessage(null, new FacesMessage("Status: 401. Request not authenticated! You need to retrieve access token first.")); break; case 403: facesContext.addMessage(null, new FacesMessage("Status: 403. Access token has insufficient privileges")); break; default: facesContext.addMessage(null, new FacesMessage("Status: " + response.getStatusLine() + ". Not able to retrieve data. See log for details")); logger.warn("Error occured. Status: " + response.getStatusLine()); } return null; } catch (IOException e) { e.printStackTrace(); facesContext.addMessage(null, new FacesMessage("Unknown error. See log for details")); return null; } } public String getBaseUrl() { KeycloakSecurityContext session = (KeycloakSecurityContext)request.getAttribute(KeycloakSecurityContext.class.getName()); return AdapterUtils.getOriginForRestCalls(request.getRequestURL().toString(), session); } }
apache-2.0
cschenyuan/hive-hack
ql/src/java/org/apache/hadoop/hive/ql/optimizer/stats/annotation/AnnotateStatsProcCtx.java
1861
/** * 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.hive.ql.optimizer.stats.annotation; import org.apache.hadoop.hive.conf.HiveConf; import org.apache.hadoop.hive.ql.lib.NodeProcessorCtx; import org.apache.hadoop.hive.ql.parse.ParseContext; import org.apache.hadoop.hive.ql.plan.Statistics; public class AnnotateStatsProcCtx implements NodeProcessorCtx { private ParseContext pctx; private HiveConf conf; private Statistics andExprStats = null; public AnnotateStatsProcCtx(ParseContext pctx) { this.setParseContext(pctx); if(pctx != null) { this.setConf(pctx.getConf()); } else { this.setConf(null); } } public HiveConf getConf() { return conf; } public void setConf(HiveConf conf) { this.conf = conf; } public ParseContext getParseContext() { return pctx; } public void setParseContext(ParseContext pctx) { this.pctx = pctx; } public Statistics getAndExprStats() { return andExprStats; } public void setAndExprStats(Statistics andExprStats) { this.andExprStats = andExprStats; } }
apache-2.0
adufilie/flex-sdk
modules/thirdparty/batik/sources/org/apache/flex/forks/batik/svggen/ExtensionHandler.java
2772
/* 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.flex.forks.batik.svggen; import java.awt.Composite; import java.awt.Paint; import java.awt.Rectangle; import java.awt.image.BufferedImageOp; /** * The ExtensionHandler interface allows the user to handle * Java 2D API extensions that map to SVG concepts (such as custom * Paints, Composites or BufferedImageOp filters). * * @author <a href="mailto:vincent.hardy@eng.sun.com">Vincent Hardy</a> * @version $Id: ExtensionHandler.java 478176 2006-11-22 14:50:50Z dvholten $ */ public interface ExtensionHandler { /** * @param paint Custom Paint to be converted to SVG * @param generatorContext allows the handler to build DOM objects as needed. * @return an SVGPaintDescriptor */ SVGPaintDescriptor handlePaint(Paint paint, SVGGeneratorContext generatorContext); /** * @param composite Custom Composite to be converted to SVG. * @param generatorContext allows the handler to build DOM objects as needed. * @return an SVGCompositeDescriptor which contains a valid SVG filter, * or null if the composite cannot be handled * */ SVGCompositeDescriptor handleComposite(Composite composite, SVGGeneratorContext generatorContext); /** * @param filter Custom filter to be converted to SVG. * @param filterRect Rectangle, in device space, that defines the area * to which filtering applies. May be null, meaning that the * area is undefined. * @param generatorContext allows the handler to build DOM objects as needed. * @return an SVGFilterDescriptor which contains a valid SVG filter, * or null if the composite cannot be handled */ SVGFilterDescriptor handleFilter(BufferedImageOp filter, Rectangle filterRect, SVGGeneratorContext generatorContext); }
apache-2.0
sake/bouncycastle-java
test/src/org/bouncycastle/crypto/test/NaccacheSternTest.java
11131
package org.bouncycastle.crypto.test; import java.math.BigInteger; import java.security.SecureRandom; import java.util.Vector; import org.bouncycastle.crypto.AsymmetricCipherKeyPair; import org.bouncycastle.crypto.InvalidCipherTextException; import org.bouncycastle.crypto.engines.NaccacheSternEngine; import org.bouncycastle.crypto.generators.NaccacheSternKeyPairGenerator; import org.bouncycastle.crypto.params.NaccacheSternKeyGenerationParameters; import org.bouncycastle.crypto.params.NaccacheSternKeyParameters; import org.bouncycastle.crypto.params.NaccacheSternPrivateKeyParameters; import org.bouncycastle.util.encoders.Hex; import org.bouncycastle.util.test.SimpleTest; /** * Test case for NaccacheStern cipher. For details on this cipher, please see * * http://www.gemplus.com/smart/rd/publications/pdf/NS98pkcs.pdf * * Performs the following tests: * <ul> * <li> Toy example from the NaccacheSternPaper </li> * <li> 768 bit test with text "Now is the time for all good men." (ripped from RSA test) and * the same test with the first byte replaced by 0xFF </li> * <li> 1024 bit test analog to 768 bit test </li> * </ul> */ public class NaccacheSternTest extends SimpleTest { static final boolean debug = false; static final NaccacheSternEngine cryptEng = new NaccacheSternEngine(); static final NaccacheSternEngine decryptEng = new NaccacheSternEngine(); static { cryptEng.setDebug(debug); decryptEng.setDebug(debug); } // Values from NaccacheStern paper static final BigInteger a = BigInteger.valueOf(101); static final BigInteger u1 = BigInteger.valueOf(3); static final BigInteger u2 = BigInteger.valueOf(5); static final BigInteger u3 = BigInteger.valueOf(7); static final BigInteger b = BigInteger.valueOf(191); static final BigInteger v1 = BigInteger.valueOf(11); static final BigInteger v2 = BigInteger.valueOf(13); static final BigInteger v3 = BigInteger.valueOf(17); static final BigInteger ONE = BigInteger.valueOf(1); static final BigInteger TWO = BigInteger.valueOf(2); static final BigInteger sigma = u1.multiply(u2).multiply(u3).multiply(v1) .multiply(v2).multiply(v3); static final BigInteger p = TWO.multiply(a).multiply(u1).multiply(u2) .multiply(u3).add(ONE); static final BigInteger q = TWO.multiply(b).multiply(v1).multiply(v2) .multiply(v3).add(ONE); static final BigInteger n = p.multiply(q); static final BigInteger phi_n = p.subtract(ONE).multiply(q.subtract(ONE)); static final BigInteger g = BigInteger.valueOf(131); static final Vector smallPrimes = new Vector(); // static final BigInteger paperTest = BigInteger.valueOf(202); static final String input = "4e6f77206973207468652074696d6520666f7220616c6c20676f6f64206d656e"; static final BigInteger paperTest = BigInteger.valueOf(202); // // to check that we handling byte extension by big number correctly. // static final String edgeInput = "ff6f77206973207468652074696d6520666f7220616c6c20676f6f64206d656e"; public String getName() { return "NaccacheStern"; } public void performTest() { // Test with given key from NaccacheSternPaper (totally insecure) // First the Parameters from the NaccacheStern Paper // (see http://www.gemplus.com/smart/rd/publications/pdf/NS98pkcs.pdf ) smallPrimes.addElement(u1); smallPrimes.addElement(u2); smallPrimes.addElement(u3); smallPrimes.addElement(v1); smallPrimes.addElement(v2); smallPrimes.addElement(v3); NaccacheSternKeyParameters pubParameters = new NaccacheSternKeyParameters(false, g, n, sigma.bitLength()); NaccacheSternPrivateKeyParameters privParameters = new NaccacheSternPrivateKeyParameters(g, n, sigma.bitLength(), smallPrimes, phi_n); AsymmetricCipherKeyPair pair = new AsymmetricCipherKeyPair(pubParameters, privParameters); // Initialize Engines with KeyPair if (debug) { System.out.println("initializing encryption engine"); } cryptEng.init(true, pair.getPublic()); if (debug) { System.out.println("initializing decryption engine"); } decryptEng.init(false, pair.getPrivate()); byte[] data = paperTest.toByteArray(); if (!new BigInteger(data).equals(new BigInteger(enDeCrypt(data)))) { fail("failed NaccacheStern paper test"); } // // key generation test // // // 768 Bit test // if (debug) { System.out.println(); System.out.println("768 Bit TEST"); } // specify key generation parameters NaccacheSternKeyGenerationParameters genParam = new NaccacheSternKeyGenerationParameters(new SecureRandom(), 768, 8, 30, debug); // Initialize Key generator and generate key pair NaccacheSternKeyPairGenerator pGen = new NaccacheSternKeyPairGenerator(); pGen.init(genParam); pair = pGen.generateKeyPair(); if (((NaccacheSternKeyParameters)pair.getPublic()).getModulus().bitLength() < 768) { System.out.println("FAILED: key size is <786 bit, exactly " + ((NaccacheSternKeyParameters)pair.getPublic()).getModulus().bitLength() + " bit"); fail("failed key generation (768) length test"); } // Initialize Engines with KeyPair if (debug) { System.out.println("initializing " + genParam.getStrength() + " bit encryption engine"); } cryptEng.init(true, pair.getPublic()); if (debug) { System.out.println("initializing " + genParam.getStrength() + " bit decryption engine"); } decryptEng.init(false, pair.getPrivate()); // Basic data input data = Hex.decode(input); if (!new BigInteger(1, data).equals(new BigInteger(1, enDeCrypt(data)))) { fail("failed encryption decryption (" + genParam.getStrength() + ") basic test"); } // Data starting with FF byte (would be interpreted as negative // BigInteger) data = Hex.decode(edgeInput); if (!new BigInteger(1, data).equals(new BigInteger(1, enDeCrypt(data)))) { fail("failed encryption decryption (" + genParam.getStrength() + ") edgeInput test"); } // // 1024 Bit Test // /* if (debug) { System.out.println(); System.out.println("1024 Bit TEST"); } // specify key generation parameters genParam = new NaccacheSternKeyGenerationParameters(new SecureRandom(), 1024, 8, 40); pGen.init(genParam); pair = pGen.generateKeyPair(); if (((NaccacheSternKeyParameters)pair.getPublic()).getModulus().bitLength() < 1024) { if (debug) { System.out.println("FAILED: key size is <1024 bit, exactly " + ((NaccacheSternKeyParameters)pair.getPublic()).getModulus().bitLength() + " bit"); } fail("failed key generation (1024) length test"); } // Initialize Engines with KeyPair if (debug) { System.out.println("initializing " + genParam.getStrength() + " bit encryption engine"); } cryptEng.init(true, pair.getPublic()); if (debug) { System.out.println("initializing " + genParam.getStrength() + " bit decryption engine"); } decryptEng.init(false, pair.getPrivate()); if (debug) { System.out.println("Data is " + new BigInteger(1, data)); } // Basic data input data = Hex.decode(input); if (!new BigInteger(1, data).equals(new BigInteger(1, enDeCrypt(data)))) { fail("failed encryption decryption (" + genParam.getStrength() + ") basic test"); } // Data starting with FF byte (would be interpreted as negative // BigInteger) data = Hex.decode(edgeInput); if (!new BigInteger(1, data).equals(new BigInteger(1, enDeCrypt(data)))) { fail("failed encryption decryption (" + genParam.getStrength() + ") edgeInput test"); } */ // END OF TEST CASE try { new NaccacheSternEngine().processBlock(new byte[]{ 1 }, 0, 1); fail("failed initialisation check"); } catch (IllegalStateException e) { // expected } catch (InvalidCipherTextException e) { fail("failed initialisation check"); } if (debug) { System.out.println("All tests successful"); } } private byte[] enDeCrypt(byte[] input) { // create work array byte[] data = new byte[input.length]; System.arraycopy(input, 0, data, 0, data.length); // Perform encryption like in the paper from Naccache-Stern if (debug) { System.out.println("encrypting data. Data representation\n" // + "As String:.... " + new String(data) + "\n" + "As BigInteger: " + new BigInteger(1, data)); System.out.println("data length is " + data.length); } try { data = cryptEng.processData(data); } catch (InvalidCipherTextException e) { if (debug) { System.out.println("failed - exception " + e.toString() + "\n" + e.getMessage()); } fail("failed - exception " + e.toString() + "\n" + e.getMessage()); } if (debug) { System.out.println("enrypted data representation\n" // + "As String:.... " + new String(data) + "\n" + "As BigInteger: " + new BigInteger(1, data)); System.out.println("data length is " + data.length); } try { data = decryptEng.processData(data); } catch (InvalidCipherTextException e) { if (debug) { System.out.println("failed - exception " + e.toString() + "\n" + e.getMessage()); } fail("failed - exception " + e.toString() + "\n" + e.getMessage()); } if (debug) { System.out.println("decrypted data representation\n" // + "As String:.... " + new String(data) + "\n" + "As BigInteger: " + new BigInteger(1, data)); System.out.println("data length is " + data.length); } return data; } public static void main(String[] args) { runTest(new NaccacheSternTest()); } }
mit
aima-java/aima-java
aima-core/src/main/java/aima/core/probability/util/RandVar.java
2171
package aima.core.probability.util; import java.util.HashSet; import java.util.Map; import java.util.Set; import aima.core.probability.RandomVariable; import aima.core.probability.domain.Domain; import aima.core.probability.proposition.TermProposition; /** * Default implementation of the RandomVariable interface. * * Note: Also implements the TermProposition interface so its easy to use * RandomVariables in conjunction with propositions about them in the * Probability Model APIs. * * @author Ciaran O'Reilly */ public class RandVar implements RandomVariable, TermProposition { private String name = null; private Domain domain = null; private Set<RandomVariable> scope = new HashSet<RandomVariable>(); public RandVar(String name, Domain domain) { ProbUtil.checkValidRandomVariableName(name); if (null == domain) { throw new IllegalArgumentException( "Domain of RandomVariable must be specified."); } this.name = name; this.domain = domain; this.scope.add(this); } // // START-RandomVariable @Override public String getName() { return name; } @Override public Domain getDomain() { return domain; } // END-RandomVariable // // // START-TermProposition @Override public RandomVariable getTermVariable() { return this; } @Override public Set<RandomVariable> getScope() { return scope; } @Override public Set<RandomVariable> getUnboundScope() { return scope; } @Override public boolean holds(Map<RandomVariable, Object> possibleWorld) { return possibleWorld.containsKey(getTermVariable()); } // END-TermProposition // @Override public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof RandomVariable)) { return false; } // The name (not the name:domain combination) uniquely identifies a // Random Variable RandomVariable other = (RandomVariable) o; return this.name.equals(other.getName()); } @Override public int hashCode() { return name.hashCode(); } @Override public String toString() { return getName(); } }
mit
aima-java/aima-java
aima-core/src/main/java/aima/core/probability/bayes/exact/EliminationAsk.java
8132
package aima.core.probability.bayes.exact; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Set; import aima.core.probability.CategoricalDistribution; import aima.core.probability.Factor; import aima.core.probability.RandomVariable; import aima.core.probability.bayes.BayesInference; import aima.core.probability.bayes.BayesianNetwork; import aima.core.probability.bayes.FiniteNode; import aima.core.probability.bayes.Node; import aima.core.probability.proposition.AssignmentProposition; import aima.core.probability.util.ProbabilityTable; /** * Artificial Intelligence A Modern Approach (3rd Edition): Figure 14.11, page * 528.<br> * <br> * * <pre> * function ELIMINATION-ASK(X, e, bn) returns a distribution over X * inputs: X, the query variable * e, observed values for variables E * bn, a Bayesian network specifying joint distribution P(X<sub>1</sub>, ..., X<sub>n</sub>) * * factors <- [] * for each var in ORDER(bn.VARS) do * factors <- [MAKE-FACTOR(var, e) | factors] * if var is hidden variable the factors <- SUM-OUT(var, factors) * return NORMALIZE(POINTWISE-PRODUCT(factors)) * </pre> * * Figure 14.11 The variable elimination algorithm for inference in Bayesian * networks. <br> * <br> * <b>Note:</b> The implementation has been extended to handle queries with * multiple variables. <br> * * @author Ciaran O'Reilly */ public class EliminationAsk implements BayesInference { // private static final ProbabilityTable _identity = new ProbabilityTable( new double[] { 1.0 }); public EliminationAsk() { } // function ELIMINATION-ASK(X, e, bn) returns a distribution over X /** * The ELIMINATION-ASK algorithm in Figure 14.11. * * @param X * the query variables. * @param e * observed values for variables E. * @param bn * a Bayes net with variables {X} &cup; E &cup; Y /* Y = hidden * variables // * @return a distribution over the query variables. */ public CategoricalDistribution eliminationAsk(final RandomVariable[] X, final AssignmentProposition[] e, final BayesianNetwork bn) { Set<RandomVariable> hidden = new HashSet<RandomVariable>(); List<RandomVariable> VARS = new ArrayList<RandomVariable>(); calculateVariables(X, e, bn, hidden, VARS); // factors <- [] List<Factor> factors = new ArrayList<Factor>(); // for each var in ORDER(bn.VARS) do for (RandomVariable var : order(bn, VARS)) { // factors <- [MAKE-FACTOR(var, e) | factors] factors.add(0, makeFactor(var, e, bn)); // if var is hidden variable then factors <- SUM-OUT(var, factors) if (hidden.contains(var)) { factors = sumOut(var, factors, bn); } } // return NORMALIZE(POINTWISE-PRODUCT(factors)) Factor product = pointwiseProduct(factors); // Note: Want to ensure the order of the product matches the // query variables return ((ProbabilityTable) product.pointwiseProductPOS(_identity, X)) .normalize(); } // // START-BayesInference public CategoricalDistribution ask(final RandomVariable[] X, final AssignmentProposition[] observedEvidence, final BayesianNetwork bn) { return this.eliminationAsk(X, observedEvidence, bn); } // END-BayesInference // // // PROTECTED METHODS // /** * <b>Note:</b>Override this method for a more efficient implementation as * outlined in AIMA3e pgs. 527-28. Calculate the hidden variables from the * Bayesian Network. The default implementation does not perform any of * these.<br> * <br> * Two calcuations to be performed here in order to optimize iteration over * the Bayesian Network:<br> * 1. Calculate the hidden variables to be enumerated over. An optimization * (AIMA3e pg. 528) is to remove 'every variable that is not an ancestor of * a query variable or evidence variable as it is irrelevant to the query' * (i.e. sums to 1). 2. The subset of variables from the Bayesian Network to * be retained after irrelevant hidden variables have been removed. * * @param X * the query variables. * @param e * observed values for variables E. * @param bn * a Bayes net with variables {X} &cup; E &cup; Y /* Y = hidden * variables // * @param hidden * to be populated with the relevant hidden variables Y. * @param bnVARS * to be populated with the subset of the random variables * comprising the Bayesian Network with any irrelevant hidden * variables removed. */ protected void calculateVariables(final RandomVariable[] X, final AssignmentProposition[] e, final BayesianNetwork bn, Set<RandomVariable> hidden, Collection<RandomVariable> bnVARS) { bnVARS.addAll(bn.getVariablesInTopologicalOrder()); hidden.addAll(bnVARS); for (RandomVariable x : X) { hidden.remove(x); } for (AssignmentProposition ap : e) { hidden.removeAll(ap.getScope()); } return; } /** * <b>Note:</b>Override this method for a more efficient implementation as * outlined in AIMA3e pgs. 527-28. The default implementation does not * perform any of these.<br> * * @param bn * the Bayesian Network over which the query is being made. Note, * is necessary to provide this in order to be able to determine * the dependencies between variables. * @param vars * a subset of the RandomVariables making up the Bayesian * Network, with any irrelevant hidden variables alreay removed. * @return a possibly opimal ordering for the random variables to be * iterated over by the algorithm. For example, one fairly effective * ordering is a greedy one: eliminate whichever variable minimizes * the size of the next factor to be constructed. */ protected List<RandomVariable> order(BayesianNetwork bn, Collection<RandomVariable> vars) { // Note: Trivial Approach: // For simplicity just return in the reverse order received, // i.e. received will be the default topological order for // the Bayesian Network and we want to ensure the network // is iterated from bottom up to ensure when hidden variables // are come across all the factors dependent on them have // been seen so far. List<RandomVariable> order = new ArrayList<RandomVariable>(vars); Collections.reverse(order); return order; } // // PRIVATE METHODS // private Factor makeFactor(RandomVariable var, AssignmentProposition[] e, BayesianNetwork bn) { Node n = bn.getNode(var); if (!(n instanceof FiniteNode)) { throw new IllegalArgumentException( "Elimination-Ask only works with finite Nodes."); } FiniteNode fn = (FiniteNode) n; List<AssignmentProposition> evidence = new ArrayList<AssignmentProposition>(); for (AssignmentProposition ap : e) { if (fn.getCPT().contains(ap.getTermVariable())) { evidence.add(ap); } } return fn.getCPT().getFactorFor( evidence.toArray(new AssignmentProposition[evidence.size()])); } private List<Factor> sumOut(RandomVariable var, List<Factor> factors, BayesianNetwork bn) { List<Factor> summedOutFactors = new ArrayList<Factor>(); List<Factor> toMultiply = new ArrayList<Factor>(); for (Factor f : factors) { if (f.contains(var)) { toMultiply.add(f); } else { // This factor does not contain the variable // so no need to sum out - see AIMA3e pg. 527. summedOutFactors.add(f); } } summedOutFactors.add(pointwiseProduct(toMultiply).sumOut(var)); return summedOutFactors; } private Factor pointwiseProduct(List<Factor> factors) { Factor product = factors.get(0); for (int i = 1; i < factors.size(); i++) { product = product.pointwiseProduct(factors.get(i)); } return product; } }
mit
Avnerus/pulse-midburn
oscP5/src/netP5/UdpServer.java
3640
/** * A network library for processing which supports UDP, TCP and Multicast. * * (c) 2004-2011 * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General * Public License along with this library; if not, write to the * Free Software Foundation, Inc., 59 Temple Place, Suite 330, * Boston, MA 02111-1307 USA * * @author Andreas Schlegel http://www.sojamo.de/libraries/oscP5 * @modified 12/19/2011 * @version 0.9.8 */ package netP5; import java.net.DatagramPacket; import java.util.Vector; /** * * @author andreas schlegel * */ public class UdpServer extends AbstractUdpServer implements UdpPacketListener { protected Object _myParent; protected NetPlug _myNetPlug; /** * new UDP server. * by default the buffersize of a udp packet is 1536 bytes. you can set * your own individual buffersize with the third parameter int in the constructor. * @param theObject Object * @param thePort int * @param theBufferSize int */ public UdpServer( final Object theObject, final int thePort, final int theBufferSize) { super(null, thePort, theBufferSize); _myParent = theObject; _myListener = this; _myNetPlug = new NetPlug(_myParent); start(); } public UdpServer( final Object theObject, final int thePort) { super(null, thePort, 1536); _myParent = theObject; _myListener = this; _myNetPlug = new NetPlug(_myParent); start(); } /** * @invisible * @param theListener * @param thePort * @param theBufferSize */ public UdpServer( final UdpPacketListener theListener, final int thePort, final int theBufferSize) { super(theListener, thePort, theBufferSize); } /** * @invisible * @param theListener * @param theAddress * @param thePort * @param theBufferSize */ protected UdpServer( final UdpPacketListener theListener, final String theAddress, final int thePort, final int theBufferSize) { super(theListener, theAddress, thePort, theBufferSize); } /** * @invisible * @param thePacket DatagramPacket * @param thePort int */ public void process(DatagramPacket thePacket, int thePort) { _myNetPlug.process(thePacket,thePort); } /** * add a listener to the udp server. each incoming packet will be forwarded * to the listener. * @param theListener * @related NetListener */ public void addListener(NetListener theListener) { _myNetPlug.addListener(theListener); } /** * * @param theListener * @related NetListener */ public void removeListener(NetListener theListener) { _myNetPlug.removeListener(theListener); } /** * * @param theIndex * @related NetListener * @return */ public NetListener getListener(int theIndex) { return _myNetPlug.getListener(theIndex); } /** * @related NetListener * @return */ public Vector getListeners() { return _myNetPlug.getListeners(); } }
mit
johannrichard/openhab2-addons
addons/binding/org.openhab.binding.innogysmarthome/src/main/java/org/openhab/binding/innogysmarthome/internal/listener/EventListener.java
1030
/** * Copyright (c) 2010-2018 by the respective copyright holders. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ package org.openhab.binding.innogysmarthome.internal.listener; import org.openhab.binding.innogysmarthome.internal.InnogyWebSocket; /** * The {@link EventListener} is called by the {@link InnogyWebSocket} on new Events and if the {@link InnogyWebSocket} * closed the connection. * * @author Oliver Kuhl - Initial contribution */ public interface EventListener { /** * This method is called, whenever a new event comes from the innogy service (like a device change for example). * * @param msg */ public void onEvent(String msg); /** * This method is called, when the evenRunner stops abnormally (statuscode <> 1000). */ public void connectionClosed(); }
epl-1.0
YouDiSN/OpenJDK-Research
jdk9/hotspot/src/jdk.internal.vm.compiler/share/classes/org.graalvm.compiler.jtt/src/org/graalvm/compiler/jtt/optimize/LLE_01.java
1754
/* * Copyright (c) 2007, 2012, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package org.graalvm.compiler.jtt.optimize; import org.junit.Test; import org.graalvm.compiler.jtt.JTTTest; /* * Test case for local load elimination. It makes sure that the second field store is not eliminated, because * it is recognized that the first store changes the field "field1", so it is no longer guaranteed that it * has its default value 0. */ public class LLE_01 extends JTTTest { private static class TestClass { int field1; } public static int test() { TestClass o = new TestClass(); o.field1 = 1; o.field1 = 0; return o.field1; } @Test public void run0() throws Throwable { runTest("test"); } }
gpl-2.0