repo_name
stringlengths
5
108
path
stringlengths
6
333
size
stringlengths
1
6
content
stringlengths
4
977k
license
stringclasses
15 values
apache/incubator-apex-core
engine/src/main/java/com/datatorrent/stram/security/StramWSPrincipal.java
1257
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package com.datatorrent.stram.security; import java.security.Principal; /** * Based on org.apache.hadoop.yarn.server.webproxy.amfilter.AmIPPrincipal * See https://issues.apache.org/jira/browse/YARN-1516 * * @since 0.9.2 */ public class StramWSPrincipal implements Principal { private final String name; public StramWSPrincipal(String name) { this.name = name; } @Override public String getName() { return name; } }
apache-2.0
md-5/jdk10
test/jdk/javax/sound/sampled/Clip/OpenNonIntegralNumberOfSampleframes.java
4036
/* * 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. */ import java.util.ArrayList; import java.util.List; import javax.sound.sampled.AudioFormat; import javax.sound.sampled.AudioFormat.Encoding; import javax.sound.sampled.AudioSystem; import javax.sound.sampled.Clip; import javax.sound.sampled.LineUnavailableException; /** * @test * @bug 8167435 */ public final class OpenNonIntegralNumberOfSampleframes { /** * We will try to use all formats, in this case all our providers will be * covered by supported/unsupported formats. */ private static final List<AudioFormat> formats = new ArrayList<>(2900); private static final Encoding[] encodings = { Encoding.ALAW, Encoding.ULAW, Encoding.PCM_SIGNED, Encoding.PCM_UNSIGNED, Encoding.PCM_FLOAT }; private static final int[] sampleRates = { 8000, 11025, 16000, 32000, 44100 }; private static final int[] sampleBits = { 4, 8, 11, 16, 20, 24, 32, 48, 64, 128 }; private static final int[] channels = { 1, 2, 3, 4, 5, 6 }; static { for (final Boolean end : new boolean[]{false, true}) { for (final int sampleSize : sampleBits) { for (final int sampleRate : sampleRates) { for (final int channel : channels) { final int frameSize = ((sampleSize + 7) / 8) * channel; if (frameSize == 1) { // frameSize=1 is ok for any buffers, skip it continue; } for (final Encoding enc : encodings) { formats.add( new AudioFormat(enc, sampleRate, sampleSize, channel, frameSize, sampleRate, end)); } } } } } } public static void main(final String[] args) { for (final AudioFormat af : formats) { try (Clip clip = AudioSystem.getClip()) { final int bufferSize = af.getFrameSize() + 1; try { clip.open(af, new byte[100], 0, bufferSize); } catch (final IllegalArgumentException ignored) { // expected exception continue; } catch (final LineUnavailableException e) { // should not occur, we passed incorrect bufferSize e.printStackTrace(); } System.err.println("af = " + af); System.err.println("bufferSize = " + bufferSize); throw new RuntimeException("Expected exception is not thrown"); } catch (IllegalArgumentException | LineUnavailableException ignored) { // the test is not applicable } } } }
gpl-2.0
mbroadst/debian-qpid-cpp-old
proton-j/src/main/java/org/apache/qpid/proton/codec/impl/Decimal64Element.java
1832
/* * * 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.qpid.proton.codec.impl; import java.nio.ByteBuffer; import org.apache.qpid.proton.amqp.Decimal64; import org.apache.qpid.proton.codec.Data; class Decimal64Element extends AtomicElement<Decimal64> { private final Decimal64 _value; Decimal64Element(Element parent, Element prev, Decimal64 d) { super(parent, prev); _value = d; } @Override public int size() { return isElementOfArray() ? 8 : 9; } @Override public Decimal64 getValue() { return _value; } @Override public Data.DataType getDataType() { return Data.DataType.DECIMAL64; } @Override public int encode(ByteBuffer b) { int size = size(); if(b.remaining()>=size) { if(size == 9) { b.put((byte)0x84); } b.putLong(_value.getBits()); return size; } else { return 0; } } }
apache-2.0
jovezhougang/subsampling-scale-image-view
sample/src/com/davemorrissey/labs/subscaleview/sample/viewpager/ViewPagerFragment.java
2191
/* Copyright 2014 David Morrissey 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.davemorrissey.labs.subscaleview.sample.viewpager; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.davemorrissey.labs.subscaleview.ImageSource; import com.davemorrissey.labs.subscaleview.SubsamplingScaleImageView; import com.davemorrissey.labs.subscaleview.sample.R.id; import com.davemorrissey.labs.subscaleview.sample.R.layout; public class ViewPagerFragment extends Fragment { private static final String BUNDLE_ASSET = "asset"; private String asset; public ViewPagerFragment() { } public void setAsset(String asset) { this.asset = asset; } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(layout.view_pager_page, container, false); if (savedInstanceState != null) { if (asset == null && savedInstanceState.containsKey(BUNDLE_ASSET)) { asset = savedInstanceState.getString(BUNDLE_ASSET); } } if (asset != null) { SubsamplingScaleImageView imageView = (SubsamplingScaleImageView)rootView.findViewById(id.imageView); imageView.setImage(ImageSource.asset(asset)); } return rootView; } @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); View rootView = getView(); if (rootView != null) { outState.putString(BUNDLE_ASSET, asset); } } }
apache-2.0
likaiwalkman/cassandra
src/java/org/apache/cassandra/io/sstable/SSTable.java
11352
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.cassandra.io.sstable; import java.io.*; import java.nio.ByteBuffer; import java.nio.charset.Charset; import java.util.*; import java.util.concurrent.CopyOnWriteArraySet; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Predicates; import com.google.common.collect.Collections2; import com.google.common.collect.Sets; import com.google.common.io.Files; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.apache.cassandra.config.CFMetaData; import org.apache.cassandra.db.BufferDecoratedKey; import org.apache.cassandra.db.DecoratedKey; import org.apache.cassandra.db.RowIndexEntry; import org.apache.cassandra.dht.IPartitioner; import org.apache.cassandra.io.FSWriteError; import org.apache.cassandra.io.util.FileUtils; import org.apache.cassandra.io.util.RandomAccessReader; import org.apache.cassandra.utils.ByteBufferUtil; import org.apache.cassandra.utils.memory.HeapAllocator; import org.apache.cassandra.utils.Pair; /** * This class is built on top of the SequenceFile. It stores * data on disk in sorted fashion. However the sorting is upto * the application. This class expects keys to be handed to it * in sorted order. * * A separate index file is maintained as well, containing the * SSTable keys and the offset into the SSTable at which they are found. * Every 1/indexInterval key is read into memory when the SSTable is opened. * * Finally, a bloom filter file is also kept for the keys in each SSTable. */ public abstract class SSTable { static final Logger logger = LoggerFactory.getLogger(SSTable.class); public static final int TOMBSTONE_HISTOGRAM_BIN_SIZE = 100; public final Descriptor descriptor; protected final Set<Component> components; public final CFMetaData metadata; public final boolean compression; public DecoratedKey first; public DecoratedKey last; protected SSTable(Descriptor descriptor, CFMetaData metadata) { this(descriptor, new HashSet<>(), metadata); } protected SSTable(Descriptor descriptor, Set<Component> components, CFMetaData metadata) { // In almost all cases, metadata shouldn't be null, but allowing null allows to create a mostly functional SSTable without // full schema definition. SSTableLoader use that ability assert descriptor != null; assert components != null; assert metadata != null; this.descriptor = descriptor; Set<Component> dataComponents = new HashSet<>(components); this.compression = dataComponents.contains(Component.COMPRESSION_INFO); this.components = new CopyOnWriteArraySet<>(dataComponents); this.metadata = metadata; } /** * We use a ReferenceQueue to manage deleting files that have been compacted * and for which no more SSTable references exist. But this is not guaranteed * to run for each such file because of the semantics of the JVM gc. So, * we write a marker to `compactedFilename` when a file is compacted; * if such a marker exists on startup, the file should be removed. * * This method will also remove SSTables that are marked as temporary. * * @return true if the file was deleted */ public static boolean delete(Descriptor desc, Set<Component> components) { // remove the DATA component first if it exists if (components.contains(Component.DATA)) FileUtils.deleteWithConfirm(desc.filenameFor(Component.DATA)); for (Component component : components) { if (component.equals(Component.DATA) || component.equals(Component.SUMMARY)) continue; FileUtils.deleteWithConfirm(desc.filenameFor(component)); } if (components.contains(Component.SUMMARY)) FileUtils.delete(desc.filenameFor(Component.SUMMARY)); logger.debug("Deleted {}", desc); return true; } public IPartitioner getPartitioner() { return metadata.partitioner; } public DecoratedKey decorateKey(ByteBuffer key) { return getPartitioner().decorateKey(key); } /** * If the given @param key occupies only part of a larger buffer, allocate a new buffer that is only * as large as necessary. */ public static DecoratedKey getMinimalKey(DecoratedKey key) { return key.getKey().position() > 0 || key.getKey().hasRemaining() || !key.getKey().hasArray() ? new BufferDecoratedKey(key.getToken(), HeapAllocator.instance.clone(key.getKey())) : key; } public String getFilename() { return descriptor.filenameFor(Component.DATA); } public String getIndexFilename() { return descriptor.filenameFor(Component.PRIMARY_INDEX); } public String getColumnFamilyName() { return descriptor.cfname; } public String getKeyspaceName() { return descriptor.ksname; } @VisibleForTesting public List<String> getAllFilePaths() { List<String> ret = new ArrayList<>(); for (Component component : components) ret.add(descriptor.filenameFor(component)); return ret; } /** * @return Descriptor and Component pair. null if given file is not acceptable as SSTable component. * If component is of unknown type, returns CUSTOM component. */ public static Pair<Descriptor, Component> tryComponentFromFilename(File dir, String name) { try { return Component.fromFilename(dir, name); } catch (Throwable e) { return null; } } /** * Discovers existing components for the descriptor. Slow: only intended for use outside the critical path. */ public static Set<Component> componentsFor(final Descriptor desc) { try { try { return readTOC(desc); } catch (FileNotFoundException e) { Set<Component> components = discoverComponentsFor(desc); if (components.isEmpty()) return components; // sstable doesn't exist yet if (!components.contains(Component.TOC)) components.add(Component.TOC); appendTOC(desc, components); return components; } } catch (IOException e) { throw new IOError(e); } } public static Set<Component> discoverComponentsFor(Descriptor desc) { Set<Component.Type> knownTypes = Sets.difference(Component.TYPES, Collections.singleton(Component.Type.CUSTOM)); Set<Component> components = Sets.newHashSetWithExpectedSize(knownTypes.size()); for (Component.Type componentType : knownTypes) { Component component = new Component(componentType); if (new File(desc.filenameFor(component)).exists()) components.add(component); } return components; } /** @return An estimate of the number of keys contained in the given index file. */ protected long estimateRowsFromIndex(RandomAccessReader ifile) throws IOException { // collect sizes for the first 10000 keys, or first 10 megabytes of data final int SAMPLES_CAP = 10000, BYTES_CAP = (int)Math.min(10000000, ifile.length()); int keys = 0; while (ifile.getFilePointer() < BYTES_CAP && keys < SAMPLES_CAP) { ByteBufferUtil.skipShortLength(ifile); RowIndexEntry.Serializer.skip(ifile); keys++; } assert keys > 0 && ifile.getFilePointer() > 0 && ifile.length() > 0 : "Unexpected empty index file: " + ifile; long estimatedRows = ifile.length() / (ifile.getFilePointer() / keys); ifile.seek(0); return estimatedRows; } public long bytesOnDisk() { long bytes = 0; for (Component component : components) { bytes += new File(descriptor.filenameFor(component)).length(); } return bytes; } @Override public String toString() { return getClass().getSimpleName() + "(" + "path='" + getFilename() + '\'' + ')'; } /** * Reads the list of components from the TOC component. * @return set of components found in the TOC */ protected static Set<Component> readTOC(Descriptor descriptor) throws IOException { File tocFile = new File(descriptor.filenameFor(Component.TOC)); List<String> componentNames = Files.readLines(tocFile, Charset.defaultCharset()); Set<Component> components = Sets.newHashSetWithExpectedSize(componentNames.size()); for (String componentName : componentNames) { Component component = new Component(Component.Type.fromRepresentation(componentName), componentName); if (!new File(descriptor.filenameFor(component)).exists()) logger.error("Missing component: {}", descriptor.filenameFor(component)); else components.add(component); } return components; } /** * Appends new component names to the TOC component. */ protected static void appendTOC(Descriptor descriptor, Collection<Component> components) { File tocFile = new File(descriptor.filenameFor(Component.TOC)); try (PrintWriter w = new PrintWriter(new FileWriter(tocFile, true))) { for (Component component : components) w.println(component.name); } catch (IOException e) { throw new FSWriteError(e, tocFile); } } /** * Registers new custom components. Used by custom compaction strategies. * Adding a component for the second time is a no-op. * Don't remove this - this method is a part of the public API, intended for use by custom compaction strategies. * @param newComponents collection of components to be added */ public synchronized void addComponents(Collection<Component> newComponents) { Collection<Component> componentsToAdd = Collections2.filter(newComponents, Predicates.not(Predicates.in(components))); appendTOC(descriptor, componentsToAdd); components.addAll(componentsToAdd); } }
apache-2.0
WANdisco/gerrit
java/com/google/gerrit/extensions/auth/oauth/OAuthVerifier.java
862
// Copyright (C) 2015 The Android Open Source Project // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.gerrit.extensions.auth.oauth; /* OAuth verifier */ public class OAuthVerifier { private final String value; public OAuthVerifier(String value) { this.value = value; } public String getValue() { return value; } }
apache-2.0
mistrydarshan99/libphonenumber
java/libphonenumber/src/com/google/i18n/phonenumbers/MetadataSource.java
1301
/* * Copyright (C) 2015 The Libphonenumber Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.i18n.phonenumbers; import com.google.i18n.phonenumbers.Phonemetadata.PhoneMetadata; /** * A source for phone metadata from resources. */ interface MetadataSource { /** * Gets phone metadata for a region. * @param regionCode the region code. * @return the phone metadata for that region, or null if there is none. */ PhoneMetadata getMetadataForRegion(String regionCode); /** * Gets phone metadata for a non-geographical region. * @param countryCallingCode the country calling code. * @return the phone metadata for that region, or null if there is none. */ PhoneMetadata getMetadataForNonGeographicalRegion(int countryCallingCode); }
apache-2.0
GlenRSmith/elasticsearch
server/src/main/java/org/elasticsearch/search/aggregations/metrics/ParsedTopHits.java
1923
/* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one * or more contributor license agreements. Licensed under the Elastic License * 2.0 and the Server Side Public License, v 1; you may not use this file except * in compliance with, at your election, the Elastic License 2.0 or the Server * Side Public License, v 1. */ package org.elasticsearch.search.aggregations.metrics; import org.elasticsearch.search.SearchHits; import org.elasticsearch.search.aggregations.ParsedAggregation; import org.elasticsearch.xcontent.ObjectParser; import org.elasticsearch.xcontent.ParseField; import org.elasticsearch.xcontent.XContentBuilder; import org.elasticsearch.xcontent.XContentParser; import java.io.IOException; public class ParsedTopHits extends ParsedAggregation implements TopHits { private SearchHits searchHits; @Override public String getType() { return TopHitsAggregationBuilder.NAME; } @Override public SearchHits getHits() { return searchHits; } @Override protected XContentBuilder doXContentBody(XContentBuilder builder, Params params) throws IOException { return searchHits.toXContent(builder, params); } private static final ObjectParser<ParsedTopHits, Void> PARSER = new ObjectParser<>( ParsedTopHits.class.getSimpleName(), true, ParsedTopHits::new ); static { declareAggregationFields(PARSER); PARSER.declareObject( (topHit, searchHits) -> topHit.searchHits = searchHits, (parser, context) -> SearchHits.fromXContent(parser), new ParseField(SearchHits.Fields.HITS) ); } public static ParsedTopHits fromXContent(XContentParser parser, String name) throws IOException { ParsedTopHits aggregation = PARSER.parse(parser, null); aggregation.setName(name); return aggregation; } }
apache-2.0
ColinZang/twitter4j
twitter4j-core/src/main/java/twitter4j/conf/PropertyConfiguration.java
18086
/* * Copyright 2007 Yusuke Yamamoto * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package twitter4j.conf; import java.io.*; import java.util.ArrayList; import java.util.Map; import java.util.Properties; /** * @author Yusuke Yamamoto - yusuke at mac.com */ public final class PropertyConfiguration extends ConfigurationBase implements java.io.Serializable { private static final String DEBUG = "debug"; private static final String USER = "user"; private static final String PASSWORD = "password"; private static final String HTTP_PRETTY_DEBUG = "http.prettyDebug"; private static final String HTTP_GZIP = "http.gzip"; private static final String HTTP_PROXY_HOST = "http.proxyHost"; private static final String HTTP_PROXY_HOST_FALLBACK = "http.proxyHost"; private static final String HTTP_PROXY_USER = "http.proxyUser"; private static final String HTTP_PROXY_PASSWORD = "http.proxyPassword"; private static final String HTTP_PROXY_PORT = "http.proxyPort"; private static final String HTTP_PROXY_PORT_FALLBACK = "http.proxyPort"; private static final String HTTP_CONNECTION_TIMEOUT = "http.connectionTimeout"; private static final String HTTP_READ_TIMEOUT = "http.readTimeout"; private static final String HTTP_STREAMING_READ_TIMEOUT = "http.streamingReadTimeout"; private static final String HTTP_RETRY_COUNT = "http.retryCount"; private static final String HTTP_RETRY_INTERVAL_SECS = "http.retryIntervalSecs"; private static final String OAUTH_CONSUMER_KEY = "oauth.consumerKey"; private static final String OAUTH_CONSUMER_SECRET = "oauth.consumerSecret"; private static final String OAUTH_ACCESS_TOKEN = "oauth.accessToken"; private static final String OAUTH_ACCESS_TOKEN_SECRET = "oauth.accessTokenSecret"; private static final String OAUTH2_TOKEN_TYPE = "oauth2.tokenType"; private static final String OAUTH2_ACCESS_TOKEN = "oauth2.accessToken"; private static final String OAUTH2_SCOPE = "oauth2.scope"; private static final String OAUTH_REQUEST_TOKEN_URL = "oauth.requestTokenURL"; private static final String OAUTH_AUTHORIZATION_URL = "oauth.authorizationURL"; private static final String OAUTH_ACCESS_TOKEN_URL = "oauth.accessTokenURL"; private static final String OAUTH_AUTHENTICATION_URL = "oauth.authenticationURL"; private static final String OAUTH2_TOKEN_URL = "oauth2.tokenURL"; private static final String OAUTH2_INVALIDATE_TOKEN_URL = "oauth2.invalidateTokenURL"; private static final String REST_BASE_URL = "restBaseURL"; private static final String STREAM_BASE_URL = "streamBaseURL"; private static final String USER_STREAM_BASE_URL = "userStreamBaseURL"; private static final String SITE_STREAM_BASE_URL = "siteStreamBaseURL"; private static final String ASYNC_NUM_THREADS = "async.numThreads"; private static final String ASYNC_DAEMON_ENABLED = "async.daemonEnabled"; private static final String CONTRIBUTING_TO = "contributingTo"; private static final String ASYNC_DISPATCHER_IMPL = "async.dispatcherImpl"; private static final String INCLUDE_MY_RETWEET = "includeMyRetweet"; private static final String INCLUDE_ENTITIES = "includeEntities"; private static final String LOGGER_FACTORY = "loggerFactory"; private static final String JSON_STORE_ENABLED = "jsonStoreEnabled"; private static final String MBEAN_ENABLED = "mbeanEnabled"; private static final String STREAM_USER_REPLIES_ALL = "stream.user.repliesAll"; private static final String STREAM_USER_WITH_FOLLOWINGS = "stream.user.withFollowings"; private static final String STREAM_STALL_WARNINGS_ENABLED = "stream.enableStallWarnings"; private static final String APPLICATION_ONLY_AUTH_ENABLED = "enableApplicationOnlyAuth"; private static final String MEDIA_PROVIDER = "media.provider"; private static final String MEDIA_PROVIDER_API_KEY = "media.providerAPIKey"; private static final String MEDIA_PROVIDER_PARAMETERS = "media.providerParameters"; private static final long serialVersionUID = -7262615247923693252L; private String OAuth2Scope; public PropertyConfiguration(InputStream is) { super(); Properties props = new Properties(); loadProperties(props, is); setFieldsWithTreePath(props, "/"); } public PropertyConfiguration(Properties props) { this(props, "/"); } public PropertyConfiguration(Properties props, String treePath) { super(); setFieldsWithTreePath(props, treePath); } PropertyConfiguration(String treePath) { super(); Properties props; // load from system properties try { props = (Properties) System.getProperties().clone(); try { Map<String, String> envMap = System.getenv(); for (String key : envMap.keySet()) { props.setProperty(key, envMap.get(key)); } } catch (SecurityException ignore) { } normalize(props); } catch (SecurityException ignore) { // Unsigned applets are not allowed to access System properties props = new Properties(); } final String TWITTER4J_PROPERTIES = "twitter4j.properties"; // override System properties with ./twitter4j.properties in the classpath loadProperties(props, "." + File.separatorChar + TWITTER4J_PROPERTIES); // then, override with /twitter4j.properties in the classpath loadProperties(props, Configuration.class.getResourceAsStream("/" + TWITTER4J_PROPERTIES)); // then, override with /WEB/INF/twitter4j.properties in the classpath loadProperties(props, Configuration.class.getResourceAsStream("/WEB-INF/" + TWITTER4J_PROPERTIES)); // for Google App Engine try { loadProperties(props, new FileInputStream("WEB-INF/" + TWITTER4J_PROPERTIES)); } catch (SecurityException ignore) { } catch (FileNotFoundException ignore) { } setFieldsWithTreePath(props, treePath); } /** * Creates a root PropertyConfiguration. This constructor is equivalent to new PropertyConfiguration("/"). */ PropertyConfiguration() { this("/"); } private boolean notNull(Properties props, String prefix, String name) { return props.getProperty(prefix + name) != null; } private boolean loadProperties(Properties props, String path) { FileInputStream fis = null; try { File file = new File(path); if (file.exists() && file.isFile()) { fis = new FileInputStream(file); props.load(fis); normalize(props); return true; } } catch (Exception ignore) { } finally { try { if (fis != null) { fis.close(); } } catch (IOException ignore) { } } return false; } private boolean loadProperties(Properties props, InputStream is) { try { props.load(is); normalize(props); return true; } catch (Exception ignore) { } return false; } private void normalize(Properties props) { ArrayList<String> toBeNormalized = new ArrayList<String>(10); for (Object key : props.keySet()) { String keyStr = (String) key; if (-1 != (keyStr.indexOf("twitter4j."))) { toBeNormalized.add(keyStr); } } for (String keyStr : toBeNormalized) { String property = props.getProperty(keyStr); int index = keyStr.indexOf("twitter4j."); String newKey = keyStr.substring(0, index) + keyStr.substring(index + 10); props.setProperty(newKey, property); } } /** * passing "/foo/bar" as treePath will result:<br> * 1. load [twitter4j.]restBaseURL<br> * 2. override the value with foo.[twitter4j.]restBaseURL<br> * 3. override the value with foo.bar.[twitter4j.]restBaseURL<br> * * @param props properties to be loaded * @param treePath the path */ private void setFieldsWithTreePath(Properties props, String treePath) { setFieldsWithPrefix(props, ""); String[] splitArray = treePath.split("/"); String prefix = null; for (String split : splitArray) { if (!"".equals(split)) { if (null == prefix) { prefix = split + "."; } else { prefix += split + "."; } setFieldsWithPrefix(props, prefix); } } } private void setFieldsWithPrefix(Properties props, String prefix) { if (notNull(props, prefix, DEBUG)) { setDebug(getBoolean(props, prefix, DEBUG)); } if (notNull(props, prefix, USER)) { setUser(getString(props, prefix, USER)); } if (notNull(props, prefix, PASSWORD)) { setPassword(getString(props, prefix, PASSWORD)); } if (notNull(props, prefix, HTTP_PRETTY_DEBUG)) { setPrettyDebugEnabled(getBoolean(props, prefix, HTTP_PRETTY_DEBUG)); } if (notNull(props, prefix, HTTP_GZIP)) { setGZIPEnabled(getBoolean(props, prefix, HTTP_GZIP)); } if (notNull(props, prefix, HTTP_PROXY_HOST)) { setHttpProxyHost(getString(props, prefix, HTTP_PROXY_HOST)); } else if (notNull(props, prefix, HTTP_PROXY_HOST_FALLBACK)) { setHttpProxyHost(getString(props, prefix, HTTP_PROXY_HOST_FALLBACK)); } if (notNull(props, prefix, HTTP_PROXY_USER)) { setHttpProxyUser(getString(props, prefix, HTTP_PROXY_USER)); } if (notNull(props, prefix, HTTP_PROXY_PASSWORD)) { setHttpProxyPassword(getString(props, prefix, HTTP_PROXY_PASSWORD)); } if (notNull(props, prefix, HTTP_PROXY_PORT)) { setHttpProxyPort(getIntProperty(props, prefix, HTTP_PROXY_PORT)); } else if (notNull(props, prefix, HTTP_PROXY_PORT_FALLBACK)) { setHttpProxyPort(getIntProperty(props, prefix, HTTP_PROXY_PORT_FALLBACK)); } if (notNull(props, prefix, HTTP_CONNECTION_TIMEOUT)) { setHttpConnectionTimeout(getIntProperty(props, prefix, HTTP_CONNECTION_TIMEOUT)); } if (notNull(props, prefix, HTTP_READ_TIMEOUT)) { setHttpReadTimeout(getIntProperty(props, prefix, HTTP_READ_TIMEOUT)); } if (notNull(props, prefix, HTTP_STREAMING_READ_TIMEOUT)) { setHttpStreamingReadTimeout(getIntProperty(props, prefix, HTTP_STREAMING_READ_TIMEOUT)); } if (notNull(props, prefix, HTTP_RETRY_COUNT)) { setHttpRetryCount(getIntProperty(props, prefix, HTTP_RETRY_COUNT)); } if (notNull(props, prefix, HTTP_RETRY_INTERVAL_SECS)) { setHttpRetryIntervalSeconds(getIntProperty(props, prefix, HTTP_RETRY_INTERVAL_SECS)); } if (notNull(props, prefix, OAUTH_CONSUMER_KEY)) { setOAuthConsumerKey(getString(props, prefix, OAUTH_CONSUMER_KEY)); } if (notNull(props, prefix, OAUTH_CONSUMER_SECRET)) { setOAuthConsumerSecret(getString(props, prefix, OAUTH_CONSUMER_SECRET)); } if (notNull(props, prefix, OAUTH_ACCESS_TOKEN)) { setOAuthAccessToken(getString(props, prefix, OAUTH_ACCESS_TOKEN)); } if (notNull(props, prefix, OAUTH_ACCESS_TOKEN_SECRET)) { setOAuthAccessTokenSecret(getString(props, prefix, OAUTH_ACCESS_TOKEN_SECRET)); } if (notNull(props, prefix, OAUTH2_TOKEN_TYPE)) { setOAuth2TokenType(getString(props, prefix, OAUTH2_TOKEN_TYPE)); } if (notNull(props, prefix, OAUTH2_ACCESS_TOKEN)) { setOAuth2AccessToken(getString(props, prefix, OAUTH2_ACCESS_TOKEN)); } if (notNull(props, prefix, OAUTH2_SCOPE)) { setOAuth2Scope(getString(props, prefix, OAUTH2_SCOPE)); } if (notNull(props, prefix, ASYNC_NUM_THREADS)) { setAsyncNumThreads(getIntProperty(props, prefix, ASYNC_NUM_THREADS)); } if (notNull(props, prefix, ASYNC_DAEMON_ENABLED)) { setDaemonEnabled(getBoolean(props, prefix, ASYNC_DAEMON_ENABLED)); } if (notNull(props, prefix, CONTRIBUTING_TO)) { setContributingTo(getLongProperty(props, prefix, CONTRIBUTING_TO)); } if (notNull(props, prefix, ASYNC_DISPATCHER_IMPL)) { setDispatcherImpl(getString(props, prefix, ASYNC_DISPATCHER_IMPL)); } if (notNull(props, prefix, OAUTH_REQUEST_TOKEN_URL)) { setOAuthRequestTokenURL(getString(props, prefix, OAUTH_REQUEST_TOKEN_URL)); } if (notNull(props, prefix, OAUTH_AUTHORIZATION_URL)) { setOAuthAuthorizationURL(getString(props, prefix, OAUTH_AUTHORIZATION_URL)); } if (notNull(props, prefix, OAUTH_ACCESS_TOKEN_URL)) { setOAuthAccessTokenURL(getString(props, prefix, OAUTH_ACCESS_TOKEN_URL)); } if (notNull(props, prefix, OAUTH_AUTHENTICATION_URL)) { setOAuthAuthenticationURL(getString(props, prefix, OAUTH_AUTHENTICATION_URL)); } if (notNull(props, prefix, OAUTH2_TOKEN_URL)) { setOAuth2TokenURL(getString(props, prefix, OAUTH2_TOKEN_URL)); } if (notNull(props, prefix, OAUTH2_INVALIDATE_TOKEN_URL)) { setOAuth2InvalidateTokenURL(getString(props, prefix, OAUTH2_INVALIDATE_TOKEN_URL)); } if (notNull(props, prefix, REST_BASE_URL)) { setRestBaseURL(getString(props, prefix, REST_BASE_URL)); } if (notNull(props, prefix, STREAM_BASE_URL)) { setStreamBaseURL(getString(props, prefix, STREAM_BASE_URL)); } if (notNull(props, prefix, USER_STREAM_BASE_URL)) { setUserStreamBaseURL(getString(props, prefix, USER_STREAM_BASE_URL)); } if (notNull(props, prefix, SITE_STREAM_BASE_URL)) { setSiteStreamBaseURL(getString(props, prefix, SITE_STREAM_BASE_URL)); } if (notNull(props, prefix, INCLUDE_MY_RETWEET)) { setIncludeMyRetweetEnabled(getBoolean(props, prefix, INCLUDE_MY_RETWEET)); } if (notNull(props, prefix, INCLUDE_ENTITIES)) { setIncludeEntitiesEnabled(getBoolean(props, prefix, INCLUDE_ENTITIES)); } if (notNull(props, prefix, LOGGER_FACTORY)) { setLoggerFactory(getString(props, prefix, LOGGER_FACTORY)); } if (notNull(props, prefix, JSON_STORE_ENABLED)) { setJSONStoreEnabled(getBoolean(props, prefix, JSON_STORE_ENABLED)); } if (notNull(props, prefix, MBEAN_ENABLED)) { setMBeanEnabled(getBoolean(props, prefix, MBEAN_ENABLED)); } if (notNull(props, prefix, STREAM_USER_REPLIES_ALL)) { setUserStreamRepliesAllEnabled(getBoolean(props, prefix, STREAM_USER_REPLIES_ALL)); } if (notNull(props, prefix, STREAM_USER_WITH_FOLLOWINGS)) { setUserStreamWithFollowingsEnabled(getBoolean(props, prefix, STREAM_USER_WITH_FOLLOWINGS)); } if (notNull(props, prefix, STREAM_STALL_WARNINGS_ENABLED)) { setStallWarningsEnabled(getBoolean(props, prefix, STREAM_STALL_WARNINGS_ENABLED)); } if (notNull(props, prefix, APPLICATION_ONLY_AUTH_ENABLED)) { setApplicationOnlyAuthEnabled(getBoolean(props, prefix, APPLICATION_ONLY_AUTH_ENABLED)); } if (notNull(props, prefix, MEDIA_PROVIDER)) { setMediaProvider(getString(props, prefix, MEDIA_PROVIDER)); } if (notNull(props, prefix, MEDIA_PROVIDER_API_KEY)) { setMediaProviderAPIKey(getString(props, prefix, MEDIA_PROVIDER_API_KEY)); } if (notNull(props, prefix, MEDIA_PROVIDER_PARAMETERS)) { String[] propsAry = getString(props, prefix, MEDIA_PROVIDER_PARAMETERS).split("&"); Properties p = new Properties(); for (String str : propsAry) { String[] parameter = str.split("="); p.setProperty(parameter[0], parameter[1]); } setMediaProviderParameters(p); } cacheInstance(); } boolean getBoolean(Properties props, String prefix, String name) { String value = props.getProperty(prefix + name); return Boolean.valueOf(value); } int getIntProperty(Properties props, String prefix, String name) { String value = props.getProperty(prefix + name); try { return Integer.parseInt(value); } catch (NumberFormatException nfe) { return -1; } } long getLongProperty(Properties props, String prefix, String name) { String value = props.getProperty(prefix + name); try { return Long.parseLong(value); } catch (NumberFormatException nfe) { return -1L; } } String getString(Properties props, String prefix, String name) { return props.getProperty(prefix + name); } // assures equality after deserialization @Override protected Object readResolve() throws ObjectStreamException { return super.readResolve(); } }
apache-2.0
rokn/Count_Words_2015
testing/openjdk/jdk/src/share/classes/sun/nio/ch/AsynchronousServerSocketChannelImpl.java
7640
/* * Copyright (c) 2008, 2009, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package sun.nio.ch; import java.nio.channels.*; import java.net.SocketAddress; import java.net.SocketOption; import java.net.StandardSocketOptions; import java.net.InetSocketAddress; import java.io.FileDescriptor; import java.io.IOException; import java.util.Set; import java.util.HashSet; import java.util.Collections; import java.util.concurrent.Future; import java.util.concurrent.locks.ReadWriteLock; import java.util.concurrent.locks.ReentrantReadWriteLock; import sun.net.NetHooks; /** * Base implementation of AsynchronousServerSocketChannel. */ abstract class AsynchronousServerSocketChannelImpl extends AsynchronousServerSocketChannel implements Cancellable, Groupable { protected final FileDescriptor fd; // the local address to which the channel's socket is bound protected volatile SocketAddress localAddress = null; // need this lock to set local address private final Object stateLock = new Object(); // close support private ReadWriteLock closeLock = new ReentrantReadWriteLock(); private volatile boolean open = true; // set true when accept operation is cancelled private volatile boolean acceptKilled; AsynchronousServerSocketChannelImpl(AsynchronousChannelGroupImpl group) { super(group.provider()); this.fd = Net.serverSocket(true); } @Override public final boolean isOpen() { return open; } /** * Marks beginning of access to file descriptor/handle */ final void begin() throws IOException { closeLock.readLock().lock(); if (!isOpen()) throw new ClosedChannelException(); } /** * Marks end of access to file descriptor/handle */ final void end() { closeLock.readLock().unlock(); } /** * Invoked to close file descriptor/handle. */ abstract void implClose() throws IOException; @Override public final void close() throws IOException { // synchronize with any threads using file descriptor/handle closeLock.writeLock().lock(); try { if (!open) return; // already closed open = false; } finally { closeLock.writeLock().unlock(); } implClose(); } /** * Invoked by accept to accept connection */ abstract Future<AsynchronousSocketChannel> implAccept(Object attachment, CompletionHandler<AsynchronousSocketChannel,Object> handler); @Override public final Future<AsynchronousSocketChannel> accept() { return implAccept(null, null); } @Override @SuppressWarnings("unchecked") public final <A> void accept(A attachment, CompletionHandler<AsynchronousSocketChannel,? super A> handler) { if (handler == null) throw new NullPointerException("'handler' is null"); implAccept(attachment, (CompletionHandler<AsynchronousSocketChannel,Object>)handler); } final boolean isAcceptKilled() { return acceptKilled; } @Override public final void onCancel(PendingFuture<?,?> task) { acceptKilled = true; } @Override public final AsynchronousServerSocketChannel bind(SocketAddress local, int backlog) throws IOException { InetSocketAddress isa = (local == null) ? new InetSocketAddress(0) : Net.checkAddress(local); SecurityManager sm = System.getSecurityManager(); if (sm != null) sm.checkListen(isa.getPort()); try { begin(); synchronized (stateLock) { if (localAddress != null) throw new AlreadyBoundException(); NetHooks.beforeTcpBind(fd, isa.getAddress(), isa.getPort()); Net.bind(fd, isa.getAddress(), isa.getPort()); Net.listen(fd, backlog < 1 ? 50 : backlog); localAddress = Net.localAddress(fd); } } finally { end(); } return this; } @Override public final SocketAddress getLocalAddress() throws IOException { if (!isOpen()) throw new ClosedChannelException(); return localAddress; } @Override public final <T> AsynchronousServerSocketChannel setOption(SocketOption<T> name, T value) throws IOException { if (name == null) throw new NullPointerException(); if (!supportedOptions().contains(name)) throw new UnsupportedOperationException("'" + name + "' not supported"); try { begin(); Net.setSocketOption(fd, Net.UNSPEC, name, value); return this; } finally { end(); } } @Override @SuppressWarnings("unchecked") public final <T> T getOption(SocketOption<T> name) throws IOException { if (name == null) throw new NullPointerException(); if (!supportedOptions().contains(name)) throw new UnsupportedOperationException("'" + name + "' not supported"); try { begin(); return (T) Net.getSocketOption(fd, Net.UNSPEC, name); } finally { end(); } } private static class DefaultOptionsHolder { static final Set<SocketOption<?>> defaultOptions = defaultOptions(); private static Set<SocketOption<?>> defaultOptions() { HashSet<SocketOption<?>> set = new HashSet<SocketOption<?>>(2); set.add(StandardSocketOptions.SO_RCVBUF); set.add(StandardSocketOptions.SO_REUSEADDR); return Collections.unmodifiableSet(set); } } @Override public final Set<SocketOption<?>> supportedOptions() { return DefaultOptionsHolder.defaultOptions; } @Override public final String toString() { StringBuilder sb = new StringBuilder(); sb.append(this.getClass().getName()); sb.append('['); if (!isOpen()) sb.append("closed"); else { if (localAddress == null) { sb.append("unbound"); } else { sb.append(localAddress.toString()); } } sb.append(']'); return sb.toString(); } }
mit
jonesgithub/AndroidDynamicLoader
workspace/lib.bitmapfun/src/com/example/android/bitmapfun/util/ImageFetcher.java
10424
/* * Copyright (C) 2012 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.android.bitmapfun.util; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileDescriptor; import java.io.FileInputStream; import java.io.IOException; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.URL; import lib.bitmapfun.R; import android.content.Context; import android.graphics.Bitmap; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.os.Build; import android.util.Log; import android.widget.Toast; import com.dianping.loader.MyResources; /** * A simple subclass of {@link ImageResizer} that fetches and resizes images fetched from a URL. */ public class ImageFetcher extends ImageResizer { private static final String TAG = "ImageFetcher"; private static final int HTTP_CACHE_SIZE = 10 * 1024 * 1024; // 10MB private static final String HTTP_CACHE_DIR = "http"; private static final int IO_BUFFER_SIZE = 8 * 1024; private DiskLruCache mHttpDiskCache; private File mHttpCacheDir; private boolean mHttpDiskCacheStarting = true; private final Object mHttpDiskCacheLock = new Object(); private static final int DISK_CACHE_INDEX = 0; /** * Initialize providing a target image width and height for the processing images. * * @param context * @param imageWidth * @param imageHeight */ public ImageFetcher(Context context, int imageWidth, int imageHeight) { super(context, imageWidth, imageHeight); init(context); } /** * Initialize providing a single target image size (used for both width and height); * * @param context * @param imageSize */ public ImageFetcher(Context context, int imageSize) { super(context, imageSize); init(context); } private void init(Context context) { checkConnection(context); mHttpCacheDir = ImageCache.getDiskCacheDir(context, HTTP_CACHE_DIR); } @Override protected void initDiskCacheInternal() { super.initDiskCacheInternal(); initHttpDiskCache(); } private void initHttpDiskCache() { if (!mHttpCacheDir.exists()) { mHttpCacheDir.mkdirs(); } synchronized (mHttpDiskCacheLock) { if (ImageCache.getUsableSpace(mHttpCacheDir) > HTTP_CACHE_SIZE) { try { mHttpDiskCache = DiskLruCache.open(mHttpCacheDir, 1, 1, HTTP_CACHE_SIZE); Log.d(TAG, "HTTP cache initialized"); } catch (IOException e) { mHttpDiskCache = null; } } mHttpDiskCacheStarting = false; mHttpDiskCacheLock.notifyAll(); } } @Override protected void clearCacheInternal() { super.clearCacheInternal(); synchronized (mHttpDiskCacheLock) { if (mHttpDiskCache != null && !mHttpDiskCache.isClosed()) { try { mHttpDiskCache.delete(); Log.d(TAG, "HTTP cache cleared"); } catch (IOException e) { Log.e(TAG, "clearCacheInternal - " + e); } mHttpDiskCache = null; mHttpDiskCacheStarting = true; initHttpDiskCache(); } } } @Override protected void flushCacheInternal() { super.flushCacheInternal(); synchronized (mHttpDiskCacheLock) { if (mHttpDiskCache != null) { try { mHttpDiskCache.flush(); Log.d(TAG, "HTTP cache flushed"); } catch (IOException e) { Log.e(TAG, "flush - " + e); } } } } @Override protected void closeCacheInternal() { super.closeCacheInternal(); synchronized (mHttpDiskCacheLock) { if (mHttpDiskCache != null) { try { if (!mHttpDiskCache.isClosed()) { mHttpDiskCache.close(); mHttpDiskCache = null; Log.d(TAG, "HTTP cache closed"); } } catch (IOException e) { Log.e(TAG, "closeCacheInternal - " + e); } } } } /** * Simple network connection check. * * @param context */ private void checkConnection(Context context) { final ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); final NetworkInfo networkInfo = cm.getActiveNetworkInfo(); if (networkInfo == null || !networkInfo.isConnectedOrConnecting()) { CharSequence txt = MyResources.getResource(ImageFetcher.class) .getText(R.string.no_network_connection_toast); Toast.makeText(context, txt, Toast.LENGTH_LONG).show(); Log.e(TAG, "checkConnection - no connection found"); } } /** * The main process method, which will be called by the ImageWorker in the AsyncTask background * thread. * * @param data The data to load the bitmap, in this case, a regular http URL * @return The downloaded and resized bitmap */ private Bitmap processBitmap(String data) { Log.d(TAG, "processBitmap - " + data); final String key = ImageCache.hashKeyForDisk(data); FileDescriptor fileDescriptor = null; FileInputStream fileInputStream = null; DiskLruCache.Snapshot snapshot; synchronized (mHttpDiskCacheLock) { // Wait for disk cache to initialize while (mHttpDiskCacheStarting) { try { mHttpDiskCacheLock.wait(); } catch (InterruptedException e) {} } if (mHttpDiskCache != null) { try { snapshot = mHttpDiskCache.get(key); if (snapshot == null) { Log.d(TAG, "processBitmap, not found in http cache, downloading..."); DiskLruCache.Editor editor = mHttpDiskCache.edit(key); if (editor != null) { if (downloadUrlToStream(data, editor.newOutputStream(DISK_CACHE_INDEX))) { editor.commit(); } else { editor.abort(); } } snapshot = mHttpDiskCache.get(key); } if (snapshot != null) { fileInputStream = (FileInputStream) snapshot.getInputStream(DISK_CACHE_INDEX); fileDescriptor = fileInputStream.getFD(); } } catch (IOException e) { Log.e(TAG, "processBitmap - " + e); } catch (IllegalStateException e) { Log.e(TAG, "processBitmap - " + e); } finally { if (fileDescriptor == null && fileInputStream != null) { try { fileInputStream.close(); } catch (IOException e) {} } } } } Bitmap bitmap = null; if (fileDescriptor != null) { bitmap = decodeSampledBitmapFromDescriptor(fileDescriptor, mImageWidth, mImageHeight, getImageCache()); } if (fileInputStream != null) { try { fileInputStream.close(); } catch (IOException e) {} } return bitmap; } @Override protected Bitmap processBitmap(Object data) { return processBitmap(String.valueOf(data)); } /** * Download a bitmap from a URL and write the content to an output stream. * * @param urlString The URL to fetch * @return true if successful, false otherwise */ public boolean downloadUrlToStream(String urlString, OutputStream outputStream) { disableConnectionReuseIfNecessary(); HttpURLConnection urlConnection = null; BufferedOutputStream out = null; BufferedInputStream in = null; try { final URL url = new URL(urlString); urlConnection = (HttpURLConnection) url.openConnection(); in = new BufferedInputStream(urlConnection.getInputStream(), IO_BUFFER_SIZE); out = new BufferedOutputStream(outputStream, IO_BUFFER_SIZE); int b; while ((b = in.read()) != -1) { out.write(b); } return true; } catch (final IOException e) { Log.e(TAG, "Error in downloadBitmap - " + e); } finally { if (urlConnection != null) { urlConnection.disconnect(); } try { if (out != null) { out.close(); } if (in != null) { in.close(); } } catch (final IOException e) {} } return false; } /** * Workaround for bug pre-Froyo, see here for more info: * http://android-developers.blogspot.com/2011/09/androids-http-clients.html */ public static void disableConnectionReuseIfNecessary() { // HTTP connection reuse which was buggy pre-froyo if (Build.VERSION.SDK_INT < Build.VERSION_CODES.FROYO) { System.setProperty("http.keepAlive", "false"); } } }
mit
md-5/jdk10
src/java.xml/share/classes/com/sun/org/apache/xml/internal/utils/SerializableLocatorImpl.java
6171
/* * reserved comment block * DO NOT REMOVE OR ALTER! */ /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.sun.org.apache.xml.internal.utils; /** * The standard SAX implementation of LocatorImpl is not serializable, * limiting its utility as "a persistent snapshot of a locator". * This is a quick hack to make it so. Note that it makes more sense * in many cases to set up fields to hold this data rather than pointing * at another object... but that decision should be made on architectural * grounds rather than serializability. *<p> * It isn't clear whether subclassing LocatorImpl and adding serialization * methods makes more sense than copying it and just adding Serializable * to its interface. Since it's so simple, I've taken the latter approach * for now. * * @see org.xml.sax.helpers.LocatorImpl * @see org.xml.sax.Locator Locator * @since XalanJ2 * @author Joe Kesselman */ public class SerializableLocatorImpl implements org.xml.sax.Locator, java.io.Serializable { static final long serialVersionUID = -2660312888446371460L; /** * Zero-argument constructor. * * <p>SAX says "This will not normally be useful, since the main purpose * of this class is to make a snapshot of an existing Locator." In fact, * it _is_ sometimes useful when you want to construct a new Locator * pointing to a specific location... which, after all, is why the * setter methods are provided. * </p> */ public SerializableLocatorImpl () { } /** * Copy constructor. * * <p>Create a persistent copy of the current state of a locator. * When the original locator changes, this copy will still keep * the original values (and it can be used outside the scope of * DocumentHandler methods).</p> * * @param locator The locator to copy. */ public SerializableLocatorImpl (org.xml.sax.Locator locator) { setPublicId(locator.getPublicId()); setSystemId(locator.getSystemId()); setLineNumber(locator.getLineNumber()); setColumnNumber(locator.getColumnNumber()); } //////////////////////////////////////////////////////////////////// // Implementation of org.xml.sax.Locator //////////////////////////////////////////////////////////////////// /** * Return the saved public identifier. * * @return The public identifier as a string, or null if none * is available. * @see org.xml.sax.Locator#getPublicId * @see #setPublicId */ public String getPublicId () { return publicId; } /** * Return the saved system identifier. * * @return The system identifier as a string, or null if none * is available. * @see org.xml.sax.Locator#getSystemId * @see #setSystemId */ public String getSystemId () { return systemId; } /** * Return the saved line number (1-based). * * @return The line number as an integer, or -1 if none is available. * @see org.xml.sax.Locator#getLineNumber * @see #setLineNumber */ public int getLineNumber () { return lineNumber; } /** * Return the saved column number (1-based). * * @return The column number as an integer, or -1 if none is available. * @see org.xml.sax.Locator#getColumnNumber * @see #setColumnNumber */ public int getColumnNumber () { return columnNumber; } //////////////////////////////////////////////////////////////////// // Setters for the properties (not in org.xml.sax.Locator) //////////////////////////////////////////////////////////////////// /** * Set the public identifier for this locator. * * @param publicId The new public identifier, or null * if none is available. * @see #getPublicId */ public void setPublicId (String publicId) { this.publicId = publicId; } /** * Set the system identifier for this locator. * * @param systemId The new system identifier, or null * if none is available. * @see #getSystemId */ public void setSystemId (String systemId) { this.systemId = systemId; } /** * Set the line number for this locator (1-based). * * @param lineNumber The line number, or -1 if none is available. * @see #getLineNumber */ public void setLineNumber (int lineNumber) { this.lineNumber = lineNumber; } /** * Set the column number for this locator (1-based). * * @param columnNumber The column number, or -1 if none is available. * @see #getColumnNumber */ public void setColumnNumber (int columnNumber) { this.columnNumber = columnNumber; } //////////////////////////////////////////////////////////////////// // Internal state. //////////////////////////////////////////////////////////////////// /** * The public ID. * @serial */ private String publicId; /** * The system ID. * @serial */ private String systemId; /** * The line number. * @serial */ private int lineNumber; /** * The column number. * @serial */ private int columnNumber; } // end of LocatorImpl.java
gpl-2.0
bocheninc/L0
vendor/github.com/cockroachdb/c-rocksdb/internal/java/src/test/java/org/rocksdb/CompressionOptionsTest.java
667
// Copyright (c) 2011-present, Facebook, Inc. All rights reserved. // This source code is licensed under the BSD-style license found in the // LICENSE file in the root directory of this source tree. An additional grant // of patent rights can be found in the PATENTS file in the same directory. package org.rocksdb; import org.junit.Test; public class CompressionOptionsTest { @Test public void getCompressionType() { for (final CompressionType compressionType : CompressionType.values()) { String libraryName = compressionType.getLibraryName(); compressionType.equals(CompressionType.getCompressionType( libraryName)); } } }
gpl-3.0
maxkondr/onos-porta
core/net/src/main/java/org/onosproject/net/intent/impl/phase/package-info.java
721
/* * Copyright 2015 Open Networking Laboratory * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * Implementations of various intent processing phases. */ package org.onosproject.net.intent.impl.phase;
apache-2.0
YzPaul3/h2o-3
h2o-core/src/test/java/water/AtomicTest.java
2494
package water; import org.junit.*; import java.util.Arrays; import java.util.Random; public class AtomicTest extends TestUtil { @BeforeClass() public static void setup() { stall_till_cloudsize(3); } public Key makeKey(String n, boolean remote) { if(!remote) return Key.make(n); H2O cloud = H2O.CLOUD; H2ONode target = cloud._memary[0]; if( target == H2O.SELF ) target = cloud._memary[1]; return Key.make(n,(byte)1,Key.BUILT_IN_KEY,true,target); } // Simple wrapper class defining an array-of-keys that is serializable. private static class Ary extends Iced { public final Key[] _keys; Ary( Key[] keys ) { _keys = keys; } } private static class Append { static private void append(Key keys, final Key k) { new Atomic() { @Override public Value atomic(Value val) { Ary ks = val == null ? new Ary(new Key[0]) : (Ary)val.get(); Key[] keys = Arrays.copyOf(ks._keys,ks._keys.length+1); keys[keys.length-1]=k; return new Value(_key,new Ary(keys)); } }.invoke(keys); } } private void doBasic(Key k) { Value v = DKV.get(k); Assert.assertNull(v); Key a1 = Key.make("tatomic 1"); Append.append(k,a1); Key[] ks = new AutoBuffer(DKV.get(k).memOrLoad()).getA(Key.class); Assert.assertEquals(1, ks.length); Assert.assertEquals(a1, ks[0]); Key a2 = Key.make("tatomic 2"); Append.append(k,a2); ks = new AutoBuffer(DKV.get(k).memOrLoad()).getA(Key.class); Assert.assertEquals(2, ks.length); Assert.assertEquals(a1, ks[0]); Assert.assertEquals(a2, ks[1]); DKV.remove(k); } @Test public void testBasic() { doBasic(makeKey("basic", false)); } @Test public void testBasicRemote() { doBasic(makeKey("basicRemote", true)); } private void doLarge(Key k) { Value v = DKV.get(k); Assert.assertNull(v); Random r = new Random(1234567890123456789L); int total = 0; while( total < AutoBuffer.MTU*8 ) { byte[] kb = new byte[Key.KEY_LENGTH]; r.nextBytes(kb); Key nk = Key.make(kb); Append.append(k,nk); v = DKV.get(k); byte[] vb = v.memOrLoad(); Assert.assertArrayEquals(kb, Arrays.copyOfRange(vb, vb.length-kb.length, vb.length)); total = vb.length; } DKV.remove(k); } @Test public void testLarge() { doLarge(makeKey("large", false)); } @Test public void testLargeRemote() { doLarge(makeKey("largeRemote", true)); } }
apache-2.0
GaloisInc/hacrypto
src/Java/BouncyCastle/BouncyCastle-1.50/core/src/main/jdk1.1/java/security/cert/CertificateNotYetValidException.java
253
package java.security.cert; public class CertificateNotYetValidException extends CertificateException { public CertificateNotYetValidException() { } public CertificateNotYetValidException(String msg) { super(msg); } }
bsd-3-clause
vt09/bazel
src/main/java/com/google/devtools/build/lib/rules/java/SourcesJavaCompilationArgsProvider.java
2350
// Copyright 2014 Google Inc. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.devtools.build.lib.rules.java; import com.google.devtools.build.lib.analysis.TransitiveInfoProvider; import com.google.devtools.build.lib.concurrent.ThreadSafety.Immutable; /** * An interface that marks configured targets that can provide Java compilation arguments through * the 'srcs' attribute of Java rules. * * <p>In a perfect world, this would not be necessary for a million reasons, but * this world is far from perfect, thus, we need this. * * <p>Please do not implement this interface with configured target implementations. */ @Immutable public final class SourcesJavaCompilationArgsProvider implements TransitiveInfoProvider { private final JavaCompilationArgs javaCompilationArgs; private final JavaCompilationArgs recursiveJavaCompilationArgs; public SourcesJavaCompilationArgsProvider( JavaCompilationArgs javaCompilationArgs, JavaCompilationArgs recursiveJavaCompilationArgs) { this.javaCompilationArgs = javaCompilationArgs; this.recursiveJavaCompilationArgs = recursiveJavaCompilationArgs; } /** * Returns non-recursively collected Java compilation information for * building this target (called when strict_java_deps = 1). * * <p>Note that some of the parameters are still collected from the complete * transitive closure. The non-recursive collection applies mainly to * compile-time jars. */ public JavaCompilationArgs getJavaCompilationArgs() { return javaCompilationArgs; } /** * Returns recursively collected Java compilation information for building * this target (called when strict_java_deps = 0). */ public JavaCompilationArgs getRecursiveJavaCompilationArgs() { return recursiveJavaCompilationArgs; } }
apache-2.0
sventorben/cucumber-jvm
examples/java-webbit-websockets-selenium/src/test/java/cucumber/examples/java/websockets/NavigationStepdefs.java
887
package cucumber.examples.java.websockets; import cucumber.api.java.en.Given; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.WebDriverWait; public class NavigationStepdefs { private final WebDriver webDriver; public NavigationStepdefs(SharedDriver webDriver) { this.webDriver = webDriver; } @Given("^I am on the front page$") public void i_am_on_the_front_page() throws InterruptedException { webDriver.get("http://localhost:" + ServerHooks.PORT); // The input fields won't be enabled until the WebSocket has established // a connection. Wait for this to happen. WebDriverWait wait = new WebDriverWait(webDriver, 1); wait.until(ExpectedConditions.elementToBeClickable(By.id("celcius"))); } }
mit
gdarmont/mybatis-3
src/main/java/org/apache/ibatis/session/AutoMappingBehavior.java
1107
/* * Copyright 2009-2012 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.ibatis.session; /** * Specifies if and how MyBatis should automatically map columns to fields/properties. * * @author Eduardo Macarron */ public enum AutoMappingBehavior { /** * Disables auto-mapping. */ NONE, /** * Will only auto-map results with no nested result mappings defined inside. */ PARTIAL, /** * Will auto-map result mappings of any complexity (containing nested or otherwise). */ FULL }
apache-2.0
tiarebalbi/spring-boot
spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/servlet/JspTemplateAvailabilityProviderTests.java
2098
/* * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.boot.autoconfigure.web.servlet; import org.junit.jupiter.api.Test; import org.springframework.core.io.DefaultResourceLoader; import org.springframework.core.io.ResourceLoader; import org.springframework.mock.env.MockEnvironment; import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link JspTemplateAvailabilityProvider}. * * @author Yunkun Huang */ class JspTemplateAvailabilityProviderTests { private final JspTemplateAvailabilityProvider provider = new JspTemplateAvailabilityProvider(); private final ResourceLoader resourceLoader = new DefaultResourceLoader(); private final MockEnvironment environment = new MockEnvironment(); @Test void availabilityOfTemplateThatDoesNotExist() { assertThat(isTemplateAvailable("whatever")).isFalse(); } @Test void availabilityOfTemplateWithCustomPrefix() { this.environment.setProperty("spring.mvc.view.prefix", "classpath:/custom-templates/"); assertThat(isTemplateAvailable("custom.jsp")).isTrue(); } @Test void availabilityOfTemplateWithCustomSuffix() { this.environment.setProperty("spring.mvc.view.prefix", "classpath:/custom-templates/"); this.environment.setProperty("spring.mvc.view.suffix", ".jsp"); assertThat(isTemplateAvailable("suffixed")).isTrue(); } private boolean isTemplateAvailable(String view) { return this.provider.isTemplateAvailable(view, this.environment, getClass().getClassLoader(), this.resourceLoader); } }
apache-2.0
spring-projects/spring-boot
spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/mockmvc/WebMvcTestPrintOverrideIntegrationTests.java
2211
/* * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.boot.test.autoconfigure.web.servlet.mockmvc; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.autoconfigure.web.servlet.MockMvcPrint; import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; import org.springframework.boot.test.system.CapturedOutput; import org.springframework.boot.test.system.OutputCaptureExtension; import org.springframework.security.test.context.support.WithMockUser; import org.springframework.test.web.servlet.MockMvc; import static org.assertj.core.api.Assertions.assertThat; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; /** * Tests for {@link WebMvcTest @WebMvcTest} when a specific print option is defined. * * @author Phillip Webb */ @WebMvcTest @WithMockUser @AutoConfigureMockMvc(print = MockMvcPrint.NONE) @ExtendWith(OutputCaptureExtension.class) class WebMvcTestPrintOverrideIntegrationTests { @Autowired private MockMvc mvc; @Test void shouldNotPrint(CapturedOutput output) throws Exception { this.mvc.perform(get("/one")).andExpect(content().string("one")).andExpect(status().isOk()); assertThat(output).doesNotContain("Request URI = /one"); } }
apache-2.0
tkaefer/camunda-bpm-platform
engine/src/main/java/org/camunda/bpm/engine/form/StartFormData.java
948
/* Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.camunda.bpm.engine.form; import org.camunda.bpm.engine.repository.ProcessDefinition; /** Specific {@link FormData} for starting a new process instance. * * @author Tom Baeyens */ public interface StartFormData extends FormData { /** The process definition for which this form is starting a new process instance */ ProcessDefinition getProcessDefinition(); }
apache-2.0
cooldoger/cassandra
src/java/org/apache/cassandra/db/marshal/FloatType.java
5099
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.cassandra.db.marshal; import java.nio.ByteBuffer; import org.apache.cassandra.cql3.CQL3Type; import org.apache.cassandra.cql3.Constants; import org.apache.cassandra.cql3.Term; import org.apache.cassandra.serializers.TypeSerializer; import org.apache.cassandra.serializers.FloatSerializer; import org.apache.cassandra.serializers.MarshalException; import org.apache.cassandra.transport.ProtocolVersion; import org.apache.cassandra.utils.ByteBufferUtil; public class FloatType extends NumberType<Float> { public static final FloatType instance = new FloatType(); FloatType() {super(ComparisonType.CUSTOM);} // singleton public boolean isEmptyValueMeaningless() { return true; } @Override public boolean isFloatingPoint() { return true; } public int compareCustom(ByteBuffer o1, ByteBuffer o2) { if (!o1.hasRemaining() || !o2.hasRemaining()) return o1.hasRemaining() ? 1 : o2.hasRemaining() ? -1 : 0; return compose(o1).compareTo(compose(o2)); } public ByteBuffer fromString(String source) throws MarshalException { // Return an empty ByteBuffer for an empty string. if (source.isEmpty()) return ByteBufferUtil.EMPTY_BYTE_BUFFER; try { return decompose(Float.parseFloat(source)); } catch (NumberFormatException e1) { throw new MarshalException(String.format("Unable to make float from '%s'", source), e1); } } @Override public Term fromJSONObject(Object parsed) throws MarshalException { try { if (parsed instanceof String) return new Constants.Value(fromString((String) parsed)); else return new Constants.Value(getSerializer().serialize(((Number) parsed).floatValue())); } catch (ClassCastException exc) { throw new MarshalException(String.format( "Expected a float value, but got a %s: %s", parsed.getClass().getSimpleName(), parsed)); } } @Override public String toJSONString(ByteBuffer buffer, ProtocolVersion protocolVersion) { Float value = getSerializer().deserialize(buffer); // JSON does not support NaN, Infinity and -Infinity values. Most of the parser convert them into null. if (value.isNaN() || value.isInfinite()) return "null"; return value.toString(); } public CQL3Type asCQL3Type() { return CQL3Type.Native.FLOAT; } public TypeSerializer<Float> getSerializer() { return FloatSerializer.instance; } @Override public int valueLengthIfFixed() { return 4; } @Override protected int toInt(ByteBuffer value) { throw new UnsupportedOperationException(); } @Override protected float toFloat(ByteBuffer value) { return ByteBufferUtil.toFloat(value); } @Override protected double toDouble(ByteBuffer value) { return toFloat(value); } public ByteBuffer add(NumberType<?> leftType, ByteBuffer left, NumberType<?> rightType, ByteBuffer right) { return ByteBufferUtil.bytes(leftType.toFloat(left) + rightType.toFloat(right)); } public ByteBuffer substract(NumberType<?> leftType, ByteBuffer left, NumberType<?> rightType, ByteBuffer right) { return ByteBufferUtil.bytes(leftType.toFloat(left) - rightType.toFloat(right)); } public ByteBuffer multiply(NumberType<?> leftType, ByteBuffer left, NumberType<?> rightType, ByteBuffer right) { return ByteBufferUtil.bytes(leftType.toFloat(left) * rightType.toFloat(right)); } public ByteBuffer divide(NumberType<?> leftType, ByteBuffer left, NumberType<?> rightType, ByteBuffer right) { return ByteBufferUtil.bytes(leftType.toFloat(left) / rightType.toFloat(right)); } public ByteBuffer mod(NumberType<?> leftType, ByteBuffer left, NumberType<?> rightType, ByteBuffer right) { return ByteBufferUtil.bytes(leftType.toFloat(left) % rightType.toFloat(right)); } public ByteBuffer negate(ByteBuffer input) { return ByteBufferUtil.bytes(-toFloat(input)); } }
apache-2.0
sitexa/android-CommonSDK
simplecropimagelib/build/generated/source/buildConfig/debug/eu/janmuller/android/simplecropimage/BuildConfig.java
476
/** * Automatically generated file. DO NOT MODIFY */ package eu.janmuller.android.simplecropimage; public final class BuildConfig { public static final boolean DEBUG = Boolean.parseBoolean("true"); public static final String APPLICATION_ID = "eu.janmuller.android.simplecropimage"; public static final String BUILD_TYPE = "debug"; public static final String FLAVOR = ""; public static final int VERSION_CODE = 1; public static final String VERSION_NAME = ""; }
mit
lewie/openhab
bundles/binding/org.openhab.binding.tinkerforge/src/main/java/org/openhab/binding/tinkerforge/internal/model/MBrickletDustDetector.java
3792
/** * Copyright (c) 2010-2016 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.tinkerforge.internal.model; import java.math.BigDecimal; import org.openhab.binding.tinkerforge.internal.types.DecimalValue; import com.tinkerforge.BrickletDustDetector; /** * <!-- begin-user-doc --> * A representation of the model object '<em><b>MBricklet Dust Detector</b></em>'. * <!-- end-user-doc --> * * <p> * The following features are supported: * </p> * <ul> * <li>{@link org.openhab.binding.tinkerforge.internal.model.MBrickletDustDetector#getDeviceType <em>Device Type</em>} * </li> * <li>{@link org.openhab.binding.tinkerforge.internal.model.MBrickletDustDetector#getThreshold <em>Threshold</em>}</li> * </ul> * * @see org.openhab.binding.tinkerforge.internal.model.ModelPackage#getMBrickletDustDetector() * @model superTypes="org.openhab.binding.tinkerforge.internal.model.MDevice * <org.openhab.binding.tinkerforge.internal.model.TinkerBrickletDustDetector> * org.openhab.binding.tinkerforge.internal.model.MSensor * <org.openhab.binding.tinkerforge.internal.model.MDecimalValue> * org.openhab.binding.tinkerforge.internal.model.MTFConfigConsumer * <org.openhab.binding.tinkerforge.internal.model.TFBaseConfiguration> * org.openhab.binding.tinkerforge.internal.model.CallbackListener" * @generated */ public interface MBrickletDustDetector extends MDevice<BrickletDustDetector>, MSensor<DecimalValue>, MTFConfigConsumer<TFBaseConfiguration>, CallbackListener { /** * Returns the value of the '<em><b>Device Type</b></em>' attribute. * The default value is <code>"bricklet_dustdetector"</code>. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Device Type</em>' attribute isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * * @return the value of the '<em>Device Type</em>' attribute. * @see org.openhab.binding.tinkerforge.internal.model.ModelPackage#getMBrickletDustDetector_DeviceType() * @model default="bricklet_dustdetector" unique="false" changeable="false" * @generated */ String getDeviceType(); /** * Returns the value of the '<em><b>Threshold</b></em>' attribute. * The default value is <code>"0"</code>. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Threshold</em>' attribute isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * * @return the value of the '<em>Threshold</em>' attribute. * @see #setThreshold(BigDecimal) * @see org.openhab.binding.tinkerforge.internal.model.ModelPackage#getMBrickletDustDetector_Threshold() * @model default="0" unique="false" * @generated */ BigDecimal getThreshold(); /** * Sets the value of the '{@link org.openhab.binding.tinkerforge.internal.model.MBrickletDustDetector#getThreshold * <em>Threshold</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @param value the new value of the '<em>Threshold</em>' attribute. * @see #getThreshold() * @generated */ void setThreshold(BigDecimal value); /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @model annotation="http://www.eclipse.org/emf/2002/GenModel body=''" * @generated */ @Override void init(); } // MBrickletDustDetector
epl-1.0
FauxFaux/jdk9-langtools
test/tools/javac/6457284/T6457284.java
3245
/* * Copyright (c) 2006, 2015, 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 6457284 * @summary Internationalize "unnamed package" when the term is used in diagnostics * @author Peter von der Ah\u00e9 * @modules jdk.compiler/com.sun.tools.javac.api * jdk.compiler/com.sun.tools.javac.util */ import java.io.IOException; import java.net.URI; import javax.lang.model.element.Element; import com.sun.source.util.JavacTask; import com.sun.tools.javac.api.JavacTool; import com.sun.tools.javac.util.Context; import com.sun.tools.javac.util.List; import com.sun.tools.javac.util.JavacMessages; import javax.tools.*; public class T6457284 { static class MyFileObject extends SimpleJavaFileObject { public MyFileObject() { super(URI.create("myfo:/Test.java"), JavaFileObject.Kind.SOURCE); } public CharSequence getCharContent(boolean ignoreEncodingErrors) { return "class Test {}"; } } public static void main(String[] args) throws IOException { Context context = new Context(); MyMessages.preRegister(context); JavacTool tool = JavacTool.create(); JavacTask task = tool.getTask(null, null, null, null, null, List.of(new MyFileObject()), context); task.parse(); for (Element e : task.analyze()) { if (!e.getEnclosingElement().toString().equals("compiler.misc.unnamed.package")) throw new AssertionError(e.getEnclosingElement()); System.out.println("OK: " + e.getEnclosingElement()); return; } throw new AssertionError("No top-level classes!"); } static class MyMessages extends JavacMessages { static void preRegister(Context context) { context.put(messagesKey, new MyMessages()); } MyMessages() { super("com.sun.tools.javac.resources.compiler"); } public String getLocalizedString(String key, Object... args) { if (key.equals("compiler.misc.unnamed.package")) return key; else return super.getLocalizedString(key, args); } } }
gpl-2.0
kurtwalker/pentaho-kettle
ui/src/main/java/org/pentaho/di/ui/job/entries/special/JobEntrySpecialDialog.java
14740
/*! ****************************************************************************** * * Pentaho Data Integration * * Copyright (C) 2002-2018 by Hitachi Vantara : http://www.pentaho.com * ******************************************************************************* * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ******************************************************************************/ package org.pentaho.di.ui.job.entries.special; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.CCombo; import org.eclipse.swt.events.ModifyEvent; import org.eclipse.swt.events.ModifyListener; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.events.ShellAdapter; import org.eclipse.swt.events.ShellEvent; import org.eclipse.swt.layout.FillLayout; import org.eclipse.swt.layout.FormAttachment; import org.eclipse.swt.layout.FormData; import org.eclipse.swt.layout.FormLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Event; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Listener; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.Spinner; import org.eclipse.swt.widgets.Text; import org.pentaho.di.core.Const; import org.pentaho.di.i18n.BaseMessages; import org.pentaho.di.job.JobMeta; import org.pentaho.di.job.entries.special.JobEntrySpecial; import org.pentaho.di.job.entry.JobEntryDialogInterface; import org.pentaho.di.job.entry.JobEntryInterface; import org.pentaho.di.repository.Repository; import org.pentaho.di.ui.core.gui.GUIResource; import org.pentaho.di.ui.core.gui.WindowProperty; import org.pentaho.di.ui.job.dialog.JobDialog; import org.pentaho.di.ui.job.entry.JobEntryDialog; import org.pentaho.di.ui.trans.step.BaseStepDialog; public class JobEntrySpecialDialog extends JobEntryDialog implements JobEntryDialogInterface { private static Class<?> PKG = JobEntrySpecial.class; // for i18n purposes, needed by Translator2!! private static final String NOSCHEDULING = BaseMessages.getString( PKG, "JobSpecial.Type.NoScheduling" ); private static final String INTERVAL = BaseMessages.getString( PKG, "JobSpecial.Type.Interval" ); private static final String DAILY = BaseMessages.getString( PKG, "JobSpecial.Type.Daily" ); private static final String WEEKLY = BaseMessages.getString( PKG, "JobSpecial.Type.Weekly" ); private static final String MONTHLY = BaseMessages.getString( PKG, "JobSpecial.Type.Monthly" ); private Button wOK, wCancel; private Listener lsOK, lsCancel; private Shell shell; private SelectionAdapter lsDef; private JobEntrySpecial jobEntry; private boolean backupChanged; private Display display; private Button wRepeat; private Spinner wIntervalSeconds, wIntervalMinutes; private CCombo wType; private Spinner wHour; private Spinner wMinutes; private CCombo wDayOfWeek; private Spinner wDayOfMonth; private Label wlName; private Text wName; private FormData fdlName, fdName; public JobEntrySpecialDialog( Shell parent, JobEntryInterface jobEntryInt, Repository rep, JobMeta jobMeta ) { super( parent, jobEntryInt, rep, jobMeta ); jobEntry = (JobEntrySpecial) jobEntryInt; } public JobEntryInterface open() { Shell parent = getParent(); display = parent.getDisplay(); shell = new Shell( parent, props.getJobsDialogStyle() ); props.setLook( shell ); JobDialog.setShellImage( shell, jobEntry ); shell.setImage( GUIResource.getInstance().getImageStart() ); ModifyListener lsMod = new ModifyListener() { public void modifyText( ModifyEvent e ) { jobEntry.setChanged(); } }; backupChanged = jobEntry.hasChanged(); FormLayout formLayout = new FormLayout(); formLayout.marginWidth = Const.FORM_MARGIN; formLayout.marginHeight = Const.FORM_MARGIN; shell.setLayout( formLayout ); shell.setText( BaseMessages.getString( PKG, "JobSpecial.Dummy.Label" ) ); int margin = Const.MARGIN; int middle = props.getMiddlePct(); wlName = new Label( shell, SWT.RIGHT ); wlName.setText( BaseMessages.getString( PKG, "JobSpecial.Jobname.Label" ) ); props.setLook( wlName ); fdlName = new FormData(); fdlName.left = new FormAttachment( 0, 0 ); fdlName.right = new FormAttachment( middle, -margin ); fdlName.top = new FormAttachment( 0, margin ); wlName.setLayoutData( fdlName ); wName = new Text( shell, SWT.SINGLE | SWT.LEFT | SWT.BORDER ); props.setLook( wName ); wName.addModifyListener( lsMod ); fdName = new FormData(); fdName.left = new FormAttachment( middle, 0 ); fdName.top = new FormAttachment( 0, margin ); fdName.right = new FormAttachment( 100, 0 ); wName.setLayoutData( fdName ); BaseStepDialog.setSize( shell, 350, 120, true ); if ( !this.jobEntry.isDummy() ) { shell.setText( BaseMessages.getString( PKG, "JobSpecial.Scheduling.Label" ) ); wRepeat = new Button( shell, SWT.CHECK ); wRepeat.addListener( SWT.Selection, new Listener() { public void handleEvent( Event arg0 ) { enableDisableControls(); } } ); placeControl( shell, BaseMessages.getString( PKG, "JobSpecial.Repeat.Label" ), wRepeat, wName ); wType = new CCombo( shell, SWT.SINGLE | SWT.LEFT | SWT.BORDER ); wType.addModifyListener( lsMod ); wType.addListener( SWT.Selection, new Listener() { public void handleEvent( Event arg0 ) { enableDisableControls(); } } ); wType.add( NOSCHEDULING ); wType.add( INTERVAL ); wType.add( DAILY ); wType.add( WEEKLY ); wType.add( MONTHLY ); wType.setEditable( false ); wType.setVisibleItemCount( wType.getItemCount() ); placeControl( shell, BaseMessages.getString( PKG, "JobSpecial.Type.Label" ), wType, wRepeat ); wIntervalSeconds = new Spinner( shell, SWT.SINGLE | SWT.LEFT | SWT.BORDER ); wIntervalSeconds.setMinimum( 0 ); wIntervalSeconds.setMaximum( Integer.MAX_VALUE ); placeControl( shell, BaseMessages.getString( PKG, "JobSpecial.IntervalSeconds.Label" ), wIntervalSeconds, wType ); wIntervalMinutes = new Spinner( shell, SWT.SINGLE | SWT.LEFT | SWT.BORDER ); wIntervalMinutes.setMinimum( 0 ); wIntervalMinutes.setMaximum( Integer.MAX_VALUE ); placeControl( shell, BaseMessages.getString( PKG, "JobSpecial.IntervalMinutes.Label" ), wIntervalMinutes, wIntervalSeconds ); Composite time = new Composite( shell, SWT.NONE ); time.setLayout( new FillLayout() ); wHour = new Spinner( time, SWT.SINGLE | SWT.LEFT | SWT.BORDER ); wHour.setMinimum( 0 ); wHour.setMaximum( 23 ); wMinutes = new Spinner( time, SWT.SINGLE | SWT.LEFT | SWT.BORDER ); wMinutes.setMinimum( 0 ); wMinutes.setMaximum( 59 ); placeControl( shell, BaseMessages.getString( PKG, "JobSpecial.TimeOfDay.Label" ), time, wIntervalMinutes ); wDayOfWeek = new CCombo( shell, SWT.SINGLE | SWT.LEFT | SWT.BORDER ); wDayOfWeek.addModifyListener( lsMod ); wDayOfWeek.add( BaseMessages.getString( PKG, "JobSpecial.DayOfWeek.Sunday" ) ); wDayOfWeek.add( BaseMessages.getString( PKG, "JobSpecial.DayOfWeek.Monday" ) ); wDayOfWeek.add( BaseMessages.getString( PKG, "JobSpecial.DayOfWeek.Tuesday" ) ); wDayOfWeek.add( BaseMessages.getString( PKG, "JobSpecial.DayOfWeek.Wednesday" ) ); wDayOfWeek.add( BaseMessages.getString( PKG, "JobSpecial.DayOfWeek.Thursday" ) ); wDayOfWeek.add( BaseMessages.getString( PKG, "JobSpecial.DayOfWeek.Friday" ) ); wDayOfWeek.add( BaseMessages.getString( PKG, "JobSpecial.DayOfWeek.Saturday" ) ); wDayOfWeek.setEditable( false ); wDayOfWeek.setVisibleItemCount( wDayOfWeek.getItemCount() ); placeControl( shell, BaseMessages.getString( PKG, "JobSpecial.DayOfWeek.Label" ), wDayOfWeek, time ); wDayOfMonth = new Spinner( shell, SWT.SINGLE | SWT.LEFT | SWT.BORDER ); wDayOfMonth.addModifyListener( lsMod ); wDayOfMonth.setMinimum( 1 ); wDayOfMonth.setMaximum( 30 ); placeControl( shell, BaseMessages.getString( PKG, "JobSpecial.DayOfMonth.Label" ), wDayOfMonth, wDayOfWeek ); lsDef = new SelectionAdapter() { public void widgetDefaultSelected( SelectionEvent e ) { ok(); } }; wType.addSelectionListener( lsDef ); BaseStepDialog.setSize( shell, 370, 285, true ); } // Some buttons wOK = new Button( shell, SWT.PUSH ); wOK.setText( BaseMessages.getString( PKG, "System.Button.OK" ) ); wCancel = new Button( shell, SWT.PUSH ); wCancel.setText( BaseMessages.getString( PKG, "System.Button.Cancel" ) ); BaseStepDialog.positionBottomButtons( shell, new Button[] { wOK, wCancel }, margin, wDayOfMonth ); // Add listeners lsCancel = new Listener() { public void handleEvent( Event e ) { cancel(); } }; lsOK = new Listener() { public void handleEvent( Event e ) { ok(); } }; wOK.addListener( SWT.Selection, lsOK ); wCancel.addListener( SWT.Selection, lsCancel ); // Detect [X] or ALT-F4 or something that kills this window... shell.addShellListener( new ShellAdapter() { public void shellClosed( ShellEvent e ) { cancel(); } } ); getData(); enableDisableControls(); shell.open(); props.setDialogSize( shell, "JobSpecialDialogSize" ); while ( !shell.isDisposed() ) { if ( !display.readAndDispatch() ) { display.sleep(); } } return jobEntry; } public void dispose() { shell.setSize( 350, 120 ); WindowProperty winprop = new WindowProperty( shell ); props.setScreen( winprop ); shell.dispose(); } public void getData() { if ( !jobEntry.isDummy() ) { wRepeat.setSelection( jobEntry.isRepeat() ); wType.select( jobEntry.getSchedulerType() ); wIntervalSeconds.setSelection( jobEntry.getIntervalSeconds() ); wIntervalMinutes.setSelection( jobEntry.getIntervalMinutes() ); wHour.setSelection( jobEntry.getHour() ); wMinutes.setSelection( jobEntry.getMinutes() ); wDayOfWeek.select( jobEntry.getWeekDay() ); wDayOfMonth.setSelection( jobEntry.getDayOfMonth() ); wType.addSelectionListener( lsDef ); } wName.setText( jobEntry.getName() ); } private void cancel() { jobEntry.setChanged( backupChanged ); jobEntry = null; dispose(); } private void ok() { if ( !jobEntry.isDummy() ) { jobEntry.setRepeat( wRepeat.getSelection() ); jobEntry.setSchedulerType( wType.getSelectionIndex() ); jobEntry.setIntervalSeconds( wIntervalSeconds.getSelection() ); jobEntry.setIntervalMinutes( wIntervalMinutes.getSelection() ); jobEntry.setHour( wHour.getSelection() ); jobEntry.setMinutes( wMinutes.getSelection() ); jobEntry.setWeekDay( wDayOfWeek.getSelectionIndex() ); jobEntry.setDayOfMonth( wDayOfMonth.getSelection() ); } jobEntry.setName( wName.getText() ); dispose(); } private void placeControl( Shell pShell, String text, Control control, Control under ) { int middle = props.getMiddlePct(); int margin = Const.MARGIN; Label label = new Label( pShell, SWT.RIGHT ); label.setText( text ); props.setLook( label ); FormData formDataLabel = new FormData(); formDataLabel.left = new FormAttachment( 0, 0 ); if ( under != null ) { formDataLabel.top = new FormAttachment( under, margin ); } else { formDataLabel.top = new FormAttachment( 0, 0 ); } formDataLabel.right = new FormAttachment( middle, 0 ); label.setLayoutData( formDataLabel ); props.setLook( control ); FormData formDataControl = new FormData(); formDataControl.left = new FormAttachment( middle, 0 ); if ( under != null ) { formDataControl.top = new FormAttachment( under, margin ); } else { formDataControl.top = new FormAttachment( 0, 0 ); } formDataControl.right = new FormAttachment( 100, 0 ); control.setLayoutData( formDataControl ); } private void enableDisableControls() { if ( !jobEntry.isDummy() ) { // if(wRepeat.getSelection()) { wType.setEnabled( true ); if ( NOSCHEDULING.equals( wType.getText() ) ) { wIntervalSeconds.setEnabled( false ); wIntervalMinutes.setEnabled( false ); wDayOfWeek.setEnabled( false ); wDayOfMonth.setEnabled( false ); wHour.setEnabled( false ); wMinutes.setEnabled( false ); } else if ( INTERVAL.equals( wType.getText() ) ) { wIntervalSeconds.setEnabled( true ); wIntervalMinutes.setEnabled( true ); wDayOfWeek.setEnabled( false ); wDayOfMonth.setEnabled( false ); wHour.setEnabled( false ); wMinutes.setEnabled( false ); } else if ( DAILY.equals( wType.getText() ) ) { wIntervalSeconds.setEnabled( false ); wIntervalMinutes.setEnabled( false ); wDayOfWeek.setEnabled( false ); wDayOfMonth.setEnabled( false ); wHour.setEnabled( true ); wMinutes.setEnabled( true ); } else if ( WEEKLY.equals( wType.getText() ) ) { wIntervalSeconds.setEnabled( false ); wIntervalMinutes.setEnabled( false ); wDayOfWeek.setEnabled( true ); wDayOfMonth.setEnabled( false ); wHour.setEnabled( true ); wMinutes.setEnabled( true ); } else if ( MONTHLY.equals( wType.getText() ) ) { wIntervalSeconds.setEnabled( false ); wIntervalMinutes.setEnabled( false ); wDayOfWeek.setEnabled( false ); wDayOfMonth.setEnabled( true ); wHour.setEnabled( true ); wMinutes.setEnabled( true ); } // } else { // wType.setEnabled( false ); // wInterval.setEnabled( false ); // wDayOfWeek.setEnabled( false ); // wDayOfMonth.setEnabled( false ); // wHour.setEnabled( false ); // wMinutes.setEnabled( false ); } } }
apache-2.0
cymcsg/UltimateAndroid
deprecated/UltimateAndroidNormal/UltimateAndroidUi/src/com/marshalchen/common/uimodule/ImageFilter/Textures/MarbleTexture.java
2816
/* * HaoRan ImageFilter Classes v0.4 * Copyright (C) 2012 Zhenjun Dai * * 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. */ package com.marshalchen.common.uimodule.ImageFilter.Textures; import com.marshalchen.common.uimodule.ImageFilter.IImageFilter; import com.marshalchen.common.uimodule.ImageFilter.*; public class MarbleTexture implements ITextureGenerator { // Perlin noise function used for texture generation private PerlinNoise noise = new PerlinNoise( 1.0 / 32, 1.0, 0.65, 2 ); private int r; private double xPeriod = 5.0; private double yPeriod = 10.0; /// <summary> /// Initializes a new instance of the <see cref="MarbleTexture"/> class /// </summary> /// public MarbleTexture( ) { Reset( ); } /// <summary> /// Initializes a new instance of the <see cref="MarbleTexture"/> class /// </summary> /// /// <param name="xPeriod">XPeriod value</param> /// <param name="yPeriod">YPeriod value</param> /// public MarbleTexture( double xPeriod, double yPeriod ) { this.xPeriod = Math.max( 2.0, xPeriod); this.yPeriod = Math.max( 2.0, yPeriod); Reset( ); } /// <summary> /// Generate texture /// </summary> /// /// <param name="width">Texture's width</param> /// <param name="height">Texture's height</param> /// /// <returns>Two dimensional array of intensities</returns> /// /// <remarks>Generates new texture with specified dimension.</remarks> /// public float[][] Generate( int width, int height ) { float[][] texture = new float[height][width]; double xFact = xPeriod / width; double yFact = yPeriod / height; for ( int y = 0; y < height; y++ ) { for ( int x = 0; x < width; x++ ) { texture[y][x] = Math.min( 1.0f, (float) Math.abs( Math.sin( ( x * xFact + y * yFact + noise.Function2D( x + r, y + r ) ) * Math.PI ) ) ); } } return texture; } /// <summary> /// Reset generator /// </summary> /// /// <remarks>Regenerates internal random numbers.</remarks> /// public void Reset( ) { r = NoiseFilter.getRandomInt(1, 5000 ); } }
apache-2.0
glenux/contrib-mitro
mitro-core/java/server/src/co/mitro/core/servlets/CreateCustomer.java
3713
/******************************************************************************* * Copyright (c) 2013, 2014 Lectorius, Inc. * Authors: * Vijay Pandurangan (vijayp@mitro.co) * Evan Jones (ej@mitro.co) * Adam Hilss (ahilss@mitro.co) * * * 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/>. * * You can contact the authors at inbound@mitro.co. *******************************************************************************/ package co.mitro.core.servlets; import java.security.SecureRandom; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.keyczar.util.Base64Coder; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import co.mitro.core.server.Manager; import co.mitro.core.server.ManagerFactory; import co.mitro.core.server.data.DBGroup; import co.mitro.core.server.data.DBStripeCustomer; import com.google.common.base.Strings; @javax.servlet.annotation.WebServlet("/CreateCustomer") public class CreateCustomer extends MitroWebServlet { private static Logger logger = LoggerFactory.getLogger(CreateCustomer.class); private static final long serialVersionUID = 1L; private static final String PASSWORD = "cynif!gbg5OzHgmK"; private static final int TOKEN_LENGTH = 24; private static final SecureRandom RANDOM = new SecureRandom(); protected static String createToken() { byte[] token = new byte[TOKEN_LENGTH]; RANDOM.nextBytes(token); return Base64Coder.encodeWebSafe(token); } @Override protected void handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception { String password = request.getParameter("password"); if (!password.equals(PASSWORD)) { response.setStatus(HttpServletResponse.SC_FORBIDDEN); return; } String orgIdString = request.getParameter("org_id"); Integer orgId; if (Strings.isNullOrEmpty(orgIdString)) { response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Missing org_id parameter"); return; } try { orgId = new Integer(Integer.parseInt(orgIdString, 10)); } catch (NumberFormatException e) { response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Invalid org_id parameter"); return; } try (Manager mgr = ManagerFactory.getInstance().newManager()) { if (!mgr.stripeCustomerDao.queryForEq("org_id", orgId).isEmpty()) { response.getWriter().write("Customer already created"); return; } DBGroup org = mgr.groupDao.queryForId(orgId); assert(null != org); int numMembers = MutateOrganization.getMemberIdsAndPrivateGroupIdsForOrg(mgr, org).keySet().size(); logger.info("Creating payment for org {} of {} members", org.getName(), numMembers); DBStripeCustomer customer = new DBStripeCustomer(); customer.setOrgId(orgId); customer.setToken(createToken()); customer.setNumUsers(numMembers); mgr.stripeCustomerDao.create(customer); mgr.commitTransaction(); response.getWriter().write(customer.getToken()); } } }
gpl-3.0
apurtell/hadoop
hadoop-tools/hadoop-openstack/src/main/java/org/apache/hadoop/fs/swift/snative/SwiftFileStatus.java
3654
/* * 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.fs.swift.snative; import org.apache.hadoop.fs.FileStatus; import org.apache.hadoop.fs.Path; import org.apache.hadoop.fs.permission.FsPermission; /** * A subclass of {@link FileStatus} that contains the * Swift-specific rules of when a file is considered to be a directory. */ public class SwiftFileStatus extends FileStatus { public SwiftFileStatus() { } public SwiftFileStatus(long length, boolean isdir, int block_replication, long blocksize, long modification_time, Path path) { super(length, isdir, block_replication, blocksize, modification_time, path); } public SwiftFileStatus(long length, boolean isdir, int block_replication, long blocksize, long modification_time, long access_time, FsPermission permission, String owner, String group, Path path) { super(length, isdir, block_replication, blocksize, modification_time, access_time, permission, owner, group, path); } //HDFS2+ only public SwiftFileStatus(long length, boolean isdir, int block_replication, long blocksize, long modification_time, long access_time, FsPermission permission, String owner, String group, Path symlink, Path path) { super(length, isdir, block_replication, blocksize, modification_time, access_time, permission, owner, group, symlink, path); } /** * Declare that the path represents a directory, which in the * SwiftNativeFileSystem means "is a directory or a 0 byte file" * * @return true if the status is considered to be a file */ @Override public boolean isDirectory() { return super.isDirectory() || getLen() == 0; } /** * A entry is a file if it is not a directory. * By implementing it <i>and not marking as an override</i> this * subclass builds and runs in both Hadoop versions. * @return the opposite value to {@link #isDirectory()} */ @Override public boolean isFile() { return !this.isDirectory(); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(getClass().getSimpleName()); sb.append("{ "); sb.append("path=").append(getPath()); sb.append("; isDirectory=").append(isDirectory()); sb.append("; length=").append(getLen()); sb.append("; blocksize=").append(getBlockSize()); sb.append("; modification_time=").append(getModificationTime()); sb.append("}"); return sb.toString(); } }
apache-2.0
ankurmitujjain/incubator-zeppelin
zeppelin-interpreter/src/main/java/org/apache/zeppelin/display/AngularObject.java
6687
/* * 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.zeppelin.display; import java.util.LinkedList; import java.util.List; import java.util.Objects; import java.util.concurrent.ExecutorService; import org.apache.zeppelin.scheduler.ExecutorFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * AngularObject provides binding between back-end (interpreter) and front-end * User provided object will automatically synchronized with front-end side. * i.e. update from back-end will be sent to front-end, update from front-end will sent-to backend * * @param <T> */ public class AngularObject<T> { private String name; private T object; private transient AngularObjectListener listener; private transient List<AngularObjectWatcher> watchers = new LinkedList<AngularObjectWatcher>(); private String noteId; // noteId belonging to. null for global scope private String paragraphId; // paragraphId belongs to. null for notebook scope /** * Public constructor, neccessary for the deserialization when using Thrift angularRegistryPush() * Without public constructor, GSON library will instantiate the AngularObject using * serialization so the <strong>watchers</strong> list won't be initialized and will throw * NullPointerException the first time it is accessed */ public AngularObject() { } /** * To create new AngularObject, use AngularObjectRegistry.add() * * @param name name of object * @param o reference to user provided object to sent to front-end * @param noteId noteId belongs to. can be null * @param paragraphId paragraphId belongs to. can be null * @param listener event listener */ protected AngularObject(String name, T o, String noteId, String paragraphId, AngularObjectListener listener) { this.name = name; this.noteId = noteId; this.paragraphId = paragraphId; this.listener = listener; object = o; } /** * Get name of this object * @return name */ public String getName() { return name; } /** * Set noteId * @param noteId noteId belongs to. can be null */ public void setNoteId(String noteId) { this.noteId = noteId; } /** * Get noteId * @return noteId */ public String getNoteId() { return noteId; } /** * get ParagraphId * @return paragraphId */ public String getParagraphId() { return paragraphId; } /** * Set paragraphId * @param paragraphId paragraphId. can be null */ public void setParagraphId(String paragraphId) { this.paragraphId = paragraphId; } /** * Check if it is global scope object * @return true it is global scope */ public boolean isGlobal() { return noteId == null; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; AngularObject<?> that = (AngularObject<?>) o; return Objects.equals(name, that.name) && Objects.equals(noteId, that.noteId) && Objects.equals(paragraphId, that.paragraphId); } @Override public int hashCode() { return Objects.hash(name, noteId, paragraphId); } /** * Get value * @return */ public Object get() { return object; } /** * fire updated() event for listener * Note that it does not invoke watcher.watch() */ public void emit(){ if (listener != null) { listener.updated(this); } } /** * Set value * @param o reference to new user provided object */ public void set(T o) { set(o, true); } /** * Set value * @param o reference to new user provided object * @param emit false on skip firing event for listener. note that it does not skip invoke * watcher.watch() in any case */ public void set(T o, boolean emit) { final T before = object; final T after = o; object = o; if (emit) { emit(); } final Logger logger = LoggerFactory.getLogger(AngularObject.class); List<AngularObjectWatcher> ws = new LinkedList<AngularObjectWatcher>(); synchronized (watchers) { ws.addAll(watchers); } ExecutorService executor = ExecutorFactory.singleton().createOrGet("angularObjectWatcher", 50); for (final AngularObjectWatcher w : ws) { executor.submit(new Runnable() { @Override public void run() { try { w.watch(before, after); } catch (Exception e) { logger.error("Exception on watch", e); } } }); } } /** * Set event listener for this object * @param listener */ public void setListener(AngularObjectListener listener) { this.listener = listener; } /** * Get event listener of this object * @return event listener */ public AngularObjectListener getListener() { return listener; } /** * Add a watcher for this object. * Multiple watcher can be registered. * * @param watcher watcher to add */ public void addWatcher(AngularObjectWatcher watcher) { synchronized (watchers) { watchers.add(watcher); } } /** * Remove a watcher from this object * @param watcher watcher to remove */ public void removeWatcher(AngularObjectWatcher watcher) { synchronized (watchers) { watchers.remove(watcher); } } /** * Remove all watchers from this object */ public void clearAllWatchers() { synchronized (watchers) { watchers.clear(); } } @Override public String toString() { final StringBuilder sb = new StringBuilder("AngularObject{"); sb.append("noteId='").append(noteId).append('\''); sb.append(", paragraphId='").append(paragraphId).append('\''); sb.append(", object=").append(object); sb.append(", name='").append(name).append('\''); sb.append('}'); return sb.toString(); } }
apache-2.0
isaacl/openjdk-jdk
src/share/classes/sun/tools/jstat/ParserException.java
1588
/* * Copyright (c) 2004, 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package sun.tools.jstat; /** * A class for describing exceptions generated by the Parser class. * * @author Brian Doherty * @since 1.5 */ @SuppressWarnings("serial") // JDK implementation class public class ParserException extends Exception { public ParserException() { super(); } public ParserException(String msg) { super(msg); } }
gpl-2.0
curso007/camel
components/camel-olingo4/camel-olingo4-api/src/main/java/org/apache/camel/component/olingo4/api/batch/Olingo4BatchQueryRequest.java
2752
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.camel.component.olingo4.api.batch; import java.util.Map; /** * Batch Query part. */ public class Olingo4BatchQueryRequest extends Olingo4BatchRequest { private Map<String, String> queryParams; public Map<String, String> getQueryParams() { return queryParams; } public static Olingo4BatchQueryRequestBuilder resourcePath(String resourcePath) { if (resourcePath == null) { throw new IllegalArgumentException("resourcePath"); } return new Olingo4BatchQueryRequestBuilder().resourcePath(resourcePath); } @Override public String toString() { return new StringBuilder("Batch Query Request{ ").append(resourceUri).append("/").append(resourcePath).append(", headers=").append(headers).append(", queryParams=") .append(queryParams).append('}').toString(); } public static class Olingo4BatchQueryRequestBuilder { private Olingo4BatchQueryRequest request = new Olingo4BatchQueryRequest(); public Olingo4BatchQueryRequest build() { // avoid later NPEs if (request.resourcePath == null) { throw new IllegalArgumentException("Null resourcePath"); } return request; } public Olingo4BatchQueryRequestBuilder resourceUri(String resourceUri) { request.resourceUri = resourceUri; return this; } public Olingo4BatchQueryRequestBuilder resourcePath(String resourcePath) { request.resourcePath = resourcePath; return this; } public Olingo4BatchQueryRequestBuilder headers(Map<String, String> headers) { request.headers = headers; return this; } public Olingo4BatchQueryRequestBuilder queryParams(Map<String, String> queryParams) { request.queryParams = queryParams; return this; } } }
apache-2.0
asedunov/intellij-community
java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/useBulkOperation/afterAnotherInstance.java
267
// "Replace iteration with bulk 'Collection.addAll' call" "true" import java.util.ArrayList; import java.util.List; class Sample { List<String> foo = new ArrayList<>(); String foo(){ Sample sm = new Sample(); sm.foo.addAll(foo); return null; } }
apache-2.0
amitsela/incubator-beam
sdks/java/core/src/test/java/org/apache/beam/sdk/transforms/windowing/AfterEachTest.java
2452
/* * 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.transforms.windowing; import static org.junit.Assert.assertEquals; import org.apache.beam.sdk.transforms.windowing.Trigger.OnceTrigger; import org.joda.time.Instant; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** * Tests for {@link AfterEach}. */ @RunWith(JUnit4.class) public class AfterEachTest { @Test public void testFireDeadline() throws Exception { BoundedWindow window = new IntervalWindow(new Instant(0), new Instant(10)); assertEquals(new Instant(9), AfterEach.inOrder(AfterWatermark.pastEndOfWindow(), AfterPane.elementCountAtLeast(4)) .getWatermarkThatGuaranteesFiring(window)); assertEquals(BoundedWindow.TIMESTAMP_MAX_VALUE, AfterEach.inOrder(AfterPane.elementCountAtLeast(2), AfterWatermark.pastEndOfWindow()) .getWatermarkThatGuaranteesFiring(window)); } @Test public void testContinuation() throws Exception { OnceTrigger trigger1 = AfterProcessingTime.pastFirstElementInPane(); OnceTrigger trigger2 = AfterWatermark.pastEndOfWindow(); Trigger afterEach = AfterEach.inOrder(trigger1, trigger2); assertEquals( Repeatedly.forever(AfterFirst.of( trigger1.getContinuationTrigger(), trigger2.getContinuationTrigger())), afterEach.getContinuationTrigger()); } @Test public void testToString() { Trigger trigger = AfterEach.inOrder( StubTrigger.named("t1"), StubTrigger.named("t2"), StubTrigger.named("t3")); assertEquals("AfterEach.inOrder(t1, t2, t3)", trigger.toString()); } }
apache-2.0
573196010/powermock
modules/module-impl/agent/src/main/java/org/powermock/objectweb/asm/Type.java
25611
/*** * ASM: a very small and fast Java bytecode manipulation framework * Copyright (c) 2000-2007 INRIA, France Telecom * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the copyright holders nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. */ package org.powermock.objectweb.asm; import java.lang.reflect.Constructor; import java.lang.reflect.Method; /** * A Java type. This class can be used to make it easier to manipulate type and * method descriptors. * * @author Eric Bruneton * @author Chris Nokleberg */ public class Type { /** * The sort of the <tt>void</tt> type. See {@link #getSort getSort}. */ public static final int VOID = 0; /** * The sort of the <tt>boolean</tt> type. See {@link #getSort getSort}. */ public static final int BOOLEAN = 1; /** * The sort of the <tt>char</tt> type. See {@link #getSort getSort}. */ public static final int CHAR = 2; /** * The sort of the <tt>byte</tt> type. See {@link #getSort getSort}. */ public static final int BYTE = 3; /** * The sort of the <tt>short</tt> type. See {@link #getSort getSort}. */ public static final int SHORT = 4; /** * The sort of the <tt>int</tt> type. See {@link #getSort getSort}. */ public static final int INT = 5; /** * The sort of the <tt>float</tt> type. See {@link #getSort getSort}. */ public static final int FLOAT = 6; /** * The sort of the <tt>long</tt> type. See {@link #getSort getSort}. */ public static final int LONG = 7; /** * The sort of the <tt>double</tt> type. See {@link #getSort getSort}. */ public static final int DOUBLE = 8; /** * The sort of array reference types. See {@link #getSort getSort}. */ public static final int ARRAY = 9; /** * The sort of object reference type. See {@link #getSort getSort}. */ public static final int OBJECT = 10; /** * The <tt>void</tt> type. */ public static final Type VOID_TYPE = new Type(VOID, null, ('V' << 24) | (5 << 16) | (0 << 8) | 0, 1); /** * The <tt>boolean</tt> type. */ public static final Type BOOLEAN_TYPE = new Type(BOOLEAN, null, ('Z' << 24) | (0 << 16) | (5 << 8) | 1, 1); /** * The <tt>char</tt> type. */ public static final Type CHAR_TYPE = new Type(CHAR, null, ('C' << 24) | (0 << 16) | (6 << 8) | 1, 1); /** * The <tt>byte</tt> type. */ public static final Type BYTE_TYPE = new Type(BYTE, null, ('B' << 24) | (0 << 16) | (5 << 8) | 1, 1); /** * The <tt>short</tt> type. */ public static final Type SHORT_TYPE = new Type(SHORT, null, ('S' << 24) | (0 << 16) | (7 << 8) | 1, 1); /** * The <tt>int</tt> type. */ public static final Type INT_TYPE = new Type(INT, null, ('I' << 24) | (0 << 16) | (0 << 8) | 1, 1); /** * The <tt>float</tt> type. */ public static final Type FLOAT_TYPE = new Type(FLOAT, null, ('F' << 24) | (2 << 16) | (2 << 8) | 1, 1); /** * The <tt>long</tt> type. */ public static final Type LONG_TYPE = new Type(LONG, null, ('J' << 24) | (1 << 16) | (1 << 8) | 2, 1); /** * The <tt>double</tt> type. */ public static final Type DOUBLE_TYPE = new Type(DOUBLE, null, ('D' << 24) | (3 << 16) | (3 << 8) | 2, 1); // ------------------------------------------------------------------------ // Fields // ------------------------------------------------------------------------ /** * The sort of this Java type. */ private final int sort; /** * A buffer containing the internal name of this Java type. This field is * only used for reference types. */ private final char[] buf; /** * The offset of the internal name of this Java type in {@link #buf buf} or, * for primitive types, the size, descriptor and getOpcode offsets for this * type (byte 0 contains the size, byte 1 the descriptor, byte 2 the offset * for IALOAD or IASTORE, byte 3 the offset for all other instructions). */ private final int off; /** * The length of the internal name of this Java type. */ private final int len; // ------------------------------------------------------------------------ // Constructors // ------------------------------------------------------------------------ /** * Constructs a reference type. * * @param sort the sort of the reference type to be constructed. * @param buf a buffer containing the descriptor of the previous type. * @param off the offset of this descriptor in the previous buffer. * @param len the length of this descriptor. */ private Type(final int sort, final char[] buf, final int off, final int len) { this.sort = sort; this.buf = buf; this.off = off; this.len = len; } /** * Returns the Java type corresponding to the given type descriptor. * * @param typeDescriptor a type descriptor. * @return the Java type corresponding to the given type descriptor. */ public static Type getType(final String typeDescriptor) { return getType(typeDescriptor.toCharArray(), 0); } /** * Returns the Java type corresponding to the given internal name. * * @param internalName an internal name. * @return the Java type corresponding to the given internal name. */ public static Type getObjectType(final String internalName) { char[] buf = internalName.toCharArray(); return new Type(buf[0] == '[' ? ARRAY : OBJECT, buf, 0, buf.length); } /** * Returns the Java type corresponding to the given class. * * @param c a class. * @return the Java type corresponding to the given class. */ public static Type getType(final Class c) { if (c.isPrimitive()) { if (c == Integer.TYPE) { return INT_TYPE; } else if (c == Void.TYPE) { return VOID_TYPE; } else if (c == Boolean.TYPE) { return BOOLEAN_TYPE; } else if (c == Byte.TYPE) { return BYTE_TYPE; } else if (c == Character.TYPE) { return CHAR_TYPE; } else if (c == Short.TYPE) { return SHORT_TYPE; } else if (c == Double.TYPE) { return DOUBLE_TYPE; } else if (c == Float.TYPE) { return FLOAT_TYPE; } else /* if (c == Long.TYPE) */{ return LONG_TYPE; } } else { return getType(getDescriptor(c)); } } /** * Returns the Java types corresponding to the argument types of the given * method descriptor. * * @param methodDescriptor a method descriptor. * @return the Java types corresponding to the argument types of the given * method descriptor. */ public static Type[] getArgumentTypes(final String methodDescriptor) { char[] buf = methodDescriptor.toCharArray(); int off = 1; int size = 0; while (true) { char car = buf[off++]; if (car == ')') { break; } else if (car == 'L') { while (buf[off++] != ';') { } ++size; } else if (car != '[') { ++size; } } Type[] args = new Type[size]; off = 1; size = 0; while (buf[off] != ')') { args[size] = getType(buf, off); off += args[size].len + (args[size].sort == OBJECT ? 2 : 0); size += 1; } return args; } /** * Returns the Java types corresponding to the argument types of the given * method. * * @param method a method. * @return the Java types corresponding to the argument types of the given * method. */ public static Type[] getArgumentTypes(final Method method) { Class[] classes = method.getParameterTypes(); Type[] types = new Type[classes.length]; for (int i = classes.length - 1; i >= 0; --i) { types[i] = getType(classes[i]); } return types; } /** * Returns the Java type corresponding to the return type of the given * method descriptor. * * @param methodDescriptor a method descriptor. * @return the Java type corresponding to the return type of the given * method descriptor. */ public static Type getReturnType(final String methodDescriptor) { char[] buf = methodDescriptor.toCharArray(); return getType(buf, methodDescriptor.indexOf(')') + 1); } /** * Returns the Java type corresponding to the return type of the given * method. * * @param method a method. * @return the Java type corresponding to the return type of the given * method. */ public static Type getReturnType(final Method method) { return getType(method.getReturnType()); } /** * Computes the size of the arguments and of the return value of a method. * * @param desc the descriptor of a method. * @return the size of the arguments of the method (plus one for the * implicit this argument), argSize, and the size of its return * value, retSize, packed into a single int i = * <tt>(argSize << 2) | retSize</tt> (argSize is therefore equal * to <tt>i >> 2</tt>, and retSize to <tt>i & 0x03</tt>). */ public static int getArgumentsAndReturnSizes(final String desc) { int n = 1; int c = 1; while (true) { char car = desc.charAt(c++); if (car == ')') { car = desc.charAt(c); return n << 2 | (car == 'V' ? 0 : (car == 'D' || car == 'J' ? 2 : 1)); } else if (car == 'L') { while (desc.charAt(c++) != ';') { } n += 1; } else if (car == '[') { while ((car = desc.charAt(c)) == '[') { ++c; } if (car == 'D' || car == 'J') { n -= 1; } } else if (car == 'D' || car == 'J') { n += 2; } else { n += 1; } } } /** * Returns the Java type corresponding to the given type descriptor. * * @param buf a buffer containing a type descriptor. * @param off the offset of this descriptor in the previous buffer. * @return the Java type corresponding to the given type descriptor. */ private static Type getType(final char[] buf, final int off) { int len; switch (buf[off]) { case 'V': return VOID_TYPE; case 'Z': return BOOLEAN_TYPE; case 'C': return CHAR_TYPE; case 'B': return BYTE_TYPE; case 'S': return SHORT_TYPE; case 'I': return INT_TYPE; case 'F': return FLOAT_TYPE; case 'J': return LONG_TYPE; case 'D': return DOUBLE_TYPE; case '[': len = 1; while (buf[off + len] == '[') { ++len; } if (buf[off + len] == 'L') { ++len; while (buf[off + len] != ';') { ++len; } } return new Type(ARRAY, buf, off, len + 1); // case 'L': default: len = 1; while (buf[off + len] != ';') { ++len; } return new Type(OBJECT, buf, off + 1, len - 1); } } // ------------------------------------------------------------------------ // Accessors // ------------------------------------------------------------------------ /** * Returns the sort of this Java type. * * @return {@link #VOID VOID}, {@link #BOOLEAN BOOLEAN}, * {@link #CHAR CHAR}, {@link #BYTE BYTE}, {@link #SHORT SHORT}, * {@link #INT INT}, {@link #FLOAT FLOAT}, {@link #LONG LONG}, * {@link #DOUBLE DOUBLE}, {@link #ARRAY ARRAY} or * {@link #OBJECT OBJECT}. */ public int getSort() { return sort; } /** * Returns the number of dimensions of this array type. This method should * only be used for an array type. * * @return the number of dimensions of this array type. */ public int getDimensions() { int i = 1; while (buf[off + i] == '[') { ++i; } return i; } /** * Returns the type of the elements of this array type. This method should * only be used for an array type. * * @return Returns the type of the elements of this array type. */ public Type getElementType() { return getType(buf, off + getDimensions()); } /** * Returns the name of the class corresponding to this type. * * @return the fully qualified name of the class corresponding to this type. */ public String getClassName() { switch (sort) { case VOID: return "void"; case BOOLEAN: return "boolean"; case CHAR: return "char"; case BYTE: return "byte"; case SHORT: return "short"; case INT: return "int"; case FLOAT: return "float"; case LONG: return "long"; case DOUBLE: return "double"; case ARRAY: StringBuffer b = new StringBuffer(getElementType().getClassName()); for (int i = getDimensions(); i > 0; --i) { b.append("[]"); } return b.toString(); // case OBJECT: default: return new String(buf, off, len).replace('/', '.'); } } /** * Returns the internal name of the class corresponding to this object or * array type. The internal name of a class is its fully qualified name (as * returned by Class.getName(), where '.' are replaced by '/'. This method * should only be used for an object or array type. * * @return the internal name of the class corresponding to this object type. */ public String getInternalName() { return new String(buf, off, len); } // ------------------------------------------------------------------------ // Conversion to type descriptors // ------------------------------------------------------------------------ /** * Returns the descriptor corresponding to this Java type. * * @return the descriptor corresponding to this Java type. */ public String getDescriptor() { StringBuffer buf = new StringBuffer(); getDescriptor(buf); return buf.toString(); } /** * Returns the descriptor corresponding to the given argument and return * types. * * @param returnType the return type of the method. * @param argumentTypes the argument types of the method. * @return the descriptor corresponding to the given argument and return * types. */ public static String getMethodDescriptor( final Type returnType, final Type[] argumentTypes) { StringBuffer buf = new StringBuffer(); buf.append('('); for (int i = 0; i < argumentTypes.length; ++i) { argumentTypes[i].getDescriptor(buf); } buf.append(')'); returnType.getDescriptor(buf); return buf.toString(); } /** * Appends the descriptor corresponding to this Java type to the given * string buffer. * * @param buf the string buffer to which the descriptor must be appended. */ private void getDescriptor(final StringBuffer buf) { if (this.buf == null) { // descriptor is in byte 3 of 'off' for primitive types (buf == null) buf.append((char) ((off & 0xFF000000) >>> 24)); } else if (sort == ARRAY) { buf.append(this.buf, off, len); } else { // sort == OBJECT buf.append('L'); buf.append(this.buf, off, len); buf.append(';'); } } // ------------------------------------------------------------------------ // Direct conversion from classes to type descriptors, // without intermediate Type objects // ------------------------------------------------------------------------ /** * Returns the internal name of the given class. The internal name of a * class is its fully qualified name, as returned by Class.getName(), where * '.' are replaced by '/'. * * @param c an object or array class. * @return the internal name of the given class. */ public static String getInternalName(final Class c) { return c.getName().replace('.', '/'); } /** * Returns the descriptor corresponding to the given Java type. * * @param c an object class, a primitive class or an array class. * @return the descriptor corresponding to the given class. */ public static String getDescriptor(final Class c) { StringBuffer buf = new StringBuffer(); getDescriptor(buf, c); return buf.toString(); } /** * Returns the descriptor corresponding to the given constructor. * * @param c a {@link Constructor Constructor} object. * @return the descriptor of the given constructor. */ public static String getConstructorDescriptor(final Constructor c) { Class[] parameters = c.getParameterTypes(); StringBuffer buf = new StringBuffer(); buf.append('('); for (int i = 0; i < parameters.length; ++i) { getDescriptor(buf, parameters[i]); } return buf.append(")V").toString(); } /** * Returns the descriptor corresponding to the given method. * * @param m a {@link Method Method} object. * @return the descriptor of the given method. */ public static String getMethodDescriptor(final Method m) { Class[] parameters = m.getParameterTypes(); StringBuffer buf = new StringBuffer(); buf.append('('); for (int i = 0; i < parameters.length; ++i) { getDescriptor(buf, parameters[i]); } buf.append(')'); getDescriptor(buf, m.getReturnType()); return buf.toString(); } /** * Appends the descriptor of the given class to the given string buffer. * * @param buf the string buffer to which the descriptor must be appended. * @param c the class whose descriptor must be computed. */ private static void getDescriptor(final StringBuffer buf, final Class c) { Class d = c; while (true) { if (d.isPrimitive()) { char car; if (d == Integer.TYPE) { car = 'I'; } else if (d == Void.TYPE) { car = 'V'; } else if (d == Boolean.TYPE) { car = 'Z'; } else if (d == Byte.TYPE) { car = 'B'; } else if (d == Character.TYPE) { car = 'C'; } else if (d == Short.TYPE) { car = 'S'; } else if (d == Double.TYPE) { car = 'D'; } else if (d == Float.TYPE) { car = 'F'; } else /* if (d == Long.TYPE) */{ car = 'J'; } buf.append(car); return; } else if (d.isArray()) { buf.append('['); d = d.getComponentType(); } else { buf.append('L'); String name = d.getName(); int len = name.length(); for (int i = 0; i < len; ++i) { char car = name.charAt(i); buf.append(car == '.' ? '/' : car); } buf.append(';'); return; } } } // ------------------------------------------------------------------------ // Corresponding size and opcodes // ------------------------------------------------------------------------ /** * Returns the size of values of this type. * * @return the size of values of this type, i.e., 2 for <tt>long</tt> and * <tt>double</tt>, 0 for <tt>void</tt> and 1 otherwise. */ public int getSize() { // the size is in byte 0 of 'off' for primitive types (buf == null) return buf == null ? (off & 0xFF) : 1; } /** * Returns a JVM instruction opcode adapted to this Java type. * * @param opcode a JVM instruction opcode. This opcode must be one of ILOAD, * ISTORE, IALOAD, IASTORE, IADD, ISUB, IMUL, IDIV, IREM, INEG, ISHL, * ISHR, IUSHR, IAND, IOR, IXOR and IRETURN. * @return an opcode that is similar to the given opcode, but adapted to * this Java type. For example, if this type is <tt>float</tt> and * <tt>opcode</tt> is IRETURN, this method returns FRETURN. */ public int getOpcode(final int opcode) { if (opcode == Opcodes.IALOAD || opcode == Opcodes.IASTORE) { // the offset for IALOAD or IASTORE is in byte 1 of 'off' for // primitive types (buf == null) return opcode + (buf == null ? (off & 0xFF00) >> 8 : 4); } else { // the offset for other instructions is in byte 2 of 'off' for // primitive types (buf == null) return opcode + (buf == null ? (off & 0xFF0000) >> 16 : 4); } } // ------------------------------------------------------------------------ // Equals, hashCode and toString // ------------------------------------------------------------------------ /** * Tests if the given object is equal to this type. * * @param o the object to be compared to this type. * @return <tt>true</tt> if the given object is equal to this type. */ public boolean equals(final Object o) { if (this == o) { return true; } if (!(o instanceof Type)) { return false; } Type t = (Type) o; if (sort != t.sort) { return false; } if (sort == OBJECT || sort == ARRAY) { if (len != t.len) { return false; } for (int i = off, j = t.off, end = i + len; i < end; i++, j++) { if (buf[i] != t.buf[j]) { return false; } } } return true; } /** * Returns a hash code value for this type. * * @return a hash code value for this type. */ public int hashCode() { int hc = 13 * sort; if (sort == OBJECT || sort == ARRAY) { for (int i = off, end = i + len; i < end; i++) { hc = 17 * (hc + buf[i]); } } return hc; } /** * Returns a string representation of this type. * * @return the descriptor of this type. */ public String toString() { return getDescriptor(); } }
apache-2.0
roboguy/pentaho-kettle
engine/src/main/java/org/pentaho/di/core/util/PluginProperty.java
2991
/*! ****************************************************************************** * * Pentaho Data Integration * * Copyright (C) 2002-2017 by Hitachi Vantara : http://www.pentaho.com * ******************************************************************************* * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ******************************************************************************/ package org.pentaho.di.core.util; import java.util.prefs.Preferences; import org.pentaho.di.core.exception.KettleException; import org.pentaho.di.repository.ObjectId; import org.pentaho.di.repository.Repository; import org.pentaho.metastore.api.IMetaStore; import org.w3c.dom.Node; /** * @author <a href="mailto:thomas.hoedl@aschauer-edv.at">Thomas Hoedl(asc042)</a> * */ public interface PluginProperty { /** * The default string value. */ String DEFAULT_STRING_VALUE = ""; /** * The default value. */ Boolean DEFAULT_BOOLEAN_VALUE = Boolean.FALSE; /** * The default integer value. */ Integer DEFAULT_INTEGER_VALUE = 0; /** * The default double value. */ Double DEFAULT_DOUBLE_VALUE = 0.0; /** * The true value. */ String BOOLEAN_STRING_TRUE = "Y"; /** * @return true if value not null or 'false'. */ boolean evaluate(); /** * @param node * preferences node */ void saveToPreferences( final Preferences node ); /** * @param node * preferences node. */ void readFromPreferences( final Preferences node ); /** * @param builder * builder to append to. */ void appendXml( final StringBuilder builder ); /** * @param node * the node. */ void loadXml( final Node node ); /** * @param repository * the repository. * @param metaStore * the MetaStore * @param transformationId * the transformationId. * @param stepId * the stepId. * @throws KettleException * ... */ void saveToRepositoryStep( final Repository repository, final IMetaStore metaStore, final ObjectId transformationId, final ObjectId stepId ) throws KettleException; /** * * @param repository * the repository. * @param stepId * the stepId. * @throws KettleException * ... */ void readFromRepositoryStep( final Repository repository, final IMetaStore metaStore, final ObjectId stepId ) throws KettleException; }
apache-2.0
aminmkhan/pentaho-kettle
engine/src/main/java/org/pentaho/di/www/SocketPortAllocation.java
5751
/*! ****************************************************************************** * * Pentaho Data Integration * * Copyright (C) 2002-2017 by Hitachi Vantara : http://www.pentaho.com * ******************************************************************************* * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ******************************************************************************/ package org.pentaho.di.www; import java.util.Date; public class SocketPortAllocation { private boolean allocated; private int port; private Date lastRequested; private String transformationName; private String clusterRunId; private String sourceSlaveName; private String sourceStepName; private String sourceStepCopy; private String targetSlaveName; private String targetStepName; private String targetStepCopy; /** * @param port * @param lastRequested * @param slaveName * @param transformationName * @param sourceStepName * @param sourceStepCopy */ public SocketPortAllocation( int port, Date lastRequested, String clusterRunId, String transformationName, String sourceSlaveName, String sourceStepName, String sourceStepCopy, String targetSlaveName, String targetStepName, String targetStepCopy ) { this.port = port; this.lastRequested = lastRequested; this.clusterRunId = clusterRunId; this.transformationName = transformationName; this.sourceSlaveName = sourceSlaveName; this.sourceStepName = sourceStepName; this.sourceStepCopy = sourceStepCopy; this.targetSlaveName = targetSlaveName; this.targetStepName = targetStepName; this.targetStepCopy = targetStepCopy; this.allocated = true; } /** * @return the port */ public int getPort() { return port; } /** * @param port * the port to set */ public void setPort( int port ) { this.port = port; } public boolean equals( Object obj ) { if ( obj == this ) { return true; } if ( !( obj instanceof SocketPortAllocation ) ) { return false; } SocketPortAllocation allocation = (SocketPortAllocation) obj; return allocation.getPort() == port; } public int hashCode() { return Integer.valueOf( port ).hashCode(); } /** * @return the lastRequested */ public Date getLastRequested() { return lastRequested; } /** * @param lastRequested * the lastRequested to set */ public void setLastRequested( Date lastRequested ) { this.lastRequested = lastRequested; } /** * @return the transformationName */ public String getTransformationName() { return transformationName; } /** * @param transformationName * the transformationName to set */ public void setTransformationName( String transformationName ) { this.transformationName = transformationName; } /** * @return the allocated */ public boolean isAllocated() { return allocated; } /** * @param allocated * the allocated to set */ public void setAllocated( boolean allocated ) { this.allocated = allocated; } /** * @return the sourceStepName */ public String getSourceStepName() { return sourceStepName; } /** * @param sourceStepName * the sourceStepName to set */ public void setSourceStepName( String sourceStepName ) { this.sourceStepName = sourceStepName; } /** * @return the sourceStepCopy */ public String getSourceStepCopy() { return sourceStepCopy; } /** * @param sourceStepCopy * the sourceStepCopy to set */ public void setSourceStepCopy( String sourceStepCopy ) { this.sourceStepCopy = sourceStepCopy; } /** * @return the targetStepName */ public String getTargetStepName() { return targetStepName; } /** * @param targetStepName * the targetStepName to set */ public void setTargetStepName( String targetStepName ) { this.targetStepName = targetStepName; } /** * @return the targetStepCopy */ public String getTargetStepCopy() { return targetStepCopy; } /** * @param targetStepCopy * the targetStepCopy to set */ public void setTargetStepCopy( String targetStepCopy ) { this.targetStepCopy = targetStepCopy; } /** * @return the sourceSlaveName */ public String getSourceSlaveName() { return sourceSlaveName; } /** * @param sourceSlaveName * the sourceSlaveName to set */ public void setSourceSlaveName( String sourceSlaveName ) { this.sourceSlaveName = sourceSlaveName; } /** * @return the targetSlaveName */ public String getTargetSlaveName() { return targetSlaveName; } /** * @param targetSlaveName * the targetSlaveName to set */ public void setTargetSlaveName( String targetSlaveName ) { this.targetSlaveName = targetSlaveName; } /** * @return the carteObjectId */ public String getClusterRunId() { return clusterRunId; } /** * @param clusterRunId * the carteObjectId to set */ public void setClusterRunId( String clusterRunId ) { this.clusterRunId = clusterRunId; } }
apache-2.0
tkafalas/pentaho-kettle
ui/src/main/java/org/pentaho/di/ui/core/dialog/EnterPrintDialog.java
15623
/*! ****************************************************************************** * * Pentaho Data Integration * * Copyright (C) 2002-2017 by Hitachi Vantara : http://www.pentaho.com * ******************************************************************************* * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ******************************************************************************/ package org.pentaho.di.ui.core.dialog; import org.eclipse.swt.SWT; import org.eclipse.swt.events.ModifyEvent; import org.eclipse.swt.events.ModifyListener; import org.eclipse.swt.events.PaintEvent; import org.eclipse.swt.events.PaintListener; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.events.ShellAdapter; import org.eclipse.swt.events.ShellEvent; import org.eclipse.swt.graphics.GC; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.graphics.ImageData; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.graphics.Rectangle; import org.eclipse.swt.layout.FormAttachment; import org.eclipse.swt.layout.FormData; import org.eclipse.swt.layout.FormLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Canvas; import org.eclipse.swt.widgets.Dialog; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Event; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Listener; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.Slider; import org.eclipse.swt.widgets.Text; import org.pentaho.di.core.Const; import org.pentaho.di.i18n.BaseMessages; import org.pentaho.di.ui.core.PropsUI; import org.pentaho.di.ui.core.gui.WindowProperty; import org.pentaho.di.ui.trans.step.BaseStepDialog; /** * A dialog that sets the printer settings for a Kettle printout. * * @author Matt * @since 19-06-2003 * */ public class EnterPrintDialog extends Dialog { private static Class<?> PKG = EnterPrintDialog.class; // for i18n purposes, needed by Translator2!! private int retval; private Image image; private Label wlCanvas; private Canvas wCanvas; private FormData fdlCanvas, fdCanvas; private Label wlCols; private Slider wCols; private FormData fdlCols, fdCols; private Label wlRows; private Slider wRows; private FormData fdlRows, fdRows; private Label wlScale; private Slider wScale; private FormData fdlScale, fdScale; private Label wlLeft; private Text wLeft; private FormData fdlLeft, fdLeft; private Label wlRight; private Text wRight; private FormData fdlRight, fdRight; private Label wlTop; private Text wTop; private FormData fdlTop, fdTop; private Label wlBottom; private Text wBottom; private FormData fdlBottom, fdBottom; private Button wOK, wCancel; private FormData fdOK, fdCancel; private Listener lsOK, lsCancel; private Shell shell; private PropsUI props; public int nrcols, nrrows, scale; public Point page; public double factorx, factory; public double leftMargin, rightMargin, topMargin, bottomMargin; public EnterPrintDialog( Shell parent, int nrcols, int nrrows, int scale, double factorX, double factorY, Rectangle m, double marginLeft, double marginRigth, double marginTop, double marginBottom, Image image ) { super( parent, SWT.NONE ); props = PropsUI.getInstance(); this.nrcols = nrcols; this.nrrows = nrrows; this.scale = scale; this.image = image; this.factorx = factorX; this.factory = factorY; this.leftMargin = marginLeft; this.rightMargin = marginRigth; this.topMargin = marginTop; this.bottomMargin = marginBottom; page = new Point( m.width, m.height ); } public int open() { Shell parent = getParent(); Display display = parent.getDisplay(); retval = SWT.OK; shell = new Shell( parent, SWT.DIALOG_TRIM | SWT.APPLICATION_MODAL | SWT.SHEET | SWT.RESIZE | SWT.MAX | SWT.MIN ); props.setLook( shell ); FormLayout formLayout = new FormLayout(); formLayout.marginWidth = Const.FORM_MARGIN; formLayout.marginHeight = Const.FORM_MARGIN; shell.setLayout( formLayout ); shell.setText( BaseMessages.getString( PKG, "EnterPrintDialog.Title" ) ); int middle = props.getMiddlePct(); int margin = Const.MARGIN; // Canvas wlCanvas = new Label( shell, SWT.NONE ); wlCanvas.setText( BaseMessages.getString( PKG, "EnterPrintDialog.PrintArea.Label" ) ); props.setLook( wlCanvas ); fdlCanvas = new FormData(); fdlCanvas.left = new FormAttachment( 0, 0 ); fdlCanvas.top = new FormAttachment( 0, margin ); wlCanvas.setLayoutData( fdlCanvas ); wCanvas = new Canvas( shell, SWT.BORDER ); props.setLook( wCanvas ); wCanvas.addPaintListener( new PaintListener() { public void paintControl( PaintEvent pe ) { repaint( pe.gc, pe.width, pe.height ); } } ); fdCanvas = new FormData(); fdCanvas.left = new FormAttachment( 0, 0 ); fdCanvas.top = new FormAttachment( wlCanvas, margin ); fdCanvas.right = new FormAttachment( 100, 0 ); fdCanvas.bottom = new FormAttachment( 100, -220 ); wCanvas.setLayoutData( fdCanvas ); // Rows wlRows = new Label( shell, SWT.NONE ); wlRows.setText( BaseMessages.getString( PKG, "EnterPrintDialog.Rows.Label" ) ); props.setLook( wlRows ); fdlRows = new FormData(); fdlRows.left = new FormAttachment( 0, 0 ); fdlRows.right = new FormAttachment( middle, -margin ); fdlRows.top = new FormAttachment( wCanvas, margin ); wlRows.setLayoutData( fdlRows ); wRows = new Slider( shell, SWT.HORIZONTAL ); wRows.setIncrement( 1 ); wRows.setMinimum( 1 ); wRows.setMaximum( 11 ); wRows.setThumb( 1 ); wRows.addSelectionListener( new SelectionAdapter() { public void widgetSelected( SelectionEvent se ) { Slider sl = (Slider) se.widget; nrrows = sl.getSelection(); wCanvas.redraw(); } } ); props.setLook( wRows ); fdRows = new FormData(); fdRows.left = new FormAttachment( middle, 0 ); fdRows.top = new FormAttachment( wCanvas, margin ); fdRows.right = new FormAttachment( 100, 0 ); wRows.setLayoutData( fdRows ); // Cols wlCols = new Label( shell, SWT.NONE ); wlCols.setText( BaseMessages.getString( PKG, "EnterPrintDialog.Cols.Label" ) ); props.setLook( wlCols ); fdlCols = new FormData(); fdlCols.left = new FormAttachment( 0, 0 ); fdlCols.right = new FormAttachment( middle, -margin ); fdlCols.top = new FormAttachment( wRows, margin ); wlCols.setLayoutData( fdlCols ); wCols = new Slider( shell, SWT.HORIZONTAL ); wCols.setIncrement( 1 ); wCols.setMinimum( 1 ); wCols.setMaximum( 11 ); wCols.setThumb( 1 ); wCols.addSelectionListener( new SelectionAdapter() { public void widgetSelected( SelectionEvent se ) { Slider sl = (Slider) se.widget; nrcols = sl.getSelection(); wCanvas.redraw(); } } ); props.setLook( wCols ); fdCols = new FormData(); fdCols.left = new FormAttachment( middle, 0 ); fdCols.top = new FormAttachment( wRows, margin ); fdCols.right = new FormAttachment( 100, 0 ); wCols.setLayoutData( fdCols ); // Scale wlScale = new Label( shell, SWT.NONE ); wlScale.setText( BaseMessages.getString( PKG, "EnterPrintDialog.Scaling.Label" ) ); props.setLook( wlScale ); fdlScale = new FormData(); fdlScale.left = new FormAttachment( 0, 0 ); fdlScale.right = new FormAttachment( middle, -margin ); fdlScale.top = new FormAttachment( wCols, margin ); wlScale.setLayoutData( fdlScale ); wScale = new Slider( shell, SWT.HORIZONTAL ); wScale.setIncrement( 10 ); wScale.setMinimum( 10 ); wScale.setMaximum( 500 ); wScale.setThumb( 10 ); wScale.setPageIncrement( 25 ); wScale.addSelectionListener( new SelectionAdapter() { public void widgetSelected( SelectionEvent se ) { Slider sl = (Slider) se.widget; scale = sl.getSelection(); wCanvas.redraw(); } } ); props.setLook( wScale ); fdScale = new FormData(); fdScale.left = new FormAttachment( middle, 0 ); fdScale.top = new FormAttachment( wCols, margin ); fdScale.right = new FormAttachment( 100, 0 ); wScale.setLayoutData( fdScale ); // Left wlLeft = new Label( shell, SWT.NONE ); wlLeft.setText( BaseMessages.getString( PKG, "EnterPrintDialog.LeftMargin.Label" ) ); props.setLook( wlLeft ); fdlLeft = new FormData(); fdlLeft.left = new FormAttachment( 0, 0 ); fdlLeft.right = new FormAttachment( middle, -margin ); fdlLeft.top = new FormAttachment( wScale, margin ); wlLeft.setLayoutData( fdlLeft ); wLeft = new Text( shell, SWT.BORDER ); wLeft.addModifyListener( new ModifyListener() { public void modifyText( ModifyEvent e ) { Text w = (Text) e.widget; leftMargin = Const.toDouble( w.getText(), 0.00 ); } } ); props.setLook( wLeft ); fdLeft = new FormData(); fdLeft.left = new FormAttachment( middle, 0 ); fdLeft.top = new FormAttachment( wScale, margin ); fdLeft.right = new FormAttachment( 100, 0 ); wLeft.setLayoutData( fdLeft ); // Right wlRight = new Label( shell, SWT.NONE ); wlRight.setText( BaseMessages.getString( PKG, "EnterPrintDialog.RightMargin.Label" ) ); props.setLook( wlRight ); fdlRight = new FormData(); fdlRight.left = new FormAttachment( 0, 0 ); fdlRight.right = new FormAttachment( middle, -margin ); fdlRight.top = new FormAttachment( wLeft, margin ); wlRight.setLayoutData( fdlRight ); wRight = new Text( shell, SWT.BORDER ); wRight.addModifyListener( new ModifyListener() { public void modifyText( ModifyEvent e ) { Text w = (Text) e.widget; rightMargin = Const.toDouble( w.getText(), 0.00 ); } } ); props.setLook( wRight ); fdRight = new FormData(); fdRight.left = new FormAttachment( middle, 0 ); fdRight.top = new FormAttachment( wLeft, margin ); fdRight.right = new FormAttachment( 100, 0 ); wRight.setLayoutData( fdRight ); // Top wlTop = new Label( shell, SWT.NONE ); wlTop.setText( BaseMessages.getString( PKG, "EnterPrintDialog.TopMargin.Label" ) ); props.setLook( wlTop ); fdlTop = new FormData(); fdlTop.left = new FormAttachment( 0, 0 ); fdlTop.right = new FormAttachment( middle, -margin ); fdlTop.top = new FormAttachment( wRight, margin ); wlTop.setLayoutData( fdlTop ); wTop = new Text( shell, SWT.BORDER ); wTop.addModifyListener( new ModifyListener() { public void modifyText( ModifyEvent e ) { Text w = (Text) e.widget; topMargin = Const.toDouble( w.getText(), 0.00 ); } } ); props.setLook( wTop ); fdTop = new FormData(); fdTop.left = new FormAttachment( middle, 0 ); fdTop.top = new FormAttachment( wRight, margin ); fdTop.right = new FormAttachment( 100, 0 ); wTop.setLayoutData( fdTop ); // Bottom wlBottom = new Label( shell, SWT.NONE ); wlBottom.setText( BaseMessages.getString( PKG, "EnterPrintDialog.BottomMargin.Label" ) ); props.setLook( wlBottom ); fdlBottom = new FormData(); fdlBottom.left = new FormAttachment( 0, 0 ); fdlBottom.right = new FormAttachment( middle, -margin ); fdlBottom.top = new FormAttachment( wTop, margin ); wlBottom.setLayoutData( fdlBottom ); wBottom = new Text( shell, SWT.BORDER ); wBottom.addModifyListener( new ModifyListener() { public void modifyText( ModifyEvent e ) { Text w = (Text) e.widget; bottomMargin = Const.toDouble( w.getText(), 0.00 ); } } ); props.setLook( wBottom ); fdBottom = new FormData(); fdBottom.left = new FormAttachment( middle, 0 ); fdBottom.top = new FormAttachment( wTop, margin ); fdBottom.right = new FormAttachment( 100, 0 ); wBottom.setLayoutData( fdBottom ); // Some buttons wOK = new Button( shell, SWT.PUSH ); wOK.setText( BaseMessages.getString( PKG, "System.Button.OK" ) ); wCancel = new Button( shell, SWT.PUSH ); wCancel.setText( BaseMessages.getString( PKG, "System.Button.Cancel" ) ); fdOK = new FormData(); fdOK.left = new FormAttachment( 33, 0 ); fdOK.bottom = new FormAttachment( 100, 0 ); wOK.setLayoutData( fdOK ); fdCancel = new FormData(); fdCancel.left = new FormAttachment( 66, 0 ); fdCancel.bottom = new FormAttachment( 100, 0 ); wCancel.setLayoutData( fdCancel ); // Add listeners lsCancel = new Listener() { public void handleEvent( Event e ) { cancel(); } }; lsOK = new Listener() { public void handleEvent( Event e ) { ok(); } }; wOK.addListener( SWT.Selection, lsOK ); wCancel.addListener( SWT.Selection, lsCancel ); // Detect [X] or ALT-F4 or something that kills this window... shell.addShellListener( new ShellAdapter() { public void shellClosed( ShellEvent e ) { cancel(); } } ); getData(); BaseStepDialog.setSize( shell ); shell.open(); while ( !shell.isDisposed() ) { if ( !display.readAndDispatch() ) { display.sleep(); } } return retval; } public void dispose() { props.setScreen( new WindowProperty( shell ) ); shell.dispose(); } public void getData() { wCols.setSelection( nrcols ); wRows.setSelection( nrrows ); wScale.setSelection( scale ); wLeft.setText( Double.toString( leftMargin ) ); wRight.setText( Double.toString( rightMargin ) ); wTop.setText( Double.toString( topMargin ) ); wBottom.setText( Double.toString( bottomMargin ) ); } private void cancel() { retval = SWT.CANCEL; dispose(); } private void ok() { nrcols = wCols.getSelection(); nrrows = wRows.getSelection(); scale = wScale.getSelection(); dispose(); } private void repaint( GC gc, int width, int height ) { ImageData imd = image.getImageData(); double sizeOnPaperX = imd.width * factorx; double sizeOnPaperY = imd.height * factory; double actualSizeX = sizeOnPaperX * scale / 100; double actualSizeY = sizeOnPaperY * scale / 100; // What % of the screen is filled? // The canvas is nrcols * nrrows nr of pages large. double percentScreenX = actualSizeX / ( page.x * nrcols ); double percentScreenY = actualSizeY / ( page.y * nrrows ); gc.drawImage( image, 0, 0, imd.width, imd.height, 0, 0, (int) ( width * percentScreenX ), (int) ( height * percentScreenY ) ); StringBuilder text = new StringBuilder(); text.append( nrcols ).append( "x" ).append( nrrows ).append( " @ " ).append( scale ).append( "%" ); gc.drawText( text.toString(), 0, 0 ); for ( int c = 1; c < nrcols; c++ ) { gc.drawLine( c * ( width / nrcols ), 0, c * ( width / nrcols ), height ); } for ( int r = 1; r < nrrows; r++ ) { gc.drawLine( 0, r * ( height / nrrows ), width, r * ( height / nrrows ) ); } } }
apache-2.0
dennishuo/hadoop
hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/fs/shell/TestPathData.java
9200
/** * 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.fs.shell; import static org.apache.hadoop.test.PlatformAssumptions.assumeWindows; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.io.File; import java.io.IOException; import java.net.URI; import java.util.Arrays; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.fs.permission.FsPermission; import org.apache.hadoop.test.GenericTestUtils; import org.apache.hadoop.util.Shell; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; public class TestPathData { private static final String TEST_ROOT_DIR = GenericTestUtils.getTestDir("testPD").getAbsolutePath(); protected Configuration conf; protected FileSystem fs; protected Path testDir; @Before public void initialize() throws Exception { conf = new Configuration(); fs = FileSystem.getLocal(conf); testDir = new Path(TEST_ROOT_DIR); // don't want scheme on the path, just an absolute path testDir = new Path(fs.makeQualified(testDir).toUri().getPath()); fs.mkdirs(testDir); FileSystem.setDefaultUri(conf, fs.getUri()); fs.setWorkingDirectory(testDir); fs.mkdirs(new Path("d1")); fs.createNewFile(new Path("d1", "f1")); fs.createNewFile(new Path("d1", "f1.1")); fs.createNewFile(new Path("d1", "f2")); fs.mkdirs(new Path("d2")); fs.create(new Path("d2","f3")); } @After public void cleanup() throws Exception { fs.delete(testDir, true); fs.close(); } @Test (timeout = 30000) public void testWithDirStringAndConf() throws Exception { String dirString = "d1"; PathData item = new PathData(dirString, conf); checkPathData(dirString, item); // properly implementing symlink support in various commands will require // trailing slashes to be retained dirString = "d1/"; item = new PathData(dirString, conf); checkPathData(dirString, item); } @Test (timeout = 30000) public void testUnqualifiedUriContents() throws Exception { String dirString = "d1"; PathData item = new PathData(dirString, conf); PathData[] items = item.getDirectoryContents(); assertEquals( sortedString("d1/f1", "d1/f1.1", "d1/f2"), sortedString(items) ); } @Test (timeout = 30000) public void testQualifiedUriContents() throws Exception { String dirString = fs.makeQualified(new Path("d1")).toString(); PathData item = new PathData(dirString, conf); PathData[] items = item.getDirectoryContents(); assertEquals( sortedString(dirString+"/f1", dirString+"/f1.1", dirString+"/f2"), sortedString(items) ); } @Test (timeout = 30000) public void testCwdContents() throws Exception { String dirString = Path.CUR_DIR; PathData item = new PathData(dirString, conf); PathData[] items = item.getDirectoryContents(); assertEquals( sortedString("d1", "d2"), sortedString(items) ); } @Test (timeout = 30000) public void testToFile() throws Exception { PathData item = new PathData(".", conf); assertEquals(new File(testDir.toString()), item.toFile()); item = new PathData("d1/f1", conf); assertEquals(new File(testDir + "/d1/f1"), item.toFile()); item = new PathData(testDir + "/d1/f1", conf); assertEquals(new File(testDir + "/d1/f1"), item.toFile()); } @Test (timeout = 5000) public void testToFileRawWindowsPaths() throws Exception { assumeWindows(); // Can we handle raw Windows paths? The files need not exist for // these tests to succeed. String[] winPaths = { "n:\\", "N:\\", "N:\\foo", "N:\\foo\\bar", "N:/", "N:/foo", "N:/foo/bar" }; PathData item; for (String path : winPaths) { item = new PathData(path, conf); assertEquals(new File(path), item.toFile()); } item = new PathData("foo\\bar", conf); assertEquals(new File(testDir + "\\foo\\bar"), item.toFile()); } @Test (timeout = 5000) public void testInvalidWindowsPath() throws Exception { assumeWindows(); // Verify that the following invalid paths are rejected. String [] winPaths = { "N:\\foo/bar" }; for (String path : winPaths) { try { PathData item = new PathData(path, conf); fail("Did not throw for invalid path " + path); } catch (IOException ioe) { } } } @Test (timeout = 30000) public void testAbsoluteGlob() throws Exception { PathData[] items = PathData.expandAsGlob(testDir+"/d1/f1*", conf); assertEquals( sortedString(testDir+"/d1/f1", testDir+"/d1/f1.1"), sortedString(items) ); String absolutePathNoDriveLetter = testDir+"/d1/f1"; if (Shell.WINDOWS) { // testDir is an absolute path with a drive letter on Windows, i.e. // c:/some/path // and for the test we want something like the following // /some/path absolutePathNoDriveLetter = absolutePathNoDriveLetter.substring(2); } items = PathData.expandAsGlob(absolutePathNoDriveLetter, conf); assertEquals( sortedString(absolutePathNoDriveLetter), sortedString(items) ); items = PathData.expandAsGlob(".", conf); assertEquals( sortedString("."), sortedString(items) ); } @Test (timeout = 30000) public void testRelativeGlob() throws Exception { PathData[] items = PathData.expandAsGlob("d1/f1*", conf); assertEquals( sortedString("d1/f1", "d1/f1.1"), sortedString(items) ); } @Test (timeout = 30000) public void testRelativeGlobBack() throws Exception { fs.setWorkingDirectory(new Path("d1")); PathData[] items = PathData.expandAsGlob("../d2/*", conf); assertEquals( sortedString("../d2/f3"), sortedString(items) ); } @Test public void testGlobThrowsExceptionForUnreadableDir() throws Exception { Path obscuredDir = new Path("foo"); Path subDir = new Path(obscuredDir, "bar"); //so foo is non-empty fs.mkdirs(subDir); fs.setPermission(obscuredDir, new FsPermission((short)0)); //no access try { PathData.expandAsGlob("foo/*", conf); Assert.fail("Should throw IOException"); } catch (IOException ioe) { // expected } finally { // make sure the test directory can be deleted fs.setPermission(obscuredDir, new FsPermission((short)0755)); //default } } @Test (timeout = 30000) public void testWithStringAndConfForBuggyPath() throws Exception { String dirString = "file:///tmp"; Path tmpDir = new Path(dirString); PathData item = new PathData(dirString, conf); // this may fail some day if Path is fixed to not crunch the uri // if the authority is null, however we need to test that the PathData // toString() returns the given string, while Path toString() does // the crunching assertEquals("file:/tmp", tmpDir.toString()); checkPathData(dirString, item); } public void checkPathData(String dirString, PathData item) throws Exception { assertEquals("checking fs", fs, item.fs); assertEquals("checking string", dirString, item.toString()); assertEquals("checking path", fs.makeQualified(new Path(item.toString())), item.path ); assertTrue("checking exist", item.stat != null); assertTrue("checking isDir", item.stat.isDirectory()); } /* junit does a lousy job of comparing arrays * if the array lengths differ, it just says that w/o showing contents * this sorts the paths, and builds a string of "i:<value>, ..." suitable * for a string compare */ private static String sortedString(Object ... list) { String[] strings = new String[list.length]; for (int i=0; i < list.length; i++) { strings[i] = String.valueOf(list[i]); } Arrays.sort(strings); StringBuilder result = new StringBuilder(); for (int i=0; i < strings.length; i++) { if (result.length() > 0) { result.append(", "); } result.append(i+":<"+strings[i]+">"); } return result.toString(); } private static String sortedString(PathData ... items) { return sortedString((Object[])items); } }
apache-2.0
Just-D/dex2jar
dex-translator/src/test/java/res/ConstValues.java
842
package res; public interface ConstValues { byte b1 = 0; byte b2 = -1; byte b3 = 1; byte b4 = 0x7F; short s1 = 0; short s2 = -1; short s3 = 1; short s4 = 0x7FFF; char c1 = 0; char c2 = 1; char c3 = 0x7FFF; int i1 = -1; int i2 = 0; int i3 = 0xFF; int i4 = 0xFFFF; int i5 = 0xFFFFFF; int i6 = 0x7FFFFFFF; float f1 = 0; float f2 = -1; float f3 = 1; float f4 = Float.MAX_VALUE; float f5 = Float.MIN_VALUE; double d1 = 0; double d2 = -1; double d3 = 1; double d4 = Double.MAX_VALUE; double d5 = Double.MIN_VALUE; long l1 = 0; long l2 = -1; long l3 = 1; long l4 = 0x7FFFFFFFFFFFFFFFL; boolean bl1 = true; boolean bl2 = false; Abc abc1 = null; Abc abc2 = Abc.X; enum Abc { X, Y } }
apache-2.0
Wesley-Lawrence/nifi
nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-properties-loader/src/main/java/org/apache/nifi/properties/MultipleSensitivePropertyProtectionException.java
5333
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.nifi.properties; import java.util.Collection; import java.util.HashSet; import java.util.Set; import org.apache.commons.lang3.StringUtils; public class MultipleSensitivePropertyProtectionException extends SensitivePropertyProtectionException { private Set<String> failedKeys; /** * Constructs a new throwable with {@code null} as its detail message. * The cause is not initialized, and may subsequently be initialized by a * call to {@link #initCause}. * <p> * <p>The {@link #fillInStackTrace()} method is called to initialize * the stack trace data in the newly created throwable. */ public MultipleSensitivePropertyProtectionException() { } /** * Constructs a new throwable with the specified detail message. The * cause is not initialized, and may subsequently be initialized by * a call to {@link #initCause}. * <p> * <p>The {@link #fillInStackTrace()} method is called to initialize * the stack trace data in the newly created throwable. * * @param message the detail message. The detail message is saved for * later retrieval by the {@link #getMessage()} method. */ public MultipleSensitivePropertyProtectionException(String message) { super(message); } /** * Constructs a new throwable with the specified detail message and * cause. <p>Note that the detail message associated with * {@code cause} is <i>not</i> automatically incorporated in * this throwable's detail message. * <p> * <p>The {@link #fillInStackTrace()} method is called to initialize * the stack trace data in the newly created throwable. * * @param message the detail message (which is saved for later retrieval * by the {@link #getMessage()} method). * @param cause the cause (which is saved for later retrieval by the * {@link #getCause()} method). (A {@code null} value is * permitted, and indicates that the cause is nonexistent or * unknown.) * @since 1.4 */ public MultipleSensitivePropertyProtectionException(String message, Throwable cause) { super(message, cause); } /** * Constructs a new throwable with the specified cause and a detail * message of {@code (cause==null ? null : cause.toString())} (which * typically contains the class and detail message of {@code cause}). * This constructor is useful for throwables that are little more than * wrappers for other throwables (for example, PrivilegedActionException). * <p> * <p>The {@link #fillInStackTrace()} method is called to initialize * the stack trace data in the newly created throwable. * * @param cause the cause (which is saved for later retrieval by the * {@link #getCause()} method). (A {@code null} value is * permitted, and indicates that the cause is nonexistent or * unknown.) * @since 1.4 */ public MultipleSensitivePropertyProtectionException(Throwable cause) { super(cause); } /** * Constructs a new exception with the provided message and a unique set of the keys that caused the error. * * @param message the message * @param failedKeys any failed keys */ public MultipleSensitivePropertyProtectionException(String message, Collection<String> failedKeys) { this(message, failedKeys, null); } /** * Constructs a new exception with the provided message and a unique set of the keys that caused the error. * * @param message the message * @param failedKeys any failed keys * @param cause the cause (which is saved for later retrieval by the * {@link #getCause()} method). (A {@code null} value is * permitted, and indicates that the cause is nonexistent or * unknown.) */ public MultipleSensitivePropertyProtectionException(String message, Collection<String> failedKeys, Throwable cause) { super(message, cause); this.failedKeys = new HashSet<>(failedKeys); } public Set<String> getFailedKeys() { return this.failedKeys; } @Override public String toString() { return "SensitivePropertyProtectionException for [" + StringUtils.join(this.failedKeys, ", ") + "]: " + getLocalizedMessage(); } }
apache-2.0
keshvari/cas
cas-server-webapp-support/src/main/java/org/jasig/cas/web/flow/InitialFlowSetupAction.java
6628
/* * Licensed to Apereo under one or more contributor license * agreements. See the NOTICE file distributed with this work * for additional information regarding copyright ownership. * Apereo 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 the following location: * * 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.jasig.cas.web.flow; import org.jasig.cas.authentication.principal.Service; import org.jasig.cas.services.RegisteredService; import org.jasig.cas.services.ServicesManager; import org.jasig.cas.services.UnauthorizedServiceException; import org.jasig.cas.web.support.ArgumentExtractor; import org.jasig.cas.web.support.CookieRetrievingCookieGenerator; import org.jasig.cas.web.support.WebUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.util.StringUtils; import org.springframework.webflow.action.AbstractAction; import org.springframework.webflow.execution.Event; import org.springframework.webflow.execution.RequestContext; import org.springframework.webflow.execution.repository.NoSuchFlowExecutionException; import javax.servlet.http.HttpServletRequest; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; import java.util.List; /** * Class to automatically set the paths for the CookieGenerators. * <p> * Note: This is technically not threadsafe, but because its overriding with a * constant value it doesn't matter. * <p> * Note: As of CAS 3.1, this is a required class that retrieves and exposes the * values in the two cookies for subclasses to use. * * @author Scott Battaglia * @since 3.1 */ public final class InitialFlowSetupAction extends AbstractAction { private final Logger logger = LoggerFactory.getLogger(this.getClass()); /** The services manager with access to the registry. **/ @NotNull private ServicesManager servicesManager; /** CookieGenerator for the Warnings. */ @NotNull private CookieRetrievingCookieGenerator warnCookieGenerator; /** CookieGenerator for the TicketGrantingTickets. */ @NotNull private CookieRetrievingCookieGenerator ticketGrantingTicketCookieGenerator; /** Extractors for finding the service. */ @NotNull @Size(min=1) private List<ArgumentExtractor> argumentExtractors; /** Boolean to note whether we've set the values on the generators or not. */ private boolean pathPopulated; /** If no authentication request from a service is present, halt and warn the user. */ private boolean enableFlowOnAbsentServiceRequest = true; @Override protected Event doExecute(final RequestContext context) throws Exception { final HttpServletRequest request = WebUtils.getHttpServletRequest(context); if (!this.pathPopulated) { final String contextPath = context.getExternalContext().getContextPath(); final String cookiePath = StringUtils.hasText(contextPath) ? contextPath + '/' : "/"; logger.info("Setting path for cookies to: {} ", cookiePath); this.warnCookieGenerator.setCookiePath(cookiePath); this.ticketGrantingTicketCookieGenerator.setCookiePath(cookiePath); this.pathPopulated = true; } WebUtils.putTicketGrantingTicketInScopes(context, this.ticketGrantingTicketCookieGenerator.retrieveCookieValue(request)); WebUtils.putWarningCookie(context, Boolean.valueOf(this.warnCookieGenerator.retrieveCookieValue(request))); final Service service = WebUtils.getService(this.argumentExtractors, context); if (service != null) { logger.debug("Placing service in context scope: [{}]", service.getId()); final RegisteredService registeredService = this.servicesManager.findServiceBy(service); if (registeredService != null && registeredService.getAccessStrategy().isServiceAccessAllowed()) { logger.debug("Placing registered service [{}] with id [{}] in context scope", registeredService.getServiceId(), registeredService.getId()); WebUtils.putRegisteredService(context, registeredService); } } else if (!this.enableFlowOnAbsentServiceRequest) { logger.warn("No service authentication request is available at [{}]. CAS is configured to disable the flow.", WebUtils.getHttpServletRequest(context).getRequestURL()); throw new NoSuchFlowExecutionException(context.getFlowExecutionContext().getKey(), new UnauthorizedServiceException("screen.service.required.message", "Service is required")); } WebUtils.putService(context, service); return result("success"); } public void setTicketGrantingTicketCookieGenerator( final CookieRetrievingCookieGenerator ticketGrantingTicketCookieGenerator) { this.ticketGrantingTicketCookieGenerator = ticketGrantingTicketCookieGenerator; } public void setWarnCookieGenerator(final CookieRetrievingCookieGenerator warnCookieGenerator) { this.warnCookieGenerator = warnCookieGenerator; } public void setArgumentExtractors(final List<ArgumentExtractor> argumentExtractors) { this.argumentExtractors = argumentExtractors; } /** * Set the service manager to allow access to the registry * to retrieve the registered service details associated * with an incoming service. * Since 4.1 * @param servicesManager the services manager */ public void setServicesManager(final ServicesManager servicesManager) { this.servicesManager = servicesManager; } /** * Decide whether CAS should allow authentication requests * when no service is present in the request. Default is enabled. * * @param enableFlowOnAbsentServiceRequest the enable flow on absent service request */ public void setEnableFlowOnAbsentServiceRequest(final boolean enableFlowOnAbsentServiceRequest) { this.enableFlowOnAbsentServiceRequest = enableFlowOnAbsentServiceRequest; } }
apache-2.0
poojits/CoreNLP
src/edu/stanford/nlp/patterns/surface/PatternsForEachTokenInMemory.java
3656
package edu.stanford.nlp.patterns.surface; import edu.stanford.nlp.io.IOUtils; import edu.stanford.nlp.patterns.Pattern; import edu.stanford.nlp.util.Execution; import edu.stanford.nlp.util.logging.Redwood; import java.io.File; import java.io.IOException; import java.util.*; import java.util.concurrent.ConcurrentHashMap; /** * Created by sonalg on 10/22/14. */ public class PatternsForEachTokenInMemory<E extends Pattern> extends PatternsForEachToken<E> { public static ConcurrentHashMap<String, Map<Integer, Set<? extends Pattern>>> patternsForEachToken = null; public PatternsForEachTokenInMemory(Properties props, Map<String, Map<Integer, Set<E>>> pats) { Execution.fillOptions(this, props); //TODO: make this atomic if(patternsForEachToken == null) patternsForEachToken = new ConcurrentHashMap<String, Map<Integer, Set<? extends Pattern>>>(); if (pats != null) addPatterns(pats); } public PatternsForEachTokenInMemory(Properties props) { this(props, null); } @Override public void addPatterns(String sentId, Map<Integer, Set<E>> patterns) { if (!patternsForEachToken.containsKey(sentId)) patternsForEachToken.put(sentId, new ConcurrentHashMap<Integer, Set<? extends Pattern>>()); patternsForEachToken.get(sentId).putAll(patterns); } @Override public void addPatterns(Map<String, Map<Integer, Set<E>>> pats) { for (Map.Entry<String, Map<Integer, Set<E>>> en : pats.entrySet()) { addPatterns(en.getKey(), en.getValue()); } } @Override public Map<Integer, Set<E>> getPatternsForAllTokens(String sentId) { return (Map<Integer, Set<E>>)(patternsForEachToken.containsKey(sentId) ? patternsForEachToken.get(sentId) : Collections.emptyMap()); } @Override public void setupSearch() { //nothing to do } // @Override // public ConcurrentHashIndex<SurfacePattern> readPatternIndex(String dir) throws IOException, ClassNotFoundException { // return IOUtils.readObjectFromFile(dir+"/patternshashindex.ser"); // } // // @Override // public void savePatternIndex(ConcurrentHashIndex<SurfacePattern> index, String dir) throws IOException { // if(dir != null){ // writePatternsIfInMemory(dir+"/allpatterns.ser"); // IOUtils.writeObjectToFile(index, dir+"/patternshashindex.ser"); // } // } @Override public Map<String, Map<Integer, Set<E>>> getPatternsForAllTokens(Collection<String> sampledSentIds) { Map<String, Map<Integer, Set<E>>> pats = new HashMap<String, Map<Integer, Set<E>>>(); for(String s: sampledSentIds){ pats.put(s, getPatternsForAllTokens(s)); } return pats; } @Override public void close() { //nothing to do } @Override public void load(String allPatternsDir) { try { addPatterns(IOUtils.readObjectFromFile(allPatternsDir+"/allpatterns.ser")); } catch (IOException e) { throw new RuntimeException(e); } catch (ClassNotFoundException e) { throw new RuntimeException(e); } } @Override public boolean save(String dir) { try { IOUtils.ensureDir(new File(dir)); String f = dir+"/allpatterns.ser"; IOUtils.writeObjectToFile(this.patternsForEachToken, f); Redwood.log(Redwood.DBG, "Saving the patterns to " + f); } catch (IOException e) { throw new RuntimeException(e); } return true; } @Override public void createIndexIfUsingDBAndNotExists() { //nothing to do return; } public boolean containsSentId(String sentId) { return this.patternsForEachToken.containsKey(sentId); } @Override public int size(){ return this.patternsForEachToken.size(); }; }
gpl-2.0
akosyakov/intellij-community
plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/codeInspection/type/GroovyTypeCheckVisitor.java
42862
/* * 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 org.jetbrains.plugins.groovy.codeInspection.type; import com.intellij.codeInspection.LocalQuickFix; import com.intellij.codeInspection.ProblemHighlightType; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.util.Condition; import com.intellij.psi.*; import com.intellij.psi.impl.PsiSubstitutorImpl; import com.intellij.psi.tree.IElementType; import com.intellij.psi.util.TypeConversionUtil; import com.intellij.util.Function; import com.intellij.util.containers.ContainerUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.PropertyKey; import org.jetbrains.plugins.groovy.GroovyBundle; import org.jetbrains.plugins.groovy.annotator.GrHighlightUtil; import org.jetbrains.plugins.groovy.codeInspection.BaseInspectionVisitor; import org.jetbrains.plugins.groovy.codeInspection.GroovyInspectionBundle; import org.jetbrains.plugins.groovy.codeInspection.assignment.*; import org.jetbrains.plugins.groovy.config.GroovyConfigUtils; import org.jetbrains.plugins.groovy.extensions.GroovyNamedArgumentProvider; import org.jetbrains.plugins.groovy.extensions.NamedArgumentDescriptor; import org.jetbrains.plugins.groovy.lang.lexer.GroovyTokenTypes; import org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElement; import org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElementFactory; import org.jetbrains.plugins.groovy.lang.psi.api.GroovyResolveResult; import org.jetbrains.plugins.groovy.lang.psi.api.auxiliary.GrListOrMap; import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrConstructorInvocation; import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrField; import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrVariable; import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrVariableDeclaration; import org.jetbrains.plugins.groovy.lang.psi.api.statements.arguments.GrArgumentList; import org.jetbrains.plugins.groovy.lang.psi.api.statements.arguments.GrNamedArgument; import org.jetbrains.plugins.groovy.lang.psi.api.statements.blocks.GrClosableBlock; import org.jetbrains.plugins.groovy.lang.psi.api.statements.branch.GrReturnStatement; import org.jetbrains.plugins.groovy.lang.psi.api.statements.branch.GrThrowStatement; import org.jetbrains.plugins.groovy.lang.psi.api.statements.clauses.GrForInClause; import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.*; import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.literals.GrString; import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.path.GrIndexProperty; import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.path.GrMethodCallExpression; import org.jetbrains.plugins.groovy.lang.psi.api.statements.params.GrParameter; import org.jetbrains.plugins.groovy.lang.psi.api.statements.params.GrParameterList; import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrBuilderMethod; import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrEnumConstant; import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrGdkMethod; import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrMethod; import org.jetbrains.plugins.groovy.lang.psi.api.types.GrCodeReferenceElement; import org.jetbrains.plugins.groovy.lang.psi.api.types.GrTypeElement; import org.jetbrains.plugins.groovy.lang.psi.impl.GrClosureType; import org.jetbrains.plugins.groovy.lang.psi.impl.PsiImplUtil; import org.jetbrains.plugins.groovy.lang.psi.impl.signatures.GrClosureSignatureUtil; import org.jetbrains.plugins.groovy.lang.psi.impl.statements.expressions.ConversionResult; import org.jetbrains.plugins.groovy.lang.psi.impl.statements.expressions.TypesUtil; import org.jetbrains.plugins.groovy.lang.psi.typeEnhancers.ClosureParameterEnhancer; import org.jetbrains.plugins.groovy.lang.psi.typeEnhancers.ClosureParamsEnhancer; import org.jetbrains.plugins.groovy.lang.psi.typeEnhancers.GrTypeConverter.ApplicableTo; import org.jetbrains.plugins.groovy.lang.psi.util.*; import org.jetbrains.plugins.groovy.lang.resolve.ResolveUtil; import java.util.List; import java.util.Map; import static com.intellij.psi.util.PsiUtil.extractIterableTypeParameter; import static org.jetbrains.plugins.groovy.codeInspection.type.GroovyTypeCheckVisitorHelper.*; public class GroovyTypeCheckVisitor extends BaseInspectionVisitor { private static final Logger LOG = Logger.getInstance(GroovyAssignabilityCheckInspection.class); private boolean checkCallApplicability(@Nullable PsiType type, boolean checkUnknownArgs, @NotNull CallInfo info) { PsiType[] argumentTypes = info.getArgumentTypes(); GrExpression invoked = info.getInvokedExpression(); if (invoked == null) return true; if (type instanceof GrClosureType) { if (argumentTypes == null) return true; GrClosureSignatureUtil.ApplicabilityResult result = PsiUtil.isApplicableConcrete(argumentTypes, (GrClosureType)type, info.getCall()); switch (result) { case inapplicable: registerCannotApplyError(invoked.getText(), info); return false; case canBeApplicable: if (checkUnknownArgs) { highlightUnknownArgs(info); } return !checkUnknownArgs; default: return true; } } else if (type != null) { final GroovyResolveResult[] calls = ResolveUtil.getMethodCandidates(type, "call", invoked, argumentTypes); for (GroovyResolveResult result : calls) { PsiElement resolved = result.getElement(); if (resolved instanceof PsiMethod && !result.isInvokedOnProperty()) { if (!checkMethodApplicability(result, checkUnknownArgs, info)) return false; } else if (resolved instanceof PsiField) { if (!checkCallApplicability(((PsiField)resolved).getType(), checkUnknownArgs && calls.length == 1, info)) return false; } } if (calls.length == 0 && !(invoked instanceof GrString)) { registerCannotApplyError(invoked.getText(), info); } return true; } return true; } private boolean checkCannotInferArgumentTypes(@NotNull CallInfo info) { if (info.getArgumentTypes() != null) { return true; } else { highlightUnknownArgs(info); return false; } } private <T extends GroovyPsiElement> boolean checkConstructorApplicability(@NotNull GroovyResolveResult constructorResolveResult, @NotNull CallInfo<T> info, boolean checkUnknownArgs) { final PsiElement element = constructorResolveResult.getElement(); LOG.assertTrue(element instanceof PsiMethod && ((PsiMethod)element).isConstructor(), element); final PsiMethod constructor = (PsiMethod)element; final GrArgumentList argList = info.getArgumentList(); if (argList != null) { final GrExpression[] exprArgs = argList.getExpressionArguments(); if (exprArgs.length == 0 && !PsiUtil.isConstructorHasRequiredParameters(constructor)) return true; } PsiType[] types = info.getArgumentTypes(); PsiClass containingClass = constructor.getContainingClass(); if (types != null && containingClass != null) { final PsiType[] newTypes = GrInnerClassConstructorUtil.addEnclosingArgIfNeeded(types, info.getCall(), containingClass); if (newTypes.length != types.length) { return checkMethodApplicability(constructorResolveResult, checkUnknownArgs, new DelegatingCallInfo<T>(info) { @Nullable @Override public PsiType[] getArgumentTypes() { return newTypes; } }); } } return checkMethodApplicability(constructorResolveResult, checkUnknownArgs, info); } private void processConstructorCall(@NotNull ConstructorCallInfo<?> info) { if (hasErrorElements(info.getArgumentList())) return; if (!checkCannotInferArgumentTypes(info)) return; final GroovyResolveResult constructorResolveResult = info.advancedResolve(); final PsiElement constructor = constructorResolveResult.getElement(); if (constructor != null) { if (!checkConstructorApplicability(constructorResolveResult, info, true)) return; } else { final GroovyResolveResult[] results = info.multiResolve(); if (results.length > 0) { for (GroovyResolveResult result : results) { PsiElement resolved = result.getElement(); if (resolved instanceof PsiMethod) { if (!checkConstructorApplicability(result, info, false)) return; } } registerError( info.getElementToHighlight(), GroovyBundle.message("constructor.call.is.ambiguous"), null, ProblemHighlightType.GENERIC_ERROR ); } else { final GrExpression[] expressionArguments = info.getExpressionArguments(); final boolean hasClosureArgs = info.getClosureArguments().length > 0; final boolean hasNamedArgs = info.getNamedArguments().length > 0; if (hasClosureArgs || hasNamedArgs && expressionArguments.length > 0 || !hasNamedArgs && expressionArguments.length > 0 && !isOnlyOneMapParam(expressionArguments)) { final GroovyResolveResult[] resolveResults = info.multiResolveClass(); if (resolveResults.length == 1) { final PsiElement element = resolveResults[0].getElement(); if (element instanceof PsiClass) { registerError( info.getElementToHighlight(), GroovyBundle.message("cannot.apply.default.constructor", ((PsiClass)element).getName()), null, ProblemHighlightType.GENERIC_ERROR ); return; } } } } } checkNamedArgumentsType(info); } private boolean checkForImplicitEnumAssigning(@Nullable PsiType expectedType, @NotNull GrExpression expression, @NotNull GroovyPsiElement elementToHighlight) { if (!(expectedType instanceof PsiClassType)) return false; if (!GroovyConfigUtils.getInstance().isVersionAtLeast(elementToHighlight, GroovyConfigUtils.GROOVY1_8)) return false; final PsiClass resolved = ((PsiClassType)expectedType).resolve(); if (resolved == null || !resolved.isEnum()) return false; final PsiType type = expression.getType(); if (type == null) return false; if (!type.equalsToText(GroovyCommonClassNames.GROOVY_LANG_GSTRING) && !type.equalsToText(CommonClassNames.JAVA_LANG_STRING)) { return false; } final Object result = GroovyConstantExpressionEvaluator.evaluate(expression); if (result == null || !(result instanceof String)) { registerError( elementToHighlight, ProblemHighlightType.WEAK_WARNING, GroovyBundle.message("cannot.assign.string.to.enum.0", expectedType.getPresentableText()) ); } else { final PsiField field = resolved.findFieldByName((String)result, true); if (!(field instanceof PsiEnumConstant)) { registerError( elementToHighlight, ProblemHighlightType.GENERIC_ERROR_OR_WARNING, GroovyBundle.message("cannot.find.enum.constant.0.in.enum.1", result, expectedType.getPresentableText()) ); } } return true; } private void checkIndexProperty(@NotNull CallInfo<? extends GrIndexProperty> info) { if (hasErrorElements(info.getArgumentList())) return; if (!checkCannotInferArgumentTypes(info)) return; final PsiType type = info.getQualifierInstanceType(); final PsiType[] types = info.getArgumentTypes(); if (checkSimpleArrayAccess(info, type, types)) return; final GroovyResolveResult[] results = info.multiResolve(); final GroovyResolveResult resolveResult = info.advancedResolve(); if (resolveResult.getElement() != null) { PsiElement resolved = resolveResult.getElement(); if (resolved instanceof PsiMethod && !resolveResult.isInvokedOnProperty()) { checkMethodApplicability(resolveResult, true, info); } else if (resolved instanceof GrField) { checkCallApplicability(((GrField)resolved).getTypeGroovy(), true, info); } else if (resolved instanceof PsiField) { checkCallApplicability(((PsiField)resolved).getType(), true, info); } } else if (results.length > 0) { for (GroovyResolveResult result : results) { PsiElement resolved = result.getElement(); if (resolved instanceof PsiMethod && !result.isInvokedOnProperty()) { if (!checkMethodApplicability(result, false, info)) return; } else if (resolved instanceof GrField) { if (!checkCallApplicability(((GrField)resolved).getTypeGroovy(), false, info)) return; } else if (resolved instanceof PsiField) { if (!checkCallApplicability(((PsiField)resolved).getType(), false, info)) return; } } registerError( info.getElementToHighlight(), ProblemHighlightType.GENERIC_ERROR, GroovyBundle.message("method.call.is.ambiguous") ); } else { final String typesString = buildArgTypesList(types); registerError( info.getElementToHighlight(), ProblemHighlightType.GENERIC_ERROR, GroovyBundle.message("cannot.find.operator.overload.method", typesString) ); } } private <T extends GroovyPsiElement> boolean checkMethodApplicability(@NotNull final GroovyResolveResult methodResolveResult, boolean checkUnknownArgs, @NotNull final CallInfo<T> info) { final PsiElement element = methodResolveResult.getElement(); if (!(element instanceof PsiMethod)) return true; if (element instanceof GrBuilderMethod) return true; final PsiMethod method = (PsiMethod)element; if ("call".equals(method.getName()) && info.getInvokedExpression() instanceof GrReferenceExpression) { final GrExpression qualifierExpression = ((GrReferenceExpression)info.getInvokedExpression()).getQualifierExpression(); if (qualifierExpression != null) { final PsiType type = qualifierExpression.getType(); if (type instanceof GrClosureType) { GrClosureSignatureUtil.ApplicabilityResult result = PsiUtil.isApplicableConcrete(info.getArgumentTypes(), (GrClosureType)type, info.getInvokedExpression()); switch (result) { case inapplicable: highlightInapplicableMethodUsage(methodResolveResult, info, method); return false; case canBeApplicable://q(1,2) if (checkUnknownArgs) { highlightUnknownArgs(info); } return !checkUnknownArgs; default: return true; } } } } if (method instanceof GrGdkMethod && info.getInvokedExpression() instanceof GrReferenceExpression) { final GrReferenceExpression invoked = (GrReferenceExpression)info.getInvokedExpression(); final GrExpression qualifier = PsiImplUtil.getRuntimeQualifier(invoked); if (qualifier == null && method.getName().equals("call")) { GroovyPsiElementFactory factory = GroovyPsiElementFactory.getInstance(invoked.getProject()); final GrReferenceExpression callRef = factory.createReferenceExpressionFromText("qualifier.call", invoked); callRef.setQualifier(invoked); return checkMethodApplicability(methodResolveResult, checkUnknownArgs, new DelegatingCallInfo<T>(info) { @Nullable @Override public GrExpression getInvokedExpression() { return callRef; } @NotNull @Override public GroovyResolveResult advancedResolve() { return methodResolveResult; } @NotNull @Override public GroovyResolveResult[] multiResolve() { return new GroovyResolveResult[]{methodResolveResult}; } @Nullable @Override public PsiType getQualifierInstanceType() { return info.getInvokedExpression().getType(); } }); } final PsiMethod staticMethod = ((GrGdkMethod)method).getStaticMethod(); final PsiType qualifierType = info.getQualifierInstanceType(); //check methods processed by @Category(ClassWhichProcessMethod) annotation if (qualifierType != null && !GdkMethodUtil.isCategoryMethod(staticMethod, qualifierType, qualifier, methodResolveResult.getSubstitutor()) && !checkCategoryQualifier(invoked, qualifier, staticMethod, methodResolveResult.getSubstitutor())) { registerError( info.getHighlightElementForCategoryQualifier(), ProblemHighlightType.GENERIC_ERROR, GroovyInspectionBundle.message( "category.method.0.cannot.be.applied.to.1", method.getName(), qualifierType.getCanonicalText() ) ); return false; } } if (info.getArgumentTypes() == null) return true; GrClosureSignatureUtil.ApplicabilityResult applicable = PsiUtil.isApplicableConcrete(info.getArgumentTypes(), method, methodResolveResult.getSubstitutor(), info.getCall(), false); switch (applicable) { case inapplicable: highlightInapplicableMethodUsage(methodResolveResult, info, method); return false; case canBeApplicable: if (checkUnknownArgs) { highlightUnknownArgs(info); } return !checkUnknownArgs; default: return true; } } private void checkMethodCall(@NotNull CallInfo<? extends GrMethodCall> info) { if (hasErrorElements(info.getArgumentList())) return; if (info.getInvokedExpression() instanceof GrReferenceExpression) { final GrReferenceExpression referenceExpression = (GrReferenceExpression)info.getInvokedExpression(); GroovyResolveResult resolveResult = info.advancedResolve(); GroovyResolveResult[] results = info.multiResolve(); PsiElement resolved = resolveResult.getElement(); if (resolved == null) { GrExpression qualifier = referenceExpression.getQualifierExpression(); if (qualifier == null && GrHighlightUtil.isDeclarationAssignment(referenceExpression)) return; } if (!checkCannotInferArgumentTypes(info)) return; if (resolved != null) { if (resolved instanceof PsiMethod && !resolveResult.isInvokedOnProperty()) { checkMethodApplicability(resolveResult, true, info); } else { checkCallApplicability(referenceExpression.getType(), true, info); } } else if (results.length > 0) { for (GroovyResolveResult result : results) { PsiElement current = result.getElement(); if (current instanceof PsiMethod && !result.isInvokedOnProperty()) { if (!checkMethodApplicability(result, false, info)) return; } else { if (!checkCallApplicability(referenceExpression.getType(), false, info)) return; } } registerError(info.getElementToHighlight(), GroovyBundle.message("method.call.is.ambiguous")); } } else if (info.getInvokedExpression() != null) { //it checks in visitRefExpr(...) final PsiType type = info.getInvokedExpression().getType(); checkCallApplicability(type, true, info); } checkNamedArgumentsType(info); } private void checkNamedArgumentsType(@NotNull CallInfo<?> info) { GroovyPsiElement rawCall = info.getCall(); if (!(rawCall instanceof GrCall)) return; GrCall call = (GrCall)rawCall; GrNamedArgument[] namedArguments = PsiUtil.getFirstMapNamedArguments(call); if (namedArguments.length == 0) return; Map<String, NamedArgumentDescriptor> map = GroovyNamedArgumentProvider.getNamedArgumentsFromAllProviders(call, null, false); if (map == null) return; for (GrNamedArgument namedArgument : namedArguments) { String labelName = namedArgument.getLabelName(); NamedArgumentDescriptor descriptor = map.get(labelName); if (descriptor == null) continue; GrExpression namedArgumentExpression = namedArgument.getExpression(); if (namedArgumentExpression == null) continue; if (getTupleInitializer(namedArgumentExpression) != null) continue; if (PsiUtil.isRawClassMemberAccess(namedArgumentExpression)) continue; PsiType expressionType = TypesUtil.boxPrimitiveType(namedArgumentExpression.getType(), call.getManager(), call.getResolveScope()); if (expressionType == null) continue; if (!descriptor.checkType(expressionType, call)) { registerError( namedArgumentExpression, ProblemHighlightType.GENERIC_ERROR, "Type of argument '" + labelName + "' can not be '" + expressionType.getPresentableText() + "'" ); } } } private void checkOperator(@NotNull CallInfo<? extends GrBinaryExpression> info) { if (hasErrorElements(info.getCall())) return; if (isSpockTimesOperator(info.getCall())) return; GroovyResolveResult[] results = info.multiResolve(); GroovyResolveResult resolveResult = info.advancedResolve(); if (isOperatorWithSimpleTypes(info.getCall(), resolveResult)) return; if (!checkCannotInferArgumentTypes(info)) return; if (resolveResult.getElement() != null) { checkMethodApplicability(resolveResult, true, info); } else if (results.length > 0) { for (GroovyResolveResult result : results) { if (!checkMethodApplicability(result, false, info)) return; } registerError( info.getElementToHighlight(), ProblemHighlightType.GENERIC_ERROR, GroovyBundle.message("method.call.is.ambiguous") ); } } private void highlightInapplicableMethodUsage(@NotNull GroovyResolveResult methodResolveResult, @NotNull CallInfo info, @NotNull PsiMethod method) { final PsiClass containingClass = method instanceof GrGdkMethod ? ((GrGdkMethod)method).getStaticMethod().getContainingClass() : method.getContainingClass(); PsiType[] argumentTypes = info.getArgumentTypes(); if (containingClass == null) { registerCannotApplyError(method.getName(), info); return; } final String typesString = buildArgTypesList(argumentTypes); final PsiElementFactory factory = JavaPsiFacade.getElementFactory(method.getProject()); final PsiClassType containingType = factory.createType(containingClass, methodResolveResult.getSubstitutor()); final String canonicalText = containingType.getInternalCanonicalText(); String message = method.isConstructor() ? GroovyBundle.message("cannot.apply.constructor", method.getName(), canonicalText, typesString) : GroovyBundle.message("cannot.apply.method1", method.getName(), canonicalText, typesString); registerError( info.getElementToHighlight(), message, genCastFixes(GrClosureSignatureUtil.createSignature(methodResolveResult), argumentTypes, info.getArgumentList()), ProblemHighlightType.GENERIC_ERROR ); } private void highlightUnknownArgs(@NotNull CallInfo info) { registerError( info.getElementToHighlight(), GroovyBundle.message("cannot.infer.argument.types"), LocalQuickFix.EMPTY_ARRAY, ProblemHighlightType.WEAK_WARNING ); } private void processAssignment(@NotNull PsiType expectedType, @NotNull GrExpression expression, @NotNull PsiElement toHighlight) { processAssignment(expectedType, expression, toHighlight, "cannot.assign", toHighlight, ApplicableTo.ASSIGNMENT); } private void processAssignment(@NotNull PsiType expectedType, @NotNull GrExpression expression, @NotNull PsiElement toHighlight, @NotNull @PropertyKey(resourceBundle = GroovyBundle.BUNDLE) String messageKey, @NotNull PsiElement context, @NotNull ApplicableTo position) { { // check if current assignment is constructor call final GrListOrMap initializer = getTupleInitializer(expression); if (initializer != null) { processConstructorCall(new GrListOrMapInfo(initializer)); return; } } if (PsiUtil.isRawClassMemberAccess(expression)) return; if (checkForImplicitEnumAssigning(expectedType, expression, expression)) return; final PsiType actualType = expression.getType(); if (actualType == null) return; final ConversionResult result = TypesUtil.canAssign(expectedType, actualType, context, position); if (result == ConversionResult.OK) return; final List<LocalQuickFix> fixes = ContainerUtil.newArrayList(); { fixes.add(new GrCastFix(expectedType, expression)); final String varName = getLValueVarName(toHighlight); if (varName != null) { fixes.add(new GrChangeVariableType(actualType, varName)); } } final String message = GroovyBundle.message(messageKey, actualType.getPresentableText(), expectedType.getPresentableText()); registerError( toHighlight, message, fixes.toArray(new LocalQuickFix[fixes.size()]), result == ConversionResult.ERROR ? ProblemHighlightType.GENERIC_ERROR : ProblemHighlightType.GENERIC_ERROR_OR_WARNING ); } private void processAssignment(@NotNull PsiType lType, @Nullable PsiType rType, @NotNull GroovyPsiElement context, @NotNull PsiElement elementToHighlight) { if (rType == null) return; final ConversionResult result = TypesUtil.canAssign(lType, rType, context, ApplicableTo.ASSIGNMENT); processResult(result, elementToHighlight, "cannot.assign", lType, rType); } protected void processAssignmentWithinMultipleAssignment(@NotNull GrExpression lhs, @NotNull GrExpression rhs, @NotNull GrExpression context) { final PsiType targetType = lhs.getType(); final PsiType actualType = rhs.getType(); if (targetType == null || actualType == null) return; final ConversionResult result = TypesUtil.canAssignWithinMultipleAssignment(targetType, actualType, context); if (result == ConversionResult.OK) return; registerError( rhs, GroovyBundle.message("cannot.assign", actualType.getPresentableText(), targetType.getPresentableText()), LocalQuickFix.EMPTY_ARRAY, result == ConversionResult.ERROR ? ProblemHighlightType.GENERIC_ERROR : ProblemHighlightType.GENERIC_ERROR_OR_WARNING ); } protected void processTupleAssignment(@NotNull GrTupleExpression tupleExpression, @NotNull GrExpression initializer) { GrExpression[] lValues = tupleExpression.getExpressions(); if (initializer instanceof GrListOrMap) { GrExpression[] initializers = ((GrListOrMap)initializer).getInitializers(); for (int i = 0; i < lValues.length; i++) { GrExpression lValue = lValues[i]; if (initializers.length <= i) break; GrExpression rValue = initializers[i]; processAssignmentWithinMultipleAssignment(lValue, rValue, tupleExpression); } } else { PsiType type = initializer.getType(); PsiType rType = extractIterableTypeParameter(type, false); for (GrExpression lValue : lValues) { PsiType lType = lValue.getNominalType(); // For assignments with spread dot if (PsiImplUtil.isSpreadAssignment(lValue)) { final PsiType argType = extractIterableTypeParameter(lType, false); if (argType != null && rType != null) { processAssignment(argType, rType, tupleExpression, getExpressionPartToHighlight(lValue)); } return; } if (lValue instanceof GrReferenceExpression && ((GrReferenceExpression)lValue).resolve() instanceof GrReferenceExpression) { //lvalue is not-declared variable return; } if (lType != null && rType != null) { processAssignment(lType, rType, tupleExpression, getExpressionPartToHighlight(lValue)); } } } } private void processResult(@NotNull ConversionResult result, @NotNull PsiElement elementToHighlight, @NotNull @PropertyKey(resourceBundle = GroovyBundle.BUNDLE) String messageKey, @NotNull PsiType lType, @NotNull PsiType rType) { if (result == ConversionResult.OK) return; registerError( elementToHighlight, GroovyBundle.message(messageKey, rType.getPresentableText(), lType.getPresentableText()), LocalQuickFix.EMPTY_ARRAY, result == ConversionResult.ERROR ? ProblemHighlightType.GENERIC_ERROR : ProblemHighlightType.GENERIC_ERROR_OR_WARNING ); } protected void processReturnValue(@NotNull GrExpression expression, @NotNull PsiElement context, @NotNull PsiElement elementToHighlight) { if (getTupleInitializer(expression) != null) return; final PsiType returnType = PsiImplUtil.inferReturnType(expression); if (returnType == null || returnType == PsiType.VOID) return; processAssignment(returnType, expression, elementToHighlight, "cannot.return.type", context, ApplicableTo.RETURN_VALUE); } private void registerCannotApplyError(@NotNull String invokedText, @NotNull CallInfo info) { if (info.getArgumentTypes() == null) return; final String typesString = buildArgTypesList(info.getArgumentTypes()); registerError( info.getElementToHighlight(), ProblemHighlightType.GENERIC_ERROR, GroovyBundle.message("cannot.apply.method.or.closure", invokedText, typesString) ); } @Override protected void registerError(@NotNull PsiElement location, @NotNull String description, @Nullable LocalQuickFix[] fixes, ProblemHighlightType highlightType) { if (PsiUtil.isCompileStatic(location)) { // filter all errors here, error will be highlighted by annotator if (highlightType != ProblemHighlightType.GENERIC_ERROR) { super.registerError(location, description, fixes, highlightType); } } else { if (highlightType == ProblemHighlightType.GENERIC_ERROR) { // if this visitor works within non-static context we will highlight all errors as warnings super.registerError(location, description, fixes, ProblemHighlightType.GENERIC_ERROR_OR_WARNING); } else { // if this visitor works within static context errors will be highlighted as errors by annotator, warnings will be highlighted as warnings here super.registerError(location, description, fixes, highlightType); } } } @Override public void visitEnumConstant(GrEnumConstant enumConstant) { super.visitEnumConstant(enumConstant); GrEnumConstantInfo info = new GrEnumConstantInfo(enumConstant); processConstructorCall(info); checkNamedArgumentsType(info); } @Override public void visitReturnStatement(GrReturnStatement returnStatement) { super.visitReturnStatement(returnStatement); final GrExpression value = returnStatement.getReturnValue(); if (value != null) { processReturnValue(value, returnStatement, returnStatement.getReturnWord()); } } @Override public void visitThrowStatement(GrThrowStatement throwStatement) { super.visitThrowStatement(throwStatement); final GrExpression exception = throwStatement.getException(); if (exception == null) return; final PsiElement throwWord = throwStatement.getFirstChild(); processAssignment( PsiType.getJavaLangThrowable( throwStatement.getManager(), throwStatement.getResolveScope() ), exception, throwWord ); } @Override public void visitExpression(GrExpression expression) { super.visitExpression(expression); if (isImplicitReturnStatement(expression)) { processReturnValue(expression, expression, expression); } } @Override public void visitMethodCallExpression(GrMethodCallExpression methodCallExpression) { super.visitMethodCallExpression(methodCallExpression); checkMethodCall(new GrMethodCallInfo(methodCallExpression)); } @Override public void visitNewExpression(GrNewExpression newExpression) { super.visitNewExpression(newExpression); if (newExpression.getArrayCount() > 0) return; GrCodeReferenceElement refElement = newExpression.getReferenceElement(); if (refElement == null) return; GrNewExpressionInfo info = new GrNewExpressionInfo(newExpression); processConstructorCall(info); } @Override public void visitApplicationStatement(GrApplicationStatement applicationStatement) { super.visitApplicationStatement(applicationStatement); checkMethodCall(new GrMethodCallInfo(applicationStatement)); } @Override public void visitAssignmentExpression(GrAssignmentExpression assignment) { super.visitAssignmentExpression(assignment); final GrExpression lValue = assignment.getLValue(); if (lValue instanceof GrIndexProperty) return; if (!PsiUtil.mightBeLValue(lValue)) return; final IElementType opToken = assignment.getOperationTokenType(); if (opToken != GroovyTokenTypes.mASSIGN) return; final GrExpression rValue = assignment.getRValue(); if (rValue == null) return; if (lValue instanceof GrReferenceExpression && ((GrReferenceExpression)lValue).resolve() instanceof GrReferenceExpression) { //lvalue is not-declared variable return; } if (lValue instanceof GrTupleExpression) { processTupleAssignment(((GrTupleExpression)lValue), rValue); } else { PsiType lValueNominalType = lValue.getNominalType(); final PsiType targetType = PsiImplUtil.isSpreadAssignment(lValue) ? extractIterableTypeParameter(lValueNominalType, false) : lValueNominalType; if (targetType != null) { processAssignment(targetType, rValue, lValue, "cannot.assign", assignment, ApplicableTo.ASSIGNMENT); } } } @Override public void visitBinaryExpression(GrBinaryExpression binary) { super.visitBinaryExpression(binary); checkOperator(new GrBinaryExprInfo(binary)); } @Override public void visitCastExpression(GrTypeCastExpression expression) { super.visitCastExpression(expression); final GrExpression operand = expression.getOperand(); if (operand == null) return; final PsiType actualType = operand.getType(); if (actualType == null) return; if (expression.getCastTypeElement() == null) return; final PsiType expectedType = expression.getCastTypeElement().getType(); final ConversionResult result = TypesUtil.canCast(expectedType, actualType, expression); if (result == ConversionResult.OK) return; final ProblemHighlightType highlightType = result == ConversionResult.ERROR ? ProblemHighlightType.GENERIC_ERROR : ProblemHighlightType.GENERIC_ERROR_OR_WARNING; final String message = GroovyBundle.message( "cannot.cast", actualType.getPresentableText(), expectedType.getPresentableText() ); registerError( expression, highlightType, message ); } @Override public void visitIndexProperty(GrIndexProperty expression) { super.visitIndexProperty(expression); checkIndexProperty(new GrIndexPropertyInfo(expression)); } /** * Handles method default values. */ @Override public void visitMethod(GrMethod method) { super.visitMethod(method); final PsiTypeParameter[] parameters = method.getTypeParameters(); final Map<PsiTypeParameter, PsiType> map = ContainerUtil.newHashMap(); for (PsiTypeParameter parameter : parameters) { final PsiClassType[] types = parameter.getSuperTypes(); final PsiType bound = PsiIntersectionType.createIntersection(types); final PsiWildcardType wildcardType = PsiWildcardType.createExtends(method.getManager(), bound); map.put(parameter, wildcardType); } final PsiSubstitutor substitutor = PsiSubstitutorImpl.createSubstitutor(map); for (GrParameter parameter : method.getParameterList().getParameters()) { final GrExpression initializer = parameter.getInitializerGroovy(); if (initializer == null) continue; final PsiType targetType = parameter.getType(); processAssignment( substitutor.substitute(targetType), initializer, parameter.getNameIdentifierGroovy(), "cannot.assign", method, ApplicableTo.ASSIGNMENT ); } } @Override public void visitConstructorInvocation(GrConstructorInvocation invocation) { super.visitConstructorInvocation(invocation); GrConstructorInvocationInfo info = new GrConstructorInvocationInfo(invocation); processConstructorCall(info); checkNamedArgumentsType(info); } @Override public void visitParameterList(final GrParameterList parameterList) { super.visitParameterList(parameterList); PsiElement parent = parameterList.getParent(); if (!(parent instanceof GrClosableBlock)) return; GrParameter[] parameters = parameterList.getParameters(); if (parameters.length > 0) { List<PsiType[]> signatures = ClosureParamsEnhancer.findFittingSignatures((GrClosableBlock)parent); final List<PsiType> paramTypes = ContainerUtil.map(parameters, new Function<GrParameter, PsiType>() { @Override public PsiType fun(GrParameter parameter) { return parameter.getType(); } }); if (signatures.size() > 1) { final PsiType[] fittingSignature = ContainerUtil.find(signatures, new Condition<PsiType[]>() { @Override public boolean value(PsiType[] types) { for (int i = 0; i < types.length; i++) { if (!typesAreEqual(types[i], paramTypes.get(i), parameterList)) { return false; } } return true; } }); if (fittingSignature == null) { registerError( parameterList, GroovyInspectionBundle.message("no.applicable.signature.found"), null, ProblemHighlightType.GENERIC_ERROR ); } } else if (signatures.size() == 1) { PsiType[] types = signatures.get(0); for (int i = 0; i < types.length; i++) { GrTypeElement typeElement = parameters[i].getTypeElementGroovy(); if (typeElement == null) continue; PsiType expected = types[i]; PsiType actual = paramTypes.get(i); if (!typesAreEqual(expected, actual, parameterList)) { registerError( typeElement, GroovyInspectionBundle.message("expected.type.0", expected.getPresentableText()), null, ProblemHighlightType.GENERIC_ERROR ); } } } } } @Override public void visitForInClause(GrForInClause forInClause) { super.visitForInClause(forInClause); final GrVariable variable = forInClause.getDeclaredVariable(); final GrExpression iterated = forInClause.getIteratedExpression(); if (variable == null || iterated == null) return; final PsiType iteratedType = ClosureParameterEnhancer.findTypeForIteration(iterated, forInClause); if (iteratedType == null) return; final PsiType targetType = variable.getType(); processAssignment(targetType, iteratedType, forInClause, variable.getNameIdentifierGroovy()); } @Override public void visitVariable(GrVariable variable) { super.visitVariable(variable); final PsiType varType = variable.getType(); final PsiElement parent = variable.getParent(); if (variable instanceof GrParameter && ((GrParameter)variable).getDeclarationScope() instanceof GrMethod || parent instanceof GrForInClause) { return; } else if (parent instanceof GrVariableDeclaration && ((GrVariableDeclaration)parent).isTuple()) { //check tuple assignment: def (int x, int y) = foo() final GrVariableDeclaration tuple = (GrVariableDeclaration)parent; final GrExpression initializer = tuple.getTupleInitializer(); if (initializer == null) return; if (!(initializer instanceof GrListOrMap)) { PsiType type = initializer.getType(); if (type == null) return; PsiType valueType = extractIterableTypeParameter(type, false); processAssignment(varType, valueType, tuple, variable.getNameIdentifierGroovy()); return; } } GrExpression initializer = variable.getInitializerGroovy(); if (initializer == null) return; processAssignment(varType, initializer, variable.getNameIdentifierGroovy(), "cannot.assign", variable, ApplicableTo.ASSIGNMENT); } @Override protected void registerError(@NotNull PsiElement location, ProblemHighlightType highlightType, Object... args) { registerError(location, (String)args[0], LocalQuickFix.EMPTY_ARRAY, highlightType); } }
apache-2.0
idea4bsd/idea4bsd
java/java-tests/testData/refactoring/renameCollisions/RenameVarParamToAlien.java
208
import static java.io.File.separatorChar; public class RenameCollisions { public static class StaticInnerClass { public static void staticContext(int param<caret>) { int var1 = separatorChar; } } }
apache-2.0
keycloak/keycloak
server-spi-private/src/main/java/org/keycloak/credential/hash/Pbkdf2Sha512PasswordHashProviderFactory.java
1043
package org.keycloak.credential.hash; import org.keycloak.Config; import org.keycloak.models.KeycloakSession; import org.keycloak.models.KeycloakSessionFactory; /** * Provider factory for SHA512 variant of the PBKDF2 password hash algorithm. * * @author @author <a href="mailto:abkaplan07@gmail.com">Adam Kaplan</a> */ public class Pbkdf2Sha512PasswordHashProviderFactory implements PasswordHashProviderFactory { public static final String ID = "pbkdf2-sha512"; public static final String PBKDF2_ALGORITHM = "PBKDF2WithHmacSHA512"; public static final int DEFAULT_ITERATIONS = 30000; @Override public PasswordHashProvider create(KeycloakSession session) { return new Pbkdf2PasswordHashProvider(ID, PBKDF2_ALGORITHM, DEFAULT_ITERATIONS); } @Override public void init(Config.Scope config) { } @Override public void postInit(KeycloakSessionFactory factory) { } @Override public String getId() { return ID; } @Override public void close() { } }
apache-2.0
rachit1303/One
src/core/Application.java
3497
/* * Copyright 2010 Aalto University, ComNet * Released under GPLv3. See LICENSE.txt for details. */ package core; import java.util.List; /** * <p> * Base class for applications. Nodes that have an application running will * forward all incoming messages to the application <code>handle()</code> * method before they are processed further. The application can change the * properties of the message before returning it or return null to signal * to the router that it wants the message to be dropped. * </p> * * <p> * In addition, the application's <code>update()</code> method is called every * simulation cycle. * </p> * * <p> * Configuration of application is done by picking a unique application instance * name (e.g., mySimpleApp) and setting its <code>type</code> property to the * concrete application class: <code>mySimpleApp.type = SimpleApplication * </code>. These application instances can be assigned to node groups using the * <code>Group.application</code> setting: <code>Group1.application = * mySimpleApp</code>. * </p> * * @author mjpitka * @author teemuk */ public abstract class Application { private List<ApplicationListener> aListeners = null; public String appID = null; public Application(){ } /** * Copy constructor. * * @param app */ public Application(Application app){ this.aListeners = app.getAppListeners(); this.appID = app.appID; } /** * This method handles application functionality related to * processing of the bundle. Application handles a messages, * which arrives to the node hosting this application. After * performing application specific handling, this method returns * a list of messages. If node wishes to continue forwarding the * incoming * * @param msg The incoming message. * @param host The host this application instance is attached to. * @return the (possibly modified) message to forward or <code>null</code> * if the application wants the router to stop forwarding the * message. */ public abstract Message handle(Message msg, DTNHost host); /** * Called every simulation cycle. * * @param host The host this application instance is attached to. */ public abstract void update(DTNHost host); /** * <p> * Returns an unique application ID. The application will only receive * messages with this application ID. If the AppID is set to * <code>null</code> the application will receive all messages. * </p> * * @return Application ID. */ public String getAppID() { return this.appID; } /** * Sets the application ID. Should only set once when the application is * created. Changing the value during simulation runtime is not recommended * unless you really know what you're doing. * * @param appID */ public void setAppID(String appID) { this.appID = appID; } public abstract Application replicate(); public void setAppListeners (List<ApplicationListener> aListeners){ this.aListeners = aListeners; } public List<ApplicationListener> getAppListeners(){ return this.aListeners; } /** * Sends an event to all listeners. * * @param event The event to send. * @param params Any additional parameters to send. * @param host The host which where the app is running. */ public void sendEventToListeners(String event, Object params, DTNHost host) { for (ApplicationListener al : this.aListeners) { al.gotEvent(event, params, this, host); } } }
gpl-3.0
akosyakov/intellij-community
platform/projectModel-impl/src/com/intellij/project/model/impl/library/JpsLibraryDelegate.java
7210
/* * 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.project.model.impl.library; import com.intellij.openapi.roots.OrderRootType; import com.intellij.openapi.roots.RootProvider; import com.intellij.openapi.roots.impl.RootProviderBaseImpl; import com.intellij.openapi.roots.impl.libraries.JarDirectories; import com.intellij.openapi.roots.impl.libraries.LibraryEx; import com.intellij.openapi.roots.impl.libraries.LibraryImpl; import com.intellij.openapi.roots.libraries.LibraryProperties; import com.intellij.openapi.roots.libraries.LibraryTable; import com.intellij.openapi.roots.libraries.PersistentLibraryKind; import com.intellij.openapi.util.InvalidDataException; import com.intellij.openapi.util.WriteExternalException; import com.intellij.openapi.vfs.VfsUtilCore; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.openapi.vfs.pointers.VirtualFilePointer; import com.intellij.openapi.vfs.pointers.VirtualFilePointerContainer; import com.intellij.util.ArrayUtil; import com.intellij.util.SmartList; import org.jdom.Element; import org.jetbrains.annotations.NotNull; import org.jetbrains.jps.model.library.JpsLibrary; import org.jetbrains.jps.model.library.JpsLibraryRoot; import org.jetbrains.jps.model.library.JpsOrderRootType; import java.util.*; /** * @author nik */ public class JpsLibraryDelegate implements LibraryEx { private final JpsLibrary myJpsLibrary; private final JpsLibraryTableImpl myLibraryTable; private final Map<OrderRootType, VirtualFilePointerContainer> myRoots; private final RootProviderBaseImpl myRootProvider = new MyRootProvider(); public JpsLibraryDelegate(JpsLibrary library, JpsLibraryTableImpl table) { myJpsLibrary = library; myLibraryTable = table; myRoots = new HashMap<OrderRootType, VirtualFilePointerContainer>(); } @Override public String getName() { return myJpsLibrary.getName(); } @Override public PersistentLibraryKind<?> getKind() { return null; } @Override public LibraryProperties getProperties() { return null; } @NotNull @Override public String[] getUrls(@NotNull OrderRootType rootType) { final VirtualFilePointerContainer container = myRoots.get(rootType); if (container == null) return ArrayUtil.EMPTY_STRING_ARRAY; return container.getUrls(); } @NotNull @Override public VirtualFile[] getFiles(@NotNull OrderRootType rootType) { final VirtualFilePointerContainer container = myRoots.get(rootType); if (container == null) return VirtualFile.EMPTY_ARRAY; final List<VirtualFile> expanded = new ArrayList<VirtualFile>(); for (JpsLibraryRoot root : myJpsLibrary.getRoots(getJpsRootType(rootType))) { final VirtualFilePointer pointer = container.findByUrl(root.getUrl()); if (pointer == null) continue; VirtualFile file = pointer.getFile(); if (file == null) continue; if (file.isDirectory() && root.getInclusionOptions() != JpsLibraryRoot.InclusionOptions.ROOT_ITSELF) { LibraryImpl.collectJarFiles(file, expanded, root.getInclusionOptions() == JpsLibraryRoot.InclusionOptions.ARCHIVES_UNDER_ROOT_RECURSIVELY); continue; } expanded.add(file); } return VfsUtilCore.toVirtualFileArray(expanded); } @Override public List<String> getInvalidRootUrls(OrderRootType type) { final VirtualFilePointerContainer container = myRoots.get(type); if (container == null) return Collections.emptyList(); final List<VirtualFilePointer> pointers = container.getList(); List<String> invalidPaths = null; for (VirtualFilePointer pointer : pointers) { if (!pointer.isValid()) { if (invalidPaths == null) { invalidPaths = new SmartList<String>(); } invalidPaths.add(pointer.getUrl()); } } return invalidPaths == null ? Collections.<String>emptyList() : invalidPaths; } @Override public boolean isDisposed() { return false; } @Override public LibraryTable getTable() { return myLibraryTable; } @NotNull @Override public RootProvider getRootProvider() { return myRootProvider; } @Override public void dispose() { } @NotNull @Override public ModifiableModelEx getModifiableModel() { throw new UnsupportedOperationException("'getModifiableModel' not implemented in " + getClass().getName()); } @NotNull @Override public String[] getExcludedRootUrls() { return ArrayUtil.EMPTY_STRING_ARRAY; } @NotNull @Override public VirtualFile[] getExcludedRoots() { return VirtualFile.EMPTY_ARRAY; } @Override public void readExternal(Element element) throws InvalidDataException { throw new UnsupportedOperationException(); } @Override public void writeExternal(Element element) throws WriteExternalException { throw new UnsupportedOperationException(); } @Override public boolean isJarDirectory(@NotNull String url) { return isJarDirectory(url, JarDirectories.DEFAULT_JAR_DIRECTORY_TYPE); } @Override public boolean isJarDirectory(@NotNull String url, @NotNull OrderRootType rootType) { for (JpsLibraryRoot root : myJpsLibrary.getRoots(getJpsRootType(rootType))) { if (url.equals(root.getUrl()) && root.getInclusionOptions() != JpsLibraryRoot.InclusionOptions.ROOT_ITSELF) { return true; } } return false; } @Override public boolean isValid(@NotNull String url, @NotNull OrderRootType rootType) { final VirtualFilePointerContainer container = myRoots.get(rootType); if (container == null) return false; final VirtualFilePointer fp = container.findByUrl(url); return fp != null && fp.isValid(); } private static JpsOrderRootType getJpsRootType(OrderRootType type) { if (type == OrderRootType.CLASSES) return JpsOrderRootType.COMPILED; if (type == OrderRootType.SOURCES) return JpsOrderRootType.SOURCES; if (type == OrderRootType.DOCUMENTATION) return JpsOrderRootType.DOCUMENTATION; return JpsOrderRootType.COMPILED; } private class MyRootProvider extends RootProviderBaseImpl { @NotNull @Override public String[] getUrls(@NotNull OrderRootType rootType) { Set<String> originalUrls = new LinkedHashSet<String>(Arrays.asList(JpsLibraryDelegate.this.getUrls(rootType))); for (VirtualFile file : getFiles(rootType)) { // Add those expanded with jar directories. originalUrls.add(file.getUrl()); } return ArrayUtil.toStringArray(originalUrls); } @NotNull @Override public VirtualFile[] getFiles(@NotNull OrderRootType rootType) { return JpsLibraryDelegate.this.getFiles(rootType); } } }
apache-2.0
daedric/buck
test/com/facebook/buck/jvm/java/testdata/genrule_test/LameTest.java
950
/* * 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.example; import com.example.library.LibraryClass; import org.junit.Test; import static org.junit.Assert.assertEquals; public class LameTest { @Test public void testBasicAssertion() throws Exception { LibraryClass instance = new LibraryClass(); assertEquals("Just a text.", instance.loadStringFromResource()); } }
apache-2.0
irudyak/ignite
modules/core/src/test/java/org/apache/ignite/p2p/GridMultinodeRedeployIsolatedModeSelfTest.java
1352
/* * 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.p2p; import org.apache.ignite.testframework.junits.common.GridCommonTest; import static org.apache.ignite.configuration.DeploymentMode.ISOLATED; /** * Isolated deployment mode test. */ @GridCommonTest(group = "P2P") public class GridMultinodeRedeployIsolatedModeSelfTest extends GridAbstractMultinodeRedeployTest { /** * Test GridDeploymentMode.ISOLATED mode. * * @throws Throwable if error occur. */ public void testIsolatedMode() throws Throwable { processTest(ISOLATED); } }
apache-2.0
marktriggs/nyu-sakai-10.4
kernel/kernel-impl/src/main/java/org/sakaiproject/conditions/impl/BooleanExpression.java
5800
/********************************************************************************** * $URL: https://source.sakaiproject.org/contrib/conditionalrelease/tags/sakai_2-4-1/impl/src/java/org/sakaiproject/conditions/impl/BooleanExpression.java $ * $Id: BooleanExpression.java 44301 2007-12-17 02:27:17Z zach.thomas@txstate.edu $ *********************************************************************************** * * Copyright (c) 2003, 2004, 2005, 2006, 2007, 2008 Sakai Foundation * * Licensed under the Educational Community License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.opensource.org/licenses/ECL-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * **********************************************************************************/ package org.sakaiproject.conditions.impl; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import org.sakaiproject.conditions.api.Condition; import org.sakaiproject.conditions.api.Operator; /** * @author Zach A. Thomas * */ public class BooleanExpression implements Condition { private String eventDataClassName; private String missingTermMethodName; private Operator op; private Object argument; public BooleanExpression() { } public BooleanExpression(String eventDataClassName, String missingTermMethodName, Operator op, Object argument) { this.eventDataClassName = eventDataClassName; this.missingTermMethodName = missingTermMethodName; this.op = op; this.argument = argument; } public BooleanExpression(String eventDataClassName, String missingTermMethodName, String operatorValue, Object argument) { this.eventDataClassName = eventDataClassName; this.missingTermMethodName = missingTermMethodName; this.argument = argument; setOperator(operatorValue); } public boolean evaluate(Object arg) { try { Class[] parameterTypes = {}; Method methodToInvoke = Class.forName(eventDataClassName).getDeclaredMethod(missingTermMethodName, parameterTypes); Object[] methodArgs = {}; Object missingTerm = methodToInvoke.invoke(arg, methodArgs); if (missingTerm == null) { return false; } if ((missingTerm instanceof Boolean) && op.getType() == Operator.NO_OP) { return ((Boolean)missingTerm).booleanValue(); } else return evalExpression(missingTerm, op, argument); } catch (SecurityException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalArgumentException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (NoSuchMethodException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalAccessException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InvocationTargetException e) { // TODO Auto-generated catch block e.printStackTrace(); } // if all else fails, return false return false; } private boolean evalExpression(Object leftTerm, Operator op, Object rightTerm) { if (argumentsAndOperatorAgree(leftTerm, op, rightTerm)) { switch(op.getType()) { case Operator.LESS_THAN: int comparison = ((Double)leftTerm).compareTo((Double)rightTerm); return (comparison < 0); case Operator.GREATER_THAN: return ((Comparable)leftTerm).compareTo(rightTerm) > 0; case Operator.EQUAL_TO: return ((Comparable)leftTerm).compareTo(rightTerm) == 0; case Operator.GREATER_THAN_EQUAL_TO: return ((((Comparable)leftTerm).compareTo(rightTerm) > 0) || (((Comparable)leftTerm).compareTo(rightTerm) == 0)); } } // fall-through return value return false; } private boolean argumentsAndOperatorAgree(Object term1, Operator op2, Object term2) { return true; } public String toString() { return eventDataClassName + "." + missingTermMethodName + "() less than " + argument; } public void setReceiver(String receiver) { this.eventDataClassName = receiver; } public void setMethod(String method) { this.missingTermMethodName = method; } public void setOperator(String operator) { if ("no_operator".equals(operator)) { this.op = new Operator() { public int getType() { return Operator.NO_OP; } }; } else if ("less_than".equals(operator)) { this.op = new Operator() { public int getType() { return Operator.LESS_THAN; } }; } else if ("greater_than_equal_to".equals(operator)) { this.op = new Operator() { public int getType() { return Operator.GREATER_THAN_EQUAL_TO; } }; } } public String getOperator() { if (op.getType() == Operator.NO_OP) { return "no_operator"; } else if (op.getType() == Operator.LESS_THAN) { return "less_than"; } else if (op.getType() == Operator.GREATER_THAN_EQUAL_TO) { return "greater_than_equal_to"; } else return null; } public String getReceiver() { return this.eventDataClassName; } public String getMethod() { return this.missingTermMethodName; } public Object getArgument() { return argument; } public void setArgument(Object argument) { if (argument instanceof String) { try { this.argument = Double.parseDouble(((String) argument).trim()); } catch (NumberFormatException e) { // this must not be a number this.argument = argument; } } else { this.argument = argument; } } }
apache-2.0
likaiwalkman/cassandra
src/java/org/apache/cassandra/db/DataRange.java
16926
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.cassandra.db; import java.io.IOException; import java.nio.ByteBuffer; import org.apache.cassandra.config.CFMetaData; import org.apache.cassandra.config.ColumnDefinition; import org.apache.cassandra.db.filter.*; import org.apache.cassandra.db.marshal.AbstractType; import org.apache.cassandra.db.marshal.CompositeType; import org.apache.cassandra.dht.*; import org.apache.cassandra.io.util.DataInputPlus; import org.apache.cassandra.io.util.DataOutputPlus; /** * Groups both the range of partitions to query, and the clustering index filter to * apply for each partition (for a (partition) range query). * <p> * The main "trick" is that the clustering index filter can only be obtained by * providing the partition key on which the filter will be applied. This is * necessary when paging range queries, as we might need a different filter * for the starting key than for other keys (because the previous page we had * queried may have ended in the middle of a partition). */ public class DataRange { public static final Serializer serializer = new Serializer(); protected final AbstractBounds<PartitionPosition> keyRange; protected final ClusteringIndexFilter clusteringIndexFilter; /** * Creates a {@code DataRange} given a range of partition keys and a clustering index filter. The * return {@code DataRange} will return the same filter for all keys. * * @param range the range over partition keys to use. * @param clusteringIndexFilter the clustering index filter to use. */ public DataRange(AbstractBounds<PartitionPosition> range, ClusteringIndexFilter clusteringIndexFilter) { this.keyRange = range; this.clusteringIndexFilter = clusteringIndexFilter; } /** * Creates a {@code DataRange} to query all data (over the whole ring). * * @param partitioner the partitioner in use for the table. * * @return the newly create {@code DataRange}. */ public static DataRange allData(IPartitioner partitioner) { return forTokenRange(new Range<Token>(partitioner.getMinimumToken(), partitioner.getMinimumToken())); } /** * Creates a {@code DataRange} to query all rows over the provided token range. * * @param tokenRange the (partition key) token range to query. * * @return the newly create {@code DataRange}. */ public static DataRange forTokenRange(Range<Token> tokenRange) { return forKeyRange(Range.makeRowRange(tokenRange)); } /** * Creates a {@code DataRange} to query all rows over the provided key range. * * @param keyRange the (partition key) range to query. * * @return the newly create {@code DataRange}. */ public static DataRange forKeyRange(Range<PartitionPosition> keyRange) { return new DataRange(keyRange, new ClusteringIndexSliceFilter(Slices.ALL, false)); } /** * Creates a {@code DataRange} to query all partitions of the ring using the provided * clustering index filter. * * @param partitioner the partitioner in use for the table queried. * @param filter the clustering index filter to use. * * @return the newly create {@code DataRange}. */ public static DataRange allData(IPartitioner partitioner, ClusteringIndexFilter filter) { return new DataRange(Range.makeRowRange(new Range<Token>(partitioner.getMinimumToken(), partitioner.getMinimumToken())), filter); } /** * The range of partition key queried by this {@code DataRange}. * * @return the range of partition key queried by this {@code DataRange}. */ public AbstractBounds<PartitionPosition> keyRange() { return keyRange; } /** * The start of the partition key range queried by this {@code DataRange}. * * @return the start of the partition key range queried by this {@code DataRange}. */ public PartitionPosition startKey() { return keyRange.left; } /** * The end of the partition key range queried by this {@code DataRange}. * * @return the end of the partition key range queried by this {@code DataRange}. */ public PartitionPosition stopKey() { return keyRange.right; } /** * Whether the underlying clustering index filter is a names filter or not. * * @return Whether the underlying clustering index filter is a names filter or not. */ public boolean isNamesQuery() { return clusteringIndexFilter instanceof ClusteringIndexNamesFilter; } /** * Whether the data range is for a paged request or not. * * @return true if for paging, false otherwise */ public boolean isPaging() { return false; } /** * Whether the range queried by this {@code DataRange} actually wraps around. * * @return whether the range queried by this {@code DataRange} actually wraps around. */ public boolean isWrapAround() { // Only range can ever wrap return keyRange instanceof Range && ((Range<?>)keyRange).isWrapAround(); } /** * Whether the provided ring position is covered by this {@code DataRange}. * * @return whether the provided ring position is covered by this {@code DataRange}. */ public boolean contains(PartitionPosition pos) { return keyRange.contains(pos); } /** * Whether this {@code DataRange} queries everything (has no restriction neither on the * partition queried, nor within the queried partition). * * @return Whether this {@code DataRange} queries everything. */ public boolean isUnrestricted() { return startKey().isMinimum() && stopKey().isMinimum() && clusteringIndexFilter.selectsAllPartition(); } /** * The clustering index filter to use for the provided key. * <p> * This may or may not be the same filter for all keys (that is, paging range * use a different filter for their start key). * * @param key the partition key for which we want the clustering index filter. * * @return the clustering filter to use for {@code key}. */ public ClusteringIndexFilter clusteringIndexFilter(DecoratedKey key) { return clusteringIndexFilter; } /** * Returns a new {@code DataRange} for use when paging {@code this} range. * * @param range the range of partition keys to query. * @param comparator the comparator for the table queried. * @param lastReturned the clustering for the last result returned by the previous page, i.e. the result we want to start our new page * from. This last returned <b>must</b> correspond to left bound of {@code range} (in other words, {@code range.left} must be the * partition key for that {@code lastReturned} result). * @param inclusive whether or not we want to include the {@code lastReturned} in the newly returned page of results. * * @return a new {@code DataRange} suitable for paging {@code this} range given the {@code lastRetuned} result of the previous page. */ public DataRange forPaging(AbstractBounds<PartitionPosition> range, ClusteringComparator comparator, Clustering lastReturned, boolean inclusive) { return new Paging(range, clusteringIndexFilter, comparator, lastReturned, inclusive); } /** * Returns a new {@code DataRange} equivalent to {@code this} one but restricted to the provided sub-range. * * @param range the sub-range to use for the newly returned data range. Note that assumes that {@code range} is a proper * sub-range of the initial range but doesn't validate it. You should make sure to only provided sub-ranges however or this * might throw off the paging case (see Paging.forSubRange()). * * @return a new {@code DataRange} using {@code range} as partition key range and the clustering index filter filter from {@code this}. */ public DataRange forSubRange(AbstractBounds<PartitionPosition> range) { return new DataRange(range, clusteringIndexFilter); } public String toString(CFMetaData metadata) { return String.format("range=%s pfilter=%s", keyRange.getString(metadata.getKeyValidator()), clusteringIndexFilter.toString(metadata)); } public String toCQLString(CFMetaData metadata) { if (isUnrestricted()) return "UNRESTRICTED"; StringBuilder sb = new StringBuilder(); boolean needAnd = false; if (!startKey().isMinimum()) { appendClause(startKey(), sb, metadata, true, keyRange.isStartInclusive()); needAnd = true; } if (!stopKey().isMinimum()) { if (needAnd) sb.append(" AND "); appendClause(stopKey(), sb, metadata, false, keyRange.isEndInclusive()); needAnd = true; } String filterString = clusteringIndexFilter.toCQLString(metadata); if (!filterString.isEmpty()) sb.append(needAnd ? " AND " : "").append(filterString); return sb.toString(); } private void appendClause(PartitionPosition pos, StringBuilder sb, CFMetaData metadata, boolean isStart, boolean isInclusive) { sb.append("token("); sb.append(ColumnDefinition.toCQLString(metadata.partitionKeyColumns())); sb.append(") ").append(getOperator(isStart, isInclusive)).append(" "); if (pos instanceof DecoratedKey) { sb.append("token("); appendKeyString(sb, metadata.getKeyValidator(), ((DecoratedKey)pos).getKey()); sb.append(")"); } else { sb.append(((Token.KeyBound)pos).getToken()); } } private static String getOperator(boolean isStart, boolean isInclusive) { return isStart ? (isInclusive ? ">=" : ">") : (isInclusive ? "<=" : "<"); } // TODO: this is reused in SinglePartitionReadCommand but this should not really be here. Ideally // we need a more "native" handling of composite partition keys. public static void appendKeyString(StringBuilder sb, AbstractType<?> type, ByteBuffer key) { if (type instanceof CompositeType) { CompositeType ct = (CompositeType)type; ByteBuffer[] values = ct.split(key); for (int i = 0; i < ct.types.size(); i++) sb.append(i == 0 ? "" : ", ").append(ct.types.get(i).getString(values[i])); } else { sb.append(type.getString(key)); } } /** * Specialized {@code DataRange} used for the paging case. * <p> * It uses the clustering of the last result of the previous page to restrict the filter on the * first queried partition (the one for that last result) so it only fetch results that follow that * last result. In other words, this makes sure this resume paging where we left off. */ public static class Paging extends DataRange { private final ClusteringComparator comparator; private final Clustering lastReturned; private final boolean inclusive; private Paging(AbstractBounds<PartitionPosition> range, ClusteringIndexFilter filter, ClusteringComparator comparator, Clustering lastReturned, boolean inclusive) { super(range, filter); // When using a paging range, we don't allow wrapped ranges, as it's unclear how to handle them properly. // This is ok for now since we only need this in range queries, and the range are "unwrapped" in that case. assert !(range instanceof Range) || !((Range<?>)range).isWrapAround() || range.right.isMinimum() : range; assert lastReturned != null; this.comparator = comparator; this.lastReturned = lastReturned; this.inclusive = inclusive; } @Override public ClusteringIndexFilter clusteringIndexFilter(DecoratedKey key) { return key.equals(startKey()) ? clusteringIndexFilter.forPaging(comparator, lastReturned, inclusive) : clusteringIndexFilter; } @Override public DataRange forSubRange(AbstractBounds<PartitionPosition> range) { // This is called for subrange of the initial range. So either it's the beginning of the initial range, // and we need to preserver lastReturned, or it's not, and we don't care about it anymore. return range.left.equals(keyRange().left) ? new Paging(range, clusteringIndexFilter, comparator, lastReturned, inclusive) : new DataRange(range, clusteringIndexFilter); } /** * @return the last Clustering that was returned (in the previous page) */ public Clustering getLastReturned() { return lastReturned; } @Override public boolean isPaging() { return true; } @Override public boolean isUnrestricted() { return false; } @Override public String toString(CFMetaData metadata) { return String.format("range=%s (paging) pfilter=%s lastReturned=%s (%s)", keyRange.getString(metadata.getKeyValidator()), clusteringIndexFilter.toString(metadata), lastReturned.toString(metadata), inclusive ? "included" : "excluded"); } } public static class Serializer { public void serialize(DataRange range, DataOutputPlus out, int version, CFMetaData metadata) throws IOException { AbstractBounds.rowPositionSerializer.serialize(range.keyRange, out, version); ClusteringIndexFilter.serializer.serialize(range.clusteringIndexFilter, out, version); boolean isPaging = range instanceof Paging; out.writeBoolean(isPaging); if (isPaging) { Clustering.serializer.serialize(((Paging)range).lastReturned, out, version, metadata.comparator.subtypes()); out.writeBoolean(((Paging)range).inclusive); } } public DataRange deserialize(DataInputPlus in, int version, CFMetaData metadata) throws IOException { AbstractBounds<PartitionPosition> range = AbstractBounds.rowPositionSerializer.deserialize(in, metadata.partitioner, version); ClusteringIndexFilter filter = ClusteringIndexFilter.serializer.deserialize(in, version, metadata); if (in.readBoolean()) { ClusteringComparator comparator = metadata.comparator; Clustering lastReturned = Clustering.serializer.deserialize(in, version, comparator.subtypes()); boolean inclusive = in.readBoolean(); return new Paging(range, filter, comparator, lastReturned, inclusive); } else { return new DataRange(range, filter); } } public long serializedSize(DataRange range, int version, CFMetaData metadata) { long size = AbstractBounds.rowPositionSerializer.serializedSize(range.keyRange, version) + ClusteringIndexFilter.serializer.serializedSize(range.clusteringIndexFilter, version) + 1; // isPaging boolean if (range instanceof Paging) { size += Clustering.serializer.serializedSize(((Paging)range).lastReturned, version, metadata.comparator.subtypes()); size += 1; // inclusive boolean } return size; } } }
apache-2.0
akosyakov/intellij-community
java/java-impl/src/com/intellij/refactoring/rename/naming/AutomaticParametersRenamerFactory.java
2013
/* * Copyright 2000-2010 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * User: anna * Date: 12-Jan-2010 */ package com.intellij.refactoring.rename.naming; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiMethod; import com.intellij.psi.PsiModifier; import com.intellij.psi.PsiParameter; import com.intellij.refactoring.JavaRefactoringSettings; import com.intellij.refactoring.RefactoringBundle; import com.intellij.usageView.UsageInfo; import java.util.Collection; public class AutomaticParametersRenamerFactory implements AutomaticRenamerFactory{ public boolean isApplicable(PsiElement element) { if (element instanceof PsiParameter) { final PsiElement declarationScope = ((PsiParameter)element).getDeclarationScope(); if (declarationScope instanceof PsiMethod && !((PsiMethod)declarationScope).hasModifierProperty(PsiModifier.STATIC)) { return true; } } return false; } public String getOptionName() { return RefactoringBundle.message("rename.parameters.hierarchy"); } public boolean isEnabled() { return JavaRefactoringSettings.getInstance().isRenameParameterInHierarchy(); } public void setEnabled(boolean enabled) { JavaRefactoringSettings.getInstance().setRenameParameterInHierarchy(enabled); } public AutomaticRenamer createRenamer(PsiElement element, String newName, Collection<UsageInfo> usages) { return new AutomaticParametersRenamer((PsiParameter)element, newName); } }
apache-2.0
rsharo/floodlight
src/main/java/net/floodlightcontroller/core/web/LoadedModuleLoaderResource.java
1124
/** * Copyright 2013, Big Switch Networks, 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 net.floodlightcontroller.core.web; import java.util.Map; import org.restlet.resource.Get; import net.floodlightcontroller.core.module.ModuleLoaderResource; public class LoadedModuleLoaderResource extends ModuleLoaderResource { /** * Retrieves information about all modules available * to Floodlight. * @return Information about all modules available. */ @Get("json") public Map<String, Object> retrieve() { return retrieveInternal(false); } }
apache-2.0
zkxok/News
xutilslibrary/src/main/java/com/lidroid/xutils/view/annotation/event/OnGroupCollapse.java
1269
/* * Copyright (c) 2013. wyouflf (wyouflf@gmail.com) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.lidroid.xutils.view.annotation.event; import android.widget.ExpandableListView; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Author: wyouflf * Date: 13-8-16 * Time: 下午2:27 */ @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) @EventBase( listenerType = ExpandableListView.OnGroupCollapseListener.class, listenerSetter = "setOnGroupCollapseListener", methodName = "onGroupCollapse") public @interface OnGroupCollapse { int[] value(); int[] parentId() default 0; }
apache-2.0
shreejay/elasticsearch
modules/analysis-common/src/test/java/org/elasticsearch/analysis/common/CJKFilterFactoryTests.java
4944
/* * 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.analysis.common; import org.apache.lucene.analysis.TokenStream; import org.apache.lucene.analysis.Tokenizer; import org.apache.lucene.analysis.miscellaneous.DisableGraphAttribute; import org.apache.lucene.analysis.standard.StandardTokenizer; import org.elasticsearch.index.analysis.AnalysisTestsHelper; import org.elasticsearch.index.analysis.TokenFilterFactory; import org.elasticsearch.test.ESTestCase; import org.elasticsearch.test.ESTokenStreamTestCase; import org.junit.Before; import java.io.IOException; import java.io.StringReader; public class CJKFilterFactoryTests extends ESTokenStreamTestCase { private static final String RESOURCE = "/org/elasticsearch/analysis/common/cjk_analysis.json"; private ESTestCase.TestAnalysis analysis; @Before public void setup() throws IOException { analysis = AnalysisTestsHelper.createTestAnalysisFromClassPath(createTempDir(), RESOURCE, new CommonAnalysisPlugin()); } public void testDefault() throws IOException { TokenFilterFactory tokenFilter = analysis.tokenFilter.get("cjk_bigram"); String source = "多くの学生が試験に落ちた。"; String[] expected = new String[]{"多く", "くの", "の学", "学生", "生が", "が試", "試験", "験に", "に落", "落ち", "ちた" }; Tokenizer tokenizer = new StandardTokenizer(); tokenizer.setReader(new StringReader(source)); assertTokenStreamContents(tokenFilter.create(tokenizer), expected); } public void testNoFlags() throws IOException { TokenFilterFactory tokenFilter = analysis.tokenFilter.get("cjk_no_flags"); String source = "多くの学生が試験に落ちた。"; String[] expected = new String[]{"多く", "くの", "の学", "学生", "生が", "が試", "試験", "験に", "に落", "落ち", "ちた" }; Tokenizer tokenizer = new StandardTokenizer(); tokenizer.setReader(new StringReader(source)); assertTokenStreamContents(tokenFilter.create(tokenizer), expected); } public void testHanOnly() throws IOException { TokenFilterFactory tokenFilter = analysis.tokenFilter.get("cjk_han_only"); String source = "多くの学生が試験に落ちた。"; String[] expected = new String[]{"多", "く", "の", "学生", "が", "試験", "に", "落", "ち", "た" }; Tokenizer tokenizer = new StandardTokenizer(); tokenizer.setReader(new StringReader(source)); assertTokenStreamContents(tokenFilter.create(tokenizer), expected); } public void testHanUnigramOnly() throws IOException { TokenFilterFactory tokenFilter = analysis.tokenFilter.get("cjk_han_unigram_only"); String source = "多くの学生が試験に落ちた。"; String[] expected = new String[]{"多", "く", "の", "学", "学生", "生", "が", "試", "試験", "験", "に", "落", "ち", "た" }; Tokenizer tokenizer = new StandardTokenizer(); tokenizer.setReader(new StringReader(source)); assertTokenStreamContents(tokenFilter.create(tokenizer), expected); } public void testDisableGraph() throws IOException { TokenFilterFactory allFlagsFactory = analysis.tokenFilter.get("cjk_all_flags"); TokenFilterFactory hanOnlyFactory = analysis.tokenFilter.get("cjk_han_only"); String source = "多くの学生が試験に落ちた。"; Tokenizer tokenizer = new StandardTokenizer(); tokenizer.setReader(new StringReader(source)); try (TokenStream tokenStream = allFlagsFactory.create(tokenizer)) { // This config outputs different size of ngrams so graph analysis is disabled assertTrue(tokenStream.hasAttribute(DisableGraphAttribute.class)); } tokenizer = new StandardTokenizer(); tokenizer.setReader(new StringReader(source)); try (TokenStream tokenStream = hanOnlyFactory.create(tokenizer)) { // This config uses only bigrams so graph analysis is enabled assertFalse(tokenStream.hasAttribute(DisableGraphAttribute.class)); } } }
apache-2.0
davidwilliams1978/camel
tooling/archetypes/camel-archetype-cxf-code-first-blueprint/src/main/resources/archetype-resources/src/main/java/incident/InputStatusIncident.java
1101
/** * 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 ${package}.incident; /** * Input status message */ public class InputStatusIncident { private String incidentId; public String getIncidentId() { return incidentId; } public void setIncidentId(String incidentId) { this.incidentId = incidentId; } }
apache-2.0
idea4bsd/idea4bsd
plugins/gradle/tooling-extension-api/src/org/jetbrains/plugins/gradle/tooling/ModelBuilderService.java
1067
/* * 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 org.jetbrains.plugins.gradle.tooling; import org.gradle.api.Project; import org.jetbrains.annotations.NotNull; import java.io.Serializable; /** * @author Vladislav.Soroka * @since 11/5/13 */ public interface ModelBuilderService extends Serializable { boolean canBuild(String modelName); Object buildAll(String modelName, Project project); @NotNull ErrorMessageBuilder getErrorMessageBuilder(@NotNull Project project, @NotNull Exception e); }
apache-2.0
asedunov/intellij-community
platform/util-rt/src/com/intellij/util/NullableConsumer.java
788
/* * Copyright 2000-2012 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.util; import org.jetbrains.annotations.Nullable; /** * @author nik */ public interface NullableConsumer<T> extends Consumer<T> { void consume(@Nullable T t); }
apache-2.0
marktriggs/nyu-sakai-10.4
portal/portal-impl/impl/src/java/org/sakaiproject/portal/charon/handlers/StaticScriptsHandler.java
1860
/********************************************************************************** * $URL$ * $Id$ *********************************************************************************** * * Copyright (c) 2003, 2004, 2005, 2006, 2007, 2008 The Sakai Foundation * * Licensed under the Educational Community License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.opensource.org/licenses/ECL-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * **********************************************************************************/ package org.sakaiproject.portal.charon.handlers; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.sakaiproject.portal.api.PortalHandlerException; import org.sakaiproject.tool.api.Session; /** * * @author ieb * @since Sakai 2.4 * @version $Rev$ * */ public class StaticScriptsHandler extends StaticHandler { private static final String URL_FRAGMENT = "scripts"; public StaticScriptsHandler() { setUrlFragment(StaticScriptsHandler.URL_FRAGMENT); } @Override public int doGet(String[] parts, HttpServletRequest req, HttpServletResponse res, Session session) throws PortalHandlerException { if ((parts.length >= 2) && parts[1].equals(StaticScriptsHandler.URL_FRAGMENT)) { try { doStatic(req, res, parts); return END; } catch (Exception ex) { throw new PortalHandlerException(ex); } } else { return NEXT; } } }
apache-2.0
ahb0327/intellij-community
java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/modifier/after7.java
132
// "Make 'inner' static" "true" import java.io.*; class a { static class inner { <caret>static int i; } void f() { } }
apache-2.0
dahlstrom-g/intellij-community
java/java-tests/testData/refactoring/introduceParameter/beforeVarargs.java
269
class Test { public int m(int a, int... values) { if(a > values.length) { return <selection>0</selection>; } else { return 0; } } } class Test1 { Test t; public int n(int v) { return t.m(v, 1); } }
apache-2.0
rokn/Count_Words_2015
testing/openjdk2/langtools/test/com/sun/javadoc/constantValues/TestConstantValues2.java
1303
/* * Copyright (c) 2002, 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. */ public interface TestConstantValues2 { /** * Test 3 passes ({@value}). */ public static final int TEST3PASSES = 500000; /** * Test 4 passes ({@value}). */ public static final String TEST4PASSES = "My String"; }
mit
titusfortner/selenium
java/src/com/thoughtworks/selenium/webdriven/commands/GetAllButtons.java
1662
// Licensed to the Software Freedom Conservancy (SFC) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The SFC licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. package com.thoughtworks.selenium.webdriven.commands; import com.thoughtworks.selenium.webdriven.SeleneseCommand; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import java.util.ArrayList; import java.util.List; public class GetAllButtons extends SeleneseCommand<String[]> { @Override protected String[] handleSeleneseCommand(WebDriver driver, String ignored, String alsoIgnored) { List<WebElement> allInputs = driver.findElements(By.xpath("//input")); List<String> ids = new ArrayList<>(); for (WebElement input : allInputs) { String type = input.getAttribute("type").toLowerCase(); if ("button".equals(type) || "submit".equals(type) || "reset".equals(type)) ids.add(input.getAttribute("id")); } return ids.toArray(new String[ids.size()]); } }
apache-2.0
punkhorn/camel-upstream
core/camel-support/src/main/java/org/apache/camel/converter/stream/ReaderCache.java
1918
/** * 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.converter.stream; import java.io.IOException; import java.io.OutputStream; import java.io.StringReader; import org.apache.camel.Exchange; import org.apache.camel.StreamCache; /** * A {@link org.apache.camel.StreamCache} for String {@link java.io.Reader}s */ public class ReaderCache extends StringReader implements StreamCache { private final String data; public ReaderCache(String data) { super(data); this.data = data; } public void close() { // Do not release the string for caching } @Override public void reset() { try { super.reset(); } catch (IOException e) { // ignore } } public void writeTo(OutputStream os) throws IOException { os.write(data.getBytes()); } public StreamCache copy(Exchange exchange) throws IOException { return new ReaderCache(data); } public boolean inMemory() { return true; } public long length() { return data.length(); } String getData() { return data; } }
apache-2.0
GabrielNicolasAvellaneda/guava
guava-tests/test/com/google/common/collect/QueuesTest.java
10730
/* * Copyright (C) 2011 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import com.google.common.util.concurrent.Uninterruptibles; import junit.framework.TestCase; import java.util.Collection; import java.util.List; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.BlockingQueue; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.PriorityBlockingQueue; import java.util.concurrent.SynchronousQueue; import java.util.concurrent.TimeUnit; /** * Tests for {@link Queues}. * * @author Dimitris Andreou */ public class QueuesTest extends TestCase { /* * All the following tests relate to BlockingQueue methods in Queues. */ public static List<BlockingQueue<Object>> blockingQueues() { return ImmutableList.<BlockingQueue<Object>>of( new LinkedBlockingQueue<Object>(), new LinkedBlockingQueue<Object>(10), new SynchronousQueue<Object>(), new ArrayBlockingQueue<Object>(10), new PriorityBlockingQueue<Object>(10, Ordering.arbitrary())); } private ExecutorService threadPool; @Override public void setUp() { threadPool = Executors.newCachedThreadPool(); } @Override public void tearDown() throws InterruptedException { // notice that if a Producer is interrupted (a bug), the Producer will go into an infinite // loop, which will be noticed here threadPool.shutdown(); assertTrue("Some worker didn't finish in time", threadPool.awaitTermination(1, TimeUnit.SECONDS)); } private static <T> int drain(BlockingQueue<T> q, Collection<? super T> buffer, int maxElements, long timeout, TimeUnit unit, boolean interruptibly) throws InterruptedException { return interruptibly ? Queues.drain(q, buffer, maxElements, timeout, unit) : Queues.drainUninterruptibly(q, buffer, maxElements, timeout, unit); } public void testMultipleProducers() throws Exception { for (BlockingQueue<Object> q : blockingQueues()) { testMultipleProducers(q); } } private void testMultipleProducers(BlockingQueue<Object> q) throws InterruptedException { for (boolean interruptibly : new boolean[] { true, false }) { threadPool.submit(new Producer(q, 20)); threadPool.submit(new Producer(q, 20)); threadPool.submit(new Producer(q, 20)); threadPool.submit(new Producer(q, 20)); threadPool.submit(new Producer(q, 20)); List<Object> buf = Lists.newArrayList(); int elements = drain(q, buf, 100, Long.MAX_VALUE, TimeUnit.NANOSECONDS, interruptibly); assertEquals(100, elements); assertEquals(100, buf.size()); assertDrained(q); } } public void testDrainTimesOut() throws Exception { for (BlockingQueue<Object> q : blockingQueues()) { testDrainTimesOut(q); } } private void testDrainTimesOut(BlockingQueue<Object> q) throws Exception { for (boolean interruptibly : new boolean[] { true, false }) { assertEquals(0, Queues.drain(q, ImmutableList.of(), 1, 10, TimeUnit.MILLISECONDS)); // producing one, will ask for two Future<?> submitter = threadPool.submit(new Producer(q, 1)); // make sure we time out long startTime = System.nanoTime(); int drained = drain(q, Lists.newArrayList(), 2, 10, TimeUnit.MILLISECONDS, interruptibly); assertTrue(drained <= 1); assertTrue((System.nanoTime() - startTime) >= TimeUnit.MILLISECONDS.toNanos(10)); // If even the first one wasn't there, clean up so that the next test doesn't see an element. submitter.get(); if (drained == 0) { assertNotNull(q.poll()); } } } public void testZeroElements() throws Exception { for (BlockingQueue<Object> q : blockingQueues()) { testZeroElements(q); } } private void testZeroElements(BlockingQueue<Object> q) throws InterruptedException { for (boolean interruptibly : new boolean[] { true, false }) { // asking to drain zero elements assertEquals(0, drain(q, ImmutableList.of(), 0, 10, TimeUnit.MILLISECONDS, interruptibly)); } } public void testEmpty() throws Exception { for (BlockingQueue<Object> q : blockingQueues()) { testEmpty(q); } } private void testEmpty(BlockingQueue<Object> q) { assertDrained(q); } public void testNegativeMaxElements() throws Exception { for (BlockingQueue<Object> q : blockingQueues()) { testNegativeMaxElements(q); } } private void testNegativeMaxElements(BlockingQueue<Object> q) throws InterruptedException { threadPool.submit(new Producer(q, 1)); List<Object> buf = Lists.newArrayList(); int elements = Queues.drain(q, buf, -1, Long.MAX_VALUE, TimeUnit.NANOSECONDS); assertEquals(elements, 0); assertTrue(buf.isEmpty()); // Clean up produced element to free the producer thread, otherwise it will complain // when we shutdown the threadpool. Queues.drain(q, buf, 1, Long.MAX_VALUE, TimeUnit.NANOSECONDS); } public void testDrain_throws() throws Exception { for (BlockingQueue<Object> q : blockingQueues()) { testDrain_throws(q); } } private void testDrain_throws(BlockingQueue<Object> q) { threadPool.submit(new Interrupter(Thread.currentThread())); try { Queues.drain(q, ImmutableList.of(), 100, Long.MAX_VALUE, TimeUnit.NANOSECONDS); fail(); } catch (InterruptedException expected) { } } public void testDrainUninterruptibly_doesNotThrow() throws Exception { for (BlockingQueue<Object> q : blockingQueues()) { testDrainUninterruptibly_doesNotThrow(q); } } private void testDrainUninterruptibly_doesNotThrow(final BlockingQueue<Object> q) { final Thread mainThread = Thread.currentThread(); threadPool.submit(new Runnable() { public void run() { new Producer(q, 50).run(); new Interrupter(mainThread).run(); new Producer(q, 50).run(); } }); List<Object> buf = Lists.newArrayList(); int elements = Queues.drainUninterruptibly(q, buf, 100, Long.MAX_VALUE, TimeUnit.NANOSECONDS); // so when this drains all elements, we know the thread has also been interrupted in between assertTrue(Thread.interrupted()); assertEquals(100, elements); assertEquals(100, buf.size()); } public void testNewLinkedBlockingDequeCapacity() { try { Queues.newLinkedBlockingDeque(0); fail("Should have thrown IllegalArgumentException"); } catch (IllegalArgumentException expected) { // any capacity less than 1 should throw IllegalArgumentException } assertEquals(1, Queues.newLinkedBlockingDeque(1).remainingCapacity()); assertEquals(11, Queues.newLinkedBlockingDeque(11).remainingCapacity()); } public void testNewLinkedBlockingQueueCapacity() { try { Queues.newLinkedBlockingQueue(0); fail("Should have thrown IllegalArgumentException"); } catch (IllegalArgumentException expected) { // any capacity less than 1 should throw IllegalArgumentException } assertEquals(1, Queues.newLinkedBlockingQueue(1).remainingCapacity()); assertEquals(11, Queues.newLinkedBlockingQueue(11).remainingCapacity()); } /** * Checks that #drain() invocations behave correctly for a drained (empty) queue. */ private void assertDrained(BlockingQueue<Object> q) { assertNull(q.peek()); assertInterruptibleDrained(q); assertUninterruptibleDrained(q); } private void assertInterruptibleDrained(BlockingQueue<Object> q) { // nothing to drain, thus this should wait doing nothing try { assertEquals(0, Queues.drain(q, ImmutableList.of(), 0, 10, TimeUnit.MILLISECONDS)); } catch (InterruptedException e) { throw new AssertionError(); } // but does the wait actually occurs? threadPool.submit(new Interrupter(Thread.currentThread())); try { // if waiting works, this should get stuck Queues.drain(q, Lists.newArrayList(), 1, Long.MAX_VALUE, TimeUnit.NANOSECONDS); fail(); } catch (InterruptedException expected) { // we indeed waited; a slow thread had enough time to interrupt us } } // same as above; uninterruptible version private void assertUninterruptibleDrained(BlockingQueue<Object> q) { assertEquals(0, Queues.drainUninterruptibly(q, ImmutableList.of(), 0, 10, TimeUnit.MILLISECONDS)); // but does the wait actually occurs? threadPool.submit(new Interrupter(Thread.currentThread())); long startTime = System.nanoTime(); Queues.drainUninterruptibly( q, Lists.newArrayList(), 1, 10, TimeUnit.MILLISECONDS); assertTrue((System.nanoTime() - startTime) >= TimeUnit.MILLISECONDS.toNanos(10)); // wait for interrupted status and clear it while (!Thread.interrupted()) { Thread.yield(); } } private static class Producer implements Runnable { final BlockingQueue<Object> q; final int elements; Producer(BlockingQueue<Object> q, int elements) { this.q = q; this.elements = elements; } @Override public void run() { try { for (int i = 0; i < elements; i++) { q.put(new Object()); } } catch (InterruptedException e) { // TODO(user): replace this when there is a better way to spawn threads in tests and // have threads propagate their errors back to the test thread. e.printStackTrace(); // never returns, so that #tearDown() notices that one worker isn't done Uninterruptibles.sleepUninterruptibly(Long.MAX_VALUE, TimeUnit.MILLISECONDS); } } } private static class Interrupter implements Runnable { final Thread threadToInterrupt; Interrupter(Thread threadToInterrupt) { this.threadToInterrupt = threadToInterrupt; } @Override public void run() { try { Thread.sleep(100); } catch (InterruptedException e) { throw new AssertionError(); } finally { threadToInterrupt.interrupt(); } } } }
apache-2.0
SanDisk-Open-Source/SSD_Dashboard
uefi/gcc/gcc-4.6.3/libjava/classpath/org/omg/CORBA/NO_MEMORY.java
3232
/* NO_MEMORY.java -- Copyright (C) 2005, 2006 Free Software Foundation, Inc. This file is part of GNU Classpath. GNU Classpath is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. GNU Classpath is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with GNU Classpath; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. Linking this library statically or dynamically with other modules is making a combined work based on this library. Thus, the terms and conditions of the GNU General Public License cover the whole combination. As a special exception, the copyright holders of this library give you permission to link this library with independent modules to produce an executable, regardless of the license terms of these independent modules, and to copy and distribute the resulting executable under terms of your choice, provided that you also meet, for each linked independent module, the terms and conditions of the license of that module. An independent module is a module which is not derived from or based on this library. If you modify this library, you may extend this exception to your version of the library, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ package org.omg.CORBA; import java.io.Serializable; /** * Means that the server has runned out of memory. * * @author Audrius Meskauskas (AudriusA@Bioinformatics.org) */ public final class NO_MEMORY extends SystemException implements Serializable { /** * Use serialVersionUID for interoperability. */ private static final long serialVersionUID = -4591569617929689285L; /** * Creates a NO_MEMORY with the default minor code of 0, * completion state COMPLETED_NO and the given explaining message. * @param message the explaining message. */ public NO_MEMORY(String message) { super(message, 0, CompletionStatus.COMPLETED_NO); } /** * Creates NO_MEMORY with the default minor code of 0 and a * completion state COMPLETED_NO. */ public NO_MEMORY() { super("", 0, CompletionStatus.COMPLETED_NO); } /** Creates a NO_MEMORY exception with the specified minor * code and completion status. * @param minor additional error code. * @param completed the method completion status. */ public NO_MEMORY(int minor, CompletionStatus completed) { super("", minor, completed); } /** * Created NO_MEMORY exception, providing full information. * @param reason explaining message. * @param minor additional error code (the "minor"). * @param completed the method completion status. */ public NO_MEMORY(String reason, int minor, CompletionStatus completed) { super(reason, minor, completed); } }
gpl-2.0
iloveyou416068/CookNIOServer
netty_source_4_0_25/codec-http/src/main/java/io/netty/handler/codec/http/websocketx/package-info.java
1667
/* * Copyright 2012 The Netty Project * * The Netty Project licenses this file to you under the Apache License, * version 2.0 (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ /** * Encoder, decoder, handshakers and their related message types for * <a href="http://en.wikipedia.org/wiki/Web_Sockets">Web Socket</a> data frames. * <p> * This package supports different web socket specification versions (hence the X suffix). * The specification current supported are: * <ul> * <li><a href="http://netty.io/s/ws-00">draft-ietf-hybi-thewebsocketprotocol-00</a></li> * <li><a href="http://netty.io/s/ws-07">draft-ietf-hybi-thewebsocketprotocol-07</a></li> * <li><a href="http://netty.io/s/ws-10">draft-ietf-hybi-thewebsocketprotocol-10</a></li> * <li><a href="http://netty.io/s/rfc6455">RFC 6455</a> * (originally <a href="http://netty.io/s/ws-17">draft-ietf-hybi-thewebsocketprotocol-17</a>)</li> * </ul> * </p> * <p> * For the detailed instruction on adding add Web Socket support to your HTTP * server, take a look into the <tt>WebSocketServerX</tt> example located in the * {@code io.netty.example.http.websocket} package. * </p> */ package io.netty.handler.codec.http.websocketx;
apache-2.0
tseen/Federated-HDFS
tseenliu/FedHDFS-hadoop-src/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/ipc/ClientId.java
2880
/** * 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.ipc; import java.nio.ByteBuffer; import java.util.UUID; import org.apache.hadoop.classification.InterfaceAudience; import com.google.common.base.Preconditions; /** * A class defining a set of static helper methods to provide conversion between * bytes and string for UUID-based client Id. */ @InterfaceAudience.Private public class ClientId { /** The byte array of a UUID should be 16 */ public static final int BYTE_LENGTH = 16; private static final int shiftWidth = 8; /** * Return clientId as byte[] */ public static byte[] getClientId() { UUID uuid = UUID.randomUUID(); ByteBuffer buf = ByteBuffer.wrap(new byte[BYTE_LENGTH]); buf.putLong(uuid.getMostSignificantBits()); buf.putLong(uuid.getLeastSignificantBits()); return buf.array(); } /** Convert a clientId byte[] to string */ public static String toString(byte[] clientId) { // clientId can be null or an empty array if (clientId == null || clientId.length == 0) { return ""; } // otherwise should be 16 bytes Preconditions.checkArgument(clientId.length == BYTE_LENGTH); long msb = getMsb(clientId); long lsb = getLsb(clientId); return (new UUID(msb, lsb)).toString(); } public static long getMsb(byte[] clientId) { long msb = 0; for (int i = 0; i < BYTE_LENGTH/2; i++) { msb = (msb << shiftWidth) | (clientId[i] & 0xff); } return msb; } public static long getLsb(byte[] clientId) { long lsb = 0; for (int i = BYTE_LENGTH/2; i < BYTE_LENGTH; i++) { lsb = (lsb << shiftWidth) | (clientId[i] & 0xff); } return lsb; } /** Convert from clientId string byte[] representation of clientId */ public static byte[] toBytes(String id) { if (id == null || "".equals(id)) { return new byte[0]; } UUID uuid = UUID.fromString(id); ByteBuffer buf = ByteBuffer.wrap(new byte[BYTE_LENGTH]); buf.putLong(uuid.getMostSignificantBits()); buf.putLong(uuid.getLeastSignificantBits()); return buf.array(); } }
apache-2.0
io7m/jcalcium
io7m-jcalcium-core/src/main/java/com/io7m/jcalcium/core/compiled/actions/CaCurveOrientationType.java
2271
/* * Copyright © 2016 <code@io7m.com> http://io7m.com * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR * IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ package com.io7m.jcalcium.core.compiled.actions; import com.io7m.jaffirm.core.Preconditions; import com.io7m.jcalcium.core.CaImmutableStyleType; import com.io7m.jfunctional.PartialBiFunctionType; import com.io7m.jnull.NullCheck; import javaslang.collection.SortedMap; import org.immutables.javaslang.encodings.JavaslangEncodingEnabled; import org.immutables.value.Value; /** * A curve that affects the orientation of a joint. */ @CaImmutableStyleType @JavaslangEncodingEnabled @Value.Immutable public interface CaCurveOrientationType extends CaCurveType { @Override default <A, B, E extends Exception> B matchCurve( final A context, final PartialBiFunctionType<A, CaCurveTranslationType, B, E> on_translation, final PartialBiFunctionType<A, CaCurveOrientationType, B, E> on_orientation, final PartialBiFunctionType<A, CaCurveScaleType, B, E> on_scale) throws E { return NullCheck.notNull(on_orientation, "on_orientation") .call(context, this); } /** * @return The list of keyframes for the joint */ SortedMap<Integer, CaCurveKeyframeOrientation> keyframes(); /** * Check preconditions for the type. */ @Value.Check default void checkPreconditions() { this.keyframes().forEach( (index, keyframe) -> Preconditions.checkPreconditionI( index.intValue(), index.intValue() == keyframe.index(), i -> "Orientation keyframe index must be " + keyframe.index())); } }
isc
gwenn/sqlitejdbc
src/org/sqlite/NativeDB.java
8278
/* * Copyright (c) 2007 David Crawshaw <david@zentus.com> * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ package org.sqlite; import java.io.*; import java.sql.SQLException; /** This class provides a thin JNI layer over the SQLite3 C API. */ final class NativeDB extends DB { /** SQLite connection handle. */ long pointer = 0; private static Boolean loaded = null; static boolean load(String[] errMsg) { if (loaded != null) return loaded == Boolean.TRUE; final String libpath = System.getProperty("org.sqlite.lib.path"); String libname = System.getProperty("org.sqlite.lib.name"); if (libname == null) libname = System.mapLibraryName("sqlitejdbc"); // look for a pre-installed library try { if (libpath == null) System.loadLibrary("sqlitejdbc"); else System.load(new File(libpath, libname).getAbsolutePath()); loaded = Boolean.TRUE; return true; } catch (UnsatisfiedLinkError e) { } // fall through // guess what a bundled library would be called String osname = System.getProperty("os.name").toLowerCase(); String osarch = System.getProperty("os.arch"); if (osname.startsWith("mac os")) { osname = "mac"; osarch = "universal"; } if (osname.startsWith("windows")) osname = "win"; if (osname.startsWith("sunos")) osname = "solaris"; if (osarch.startsWith("i") && osarch.endsWith("86")) osarch = "x86"; String bundled_libname = osname + '-' + osarch + ".lib"; // try a bundled library final File tmplib = unpackBundledLibrary(bundled_libname); if (null != tmplib) { try { System.load(tmplib.getAbsolutePath()); loaded = Boolean.TRUE; return true; } catch (Exception e) { } } if (null == libpath) { errMsg[0] = String.format("No bundled library '%s' found in classpath/jar,%n" + "and no pre-installed library '%s' found in default library path.%n" + "Just bundle '%1$s' in the sqlite driver jar%nor set 'org.sqlite.lib.name' " + "(and/or 'org.sqlite.lib.path'/'java.library.path') system properties to customize pre-installed library lookup.", bundled_libname, libname); } else { errMsg[0] = String.format("No bundled library '%s' found in classpath/jar,%n" + "and no pre-installed library found in custom library path '%s' ('%s').", bundled_libname, libpath, libname); } loaded = Boolean.FALSE; return false; } private static File unpackBundledLibrary(String bundled_libname) { InputStream in = null; OutputStream out = null; try { final ClassLoader cl = NativeDB.class.getClassLoader(); in = cl.getResourceAsStream(bundled_libname); if (in != null) { final File tmplib = File.createTempFile("libsqlitejdbc-", ".lib"); tmplib.deleteOnExit(); out = new FileOutputStream(tmplib); final byte[] buf = new byte[1024]; for (int len; (len = in.read(buf)) != -1;) out.write(buf, 0, len); return tmplib; } } catch (Exception e) { } finally { if (null != in) { try { in.close(); } catch (IOException e) { } } if (null != out) { try { out.close(); } catch (IOException e) { } } } return null; } /** linked list of all instanced UDFDatas */ private long udfdatalist = 0; // WRAPPER FUNCTIONS //////////////////////////////////////////// protected native synchronized void _open(String file) throws SQLException; protected native synchronized void _close() throws SQLException; native synchronized int shared_cache(boolean enable); native synchronized void interrupt(); native synchronized void busy_timeout(int ms); //native synchronized void exec(String sql) throws SQLException; protected native synchronized long prepare(String sql) throws SQLException; native synchronized String errmsg(); native synchronized String libversion(); native synchronized int changes(); protected native synchronized int finalize(long stmt); protected native synchronized int step(long stmt); protected native synchronized int reset(long stmt); native synchronized int clear_bindings(long stmt); native synchronized int bind_parameter_count(long stmt); native synchronized int column_count (long stmt); native synchronized int column_type (long stmt, int col); native synchronized String column_decltype (long stmt, int col); native synchronized String column_table_name (long stmt, int col); native synchronized String column_name (long stmt, int col); native synchronized String column_text (long stmt, int col); native synchronized byte[] column_blob (long stmt, int col); native synchronized double column_double (long stmt, int col); native synchronized long column_long (long stmt, int col); native synchronized int column_int (long stmt, int col); native synchronized int bind_null (long stmt, int pos); native synchronized int bind_int (long stmt, int pos, int v); native synchronized int bind_long (long stmt, int pos, long v); native synchronized int bind_double(long stmt, int pos, double v); native synchronized int bind_text (long stmt, int pos, String v); native synchronized int bind_blob (long stmt, int pos, byte[] v); native synchronized void result_null (long context); native synchronized void result_text (long context, String val); native synchronized void result_blob (long context, byte[] val); native synchronized void result_double(long context, double val); native synchronized void result_long (long context, long val); native synchronized void result_int (long context, int val); native synchronized void result_error (long context, String err); native synchronized int value_bytes (Function f, int arg); native synchronized String value_text (Function f, int arg); native synchronized byte[] value_blob (Function f, int arg); native synchronized double value_double(Function f, int arg); native synchronized long value_long (Function f, int arg); native synchronized int value_int (Function f, int arg); native synchronized int value_type (Function f, int arg); native synchronized int create_function(String name, Function func); native synchronized void destroy_function(String name); native synchronized void free_functions(); // COMPOUND FUNCTIONS (for optimisation) ///////////////////////// /** Provides metadata for the columns of a statement. Returns: * res[col][0] = true if column constrained NOT NULL * res[col][1] = true if column is part of the primary key * res[col][2] = true if column is auto-increment */ native synchronized boolean[][] column_metadata(long stmt); static void throwex(String msg) throws SQLException { throw new SQLException(msg); } }
isc
steve-goldman/volksempfaenger
app/src/main/java/net/x4a42/volksempfaenger/ui/settings/SettingsActivityIntentProvider.java
634
package net.x4a42.volksempfaenger.ui.settings; import android.content.Context; import android.content.Intent; import net.x4a42.volksempfaenger.IntentBuilder; public class SettingsActivityIntentProvider { private final Context context; private final IntentBuilder intentBuilder; public SettingsActivityIntentProvider(Context context, IntentBuilder intentBuilder) { this.context = context; this.intentBuilder = intentBuilder; } public Intent get() { return intentBuilder.build(context, SettingsActivity.class); } }
isc
zellerdev/jabref
src/main/java/org/jabref/gui/fieldeditors/LinkedEntriesEditor.java
1922
package org.jabref.gui.fieldeditors; import javafx.beans.binding.Bindings; import javafx.fxml.FXML; import javafx.scene.Parent; import javafx.scene.layout.HBox; import org.jabref.gui.autocompleter.AutoCompleteSuggestionProvider; import org.jabref.gui.autocompleter.AutoCompletionTextInputBinding; import org.jabref.gui.util.component.TagBar; import org.jabref.logic.integrity.FieldCheckers; import org.jabref.model.database.BibDatabaseContext; import org.jabref.model.entry.BibEntry; import org.jabref.model.entry.ParsedEntryLink; import org.jabref.model.entry.field.Field; import com.airhacks.afterburner.views.ViewLoader; public class LinkedEntriesEditor extends HBox implements FieldEditorFX { @FXML private final LinkedEntriesEditorViewModel viewModel; @FXML private TagBar<ParsedEntryLink> linkedEntriesBar; public LinkedEntriesEditor(Field field, BibDatabaseContext databaseContext, AutoCompleteSuggestionProvider<?> suggestionProvider, FieldCheckers fieldCheckers) { this.viewModel = new LinkedEntriesEditorViewModel(field, suggestionProvider, databaseContext, fieldCheckers); ViewLoader.view(this) .root(this) .load(); linkedEntriesBar.setStringConverter(viewModel.getStringConverter()); linkedEntriesBar.setOnTagClicked((parsedEntryLink, mouseEvent) -> viewModel.jumpToEntry(parsedEntryLink)); AutoCompletionTextInputBinding.autoComplete(linkedEntriesBar.getInputTextField(), viewModel::complete, viewModel.getStringConverter()); Bindings.bindContentBidirectional(linkedEntriesBar.tagsProperty(), viewModel.linkedEntriesProperty()); } public LinkedEntriesEditorViewModel getViewModel() { return viewModel; } @Override public void bindToEntry(BibEntry entry) { viewModel.bindToEntry(entry); } @Override public Parent getNode() { return this; } }
mit
ben-kimmel/caching
src/cache/logging/AbstractLogEntryBuilder.java
825
package cache.logging; /** * An abstraction of the {@link ILogEntryBuilder} interface. Handles all methods * in ILogEntryBuilder. * * @author Ben Kimmel * */ public abstract class AbstractLogEntryBuilder implements ILogEntryBuilder { protected LogEntry le; /** * Initializes an AbstractLogEntryBuilder with an empty {@link LogEntry}. */ public AbstractLogEntryBuilder() { this.le = new LogEntry(); } /** * Initializes an AbstractLogEntryBuilder with the given {@link LogEntry}. * * @param le * The LogEntry to build from */ public AbstractLogEntryBuilder(LogEntry le) { this.le = le; } @Override public LogEntry build() { return this.le; } @Override public ILogEntryBuilder addField(String field, Object value) { this.le.addField(field, value); return this; } }
mit
dmichelin/No-Man-s-Tri
No Man's Tri/src/daniel/game/Market.java
6618
/** * */ package daniel.game; import java.util.ArrayList; import java.util.Hashtable; import java.util.List; import java.util.Random; /** * @author Daniel * This class provides the market mechanics for the game */ public class Market { Hashtable<String,Item> globalMarket; List<Item> localMarket; public Market(){ globalMarket = fetchGlobalMarket(); createLocalMarket(); } /** * Fetches a permanent list of all available resources in the world. Could be later refactored to generate the list * from an XML file or by creating a new class containing methods for finding and retriving all the items in the game using * a hashtable. The programming here is pretty scrappy right now * @return */ private Hashtable<String,Item> fetchGlobalMarket() { Hashtable<String, Item> allItems = new Hashtable<String,Item>(); //Uses all resources from No Man's Sky, according to here http://nomanssky.gamepedia.com/Resource //Oxides allItems.put("Iron",new Item("Iron",10,"A common oxide, found in all sorts of creations")); allItems.put("Zinc",new Item("Zinc",40,"An uncommon metal, found in many electronic components and defensive devices")); allItems.put("Titanium",new Item("Titanium",60,"An uncommon metal, found in many electronic components and defensive devices")); //Silicates allItems.put("Heridium",new Item("Heridium",30,"A common silicate, often used in vital elements for space exploration")); allItems.put("Platinum",new Item("Platinum",50,"An uncommon silicate, used in many blueprints")); //Isotopes allItems.put("Carbon",new Item("Carbon",6,"A common isotope, found in nearly everything")); allItems.put("Thamium9",new Item("Thamium9",20,"An uncommon isotope, and a powerful energy source")); allItems.put("Plutonium",new Item("Plutonium",40,"A rare isotope, used as a potent energy source")); //Neutrals allItems.put("Gold",new Item("Gold",200,"A rare neutral, sold widely and found in many electronics")); allItems.put("Nickel",new Item("Nickel",137,"A common neutral, worth a good amount of money and used in armor plating")); allItems.put("Iridium",new Item("Iridium",96,"An uncommon neutral, a lustrous transition metal favored by traders")); allItems.put("Copper",new Item("Copper",110,"An uncommon neutral, commonly found in electronics")); allItems.put("Aluminium",new Item("Aluminium",165,"A rare neutral, frequnetly used in construction of space crafts and weapons")); allItems.put("Emeril",new Item("Emeril",275,"A rare neutral, it emits a small amount of radiation. Used in colonial stations")); //Precious allItems.put("Omegon",new Item("Omegon",309,"Dark matter element. A hugely powerful, largely unknown and entirely untested substance. It is extremely rare.")); allItems.put("Radnox",new Item("Radnox",302,"Mysterious and valuable chemical resource.")); allItems.put("Murrine",new Item("Murrine",302,"Valuable commodity known for it's charming qualities.")); allItems.put("Calium",new Item("Calium",288,"Calium is a rare substance, and can be found on extremely hostile planets.")); //Other items allItems.put("SuspensionFluid",new Item("Suspension Fluid",1100,"Non-reactive and pressure-resistant liquid. Vital to the manufacture of starship and exosuit technologies.")); allItems.put("Electron Vapor", new Item("Electron Vapor",4950,"Captured cloud of ionised electrons. A fundamental component of many technologies, and often used in the creation of antimatter.")); allItems.put("Antimatter", new Item ("Antimatter",5232,"Captured cloud of ionised electrons. A fundamental component of many technologies, and often used in the creation of antimatter.")); allItems.put("Warp Cell", new Item("Warp Cell",46750,"Warp Cells are used to charge starship Hyperdrives and to enable Faster Than Light (FTL) warp speeds.")); //Recipies //Recipe for suspension fluid, 50x Carbon List<Item> suspenList = new ArrayList<Item>(); for(int i = 0; i<50;i++){ suspenList.add(allItems.get("Carbon")); } // Add the recipe allItems.put("SuspensionFluidBlueprint",new Blueprint("Suspension Fluid Blueprint",1100,"Non-reactive and pressure-resistant liquid. Vital to the manufacture of starship and exosuit technologies.", suspenList,allItems.get("SuspensionFluid"))); //Recipe for electron vapor , 1x Suspension Fluid and 100x Plutonium List<Item> vaporList = new ArrayList<Item>(); for(int i = 0; i<100;i++){ vaporList.add(allItems.get("Plutonium")); } vaporList.add(allItems.get("SuspensionFluid")); // Add the recipe allItems.put("ElectronVaporBlueprint",new Blueprint("Electron Vapor Blueprint",4950,"Captured cloud of ionised electrons. A fundamental component of many technologies, and often used in the creation of antimatter.",vaporList,allItems.get("Electron Vapor"))); // recipe for Antimatter, 1x Electron Vapor, 50x Heridium, 20x Zinc List<Item> antiList = new ArrayList<Item>(); for(int i = 0; i<50;i++){ antiList.add(allItems.get("Heridium")); } for(int i = 0; i<20;i++){ antiList.add(allItems.get("Zinc")); } antiList.add(allItems.get("Electron Vapor")); // Add the recipe allItems.put("AntimatterBlueprint",new Blueprint("Antimatter Blueprint",5232,"Captured cloud of ionised electrons. A fundamental component of many technologies, and often used in the creation of antimatter.",vaporList,allItems.get("Antimatter"))); // Recipe for Warp Cell List<Item> warpList = new ArrayList<Item>(); for(int i = 0; i<100;i++){ warpList.add(allItems.get("Thamium9")); } warpList.add(allItems.get("Antimatter")); allItems.put("WarpCellBlueprint",new Blueprint("Warp Cell Blueprint",46750,"Warp Cells are used to charge starship Hyperdrives and to enable Faster Than Light (FTL) warp speeds.",antiList,allItems.get("Warp Cell"))); return allItems; } public Hashtable<String,Item> getGlobalMarket() { return globalMarket; } public List<Item> getLocalMarket() { return localMarket; } /** * Creates a new market for each locale. Simply grabs an item out of the global market database and generates * it using a range of values * @return */ public List<Item> createLocalMarket(){ List<Item> localMarket = new ArrayList<Item>(); Random rand = new Random(); List<Item> globMark = new ArrayList<Item>(globalMarket.values()); for(Item i : globMark){ if(i.getPrice()<=rand.nextInt(330)&&!(i instanceof Blueprint)) // Just checking to make sure the store is not populated with any blueprints { localMarket.add(i); } } return localMarket; } }
mit
CS2103JAN2017-W14-B3/main
src/main/java/seedu/doit/ui/UiPart.java
3148
package seedu.doit.ui; import java.io.IOException; import java.net.URL; import javafx.fxml.FXMLLoader; import javafx.scene.Scene; import javafx.scene.layout.AnchorPane; import javafx.stage.Modality; import javafx.stage.Stage; import seedu.doit.MainApp; import seedu.doit.commons.core.EventsCenter; import seedu.doit.commons.events.BaseEvent; /** * Represents a distinct part of the UI. e.g. Windows, dialogs, panels, status bars, etc. * It contains a scene graph with a root node of type {@code T}. */ public abstract class UiPart<T> { /** * Resource folder where FXML files are stored. */ public static final String FXML_FILE_FOLDER = "/view/"; private FXMLLoader fxmlLoader; /** * The primary stage for the UI Part. */ protected Stage primaryStage; /** * Constructs a UiPart with the specified FXML file URL. * The FXML file must not specify the {@code fx:controller} attribute. */ public UiPart(URL fxmlFileUrl) { assert fxmlFileUrl != null; this.fxmlLoader = new FXMLLoader(fxmlFileUrl); this.fxmlLoader.setController(this); try { this.fxmlLoader.load(); } catch (IOException e) { throw new AssertionError(e); } } /** * Constructs a UiPart using the specified FXML file within {@link #FXML_FILE_FOLDER}. * * @see #UiPart(URL) */ public UiPart(String fxmlFileName) { this(fxmlFileName != null ? MainApp.class.getResource(FXML_FILE_FOLDER + fxmlFileName) : null); } /** * Returns the root object of the scene graph of this UiPart. */ public T getRoot() { return this.fxmlLoader.getRoot(); } /** * Raises the event via {@link EventsCenter#post(BaseEvent)} * * @param event */ protected void raise(BaseEvent event) { EventsCenter.getInstance().post(event); } /** * Registers the object as an event handler at the {@link EventsCenter} * * @param handler usually {@code this} */ protected void registerAsAnEventHandler(Object handler) { EventsCenter.getInstance().registerHandler(handler); } /** * Creates a modal dialog. * * @param title Title of the dialog. * @param parentStage The owner stage of the dialog. * @param scene The scene that will contain the dialog. * @return the created dialog, not yet made visible. */ protected Stage createDialogStage(String title, Stage parentStage, Scene scene) { Stage dialogStage = new Stage(); dialogStage.setTitle(title); dialogStage.initModality(Modality.WINDOW_MODAL); dialogStage.initOwner(parentStage); dialogStage.setScene(scene); return dialogStage; } public void setPlaceholder(AnchorPane placeholder) { //Do nothing by default. } /** * Override this method to receive the main Node generated while loading the view from the .fxml file. * @param node */ public void setStage(Stage primaryStage) { this.primaryStage = primaryStage; } }
mit
ushahidi/Crowdmap-Java
src/main/java/com/crowdmap/java/sdk/service/UserService.java
6862
/******************************************************************************* * Copyright (c) 2010 - 2013 Ushahidi Inc. * All rights reserved * Website: http://www.ushahidi.com * * GNU AFFERO GENERAL PUBLIC LICENSE Version 3 Usage * This file may be used under the terms of the GNU AFFERO GENERAL * PUBLIC LICENSE Version 3 as published by the Free Software * Foundation and appearing in the file LICENSE included in the * packaging of this file. Please review the following information to * ensure the GNU AFFERO GENERAL PUBLIC LICENSE Version 3 requirements * will be met: http://www.gnu.org/licenses/agpl.html. ******************************************************************************/ package com.crowdmap.java.sdk.service; import com.crowdmap.java.sdk.SessionToken; import com.crowdmap.java.sdk.json.Maps; import com.crowdmap.java.sdk.json.Notifications; import com.crowdmap.java.sdk.json.Posts; import com.crowdmap.java.sdk.json.Response; import com.crowdmap.java.sdk.json.Users; import com.crowdmap.java.sdk.service.api.UserInterface; import retrofit.RestAdapter; /** * User service */ public class UserService extends CrowdmapService<UserService> { private UserInterface mUserInterface; public UserService(RestAdapter restAdapter) { super(restAdapter); mUserInterface = restAdapter.create(UserInterface.class); } /** * Get users registered on Crowdmap * * @return Users detail */ public Users getUsers() { return mUserInterface.getUsers(); } /** * Get Posts a particular user has created * * @param userId The user's ID * @return Posts the user has created */ public Posts getUsersPosts(long userId) { checkId(userId); return mUserInterface.getUsersPosts(userId); } /** * Update details of a particular user * * @param userId The user's ID * @param name User fields; */ public Users updateUser(long userId, String name, String bio, String baseLayer, boolean isTwitterAutoPost, boolean isInstagramAutoPost, boolean isTwitterAutoPostRetweets, @SessionToken String sessionToken) { checkId(userId); // Not sure how to send boolean value to the server. So turn true to 1 and false to 0 final int twitterAutoPost = isTwitterAutoPost ? 1 : 0; final int instagramAutoPost = isInstagramAutoPost ? 1 : 0; final int twitterAutoPostRetweet = isTwitterAutoPostRetweets ? 1 : 0; return mUserInterface .updateUser(userId, name, bio, baseLayer, twitterAutoPost, instagramAutoPost, twitterAutoPostRetweet, sessionToken); } /** * Get a user by the ID * * @return The User */ public Users getUser(long userId) { checkId(userId); return mUserInterface.getUser(userId); } /** * Update user avatar * * @param userId The user's ID * @return The updated user */ public Users updateUserAvatar(long userId, String avatar, @SessionToken String sessionToken) { checkId(userId); return mUserInterface.updateAvatar(userId, avatar, sessionToken); } /** * Delete a user's avatar * * @param userId The user's ID * @return The user. */ public Users deleteUserAvatar(long userId, @SessionToken String sessionToken) { checkId(userId); return mUserInterface.deleteUserAvatar(userId, sessionToken); } /** * Get Users followed by a particular users * * @param userId The user ID of the user to get his/her followers. * @return The users */ public Users getUsersFollowedBy(long userId) { return mUserInterface.getUsersFollowedBy(userId); } /** * Verify that a user follows the provided user ID * * @return The Users */ public Users verifyUsersFollowing(long userId, long followerId) { checkId(userId); return mUserInterface.verifyUsersFollowing(userId, followerId); } /** * Get a User's followers * * @return The User the user follows */ public Users getUsersFollowers(long userId) { checkId(userId); return mUserInterface.getUsersFollowers(userId); } /** * Follow a user. * * This requires authentication * * @return The Users the user follows with the new user the user is following. */ public Users followUser(long userId, @SessionToken String sessionToken) { checkId(userId); return mUserInterface.followUser(userId, sessionToken); } /** * Stop following a user * * @param userId The user's ID * @return The users the user follows without including the user the user stopped following. */ public Users stopFollowingUser(long userId, @SessionToken String sessionToken) { checkId(userId); return mUserInterface.stopFollowingUser(userId, sessionToken); } /** * Get the map the user follows * * @param userId The user's ID * @return The map the user follows */ public Maps getUserFollowedMap(long userId) { checkId(userId); return mUserInterface.getUserFollowedMap(userId); } /** * Get the map a user collaborates on. * * @param userId The user's ID * @return The maps the user collaborates on. */ public Maps getMapsUserCollaboratesOn(long userId) { checkId(userId); return mUserInterface.getMapsUserCollaboratesOn(userId); } /** * Get a user's map. * * @param userId The user's ID * @return The maps by the user. */ public Maps getUsersMaps(long userId) { checkId(userId); return mUserInterface.getUsersMaps(userId); } /** * The map a user is associated with. * * @param userId The user's ID * @return The maps by the user. */ public Maps getUsersAssociatedMaps(long userId) { checkId(userId); return mUserInterface.getUsersAssociatedMaps(userId); } /** * Get users notifications * * @param userId The user's ID to be used for fetching the notification details * @return The list of notifications */ public Notifications getNotifications(long userId) { checkId(userId); return mUserInterface.getNotifications(userId); } /** * Mark a notification as read * * @param userId The user's ID * @return The user's notifications */ public Response markNotificationAsRead(long userId, @SessionToken String sessionToken) { checkId(userId); return mUserInterface.markNotificationAsRead(userId, sessionToken); } }
mit
lucarin91/PAD-project
core/src/main/libs/ie/ucd/murmur/MurmurHash.java
5393
/** * Created by luca on 24/02/16. */ package ie.ucd.murmur; /** Murmur hash 2.0. * * The ie.ucd.murmur hash is a relative fast hash function from * http://murmurhash.googlepages.com/ for platforms with efficient * multiplication. * * This is a re-implementation of the original C code plus some * additional features. * * Public domain. * * @author Viliam Holub * @version 1.0.2 * */ public final class MurmurHash { /** Generates 32 bit hash from byte array of the given length and * seed. * * @param data byte array to hash * @param length length of the array to hash * @param seed initial seed value * @return 32 bit hash of the given array */ public static int hash32( final byte[] data, int length, int seed) { // 'm' and 'r' are mixing constants generated offline. // They're not really 'magic', they just happen to work well. final int m = 0x5bd1e995; final int r = 24; // Initialize the hash to a random value int h = seed^length; int length4 = length/4; for (int i=0; i<length4; i++) { final int i4 = i*4; int k = (data[i4+0]&0xff) +((data[i4+1]&0xff)<<8) +((data[i4+2]&0xff)<<16) +((data[i4+3]&0xff)<<24); k *= m; k ^= k >>> r; k *= m; h *= m; h ^= k; } // Handle the last few bytes of the input array switch (length%4) { case 3: h ^= (data[(length&~3) +2]&0xff) << 16; case 2: h ^= (data[(length&~3) +1]&0xff) << 8; case 1: h ^= (data[length&~3]&0xff); h *= m; } h ^= h >>> 13; h *= m; h ^= h >>> 15; return h; } /** Generates 32 bit hash from byte array with default seed value. * * @param data byte array to hash * @param length length of the array to hash * @return 32 bit hash of the given array */ public static int hash32( final byte[] data, int length) { return hash32( data, length, 0x9747b28c); } /** Generates 32 bit hash from a string. * * @param text string to hash * @return 32 bit hash of the given string */ public static int hash32( final String text) { final byte[] bytes = text.getBytes(); return hash32( bytes, bytes.length); } /** Generates 32 bit hash from a substring. * * @param text string to hash * @param from starting index * @param length length of the substring to hash * @return 32 bit hash of the given string */ public static int hash32( final String text, int from, int length) { return hash32( text.substring( from, from+length)); } /** Generates 64 bit hash from byte array of the given length and seed. * * @param data byte array to hash * @param length length of the array to hash * @param seed initial seed value * @return 64 bit hash of the given array */ public static long hash64( final byte[] data, int length, int seed) { final long m = 0xc6a4a7935bd1e995L; final int r = 47; long h = (seed&0xffffffffl)^(length*m); int length8 = length/8; for (int i=0; i<length8; i++) { final int i8 = i*8; long k = ((long)data[i8+0]&0xff) +(((long)data[i8+1]&0xff)<<8) +(((long)data[i8+2]&0xff)<<16) +(((long)data[i8+3]&0xff)<<24) +(((long)data[i8+4]&0xff)<<32) +(((long)data[i8+5]&0xff)<<40) +(((long)data[i8+6]&0xff)<<48) +(((long)data[i8+7]&0xff)<<56); k *= m; k ^= k >>> r; k *= m; h ^= k; h *= m; } switch (length%8) { case 7: h ^= (long)(data[(length&~7)+6]&0xff) << 48; case 6: h ^= (long)(data[(length&~7)+5]&0xff) << 40; case 5: h ^= (long)(data[(length&~7)+4]&0xff) << 32; case 4: h ^= (long)(data[(length&~7)+3]&0xff) << 24; case 3: h ^= (long)(data[(length&~7)+2]&0xff) << 16; case 2: h ^= (long)(data[(length&~7)+1]&0xff) << 8; case 1: h ^= (long)(data[length&~7]&0xff); h *= m; }; h ^= h >>> r; h *= m; h ^= h >>> r; return h; } /** Generates 64 bit hash from byte array with default seed value. * * @param data byte array to hash * @param length length of the array to hash * @return 64 bit hash of the given string */ public static long hash64( final byte[] data, int length) { return hash64( data, length, 0xe17a1465); } /** Generates 64 bit hash from a string. * * @param text string to hash * @return 64 bit hash of the given string */ public static long hash64( final String text) { final byte[] bytes = text.getBytes(); return hash64( bytes, bytes.length); } /** Generates 64 bit hash from a substring. * * @param text string to hash * @param from starting index * @param length length of the substring to hash * @return 64 bit hash of the given array */ public static long hash64( final String text, int from, int length) { return hash64( text.substring( from, from+length)); } }
mit
BeeHache/bh-crypto
src/main/java/net/blackhacker/crypto/CryptoFactory.java
18013
/** * The MIT License (MIT) * * Copyright (c) 2015-2019 Benjamin King aka Blackhacker(bh@blackhacker.net) * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package net.blackhacker.crypto; import net.blackhacker.crypto.algorithm.SymmetricAlgorithm; import net.blackhacker.crypto.algorithm.Mode; import net.blackhacker.crypto.algorithm.DigestAlgorithm; import net.blackhacker.crypto.algorithm.AsymmetricAlgorithm; /** * * @author Benjamin King aka Blackhacker(bh@blackhacker.net) */ final public class CryptoFactory { /** * Factory method for generating PK object using RSA * * @param name * @return PK object * @throws CryptoException * @see PK */ static public PK newEncryptorRSAWithECB(String name) throws CryptoException { return new PK( new Transformation(AsymmetricAlgorithm.RSA1024, Mode.ECB), name); } /** * Factory method for building PK object from public and private keys using * RSA * * @param publicKeyEncoded * @param privateKeyEncoded * @param name * @return PK object * @throws CryptoException * @see PK */ static public PK newEncryptorRSAWithECB( final byte[] publicKeyEncoded, final byte[] privateKeyEncoded, String name) throws CryptoException { return new PK( new Transformation(AsymmetricAlgorithm.RSA1024, Mode.ECB) ,publicKeyEncoded,privateKeyEncoded, name); } /** * Factory method for building PK object from public keys using RSA * * @param publicKeyEncoded * @param name * @return PK object * @throws CryptoException * @see PK */ static public PK newEncryptorRSAWithECB(final byte[] publicKeyEncoded, String name) throws CryptoException { return new PK( new Transformation(AsymmetricAlgorithm.RSA1024, Mode.ECB), publicKeyEncoded, name); } /** * Factory method for generating SK object using DES algorithm in ECB mode * * @return SK Object * @throws CryptoException * @see SK */ final static public SK newEncryptorDESWithECB() throws CryptoException { return new SK(new Transformation(SymmetricAlgorithm.DES, Mode.ECB)); } /** * Factory method for building SK object from encoded key using DES * algorithm in ECB mode * * @param key * @return SK Object * @throws CryptoException * @see SK */ final static public SK newEncryptorDESWithECB(final byte[] key) throws CryptoException { return new SK(new Transformation(SymmetricAlgorithm.DES, Mode.ECB), key); } /** * Factory method for generating an SK object using DES algorithm in CBC * mode with the given IV * * @return SK Object * @throws CryptoException * @see SK */ final static public SK newEncryptorDESWithCBC() throws CryptoException { return new SK(new Transformation(SymmetricAlgorithm.DES, Mode.CBC)); } /** * Factory method for generating an SK object using DES algorithm in CBC * mode with the given IV * * @param key * @return SK Object * @throws CryptoException * @see SK */ final static public SK newEncryptorDESWithCBC(final byte[] key) throws CryptoException { return new SK(new Transformation(SymmetricAlgorithm.DES, Mode.CBC), key); } /** * Factory method for generating an SK object using DES algorithm in CFB mode * * @return SK Object * @throws CryptoException * @see SK */ final static public SK newEncryptorDESWithCFB() throws CryptoException { return new SK(new Transformation(SymmetricAlgorithm.DES, Mode.CFB)); } /** * Factory method for generating an SK object using DES algorithm in CFB mode * * @param key * @return SK Object * @throws CryptoException * @see SK */ final static public SK newEncryptorDESWithCFB(final byte[] key) throws CryptoException { return new SK(new Transformation(SymmetricAlgorithm.DES, Mode.CFB), key); } /** * Factory method for building an SK object using DES algorithm in OFB mode * * @return SK Object * @throws CryptoException * @see SK */ final static public SK newEncryptorDESWithOFB() throws CryptoException { return new SK(new Transformation(SymmetricAlgorithm.DES, Mode.OFB)); } /** * Factory method for building an SK object using DES algorithm in OFB mode * * @param key * @return SK Object * @throws CryptoException * @see SK */ final static public SK newEncryptorDESWithOFB(final byte[] key) throws CryptoException { return new SK(new Transformation(SymmetricAlgorithm.DES, Mode.OFB), key); } /** * Factory method for building an SK object using Triple DES algorithm in ECB mode * * @return SK Object * @throws CryptoException * @see SK */ final static public SK newEncryptorDESedeWithECB() throws CryptoException { return new SK(new Transformation(SymmetricAlgorithm.DESede, Mode.ECB)); } /** * Factory method for building an SK object using Triple DES algorithm * from encoded key in ECB mode * * @param key * @return SK Object * @throws CryptoException * @see SK */ final static public SK newEncryptorDESedeWithECB(final byte[] key) throws CryptoException { return new SK(new Transformation(SymmetricAlgorithm.DESede, Mode.ECB), key); } /** * Factory method for building an SK object using Triple DES algorithm * in CBC mode with the given IV * * @return SK Object * @throws CryptoException * @see SK */ final static public SK newEncryptorDESedeWithCBC() throws CryptoException { return new SK(new Transformation(SymmetricAlgorithm.DESede, Mode.CBC)); } /** * Factory method for building an SK object using Triple DES algorithm * from encoded key in CBS mode with the given IV * * @param key * @return SK Object * @throws CryptoException * @see SK */ final static public SK newEncryptorDESedeWithCBC(final byte[] key) throws CryptoException { return new SK(new Transformation(SymmetricAlgorithm.DESede, Mode.CBC), key); } /** * Factory method for building an SK object using Triple DES algorithm * in CFB mode with the given IV * * @return SK Object * @throws CryptoException * @see SK */ final static public SK newEncryptorDESedeWithCFB() throws CryptoException { return new SK(new Transformation(SymmetricAlgorithm.DESede, Mode.CFB)); } /** * Factory method for building an SK object using Triple DES algorithm * from encoded key in CFB mode with the given IV * * @param key * @return SK Object * @throws CryptoException * @see SK */ final static public SK newEncryptorDESedeWithCFB(final byte[] key) throws CryptoException { return new SK( new Transformation(SymmetricAlgorithm.DESede, Mode.CFB), key); } /** * Factory method for building an SK object using Triple DES algorithm * in OFB mode with the given IV * * @return SK Object * @throws CryptoException * @see SK */ final static public SK newEncryptorDESedeWithOFB() throws CryptoException { return new SK( new Transformation(SymmetricAlgorithm.DESede, Mode.OFB)); } /** * Factory method for building an SK object using Triple DES algorithm * from encoded key in OFB mode with the given IV * * @param key * @return SK Object * @throws CryptoException * @see SK */ final static public SK newEncryptorDESedeWithOFB(final byte[] key) throws CryptoException { return new SK( new Transformation(SymmetricAlgorithm.DESede, Mode.OFB), key); } /** * Factory method for building an SK object using AES algorithm * from encoded key in CFB mode * * @param key * @return SK Object * @throws CryptoException * @see SK */ final static public SK newEncryptorAES128WithECB(final byte[] key) throws CryptoException { return new SK( new Transformation(SymmetricAlgorithm.AES, Mode.ECB),key); } /** * Factory method for building an SK object using AES algorithm * * @return SK Object * @throws CryptoException * @see SK */ final static public SK newEncryptorAES128WithECB() throws CryptoException { return new SK(new Transformation(SymmetricAlgorithm.AES, Mode.ECB)); } /** * Factory method for building an SK object using AES algorithm in CBC mode * * @return SK Object * @throws CryptoException * @see SK */ final static public SK newEncryptorAES128WithCBC() throws CryptoException { return new SK(new Transformation(SymmetricAlgorithm.DESede, Mode.CBC)); } /** * Factory method for building an SK object using AES algorithm in CBC mode * from encoded key with the given IV * * @param key * @return SK Object * @throws CryptoException * @see SK */ final static public SK newEncryptorAES128WithCBC(final byte[] key) throws CryptoException { return new SK(new Transformation(SymmetricAlgorithm.AES, Mode.CBC), key); } /** * Factory method for building an SK object using AES algorithm in CBC mode * from encoded key with the given IV * * @param key * @return SK Object * @throws CryptoException * @see SK */ final static public SK newEncryptorAES128WithCFB(final byte[] key) throws CryptoException { return new SK( new Transformation(SymmetricAlgorithm.AES, Mode.CFB), key ); } /** * Factory method for building an SK object using AES algorithm in CFB mode * with the given IV * * @return SK Object * @throws CryptoException * @see SK */ final static public SK newEncryptorAES128WithCFB() throws CryptoException { return new SK( new Transformation(SymmetricAlgorithm.AES, Mode.CFB)); } /** * Factory method for building an SK object using AES algorithm in OFB mode * from encoded key with the given IV * * @param key * @return SK Object * @throws CryptoException * @see SK */ final static public SK newEncryptorAES128WithOFB(final byte[] key) throws CryptoException { return new SK( new Transformation(SymmetricAlgorithm.AES, Mode.OFB), key); } /** * Factory method for building an SK object using AES algorithm in OFB mode * * @return SK Object * @throws CryptoException * @see SK */ final static public SK newEncryptorAES128WithOFB() throws CryptoException { return new SK( new Transformation(SymmetricAlgorithm.AES, Mode.OFB)); } /** * Factory method for building an SK object using AES algorithm in CTR mode * from encoded key with the given IV * * @param key * @return SK Object * @throws CryptoException * @see SK */ final static public SK newEncryptorAES128WithCTR(final byte[] key) throws CryptoException { return new SK( new Transformation(SymmetricAlgorithm.AES, Mode.CTR),key); } /** * Factory method for building an SK object using AES algorithm in CTR mode * from encoded key with the given IV * * @return SK Object * @throws CryptoException * @see SK */ final static public SK newEncryptorAES128WithCTR() throws CryptoException { return new SK( new Transformation(SymmetricAlgorithm.AES, Mode.CTR)); } /** * Factory method for building an SK object using AES algorithm in OCB mode * from encoded key with the given IV * * @param key * @return SK Object * @throws CryptoException * @see SK */ final static public SK newEncryptorAES128WithOCB(final byte[] key) throws CryptoException { return new SK( new Transformation(SymmetricAlgorithm.AES, Mode.OCB), key); } /** * Factory method for building an SK object using AES algorithm in OCB mode * from encoded key * * @return SK Object * @throws CryptoException * @see SK */ final static public SK newEncryptorAES128WithOCB() throws CryptoException { return new SK( new Transformation(SymmetricAlgorithm.AES, Mode.OCB)); } /** * Factory method for building an SK object using AES algorithm in ECB mode * from encoded key * * @param key * @return SK Object * @throws CryptoException * @see SK */ final static public SK newEncryptorAES192WithECB(final byte[] key) throws CryptoException { return new SK( new Transformation(SymmetricAlgorithm.AES192, Mode.ECB), key); } /** * Factory method for building an SK object using AES algorithm in ECB mode * from encoded key with the given IV * * @return SK Object * @throws CryptoException * @see SK */ final static public SK newEncryptorAES192WithECB() throws CryptoException { return new SK( new Transformation(SymmetricAlgorithm.AES192, Mode.ECB)); } /** * Factory method for building an SK object using AES algorithm in CBC mode * with the given IV * * @return SK Object * @throws CryptoException * @see SK */ final static public SK newEncryptorAES192WithCBC() throws CryptoException { return new SK( new Transformation(SymmetricAlgorithm.AES192, Mode.ECB)); } /** * Factory method for building an SK object using AES algorithm in CBC mode * from encoded key with the given IV * * @param key * @return SK Object * @throws CryptoException * @see SK */ final static public SK newEncryptorAES192WithCBC(final byte[] key) throws CryptoException { return new SK( new Transformation(SymmetricAlgorithm.AES192, Mode.CBC), key); } /** * Builds a new Password Based Encryption (PBE) enabled SK object based on * the given password * * @param password * @return SK * @throws CryptoException * @see SK */ final static public SK newEncryptorPBEWithSHAAnd3KeyTripleDES(String password) throws CryptoException { return new SK( new Transformation(DigestAlgorithm.SHA1, SymmetricAlgorithm.DESede), password.toCharArray() ); } /** * Builds a new Password Based Encryption (PBE) enabled SK object based on * the given password * * @param password * @return SK object * @throws CryptoException * @see SK */ final static public SK newEncryptorPBEWithMD5AndTripleDES(String password) throws CryptoException { return new SK( new Transformation(DigestAlgorithm.MD5, SymmetricAlgorithm.DESede), password.toCharArray() ); } /** * Builds a new Password Based Encryption (PBE) enabled SK object based on * the given password * * @param password * @return SK object * @throws CryptoException * @see SK */ final static public SK newEncryptorPBEWithMD5AndDES(String password) throws CryptoException { return new SK( new Transformation(DigestAlgorithm.MD5, SymmetricAlgorithm.DES), password.toCharArray() ); } /** * Builds a new Password Based Encryption (PBE) enabled SK object based on * the given password * * @param password * @return SK object * @throws CryptoException * @see SK */ final static public SK newEncryptorPBEWithSHA256And256BitAES(String password) throws CryptoException { return new SK( new Transformation(DigestAlgorithm.SHA256, SymmetricAlgorithm.AES), password.toCharArray() ); } /** * Builds a new Password Based Encryption (PBE) enabled SK object based on * the given password * * @param password * @return SK object * @throws CryptoException * @see SK */ final static public SK newEncryptorPBEWithSHA1AndDESede(String password) throws CryptoException { return new SK( new Transformation(DigestAlgorithm.SHA1, SymmetricAlgorithm.DESede), password.toCharArray() ); } }
mit
derari/cthul
matcher-fluent-gen/src/main/java/org/cthul/matchers/fluent/gen/Main.java
67
package org.cthul.matchers.fluent.gen; public class Main { }
mit
Jiaran/Slogo
src/GUIObject/CommandsWindow.java
2151
package GUIObject; import java.awt.Dimension; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.util.List; import javax.swing.JPanel; import javax.swing.JTextField; import actionfactory.ActionFactory; @SuppressWarnings("serial") public class CommandsWindow extends JPanel implements View { private final int ITEM_HEIGHT = 30; private ActionFactory actionFac; private String buttonName; private List<String> myStrings = null; public CommandsWindow (ActionFactory act, String buttonName) { actionFac = act; this.buttonName = buttonName; // setLayout( new GridLayout(0,2)); setLayout(new GridBagLayout()); this.setAlignmentX(LEFT_ALIGNMENT); this.setVisible(true); } public void setStrings (List<String> strings) { myStrings = strings; } private void createGUI (List<String> strings) { if (strings == null) { return; } this.setPreferredSize(new Dimension(300, ITEM_HEIGHT * strings.size())); for (int i = 0; i < strings.size(); i++) { // System.out.println(strings.get(i)+"\n"); JTextField tempText = new JTextField(); tempText.setText(strings.get(i)); tempText.setEditable(false); tempText.setPreferredSize(new Dimension(100, ITEM_HEIGHT)); tempText.setMinimumSize(new Dimension(150, ITEM_HEIGHT)); GUIButton button = new GUIButton(actionFac.create(tempText), buttonName); button.setPreferredSize(new Dimension(80, ITEM_HEIGHT)); button.setMinimumSize(new Dimension(80, ITEM_HEIGHT)); GridBagConstraints c = new GridBagConstraints(); c.fill = GridBagConstraints.HORIZONTAL; c.gridx = 0; c.gridy = i; c.weightx = 0.6; c.anchor = GridBagConstraints.PAGE_START; add(tempText, c); c.gridx = 1; c.weightx = 0.4; add(button, c); } } @Override public void updateView () { removeAll(); createGUI(myStrings); revalidate(); } }
mit
EaW1805/engine
src/main/java/com/eaw1805/orders/economy/RepairBaggageTrain.java
6426
package com.eaw1805.orders.economy; import com.eaw1805.data.constants.GoodConstants; import com.eaw1805.data.constants.RegionConstants; import com.eaw1805.data.managers.economy.BaggageTrainManager; import com.eaw1805.data.managers.map.SectorManager; import com.eaw1805.data.model.economy.BaggageTrain; import com.eaw1805.data.model.map.Sector; import com.eaw1805.orders.AbstractOrderProcessor; import com.eaw1805.orders.OrderProcessor; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import java.util.HashMap; import java.util.Map; /** * Order - Repair Ship. * ticket:20. */ public class RepairBaggageTrain extends AbstractOrderProcessor implements GoodConstants, RegionConstants { /** * a log4j logger to print messages. */ private static final Logger LOGGER = LogManager.getLogger(RepairBaggageTrain.class); /** * Type of the order. */ public static final int ORDER_TYPE = ORDER_R_BTRAIN; /** * Default constructor. * * @param myParent the parent object that invoked us. */ public RepairBaggageTrain(final OrderProcessor myParent) { super(myParent); LOGGER.debug("RepairBaggageTrain instantiated."); } /** * Process this particular order. */ public void process() { final int trainId = Integer.parseInt(getOrder().getParameter1()); // Retrieve Ship final BaggageTrain thisBTrain = BaggageTrainManager.getInstance().getByID(trainId); // Check ownership of ship if (thisBTrain.getNation().getId() == getOrder().getNation().getId()) { // Retrieve the sector where we wish to repair the ship final Sector thisSector = SectorManager.getInstance().getByPosition(thisBTrain.getPosition()); // Update order's region of effect getOrder().setRegion(thisSector.getPosition().getRegion()); final int ownerId = getOrder().getNation().getId(); final int regionId = thisSector.getPosition().getRegion().getId(); // Make sure that it can be built at the colonies if (thisSector.hasBarrack()) { final double modifier = (100d - thisBTrain.getCondition()) / 100d; final int reqMoney = (int) (300000 * modifier); final int reqHorse = (int) (2000 * modifier); final int reqWood = (int) (1000 * modifier); final int reqCitizens = (int) (1000 * modifier); final int reqIndPt = (int) (500 * modifier); // Make sure that enough money are available if (getParent().getTotGoods(ownerId, EUROPE, GOOD_MONEY) >= reqMoney) { // Make sure that enough citizens are available if (getParent().getTotGoods(ownerId, regionId, GOOD_PEOPLE) >= reqCitizens) { // Make sure that enough Industrial Points are available if (getParent().getTotGoods(ownerId, regionId, GOOD_INPT) >= reqHorse) { // Make sure that enough Wood are available if (getParent().getTotGoods(ownerId, regionId, GOOD_WOOD) >= reqWood) { // Make sure that enough Industrial Points are available if (getParent().getTotGoods(ownerId, regionId, GOOD_INPT) >= reqIndPt) { // Reduce materials getParent().decTotGoods(ownerId, EUROPE, GOOD_MONEY, reqMoney); getParent().decTotGoods(ownerId, regionId, GOOD_PEOPLE, reqCitizens); getParent().decTotGoods(ownerId, regionId, GOOD_HORSE, reqHorse); getParent().decTotGoods(ownerId, regionId, GOOD_WOOD, reqWood); getParent().decTotGoods(ownerId, regionId, GOOD_INPT, reqIndPt); // Update goods used by order final Map<Integer, Integer> usedGoods = new HashMap<Integer, Integer>(); usedGoods.put(GOOD_MONEY, reqMoney); usedGoods.put(GOOD_WOOD, reqWood); usedGoods.put(GOOD_PEOPLE, reqCitizens); usedGoods.put(GOOD_HORSE, reqHorse); usedGoods.put(GOOD_INPT, reqIndPt); getOrder().setUsedGoodsQnt(usedGoods); // Repair ship thisBTrain.setCondition(100); BaggageTrainManager.getInstance().update(thisBTrain); // Report success getOrder().setResult(1); getOrder().setExplanation("repaired baggage train " + thisBTrain.getName()); } else { getOrder().setResult(-8); getOrder().setExplanation("not enough industrial points at regional warehouse"); } } else { getOrder().setResult(-2); getOrder().setExplanation("not enough wood at regional warehouse"); } } else { getOrder().setResult(-3); getOrder().setExplanation("not enough horses at regional warehouse"); } } else { getOrder().setResult(-4); getOrder().setExplanation("not enough citizens at regional warehouse"); } } else { getOrder().setResult(-5); getOrder().setExplanation("not enough money at empire warehouse"); } } else { getOrder().setResult(-6); getOrder().setExplanation("sector does not have a barrack"); } } else { getOrder().setResult(-7); getOrder().setExplanation("not owner of sector"); } } }
mit
gaborkolozsy/XChange
xchange-taurus/src/main/java/org/knowm/xchange/taurus/service/TaurusAccountService.java
2452
package org.knowm.xchange.taurus.service; import java.io.IOException; import java.math.BigDecimal; import java.util.List; import org.knowm.xchange.Exchange; import org.knowm.xchange.currency.Currency; import org.knowm.xchange.dto.account.AccountInfo; import org.knowm.xchange.dto.account.FundingRecord; import org.knowm.xchange.exceptions.ExchangeException; import org.knowm.xchange.exceptions.NotAvailableFromExchangeException; import org.knowm.xchange.exceptions.NotYetImplementedForExchangeException; import org.knowm.xchange.service.account.AccountService; import org.knowm.xchange.service.trade.params.DefaultWithdrawFundsParams; import org.knowm.xchange.service.trade.params.TradeHistoryParams; import org.knowm.xchange.service.trade.params.WithdrawFundsParams; import org.knowm.xchange.taurus.TaurusAdapters; /** * @author Matija Mazi */ public class TaurusAccountService extends TaurusAccountServiceRaw implements AccountService { public TaurusAccountService(Exchange exchange) { super(exchange); } @Override public AccountInfo getAccountInfo() throws IOException { return TaurusAdapters.adaptAccountInfo(getTaurusBalance(), exchange.getExchangeSpecification().getUserName()); } @Override public String withdrawFunds(Currency currency, BigDecimal amount, String address) throws IOException { return withdrawTaurusFunds(amount, address); } @Override public String withdrawFunds(WithdrawFundsParams params) throws ExchangeException, NotAvailableFromExchangeException, NotYetImplementedForExchangeException, IOException { if (params instanceof DefaultWithdrawFundsParams) { DefaultWithdrawFundsParams defaultParams = (DefaultWithdrawFundsParams) params; return withdrawFunds(defaultParams.currency, defaultParams.amount, defaultParams.address); } throw new IllegalStateException("Don't know how to withdraw: " + params); } @Override public String requestDepositAddress(Currency currency, String... arguments) throws IOException { return getTaurusBitcoinDepositAddress(); } @Override public TradeHistoryParams createFundingHistoryParams() { throw new NotAvailableFromExchangeException(); } @Override public List<FundingRecord> getFundingHistory( TradeHistoryParams params) throws ExchangeException, NotAvailableFromExchangeException, NotYetImplementedForExchangeException, IOException { throw new NotYetImplementedForExchangeException(); } }
mit
zaplatynski/second-hand-log
console/src/main/java/de/marza/firstspirit/modules/logging/console/utilities/ReadTextFromFile.java
1868
package de.marza.firstspirit.modules.logging.console.utilities; import java.awt.Color; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import javax.swing.JEditorPane; import javax.swing.UIManager; /** * The type Read text from file. */ public class ReadTextFromFile { private static final Logger LOGGER = Logger.getInstance(); private final String filePath; private JEditorPane message; /** * Instantiates a new Read text from file. * * @param filePath the file path */ public ReadTextFromFile(final String filePath) { if (filePath == null || filePath.trim().isEmpty()) { throw new IllegalArgumentException("filePath null or empty"); } this.filePath = filePath; } /** * Read as j editor j editor pane. * * @return the j editor pane */ public final JEditorPane readAsJEditor() { if (message == null) { final InputStream inputStream = getClass().getResourceAsStream(filePath); //NOPMD final InputStreamReader streamReader = new InputStreamReader(inputStream); try (final BufferedReader txtReader = new BufferedReader(streamReader)) { String line; final StringBuilder buffer = new StringBuilder(12); while ((line = txtReader.readLine()) != null) { buffer.append(line); } message = new JEditorPane("text/html", buffer.toString()); message.setEditable(false); final Color backgrounfdColor = UIManager.getColor("Panel.background"); message.setBackground(backgrounfdColor); message.addHyperlinkListener(new HyperlinkExecutor()); } catch (final IOException exception) { LOGGER.logError("An logError occurred while reading the about text: %s", exception.toString()); } } return message; } }
mit
ControlSystemStudio/diirt
graphene/graphene/src/test/java/org/diirt/graphene/Point2DTestDatasets.java
2733
/** * Copyright (C) 2010-14 diirt developers. See COPYRIGHT.TXT * All rights reserved. Use is subject to license terms. See LICENSE.TXT */ package org.diirt.graphene; import org.diirt.util.stats.Range; import java.util.Random; import org.diirt.util.array.ArrayDouble; /** * * @author carcassi */ public class Point2DTestDatasets { public static Point2DDataset sineDataset(int nSamples, int wavelengthInSamples, double initialAngleInRad, double amplitude, double average, Range xRange) { double[] data = new double[nSamples]; for (int j = 0; j < nSamples; j++) { data[j] = amplitude * Math.sin(j * 2.0 * Math.PI / wavelengthInSamples + initialAngleInRad) + average; } return Point2DDatasets.lineData(xRange, new ArrayDouble(data)); } public static double[] randomDataset() { Random rand = new Random(1); int nSamples = 100000; double[] waveform = new double[nSamples]; for (int i = 0; i < nSamples; i++) { waveform[i] = rand.nextGaussian(); } return waveform; } public static Point2DDataset sharpPeakData() { double[] dataSet = new double[100]; for (int i = 0; i < 50; i++) { dataSet[i] = i; } for (int i = 50; i < 100; i++) { dataSet[i] = 100 - i; } Point2DDataset data = Point2DDatasets.lineData(dataSet); return data; } public static Point2DDataset oneValueDataset() { double[] dataSet = {1.5}; Point2DDataset data = Point2DDatasets.lineData(dataSet); return data; } public static Point2DDataset twoValueDataset() { double[] dataSet = {10, 20}; Point2DDataset data = Point2DDatasets.lineData(dataSet); return data; } public static Point2DDataset negativeDataset() { double[] dataSet = new double[100]; for (int i = 0; i < 100; i++) { dataSet[i] = (i * -.5) / Math.pow(i, 2); } Point2DDataset data = Point2DDatasets.lineData(dataSet); return data; } public static Point2DDataset consecNaNDataset() { double[] dataSet = {Double.NaN, Double.NaN, 2, 5, 9, 15}; Point2DDataset data = Point2DDatasets.lineData(dataSet); return data; } public static Point2DDataset oneNaNDataset() { double[] dataSet = {1, Double.NaN, 10, 20}; Point2DDataset data = Point2DDatasets.lineData(dataSet); return data; } public static Point2DDataset twoSpacedNaNDataset() { double[] dataSet = {1, 8, 27, Double.NaN, 125, Double.NaN, 349}; Point2DDataset data = Point2DDatasets.lineData(dataSet); return data; } }
mit
LothrazarMinecraftMods/EnderBook
src/main/java/com/lothrazar/enderbook/UtilSound.java
568
package com.lothrazar.enderbook; import net.minecraft.entity.Entity; import net.minecraft.util.SoundCategory; import net.minecraft.util.SoundEvent; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; public class UtilSound{ public static void playSound(World world,BlockPos pos, SoundEvent s, SoundCategory c){ world.playSound(pos.getX(), pos.getY(), pos.getZ(), s, c, 1.0F, 1.0F, false); } public static void playSound(Entity entity, SoundEvent s, SoundCategory c){ playSound(entity.getEntityWorld(),entity.getPosition(),s,c); } }
mit
Arthur-Igor/project-manager-
src/project/tela/Tela.java
13063
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package project.tela; import banco_de_dados.CadastroCRUD; import model.Usuario; /** * * @author pc */ public class Tela extends javax.swing.JFrame { /** * Creates new form CalculadoraTela */ public Tela() { initComponents(); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jPanel1 = new javax.swing.JPanel(); jLabel1 = new javax.swing.JLabel(); jLabel2 = new javax.swing.JLabel(); jLabel3 = new javax.swing.JLabel(); jLabel4 = new javax.swing.JLabel(); TxtCapturaEmail = new javax.swing.JTextField(); TxtCapturaLogin = new javax.swing.JTextField(); TxtCapturaSenha = new javax.swing.JPasswordField(); BotaoLogar = new javax.swing.JButton(); TxtCapturaNome = new javax.swing.JTextField(); jLabel5 = new javax.swing.JLabel(); jButton1 = new javax.swing.JButton(); jMenuBar1 = new javax.swing.JMenuBar(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setTitle("Tela de Cadastro"); setBackground(new java.awt.Color(255, 153, 153)); setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR)); jPanel1.setBackground(new java.awt.Color(255, 102, 102)); jLabel1.setFont(new java.awt.Font("Jokerman", 0, 18)); // NOI18N jLabel1.setForeground(new java.awt.Color(255, 255, 255)); jLabel1.setText("Cadastro de usuário"); jLabel2.setText("Senha"); jLabel3.setText("Email"); jLabel4.setText("Login"); TxtCapturaEmail.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { TxtCapturaEmailActionPerformed(evt); } }); TxtCapturaLogin.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { TxtCapturaLoginActionPerformed(evt); } }); TxtCapturaSenha.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { TxtCapturaSenhaActionPerformed(evt); } }); BotaoLogar.setText("Cadastrar"); BotaoLogar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { BotaoLogarActionPerformed(evt); } }); TxtCapturaNome.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { TxtCapturaNomeActionPerformed(evt); } }); jLabel5.setText("Nome"); jButton1.setText("Sair"); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup() .addGap(74, 74, 74) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jLabel2) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(TxtCapturaSenha, javax.swing.GroupLayout.PREFERRED_SIZE, 214, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(jPanel1Layout.createSequentialGroup() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel4) .addComponent(jLabel3) .addComponent(jLabel5, javax.swing.GroupLayout.PREFERRED_SIZE, 31, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 84, Short.MAX_VALUE) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(TxtCapturaNome, javax.swing.GroupLayout.PREFERRED_SIZE, 214, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(TxtCapturaLogin, javax.swing.GroupLayout.PREFERRED_SIZE, 214, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(TxtCapturaEmail, javax.swing.GroupLayout.PREFERRED_SIZE, 214, javax.swing.GroupLayout.PREFERRED_SIZE)))) .addGap(87, 87, 87)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup() .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup() .addComponent(jButton1) .addContainerGap()) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup() .addComponent(BotaoLogar) .addGap(176, 176, 176)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup() .addComponent(jLabel1) .addGap(110, 110, 110)))) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap(88, Short.MAX_VALUE) .addComponent(jLabel1) .addGap(18, 18, 18) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(TxtCapturaNome, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel5)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel4) .addComponent(TxtCapturaLogin, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel3) .addComponent(TxtCapturaEmail, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel2) .addComponent(TxtCapturaSenha, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addComponent(BotaoLogar) .addGap(46, 46, 46) .addComponent(jButton1) .addContainerGap()) ); setJMenuBar(jMenuBar1); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); pack(); setLocationRelativeTo(null); }// </editor-fold>//GEN-END:initComponents private void TxtCapturaSenhaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_TxtCapturaSenhaActionPerformed // TODO add your handling code here: }//GEN-LAST:event_TxtCapturaSenhaActionPerformed private void TxtCapturaEmailActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_TxtCapturaEmailActionPerformed // TODO add your handling code here: }//GEN-LAST:event_TxtCapturaEmailActionPerformed private void BotaoLogarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BotaoLogarActionPerformed Usuario usuario = new Usuario(); usuario.setLogin(TxtCapturaLogin.getText().toString()); usuario.setEmail(TxtCapturaEmail.getText().toString()); usuario.setSenha(TxtCapturaSenha.getText().toString()); usuario.setNomeCompleto(TxtCapturaNome.getText().toString()); CadastroCRUD cRUD = new CadastroCRUD(); cRUD.cadastroUsuario(usuario); }//GEN-LAST:event_BotaoLogarActionPerformed private void TxtCapturaLoginActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_TxtCapturaLoginActionPerformed // TODO add your handling code here: }//GEN-LAST:event_TxtCapturaLoginActionPerformed private void TxtCapturaNomeActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_TxtCapturaNomeActionPerformed // TODO add your handling code here: }//GEN-LAST:event_TxtCapturaNomeActionPerformed /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(Tela.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(Tela.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(Tela.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(Tela.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new Tela().setVisible(false); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton BotaoLogar; private javax.swing.JTextField TxtCapturaEmail; private javax.swing.JTextField TxtCapturaLogin; private javax.swing.JTextField TxtCapturaNome; private javax.swing.JPasswordField TxtCapturaSenha; private javax.swing.JButton jButton1; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JLabel jLabel5; private javax.swing.JMenuBar jMenuBar1; private javax.swing.JPanel jPanel1; // End of variables declaration//GEN-END:variables }
mit
smallcreep/jb-hub-client
src/test/java/com/github/smallcreep/jb/hub/api/FieldTest.java
1824
/** * The MIT License (MIT) * * Copyright (c) 2017 Ilia Rogozhin (ilia.rogozhin@gmail.com) * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.github.smallcreep.jb.hub.api; import org.cactoos.ScalarHasValue; import org.hamcrest.MatcherAssert; import org.junit.Test; /** * Test Case for {@link Field}. * @author Ilia Rogozhin (ilia.rogozhin@gmail.com) * @version $Id$ * @since 0.2.0 */ public final class FieldTest { /** * Check field return encapsulated field name. * * @throws Exception If fails */ @Test public void field() throws Exception { MatcherAssert.assertThat( "Field doesn't return encapsulated field name!", new Field.Simple("first"), new ScalarHasValue<>("first") ); } }
mit
tbian7/pst
training/src/leetcode/Solution124.java
880
package leetcode; /** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Solution124 { private int maxSum; public Solution124() { maxSum = Integer.MIN_VALUE; } public int maxPathSum(TreeNode root) { recMaxPathSum(root); return maxSum; } private int recMaxPathSum(TreeNode root) { if (root == null) return 0; int left = recMaxPathSum(root.left); int right = recMaxPathSum(root.right); int maxPassThisNode = root.val; if (left > 0) maxPassThisNode += left; if (right > 0) maxPassThisNode += right; maxSum = Math.max(maxSum, maxPassThisNode); return Math.max(root.val + left, Math.max(root.val + right, root.val)); } }
mit
ivandejanovic/JavaTree
src/main/java/com/quine/javatree/JavaTreeNodeObject.java
2588
/** * The MIT License (MIT) * * Copyright 2008-2018 Ivan Dejanovic and Quine Interactive * www.quineinteractive.com * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * */ package com.quine.javatree; /** * JavaTreeNodeObject is a POJO class used as object property of DefaultMutableTreeNode in JavaTree application. * * @author Ivan Dejanovic * * @version 1.0 * * @since 1.0 * */ public class JavaTreeNodeObject { private String title; private String text; /** * Creates JavaTreeNodeObject and initialize title to "New Node", text to empty string. */ public JavaTreeNodeObject() { title = "New Node"; text = ""; } /** * Creates JavaTreeNodeObject and initialize title to title, text to empty string. * * @param title the node title */ public JavaTreeNodeObject(String title) { this.title = title; text = ""; } /** * @return title */ public String getTitle() { return title; } /** * @param title */ public void setTitle(String title) { this.title = title; } /** * @return text */ public String getText() { return text; } /** * @param text */ public void setText(String text) { this.text = text; } /** * Method used by JTree class to show Node from a model. Implemented using getTitle method. * * @return title */ @Override public String toString() { return getTitle(); } }
mit
hyperfresh/mc-universe
src/main/java/com/hyperfresh/mcuniverse/exceptions/ServerOfflineException.java
228
package com.hyperfresh.mcuniverse.exceptions; /** * @author Octopod - octopodsquad@gmail.com */ public class ServerOfflineException extends Exception { public ServerOfflineException(String message) { super(message); } }
mit
openforis/calc
calc-core/src/generated/java/org/openforis/calc/persistence/jooq/tables/ProcessingChainTable.java
4661
/** * This class is generated by jOOQ */ package org.openforis.calc.persistence.jooq.tables; import java.util.Arrays; import java.util.List; import javax.annotation.Generated; import org.jooq.Field; import org.jooq.ForeignKey; import org.jooq.Identity; import org.jooq.Table; import org.jooq.TableField; import org.jooq.UniqueKey; import org.jooq.impl.TableImpl; import org.openforis.calc.engine.ParameterMap; import org.openforis.calc.engine.Worker.Status; import org.openforis.calc.persistence.jooq.CalcSchema; import org.openforis.calc.persistence.jooq.Keys; import org.openforis.calc.persistence.jooq.ParameterMapConverter; import org.openforis.calc.persistence.jooq.WorkerStatusConverter; import org.openforis.calc.persistence.jooq.tables.records.ProcessingChainRecord; /** * This class is generated by jOOQ. */ @Generated( value = { "http://www.jooq.org", "jOOQ version:3.6.2" }, comments = "This class is generated by jOOQ" ) @SuppressWarnings({ "all", "unchecked", "rawtypes" }) public class ProcessingChainTable extends TableImpl<ProcessingChainRecord> { private static final long serialVersionUID = -564183359; /** * The reference instance of <code>calc.processing_chain</code> */ public static final ProcessingChainTable PROCESSING_CHAIN = new ProcessingChainTable(); /** * The class holding records for this type */ @Override public Class<ProcessingChainRecord> getRecordType() { return ProcessingChainRecord.class; } /** * The column <code>calc.processing_chain.id</code>. */ public final TableField<ProcessingChainRecord, Integer> ID = createField("id", org.jooq.impl.SQLDataType.INTEGER.nullable(false).defaulted(true), this, ""); /** * The column <code>calc.processing_chain.workspace_id</code>. */ public final TableField<ProcessingChainRecord, Integer> WORKSPACE_ID = createField("workspace_id", org.jooq.impl.SQLDataType.INTEGER.nullable(false), this, ""); /** * The column <code>calc.processing_chain.parameters</code>. */ public final TableField<ProcessingChainRecord, ParameterMap> PARAMETERS = createField("parameters", org.jooq.impl.SQLDataType.CLOB, this, "", new ParameterMapConverter()); /** * The column <code>calc.processing_chain.caption</code>. */ public final TableField<ProcessingChainRecord, String> CAPTION = createField("caption", org.jooq.impl.SQLDataType.VARCHAR.length(255), this, ""); /** * The column <code>calc.processing_chain.description</code>. */ public final TableField<ProcessingChainRecord, String> DESCRIPTION = createField("description", org.jooq.impl.SQLDataType.VARCHAR.length(1024), this, ""); /** * The column <code>calc.processing_chain.status</code>. */ public final TableField<ProcessingChainRecord, Status> STATUS = createField("status", org.jooq.impl.SQLDataType.VARCHAR.length(255), this, "", new WorkerStatusConverter()); /** * The column <code>calc.processing_chain.common_script</code>. */ public final TableField<ProcessingChainRecord, String> COMMON_SCRIPT = createField("common_script", org.jooq.impl.SQLDataType.CLOB, this, ""); /** * Create a <code>calc.processing_chain</code> table reference */ public ProcessingChainTable() { this("processing_chain", null); } /** * Create an aliased <code>calc.processing_chain</code> table reference */ public ProcessingChainTable(String alias) { this(alias, PROCESSING_CHAIN); } private ProcessingChainTable(String alias, Table<ProcessingChainRecord> aliased) { this(alias, aliased, null); } private ProcessingChainTable(String alias, Table<ProcessingChainRecord> aliased, Field<?>[] parameters) { super(alias, CalcSchema.CALC, aliased, parameters, ""); } /** * {@inheritDoc} */ @Override public Identity<ProcessingChainRecord, Integer> getIdentity() { return Keys.IDENTITY_PROCESSING_CHAIN; } /** * {@inheritDoc} */ @Override public UniqueKey<ProcessingChainRecord> getPrimaryKey() { return Keys.PROCESSING_CHAIN_PKEY; } /** * {@inheritDoc} */ @Override public List<UniqueKey<ProcessingChainRecord>> getKeys() { return Arrays.<UniqueKey<ProcessingChainRecord>>asList(Keys.PROCESSING_CHAIN_PKEY); } /** * {@inheritDoc} */ @Override public List<ForeignKey<ProcessingChainRecord, ?>> getReferences() { return Arrays.<ForeignKey<ProcessingChainRecord, ?>>asList(Keys.PROCESSING_CHAIN__PROCESSING_CHAIN_WORKSPACE_FKEY); } /** * {@inheritDoc} */ @Override public ProcessingChainTable as(String alias) { return new ProcessingChainTable(alias, this); } /** * Rename this table */ public ProcessingChainTable rename(String name) { return new ProcessingChainTable(name, null); } }
mit
SpongePowered/SpongeAPI
src/main/java/org/spongepowered/api/scheduler/TaskExecutorService.java
3000
/* * This file is part of SpongeAPI, licensed under the MIT License (MIT). * * Copyright (c) SpongePowered <https://www.spongepowered.org> * Copyright (c) contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.spongepowered.api.scheduler; import org.checkerframework.checker.nullness.qual.Nullable; import java.time.temporal.TemporalUnit; import java.util.concurrent.Callable; import java.util.concurrent.ExecutorService; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; /** * A delegating {@link ExecutorService} that schedules all its tasks on * Sponge's {@link Scheduler}. * * <p>This class can be used to allow any libraries that support the * standard concurrency interface to schedule their asynchronous * tasks through Sponge.</p> */ public interface TaskExecutorService extends ScheduledExecutorService { @Override <T> TaskFuture<T> submit(Callable<T> task); @Override TaskFuture<?> submit(Runnable task); @Override <T> TaskFuture<T> submit(Runnable task, @Nullable T result); ScheduledTaskFuture<?> schedule(Runnable command, long delay, TemporalUnit unit); @Override ScheduledTaskFuture<?> schedule(Runnable command, long delay, TimeUnit unit); <V> ScheduledTaskFuture<V> schedule(Callable<V> callable, long delay, TemporalUnit unit); @Override <V> ScheduledTaskFuture<V> schedule(Callable<V> callable, long delay, TimeUnit unit); ScheduledTaskFuture<?> scheduleAtFixedRate(Runnable command, long initialDelay, long period, TemporalUnit unit); @Override ScheduledTaskFuture<?> scheduleAtFixedRate(Runnable command, long initialDelay, long period, TimeUnit unit); ScheduledTaskFuture<?> scheduleWithFixedDelay(Runnable command, long initialDelay, long delay, TemporalUnit unit); @Override ScheduledTaskFuture<?> scheduleWithFixedDelay(Runnable command, long initialDelay, long delay, TimeUnit unit); }
mit
shokai/ArduinoFirmata-Android
samples/sysex/SysexSampleApp/gen/org/shokai/firmata/sysexsample/BuildConfig.java
172
/** Automatically generated file. DO NOT MODIFY */ package org.shokai.firmata.sysexsample; public final class BuildConfig { public final static boolean DEBUG = true; }
mit
mhogrefe/qbar
src/test/java/mho/qbar/objects/IntervalDemos.java
17278
package mho.qbar.objects; import mho.qbar.testing.QBarDemos; import mho.wheels.ordering.Ordering; import mho.wheels.structures.Either; import mho.wheels.structures.Pair; import mho.wheels.structures.Triple; import org.jetbrains.annotations.NotNull; import java.math.BigDecimal; import java.math.BigInteger; import java.util.Arrays; import java.util.List; import java.util.Optional; import static mho.qbar.objects.Interval.*; import static mho.qbar.objects.Interval.sum; import static mho.qbar.testing.QBarTesting.QEP; import static mho.wheels.iterables.IterableUtils.*; import static mho.wheels.testing.Testing.*; @SuppressWarnings("UnusedDeclaration") public class IntervalDemos extends QBarDemos { private static final @NotNull String INTERVAL_CHARS = " (),-/0123456789I[]finty"; public IntervalDemos(boolean useRandom) { super(useRandom); } private void demoGetLower() { for (Interval a : take(LIMIT, P.intervals())) { System.out.println("getLower(" + a + ") = " + a.getLower()); } } private void demoGetUpper() { for (Interval a : take(LIMIT, P.intervals())) { System.out.println("getUpper(" + a + ") = " + a.getUpper()); } } private void demoOf_Rational_Rational() { for (Pair<Rational, Rational> p : take(LIMIT, P.bagPairs(P.rationals()))) { System.out.println("of(" + p.a + ", " + p.b + ") = " + of(p.a, p.b)); } } private void demoLessThanOrEqualTo() { for (Rational r : take(LIMIT, P.rationals())) { System.out.println("lessThanOrEqualTo(" + r + ") = " + lessThanOrEqualTo(r)); } } private void demoGreaterThanOrEqualTo() { for (Rational r : take(LIMIT, P.rationals())) { System.out.println("greaterThanOrEqualTo(" + r + ") = " + greaterThanOrEqualTo(r)); } } private void demoOf_Rational() { for (Rational r : take(LIMIT, P.rationals())) { System.out.println("of(" + r + ") = " + Interval.of(r)); } } private void demoBitLength() { for (Interval a : take(LIMIT, P.intervals())) { System.out.println("bitLength(" + a + ") = " + a.bitLength()); } } private void demoIsFinitelyBounded() { for (Interval a : take(LIMIT, P.intervals())) { System.out.println(a + " is " + (a.isFinitelyBounded() ? "" : "not ") + "finitely bounded"); } } private void demoContains_Rational() { for (Pair<Interval, Rational> p : take(LIMIT, P.pairs(P.intervals(), P.rationals()))) { System.out.println(p.a + (p.a.contains(p.b) ? " contains " : " does not contain ") + p.b); } } private void demoContains_Algebraic() { for (Pair<Interval, Algebraic> p : take(LIMIT, P.pairs(P.intervals(), P.withScale(4).algebraics()))) { System.out.println(p.a + (p.a.contains(p.b) ? " contains " : " does not contain ") + p.b); } } private void demoContainsUnsafe() { Iterable<Rational> rs = P.rationals(); //noinspection RedundantCast,Convert2MethodRef Iterable<Pair<Interval, Real>> ps = map( q -> { Either<Algebraic, Pair<Rational, Integer>> e = q.b; switch (e.whichSlot()) { case A: return new Pair<>(q.a, e.a().realValue()); case B: Pair<Rational, Integer> r = e.b(); switch (r.b) { case -1: return new Pair<>(q.a, Real.leftFuzzyRepresentation(r.a)); case 1: return new Pair<>(q.a, Real.rightFuzzyRepresentation(r.a)); case 0: return new Pair<>(q.a, Real.fuzzyRepresentation(r.a)); default: throw new IllegalStateException(); } default: throw new IllegalStateException(); } }, filterInfinite( p -> { if (p.b.whichSlot() == Either.Slot.A) { return true; } Pair<Rational, Integer> q = p.b.b(); Optional<Rational> lower = p.a.getLower(); if (lower.isPresent() && lower.get().equals(q.a) && q.b < 1) { return false; } Optional<Rational> upper = p.a.getUpper(); //noinspection RedundantIfStatement if (upper.isPresent() && upper.get().equals(q.a) && q.b > -1) { return false; } return true; }, P.pairs( P.intervals(), (Iterable<Either<Algebraic, Pair<Rational, Integer>>>) P.withScale(1).choose( (Iterable<Either<Algebraic, Pair<Rational, Integer>>>) map( x -> Either.<Algebraic, Pair<Rational, Integer>>ofA(x), P.withScale(4).algebraics() ), P.choose( Arrays.asList( map(r -> Either.ofB(new Pair<>(r, -1)), rs), map(r -> Either.ofB(new Pair<>(r, 1)), rs), map(r -> Either.ofB(new Pair<>(r, 0)), rs) ) ) ) ) ) ); for (Pair<Interval, Real> p : take(LIMIT, ps)) { System.out.println(p.a + (p.a.containsUnsafe(p.b) ? " contains " : " does not contain ") + p.b); } } private void demoContains_Real_Rational() { Iterable<Triple<Interval, Real, Rational>> ts = P.triples( P.intervals(), P.withScale(4).reals(), P.positiveRationals() ); for (Triple<Interval, Real, Rational> t : take(LIMIT, ts)) { System.out.println("contains(" + t.a + ", " + t.b + ", " + t.c + ") = " + t.a.contains(t.b, t.c)); } } private void demoContains_Interval() { for (Pair<Interval, Interval> p : take(LIMIT, P.pairs(P.intervals()))) { System.out.println(p.a + (p.a.contains(p.b) ? " contains " : " does not contain ") + p.b); } } private void demoDiameter() { for (Interval a : take(LIMIT, P.intervals())) { System.out.println("diameter(" + a + ") = " + a.diameter()); } } private void demoConvexHull_Interval() { for (Pair<Interval, Interval> p : take(LIMIT, P.pairs(P.intervals()))) { System.out.println("convexHull(" + p.a + ", " + p.b + ") = " + p.a.convexHull(p.b)); } } private void demoConvexHull_List_Interval() { for (List<Interval> as : take(LIMIT, P.withScale(4).listsAtLeast(1, P.intervals()))) { System.out.println("convexHull(" + middle(as.toString()) + ") = " + convexHull(as)); } } private void demoIntersection() { for (Pair<Interval, Interval> p : take(LIMIT, P.pairs(P.intervals()))) { System.out.println(p.a + " ∩ " + p.b + " = " + p.a.intersection(p.b)); } } private void demoDisjoint() { for (Pair<Interval, Interval> p : take(LIMIT, P.pairs(P.intervals()))) { System.out.println(p.a + " and " + p.b + " are " + (p.a.disjoint(p.b) ? "" : "not ") + "disjoint"); } } private void demoUnion() { for (List<Interval> as : take(LIMIT, P.withScale(4).lists(P.intervals()))) { System.out.println("⋃(" + middle(as.toString()) + ") = " + union(as)); } } private void demoComplement() { for (Interval a : take(LIMIT, P.intervals())) { System.out.println("complement(" + a + ") = " + a.complement()); } } private void demoMidpoint() { for (Interval a : take(LIMIT, P.finitelyBoundedIntervals())) { System.out.println("midpoint(" + a + ") = " + a.midpoint()); } } private void demoSplit() { Iterable<Pair<Interval, Rational>> ps = filterInfinite( q -> q.a.contains(q.b), P.pairs(P.intervals(), P.rationals()) ); for (Pair<Interval, Rational> p : take(LIMIT, ps)) { System.out.println("split(" + p.a + ", " + p.b + ") = " + p.a.split(p.b)); } } private void demoBisect() { for (Interval a : take(LIMIT, P.finitelyBoundedIntervals())) { System.out.println("bisect(" + a + ") = " + a.bisect()); } } private void demoRoundingPreimage_float() { for (float f : take(LIMIT, filter(g -> !Float.isNaN(g), P.floats()))) { System.out.println("roundingPreimage(" + f + ") = " + roundingPreimage(f)); } } private void demoRoundingPreimage_double() { for (double d : take(MEDIUM_LIMIT, filter(e -> !Double.isNaN(e), P.doubles()))) { System.out.println("roundingPreimage(" + d + ") = " + roundingPreimage(d)); } } private void demoRoundingPreimage_BigDecimal() { for (BigDecimal bd : take(LIMIT, P.bigDecimals())) { System.out.println("roundingPreimage(" + bd + ") = " + roundingPreimage(bd)); } } private void demoAdd() { for (Pair<Interval, Interval> p : take(LIMIT, P.pairs(P.intervals()))) { System.out.println(p.a + " + " + p.b + " = " + p.a.add(p.b)); } } private void demoNegate() { for (Interval a : take(LIMIT, P.intervals())) { System.out.println("-" + a + " = " + a.negate()); } } private void demoAbs() { for (Interval a : take(LIMIT, P.intervals())) { System.out.println("|" + a + "| = " + a.abs()); } } private void demoSignum() { for (Interval a : take(LIMIT, P.intervals())) { System.out.println("signum(" + a + ") = " + a.signum()); } } private void demoSubtract() { for (Pair<Interval, Interval> p : take(LIMIT, P.pairs(P.intervals()))) { System.out.println(p.a + " - " + p.b + " = " + p.a.subtract(p.b)); } } private void demoMultiply_Interval() { for (Pair<Interval, Interval> p : take(LIMIT, P.pairs(P.intervals()))) { System.out.println(p.a + " * " + p.b + " = " + p.a.multiply(p.b)); } } private void demoMultiply_Rational() { for (Pair<Interval, Rational> p : take(LIMIT, P.pairs(P.intervals(), P.rationals()))) { System.out.println(p.a + " * " + p.b + " = " + p.a.multiply(p.b)); } } private void demoMultiply_BigInteger() { for (Pair<Interval, BigInteger> p : take(LIMIT, P.pairs(P.intervals(), P.bigIntegers()))) { System.out.println(p.a + " * " + p.b + " = " + p.a.multiply(p.b)); } } private void demoMultiply_int() { for (Pair<Interval, Integer> p : take(LIMIT, P.pairs(P.intervals(), P.integers()))) { System.out.println(p.a + " * " + p.b + " = " + p.a.multiply(p.b)); } } private void demoInvert() { for (Interval a : take(LIMIT, P.intervals())) { System.out.println("1 / " + a + " = " + a.invert()); } } private void demoInvertHull() { for (Interval a : take(LIMIT, filterInfinite(b -> !b.equals(ZERO), P.intervals()))) { System.out.println("invertHull(" + a + ") = " + a.invertHull()); } } private void demoDivide_Interval() { for (Pair<Interval, Interval> p : take(LIMIT, P.pairs(P.intervals()))) { System.out.println(p.a + " / " + p.b + " = " + p.a.divide(p.b)); } } private void demoDivideHull() { Iterable<Pair<Interval, Interval>> ps = filterInfinite(q -> !q.b.equals(ZERO), P.pairs(P.intervals())); for (Pair<Interval, Interval> p : take(LIMIT, ps)) { System.out.println("divideHull(" + p.a + ", " + p.b + ") = " + p.a.divideHull(p.b)); } } private void demoDivide_Rational() { for (Pair<Interval, Rational> p : take(LIMIT, P.pairs(P.intervals(), P.nonzeroRationals()))) { System.out.println(p.a + " / " + p.b + " = " + p.a.divide(p.b)); } } private void demoDivide_BigInteger() { for (Pair<Interval, BigInteger> p : take(LIMIT, P.pairs(P.intervals(), P.nonzeroBigIntegers()))) { System.out.println(p.a + " / " + p.b + " = " + p.a.divide(p.b)); } } private void demoDivide_int() { for (Pair<Interval, Integer> p : take(LIMIT, P.pairs(P.intervals(), P.nonzeroIntegers()))) { System.out.println(p.a + " / " + p.b + " = " + p.a.divide(p.b)); } } private void demoShiftLeft() { for (Pair<Interval, Integer> p : take(LIMIT, P.pairs(P.intervals(), P.integersGeometric()))) { System.out.println(p.a + " << " + p.b + " = " + p.a.shiftLeft(p.b)); } } private void demoShiftRight() { for (Pair<Interval, Integer> p : take(LIMIT, P.pairs(P.intervals(), P.integersGeometric()))) { System.out.println(p.a + " >> " + p.b + " = " + p.a.shiftRight(p.b)); } } private void demoSum() { for (List<Interval> rs : take(LIMIT, P.withScale(4).lists(P.intervals()))) { System.out.println("Σ(" + middle(rs.toString()) + ") = " + sum(rs)); } } private void demoProduct() { for (List<Interval> rs : take(LIMIT, P.withScale(4).lists(P.intervals()))) { System.out.println("Π(" + middle(rs.toString()) + ") = " + product(rs)); } } private void demoDelta_finite() { for (List<Interval> rs : take(LIMIT, P.withScale(4).listsAtLeast(1, P.intervals()))) { System.out.println("Δ(" + middle(rs.toString()) + ") = " + its(delta(rs))); } } private void demoDelta_infinite() { for (Iterable<Interval> as : take(MEDIUM_LIMIT, P.prefixPermutations(QEP.intervals()))) { System.out.println("Δ(" + middle(its(as)) + ") = " + its(delta(as))); } } private void demoPow() { for (Pair<Interval, Integer> p : take(LIMIT, P.pairs(P.intervals(), P.integersGeometric()))) { System.out.println(p.a + " ^ " + p.b + " = " + p.a.pow(p.b)); } } private void demoPowHull() { Iterable<Pair<Interval, Integer>> ps = filterInfinite( p -> p.b >= 0 || !p.a.equals(ZERO), P.pairs(P.intervals(), P.integersGeometric()) ); for (Pair<Interval, Integer> p : take(LIMIT, ps)) { System.out.println("powHull(" + p.a + ", " + p.b + ") = " + p.a.powHull(p.b)); } } private void demoElementCompare() { for (Pair<Interval, Interval> p : take(LIMIT, P.pairs(P.intervals()))) { System.out.println("elementCompare(" + p.a + ", " + p.b + ") = " + p.a.elementCompare(p.b)); } } private void demoEquals_Interval() { for (Pair<Interval, Interval> p : take(LIMIT, P.pairs(P.intervals()))) { System.out.println(p.a + (p.a.equals(p.b) ? " = " : " ≠ ") + p.b); } } private void demoEquals_null() { for (Interval a : take(LIMIT, P.intervals())) { //noinspection ObjectEqualsNull System.out.println(a + (a.equals(null) ? " = " : " ≠ ") + null); } } private void demoHashCode() { for (Interval a : take(LIMIT, P.intervals())) { System.out.println("hashCode(" + a + ") = " + a.hashCode()); } } private void demoCompareTo() { for (Pair<Interval, Interval> p : take(LIMIT, P.pairs(P.intervals()))) { System.out.println(p.a + " " + Ordering.compare(p.a, p.b) + " " + p.b); } } private void demoReadStrict() { for (String s : take(LIMIT, P.strings())) { System.out.println("readStrict(" + nicePrint(s) + ") = " + readStrict(s)); } } private void demoReadStrict_targeted() { for (String s : take(LIMIT, P.strings(INTERVAL_CHARS))) { System.out.println("readStrict(" + s + ") = " + readStrict(s)); } } private void demoToString() { for (Interval a : take(LIMIT, P.intervals())) { System.out.println(a); } } }
mit
GWYOG/GTVeinLocator
src/main/java/pers/gwyog/gtveinlocator/util/GTVeinNameHelper.java
633
package pers.gwyog.gtveinlocator.util; import java.util.HashMap; import java.util.List; import java.util.Map; public class GTVeinNameHelper { private static byte id = 0; private static Map<String, Byte> map1 = new HashMap<String, Byte>(); private static Map<Byte, String> map2 = new HashMap<Byte, String>(); public static void registerVeinName(String str) { map1.put(str, id); map2.put(id++, str); } public static byte getIndex(String str) { return map1.get(str); } public static String getName(byte index) { return map2.get(index); } }
mit
RogueLogic/Big-Fusion
src/main/java/net/RogueLogic/mods/bigfusion/common/multiblock/Tokamak/Blocks/TokamakBlockCoolantIOPort.java
3527
package net.roguelogic.mods.bigfusion.common.multiblock.Tokamak.Blocks; import it.zerono.mods.zerocore.api.multiblock.MultiblockTileEntityBase; import net.minecraft.util.text.TextComponentTranslation; import net.roguelogic.mods.bigfusion.common.multiblock.Tokamak.Enums.PortDirection; import net.roguelogic.mods.bigfusion.common.multiblock.Tokamak.TileEntitys.TokamakTileEntityCoolantIO; import net.minecraft.block.properties.PropertyEnum; import net.minecraft.block.state.BlockStateContainer; import net.minecraft.block.state.IBlockState; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.EnumFacing; import net.minecraft.util.EnumHand; import net.minecraft.util.math.BlockPos; import net.minecraft.world.IBlockAccess; import net.minecraft.world.World; import javax.annotation.Nonnull; import java.util.Random; //import static net.roguelogic.mods.bigfusion.utils.LogHelper.log; public class TokamakBlockCoolantIOPort extends TokamakBlockBase { public TokamakBlockCoolantIOPort(String name, boolean addToTab) { super(name, addToTab); } @Override public TileEntity createTileEntity(World world, IBlockState state) { return new TokamakTileEntityCoolantIO(); } @Override public boolean onBlockActivated(World world, BlockPos position, IBlockState state, EntityPlayer player, EnumHand hand, ItemStack heldItem, EnumFacing side, float hitX, float hitY, float hitZ) { if (world.isRemote || hand == EnumHand.OFF_HAND) return false; if (player.isSneaking()) { ((TokamakTileEntityCoolantIO) world.getTileEntity(position)).toggle(player); return true; } else { return super.onBlockActivated(world, position, state, player, hand, heldItem, side, hitX, hitY, hitZ); } } @Override public void updateTick(World worldIn, BlockPos pos, IBlockState state, Random rand) { super.updateTick(worldIn, pos, state, rand); } @Override public IBlockState getStateFromMeta(int state) { return this.getDefaultState(); } @Override public int getMetaFromState(IBlockState state) { return 0; } @Override public BlockStateContainer createBlockState() { return new BlockStateContainer(this, PORT_STATE); } @Override public IBlockState getActualState(IBlockState state, IBlockAccess world, BlockPos position) { TileEntity te = world.getTileEntity(position); if (te instanceof MultiblockTileEntityBase) state = this.buildActualState(state, world, position, (MultiblockTileEntityBase) te); return state; } @Override public void onNeighborChange(IBlockAccess world, BlockPos pos, BlockPos neighbor) { if (world.getTileEntity(pos) instanceof TokamakTileEntityCoolantIO) { ((TokamakTileEntityCoolantIO) world.getTileEntity(pos)).checkForAdjacentTank(); } super.onNeighborChange(world, pos, neighbor); } public static final PropertyEnum<PortDirection> PORT_STATE = PropertyEnum.create("state", PortDirection.class); protected IBlockState buildActualState(@Nonnull IBlockState state, @Nonnull IBlockAccess world, @Nonnull BlockPos position, @Nonnull MultiblockTileEntityBase part) { return state.withProperty(PORT_STATE, ((TokamakTileEntityCoolantIO) part).state); } }
mit
Otanikotani/jacoco-parser
src/main/java/com/aurea/coverage/unit/MethodContainerUnit.java
679
package com.aurea.coverage.unit; import java.util.stream.Stream; public abstract class MethodContainerUnit extends NamedImpl implements CoverageUnit { protected MethodContainerUnit(String name) { super(name); } public abstract Stream<MethodCoverage> methodCoverages(); @Override public int getCovered() { return methodCoverages().mapToInt(MethodCoverage::getCovered).sum(); } @Override public int getUncovered() { return methodCoverages().mapToInt(MethodCoverage::getUncovered).sum(); } @Override public int getTotal() { return methodCoverages().mapToInt(MethodCoverage::getTotal).sum(); } }
mit
Programming-Systems-Lab/knarr
Phosphor/src/edu/columbia/cs/psl/phosphor/org/objectweb/asm/tree/LabelNode.java
2670
/*** * ASM: a very small and fast Java bytecode manipulation framework * Copyright (c) 2000-2011 INRIA, France Telecom * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the copyright holders nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. */ package edu.columbia.cs.psl.phosphor.org.objectweb.asm.tree; import java.util.Map; import edu.columbia.cs.psl.phosphor.org.objectweb.asm.Label; import edu.columbia.cs.psl.phosphor.org.objectweb.asm.MethodVisitor; /** * An {@link AbstractInsnNode} that encapsulates a {@link Label}. */ public class LabelNode extends AbstractInsnNode { private Label label; public LabelNode() { super(-1); } public LabelNode(final Label label) { super(-1); this.label = label; } @Override public int getType() { return LABEL; } public Label getLabel() { if (label == null) { label = new Label(); } return label; } @Override public void accept(final MethodVisitor cv) { cv.visitLabel(getLabel()); } @Override public AbstractInsnNode clone(final Map<LabelNode, LabelNode> labels) { return labels.get(this); } public void resetLabel() { label = null; } }
mit