repo_name stringlengths 5 108 | path stringlengths 6 333 | size stringlengths 1 6 | content stringlengths 4 977k | license stringclasses 15
values |
|---|---|---|---|---|
gfyoung/elasticsearch | server/src/test/java/org/elasticsearch/search/aggregations/pipeline/bucketmetrics/avg/AvgBucketAggregatorTests.java | 6720 | /*
* 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.search.aggregations.pipeline.bucketmetrics.avg;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.SortedNumericDocValuesField;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.RandomIndexWriter;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.MatchAllDocsQuery;
import org.apache.lucene.search.Query;
import org.apache.lucene.store.Directory;
import org.elasticsearch.index.mapper.DateFieldMapper;
import org.elasticsearch.index.mapper.MappedFieldType;
import org.elasticsearch.index.mapper.NumberFieldMapper;
import org.elasticsearch.search.aggregations.Aggregation;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.AggregatorTestCase;
import org.elasticsearch.search.aggregations.InternalAggregation;
import org.elasticsearch.search.aggregations.bucket.histogram.DateHistogramAggregationBuilder;
import org.elasticsearch.search.aggregations.bucket.histogram.DateHistogramInterval;
import org.elasticsearch.search.aggregations.bucket.histogram.InternalDateHistogram;
import org.elasticsearch.search.aggregations.metrics.AvgAggregationBuilder;
import org.elasticsearch.search.aggregations.metrics.InternalAvg;
import org.elasticsearch.search.aggregations.pipeline.PipelineAggregator;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class AvgBucketAggregatorTests extends AggregatorTestCase {
private static final String DATE_FIELD = "date";
private static final String VALUE_FIELD = "value";
private static final List<String> dataset = Arrays.asList(
"2010-03-12T01:07:45",
"2010-04-27T03:43:34",
"2012-05-18T04:11:00",
"2013-05-29T05:11:31",
"2013-10-31T08:24:05",
"2015-02-13T13:09:32",
"2015-06-24T13:47:43",
"2015-11-13T16:14:34",
"2016-03-04T17:09:50",
"2017-12-12T22:55:46");
/**
* Test for issue #30608. Under the following circumstances:
*
* A. Multi-bucket agg in the first entry of our internal list
* B. Regular agg as the immediate child of the multi-bucket in A
* C. Regular agg with the same name as B at the top level, listed as the second entry in our internal list
* D. Finally, a pipeline agg with the path down to B
*
* BucketMetrics reduction would throw a class cast exception due to bad subpathing. This test ensures
* it is fixed.
*
* Note: we have this test inside of the `avg_bucket` package so that we can get access to the package-private
* `doReduce()` needed for testing this
*/
public void testSameAggNames() throws IOException {
Query query = new MatchAllDocsQuery();
AvgAggregationBuilder avgBuilder = new AvgAggregationBuilder("foo").field(VALUE_FIELD);
DateHistogramAggregationBuilder histo = new DateHistogramAggregationBuilder("histo")
.dateHistogramInterval(DateHistogramInterval.YEAR)
.field(DATE_FIELD)
.subAggregation(new AvgAggregationBuilder("foo").field(VALUE_FIELD));
AvgBucketPipelineAggregationBuilder avgBucketBuilder
= new AvgBucketPipelineAggregationBuilder("the_avg_bucket", "histo>foo");
try (Directory directory = newDirectory()) {
try (RandomIndexWriter indexWriter = new RandomIndexWriter(random(), directory)) {
Document document = new Document();
for (String date : dataset) {
if (frequently()) {
indexWriter.commit();
}
document.add(new SortedNumericDocValuesField(DATE_FIELD, asLong(date)));
document.add(new SortedNumericDocValuesField(VALUE_FIELD, randomInt()));
indexWriter.addDocument(document);
document.clear();
}
}
InternalAvg avgResult;
InternalDateHistogram histogramResult;
try (IndexReader indexReader = DirectoryReader.open(directory)) {
IndexSearcher indexSearcher = newSearcher(indexReader, true, true);
DateFieldMapper.Builder builder = new DateFieldMapper.Builder("histo");
DateFieldMapper.DateFieldType fieldType = builder.fieldType();
fieldType.setHasDocValues(true);
fieldType.setName(DATE_FIELD);
MappedFieldType valueFieldType = new NumberFieldMapper.NumberFieldType(NumberFieldMapper.NumberType.LONG);
valueFieldType.setName(VALUE_FIELD);
valueFieldType.setHasDocValues(true);
avgResult = searchAndReduce(indexSearcher, query, avgBuilder, 10000, null,
new MappedFieldType[]{fieldType, valueFieldType});
histogramResult = searchAndReduce(indexSearcher, query, histo, 10000, null,
new MappedFieldType[]{fieldType, valueFieldType});
}
// Finally, reduce the pipeline agg
PipelineAggregator avgBucketAgg = avgBucketBuilder.createInternal(Collections.emptyMap());
List<Aggregation> reducedAggs = new ArrayList<>(2);
// Histo has to go first to exercise the bug
reducedAggs.add(histogramResult);
reducedAggs.add(avgResult);
Aggregations aggregations = new Aggregations(reducedAggs);
InternalAggregation pipelineResult = ((AvgBucketPipelineAggregator)avgBucketAgg).doReduce(aggregations, null);
assertNotNull(pipelineResult);
}
}
private static long asLong(String dateTime) {
return DateFieldMapper.DEFAULT_DATE_TIME_FORMATTER.parser().parseDateTime(dateTime).getMillis();
}
}
| apache-2.0 |
nmirasch/kie-wb-common | kie-wb-common-widgets/kie-wb-decorated-grid-widget/src/test/java/org/kie/workbench/common/widgets/decoratedgrid/data/DynamicDataTestsWithMerging.java | 7664 | /*
* Copyright 2011 JBoss Inc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.kie.workbench.common.widgets.decoratedgrid.data;
import org.junit.Before;
import org.junit.Test;
import org.kie.workbench.common.widgets.decoratedgrid.client.widget.CellValue;
import org.kie.workbench.common.widgets.decoratedgrid.client.widget.data.Coordinate;
import static junit.framework.Assert.assertEquals;
/**
* Tests for DynamicData
*/
public class DynamicDataTestsWithMerging extends BaseDynamicDataTests {
@Before
public void setup() {
super.setup();
//Setup date to merge
//[1][-][3]
//[1][2][3]
//[-][2][3]
data.get( 0 ).get( 0 ).setValue( "1" );
data.get( 0 ).get( 1 ).setValue( "-" );
data.get( 0 ).get( 2 ).setValue( "3" );
data.get( 1 ).get( 0 ).setValue( "1" );
data.get( 1 ).get( 1 ).setValue( "2" );
data.get( 1 ).get( 2 ).setValue( "3" );
data.get( 2 ).get( 0 ).setValue( "-" );
data.get( 2 ).get( 1 ).setValue( "2" );
data.get( 2 ).get( 2 ).setValue( "3" );
}
@Test
public void testIndexing_DataCoordinates() {
//[1][-][3] --> [0,0][0,1][0,2]
//[1][2][3] --> [1,0][1,1][1,2]
//[-][2][3] --> [2,0][2,1][2,2]
data.setMerged( true );
Coordinate c;
c = data.get( 0 ).get( 0 ).getCoordinate();
assertEquals( c.getRow(),
0 );
assertEquals( c.getCol(),
0 );
c = data.get( 0 ).get( 1 ).getCoordinate();
assertEquals( c.getRow(),
0 );
assertEquals( c.getCol(),
1 );
c = data.get( 0 ).get( 2 ).getCoordinate();
assertEquals( c.getRow(),
0 );
assertEquals( c.getCol(),
2 );
c = data.get( 1 ).get( 0 ).getCoordinate();
assertEquals( c.getRow(),
1 );
assertEquals( c.getCol(),
0 );
c = data.get( 1 ).get( 1 ).getCoordinate();
assertEquals( c.getRow(),
1 );
assertEquals( c.getCol(),
1 );
c = data.get( 1 ).get( 2 ).getCoordinate();
assertEquals( c.getRow(),
1 );
assertEquals( c.getCol(),
2 );
c = data.get( 2 ).get( 0 ).getCoordinate();
assertEquals( c.getRow(),
2 );
assertEquals( c.getCol(),
0 );
c = data.get( 2 ).get( 1 ).getCoordinate();
assertEquals( c.getRow(),
2 );
assertEquals( c.getCol(),
1 );
c = data.get( 2 ).get( 2 ).getCoordinate();
assertEquals( c.getRow(),
2 );
assertEquals( c.getCol(),
2 );
}
@Test
public void testIndexing_HtmlCoordinates() {
//[1][-][3] --> [0,0][0,1][0,2]
//[1][2][3] --> [0,0][1,0][0,2]
//[-][2][3] --> [2,0][1,0][0,2]
data.setMerged( true );
Coordinate c;
c = data.get( 0 ).get( 0 ).getHtmlCoordinate();
assertEquals( c.getRow(),
0 );
assertEquals( c.getCol(),
0 );
c = data.get( 0 ).get( 1 ).getHtmlCoordinate();
assertEquals( c.getRow(),
0 );
assertEquals( c.getCol(),
1 );
c = data.get( 0 ).get( 2 ).getHtmlCoordinate();
assertEquals( c.getRow(),
0 );
assertEquals( c.getCol(),
2 );
c = data.get( 1 ).get( 0 ).getHtmlCoordinate();
assertEquals( c.getRow(),
0 );
assertEquals( c.getCol(),
0 );
c = data.get( 1 ).get( 1 ).getHtmlCoordinate();
assertEquals( c.getRow(),
1 );
assertEquals( c.getCol(),
0 );
c = data.get( 1 ).get( 2 ).getHtmlCoordinate();
assertEquals( c.getRow(),
0 );
assertEquals( c.getCol(),
2 );
c = data.get( 2 ).get( 0 ).getHtmlCoordinate();
assertEquals( c.getRow(),
2 );
assertEquals( c.getCol(),
0 );
c = data.get( 2 ).get( 1 ).getHtmlCoordinate();
assertEquals( c.getRow(),
1 );
assertEquals( c.getCol(),
0 );
c = data.get( 2 ).get( 2 ).getHtmlCoordinate();
assertEquals( c.getRow(),
0 );
assertEquals( c.getCol(),
2 );
}
@Test
public void testIndexing_PhysicalCoordinates() {
//[1][-][3] --> [0,0][0,1][0,2] --> [0,0][0,1][0,2]
//[1][2][3] --> [0,0][1,0][0,2] --> [1,1][-,-][-,-]
//[-][2][3] --> [2,0][1,0][0,2] --> [2,0][-,-][-,-]
data.setMerged( true );
Coordinate c;
c = data.get( 0 ).get( 0 ).getPhysicalCoordinate();
assertEquals( c.getRow(),
0 );
assertEquals( c.getCol(),
0 );
c = data.get( 0 ).get( 1 ).getPhysicalCoordinate();
assertEquals( c.getRow(),
0 );
assertEquals( c.getCol(),
1 );
c = data.get( 0 ).get( 2 ).getPhysicalCoordinate();
assertEquals( c.getRow(),
0 );
assertEquals( c.getCol(),
2 );
c = data.get( 1 ).get( 0 ).getPhysicalCoordinate();
assertEquals( c.getRow(),
1 );
assertEquals( c.getCol(),
1 );
c = data.get( 2 ).get( 0 ).getPhysicalCoordinate();
assertEquals( c.getRow(),
2 );
assertEquals( c.getCol(),
0 );
}
@Test
public void testIndexing_RowSpans() {
//[1][-][3] --> [2][1][3]
//[1][2][3] --> [0][2][0]
//[-][2][3] --> [1][0][0]
data.setMerged( true );
CellValue<? extends Comparable<?>> cv;
cv = data.get( 0 ).get( 0 );
assertEquals( cv.getRowSpan(),
2 );
cv = data.get( 0 ).get( 1 );
assertEquals( cv.getRowSpan(),
1 );
cv = data.get( 0 ).get( 2 );
assertEquals( cv.getRowSpan(),
3 );
cv = data.get( 1 ).get( 0 );
assertEquals( cv.getRowSpan(),
0 );
cv = data.get( 1 ).get( 1 );
assertEquals( cv.getRowSpan(),
2 );
cv = data.get( 1 ).get( 2 );
assertEquals( cv.getRowSpan(),
0 );
cv = data.get( 2 ).get( 0 );
assertEquals( cv.getRowSpan(),
1 );
cv = data.get( 2 ).get( 1 );
assertEquals( cv.getRowSpan(),
0 );
cv = data.get( 2 ).get( 2 );
assertEquals( cv.getRowSpan(),
0 );
}
}
| apache-2.0 |
delkyd/oreva | odata-core/src/main/java/org/odata4j/core/ImmutableList.java | 4154 | package org.odata4j.core;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import java.util.RandomAccess;
/**
* A List implementation whose structure is immutable after construction.
* <p>Useful for apis that assume a returned list remains unmodified.
* <p>All mutation methods throw <code>UnsupportedOperationException</code>
*
* @param <T> the list item type
*/
public class ImmutableList<T> implements List<T>, RandomAccess {
private final List<T> values;
private static final ImmutableList<Object> EMPTY = new ImmutableList<Object>(Collections.emptyList());
private ImmutableList(List<T> values) {
this.values = values;
}
@SuppressWarnings("unchecked")
public static <T> ImmutableList<T> create(T... values) {
if (values.length == 0)
return (ImmutableList<T>) EMPTY;
return new ImmutableList<T>(Arrays.asList(values));
}
@SuppressWarnings("unchecked")
public static <T> ImmutableList<T> copyOf(List<T> values) {
if (values == null)
return (ImmutableList<T>) EMPTY;
if (values instanceof ImmutableList)
return (ImmutableList<T>) values;
return (ImmutableList<T>) create(values.toArray());
}
@Override
public String toString() {
return values.toString();
}
@Override
public boolean equals(Object obj) {
return (obj instanceof ImmutableList) && ((ImmutableList<?>) obj).values.equals(values);
}
@Override
public int hashCode() {
return values.hashCode();
}
@Override
public int size() {
return values.size();
}
@Override
public boolean isEmpty() {
return values.isEmpty();
}
@Override
public boolean contains(Object o) {
return values.contains(o);
}
@Override
public Iterator<T> iterator() {
return values.iterator();
}
@Override
public Object[] toArray() {
return values.toArray();
}
@Override
public <TArray> TArray[] toArray(TArray[] a) {
return values.toArray(a);
}
@Override
public boolean containsAll(Collection<?> c) {
return values.containsAll(c);
}
@Override
public T get(int index) {
return values.get(index);
}
@Override
public int indexOf(Object o) {
return values.indexOf(o);
}
@Override
public int lastIndexOf(Object o) {
return values.lastIndexOf(o);
}
@Override
public ListIterator<T> listIterator() {
return values.listIterator();
}
@Override
public ListIterator<T> listIterator(int index) {
return values.listIterator(index);
}
@Override
public List<T> subList(int fromIndex, int toIndex) {
return values.subList(fromIndex, toIndex);
}
private static UnsupportedOperationException newModificationUnsupported() {
return new UnsupportedOperationException(ImmutableList.class.getSimpleName() + " cannot be modified");
}
@Override
public void clear() {
throw newModificationUnsupported();
}
@Override
public T set(int paramInt, T paramE) {
throw newModificationUnsupported();
}
@Override
public void add(int paramInt, T paramE) {
throw newModificationUnsupported();
}
@Override
public T remove(int paramInt) {
throw newModificationUnsupported();
}
@Override
public boolean add(T paramE) {
throw newModificationUnsupported();
}
@Override
public boolean remove(Object paramObject) {
throw newModificationUnsupported();
}
@Override
public boolean addAll(Collection<? extends T> paramCollection) {
throw newModificationUnsupported();
}
@Override
public boolean addAll(int paramInt, Collection<? extends T> paramCollection) {
throw newModificationUnsupported();
}
@Override
public boolean removeAll(Collection<?> paramCollection) {
throw newModificationUnsupported();
}
@Override
public boolean retainAll(Collection<?> paramCollection) {
throw newModificationUnsupported();
}
}
| apache-2.0 |
resmo/cloudstack | core/src/org/apache/cloudstack/storage/command/CopyCommand.java | 2664 | //
// 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.cloudstack.storage.command;
import java.util.HashMap;
import java.util.Map;
import com.cloud.agent.api.to.DataTO;
public final class CopyCommand extends StorageSubSystemCommand {
private DataTO srcTO;
private DataTO destTO;
private DataTO cacheTO;
private boolean executeInSequence = false;
private Map<String, String> options = new HashMap<String, String>();
private Map<String, String> options2 = new HashMap<String, String>();
public CopyCommand(final DataTO srcData, final DataTO destData, final int timeout, final boolean executeInSequence) {
super();
srcTO = srcData;
destTO = destData;
setWait(timeout);
this.executeInSequence = executeInSequence;
}
public DataTO getDestTO() {
return destTO;
}
public void setSrcTO(final DataTO srcTO) {
this.srcTO = srcTO;
}
public void setDestTO(final DataTO destTO) {
this.destTO = destTO;
}
public DataTO getSrcTO() {
return srcTO;
}
@Override
public boolean executeInSequence() {
return executeInSequence;
}
public DataTO getCacheTO() {
return cacheTO;
}
public void setCacheTO(final DataTO cacheTO) {
this.cacheTO = cacheTO;
}
public int getWaitInMillSeconds() {
return getWait() * 1000;
}
public void setOptions(final Map<String, String> options) {
this.options = options;
}
public Map<String, String> getOptions() {
return options;
}
public void setOptions2(final Map<String, String> options2) {
this.options2 = options2;
}
public Map<String, String> getOptions2() {
return options2;
}
@Override
public void setExecuteInSequence(final boolean inSeq) {
executeInSequence = inSeq;
}
}
| apache-2.0 |
mattnworb/helios | helios-tools/src/main/java/com/spotify/helios/cli/Output.java | 2828 | /*-
* -\-\-
* Helios Tools
* --
* Copyright (C) 2016 Spotify AB
* --
* 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.spotify.helios.cli;
import static java.lang.String.format;
import java.io.PrintStream;
import org.joda.time.Duration;
import org.joda.time.Period;
import org.xbill.DNS.Name;
import org.xbill.DNS.ResolverConfig;
import org.xbill.DNS.TextParseException;
public class Output {
public static String humanDuration(final long millis) {
return humanDuration(Duration.millis(millis));
}
public static String humanDuration(final Duration dur) {
final Period p = dur.toPeriod().normalizedStandard();
if (dur.getStandardSeconds() == 0) {
return "0 seconds";
} else if (dur.getStandardSeconds() < 60) {
return format("%d second%s", p.getSeconds(), p.getSeconds() > 1 ? "s" : "");
} else if (dur.getStandardMinutes() < 60) {
return format("%d minute%s", p.getMinutes(), p.getMinutes() > 1 ? "s" : "");
} else if (dur.getStandardHours() < 24) {
return format("%d hour%s", p.getHours(), p.getHours() > 1 ? "s" : "");
} else {
return format("%d day%s", dur.getStandardDays(), dur.getStandardDays() > 1 ? "s" : "");
}
}
public static Table table(final PrintStream out) {
return new Table(out);
}
public static JobStatusTable jobStatusTable(final PrintStream out, final boolean full) {
return new JobStatusTable(out, full);
}
public static String shortHostname(final String host) {
final Name root = Name.fromConstantString(".");
final Name hostname;
try {
hostname = Name.fromString(host, root);
} catch (TextParseException e) {
throw new IllegalArgumentException("Invalid hostname '" + host + "'");
}
final ResolverConfig currentConfig = ResolverConfig.getCurrentConfig();
if (currentConfig != null) {
final Name[] searchPath = currentConfig.searchPath();
if (searchPath != null) {
for (final Name domain : searchPath) {
if (hostname.subdomain(domain)) {
return hostname.relativize(domain).toString();
}
}
}
}
return hostname.toString();
}
public static String formatHostname(final boolean full, final String host) {
return full ? host : shortHostname(host);
}
}
| apache-2.0 |
christophd/camel | dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/PgEventEndpointBuilderFactory.java | 19728 | /*
* 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.builder.endpoint.dsl;
import java.util.*;
import java.util.concurrent.*;
import java.util.function.*;
import java.util.stream.*;
import javax.annotation.Generated;
import org.apache.camel.builder.EndpointConsumerBuilder;
import org.apache.camel.builder.EndpointProducerBuilder;
import org.apache.camel.builder.endpoint.AbstractEndpointBuilder;
/**
* Send and receive PostgreSQL events via LISTEN and NOTIFY commands.
*
* Generated by camel build tools - do NOT edit this file!
*/
@Generated("org.apache.camel.maven.packaging.EndpointDslMojo")
public interface PgEventEndpointBuilderFactory {
/**
* Builder for endpoint consumers for the PostgresSQL Event component.
*/
public interface PgEventEndpointConsumerBuilder
extends
EndpointConsumerBuilder {
default AdvancedPgEventEndpointConsumerBuilder advanced() {
return (AdvancedPgEventEndpointConsumerBuilder) this;
}
/**
* To connect using the given javax.sql.DataSource instead of using
* hostname and port.
*
* The option is a: <code>javax.sql.DataSource</code> type.
*
* Group: common
*
* @param datasource the value to set
* @return the dsl builder
*/
default PgEventEndpointConsumerBuilder datasource(
javax.sql.DataSource datasource) {
doSetProperty("datasource", datasource);
return this;
}
/**
* To connect using the given javax.sql.DataSource instead of using
* hostname and port.
*
* The option will be converted to a
* <code>javax.sql.DataSource</code> type.
*
* Group: common
*
* @param datasource the value to set
* @return the dsl builder
*/
default PgEventEndpointConsumerBuilder datasource(String datasource) {
doSetProperty("datasource", datasource);
return this;
}
/**
* Allows for bridging the consumer to the Camel routing Error Handler,
* which mean any exceptions occurred while the consumer is trying to
* pickup incoming messages, or the likes, will now be processed as a
* message and handled by the routing Error Handler. By default the
* consumer will use the org.apache.camel.spi.ExceptionHandler to deal
* with exceptions, that will be logged at WARN or ERROR level and
* ignored.
*
* The option is a: <code>boolean</code> type.
*
* Default: false
* Group: consumer
*
* @param bridgeErrorHandler the value to set
* @return the dsl builder
*/
default PgEventEndpointConsumerBuilder bridgeErrorHandler(
boolean bridgeErrorHandler) {
doSetProperty("bridgeErrorHandler", bridgeErrorHandler);
return this;
}
/**
* Allows for bridging the consumer to the Camel routing Error Handler,
* which mean any exceptions occurred while the consumer is trying to
* pickup incoming messages, or the likes, will now be processed as a
* message and handled by the routing Error Handler. By default the
* consumer will use the org.apache.camel.spi.ExceptionHandler to deal
* with exceptions, that will be logged at WARN or ERROR level and
* ignored.
*
* The option will be converted to a <code>boolean</code>
* type.
*
* Default: false
* Group: consumer
*
* @param bridgeErrorHandler the value to set
* @return the dsl builder
*/
default PgEventEndpointConsumerBuilder bridgeErrorHandler(
String bridgeErrorHandler) {
doSetProperty("bridgeErrorHandler", bridgeErrorHandler);
return this;
}
/**
* Password for login.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: security
*
* @param pass the value to set
* @return the dsl builder
*/
default PgEventEndpointConsumerBuilder pass(String pass) {
doSetProperty("pass", pass);
return this;
}
/**
* Username for login.
*
* The option is a: <code>java.lang.String</code> type.
*
* Default: postgres
* Group: security
*
* @param user the value to set
* @return the dsl builder
*/
default PgEventEndpointConsumerBuilder user(String user) {
doSetProperty("user", user);
return this;
}
}
/**
* Advanced builder for endpoint consumers for the PostgresSQL Event
* component.
*/
public interface AdvancedPgEventEndpointConsumerBuilder
extends
EndpointConsumerBuilder {
default PgEventEndpointConsumerBuilder basic() {
return (PgEventEndpointConsumerBuilder) this;
}
/**
* To let the consumer use a custom ExceptionHandler. Notice if the
* option bridgeErrorHandler is enabled then this option is not in use.
* By default the consumer will deal with exceptions, that will be
* logged at WARN or ERROR level and ignored.
*
* The option is a:
* <code>org.apache.camel.spi.ExceptionHandler</code> type.
*
* Group: consumer (advanced)
*
* @param exceptionHandler the value to set
* @return the dsl builder
*/
default AdvancedPgEventEndpointConsumerBuilder exceptionHandler(
org.apache.camel.spi.ExceptionHandler exceptionHandler) {
doSetProperty("exceptionHandler", exceptionHandler);
return this;
}
/**
* To let the consumer use a custom ExceptionHandler. Notice if the
* option bridgeErrorHandler is enabled then this option is not in use.
* By default the consumer will deal with exceptions, that will be
* logged at WARN or ERROR level and ignored.
*
* The option will be converted to a
* <code>org.apache.camel.spi.ExceptionHandler</code> type.
*
* Group: consumer (advanced)
*
* @param exceptionHandler the value to set
* @return the dsl builder
*/
default AdvancedPgEventEndpointConsumerBuilder exceptionHandler(
String exceptionHandler) {
doSetProperty("exceptionHandler", exceptionHandler);
return this;
}
/**
* Sets the exchange pattern when the consumer creates an exchange.
*
* The option is a:
* <code>org.apache.camel.ExchangePattern</code> type.
*
* Group: consumer (advanced)
*
* @param exchangePattern the value to set
* @return the dsl builder
*/
default AdvancedPgEventEndpointConsumerBuilder exchangePattern(
org.apache.camel.ExchangePattern exchangePattern) {
doSetProperty("exchangePattern", exchangePattern);
return this;
}
/**
* Sets the exchange pattern when the consumer creates an exchange.
*
* The option will be converted to a
* <code>org.apache.camel.ExchangePattern</code> type.
*
* Group: consumer (advanced)
*
* @param exchangePattern the value to set
* @return the dsl builder
*/
default AdvancedPgEventEndpointConsumerBuilder exchangePattern(
String exchangePattern) {
doSetProperty("exchangePattern", exchangePattern);
return this;
}
}
/**
* Builder for endpoint producers for the PostgresSQL Event component.
*/
public interface PgEventEndpointProducerBuilder
extends
EndpointProducerBuilder {
default AdvancedPgEventEndpointProducerBuilder advanced() {
return (AdvancedPgEventEndpointProducerBuilder) this;
}
/**
* To connect using the given javax.sql.DataSource instead of using
* hostname and port.
*
* The option is a: <code>javax.sql.DataSource</code> type.
*
* Group: common
*
* @param datasource the value to set
* @return the dsl builder
*/
default PgEventEndpointProducerBuilder datasource(
javax.sql.DataSource datasource) {
doSetProperty("datasource", datasource);
return this;
}
/**
* To connect using the given javax.sql.DataSource instead of using
* hostname and port.
*
* The option will be converted to a
* <code>javax.sql.DataSource</code> type.
*
* Group: common
*
* @param datasource the value to set
* @return the dsl builder
*/
default PgEventEndpointProducerBuilder datasource(String datasource) {
doSetProperty("datasource", datasource);
return this;
}
/**
* Whether the producer should be started lazy (on the first message).
* By starting lazy you can use this to allow CamelContext and routes to
* startup in situations where a producer may otherwise fail during
* starting and cause the route to fail being started. By deferring this
* startup to be lazy then the startup failure can be handled during
* routing messages via Camel's routing error handlers. Beware that when
* the first message is processed then creating and starting the
* producer may take a little time and prolong the total processing time
* of the processing.
*
* The option is a: <code>boolean</code> type.
*
* Default: false
* Group: producer
*
* @param lazyStartProducer the value to set
* @return the dsl builder
*/
default PgEventEndpointProducerBuilder lazyStartProducer(
boolean lazyStartProducer) {
doSetProperty("lazyStartProducer", lazyStartProducer);
return this;
}
/**
* Whether the producer should be started lazy (on the first message).
* By starting lazy you can use this to allow CamelContext and routes to
* startup in situations where a producer may otherwise fail during
* starting and cause the route to fail being started. By deferring this
* startup to be lazy then the startup failure can be handled during
* routing messages via Camel's routing error handlers. Beware that when
* the first message is processed then creating and starting the
* producer may take a little time and prolong the total processing time
* of the processing.
*
* The option will be converted to a <code>boolean</code>
* type.
*
* Default: false
* Group: producer
*
* @param lazyStartProducer the value to set
* @return the dsl builder
*/
default PgEventEndpointProducerBuilder lazyStartProducer(
String lazyStartProducer) {
doSetProperty("lazyStartProducer", lazyStartProducer);
return this;
}
/**
* Password for login.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: security
*
* @param pass the value to set
* @return the dsl builder
*/
default PgEventEndpointProducerBuilder pass(String pass) {
doSetProperty("pass", pass);
return this;
}
/**
* Username for login.
*
* The option is a: <code>java.lang.String</code> type.
*
* Default: postgres
* Group: security
*
* @param user the value to set
* @return the dsl builder
*/
default PgEventEndpointProducerBuilder user(String user) {
doSetProperty("user", user);
return this;
}
}
/**
* Advanced builder for endpoint producers for the PostgresSQL Event
* component.
*/
public interface AdvancedPgEventEndpointProducerBuilder
extends
EndpointProducerBuilder {
default PgEventEndpointProducerBuilder basic() {
return (PgEventEndpointProducerBuilder) this;
}
}
/**
* Builder for endpoint for the PostgresSQL Event component.
*/
public interface PgEventEndpointBuilder
extends
PgEventEndpointConsumerBuilder,
PgEventEndpointProducerBuilder {
default AdvancedPgEventEndpointBuilder advanced() {
return (AdvancedPgEventEndpointBuilder) this;
}
/**
* To connect using the given javax.sql.DataSource instead of using
* hostname and port.
*
* The option is a: <code>javax.sql.DataSource</code> type.
*
* Group: common
*
* @param datasource the value to set
* @return the dsl builder
*/
default PgEventEndpointBuilder datasource(
javax.sql.DataSource datasource) {
doSetProperty("datasource", datasource);
return this;
}
/**
* To connect using the given javax.sql.DataSource instead of using
* hostname and port.
*
* The option will be converted to a
* <code>javax.sql.DataSource</code> type.
*
* Group: common
*
* @param datasource the value to set
* @return the dsl builder
*/
default PgEventEndpointBuilder datasource(String datasource) {
doSetProperty("datasource", datasource);
return this;
}
/**
* Password for login.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: security
*
* @param pass the value to set
* @return the dsl builder
*/
default PgEventEndpointBuilder pass(String pass) {
doSetProperty("pass", pass);
return this;
}
/**
* Username for login.
*
* The option is a: <code>java.lang.String</code> type.
*
* Default: postgres
* Group: security
*
* @param user the value to set
* @return the dsl builder
*/
default PgEventEndpointBuilder user(String user) {
doSetProperty("user", user);
return this;
}
}
/**
* Advanced builder for endpoint for the PostgresSQL Event component.
*/
public interface AdvancedPgEventEndpointBuilder
extends
AdvancedPgEventEndpointConsumerBuilder,
AdvancedPgEventEndpointProducerBuilder {
default PgEventEndpointBuilder basic() {
return (PgEventEndpointBuilder) this;
}
}
public interface PgEventBuilders {
/**
* PostgresSQL Event (camel-pgevent)
* Send and receive PostgreSQL events via LISTEN and NOTIFY commands.
*
* Category: database,sql
* Since: 2.15
* Maven coordinates: org.apache.camel:camel-pgevent
*
* Syntax: <code>pgevent:host:port/database/channel</code>
*
* Path parameter: host
* To connect using hostname and port to the database.
* Default value: localhost
*
* Path parameter: port
* To connect using hostname and port to the database.
* Default value: 5432
*
* Path parameter: database (required)
* The database name. The database name can take any characters because
* it is sent as a quoted identifier. It is part of the endpoint URI, so
* diacritical marks and non-Latin letters have to be URL encoded.
*
* Path parameter: channel (required)
* The channel name
*
* @param path host:port/database/channel
* @return the dsl builder
*/
default PgEventEndpointBuilder pgevent(String path) {
return PgEventEndpointBuilderFactory.endpointBuilder("pgevent", path);
}
/**
* PostgresSQL Event (camel-pgevent)
* Send and receive PostgreSQL events via LISTEN and NOTIFY commands.
*
* Category: database,sql
* Since: 2.15
* Maven coordinates: org.apache.camel:camel-pgevent
*
* Syntax: <code>pgevent:host:port/database/channel</code>
*
* Path parameter: host
* To connect using hostname and port to the database.
* Default value: localhost
*
* Path parameter: port
* To connect using hostname and port to the database.
* Default value: 5432
*
* Path parameter: database (required)
* The database name. The database name can take any characters because
* it is sent as a quoted identifier. It is part of the endpoint URI, so
* diacritical marks and non-Latin letters have to be URL encoded.
*
* Path parameter: channel (required)
* The channel name
*
* @param componentName to use a custom component name for the endpoint
* instead of the default name
* @param path host:port/database/channel
* @return the dsl builder
*/
default PgEventEndpointBuilder pgevent(String componentName, String path) {
return PgEventEndpointBuilderFactory.endpointBuilder(componentName, path);
}
}
static PgEventEndpointBuilder endpointBuilder(
String componentName,
String path) {
class PgEventEndpointBuilderImpl extends AbstractEndpointBuilder implements PgEventEndpointBuilder, AdvancedPgEventEndpointBuilder {
public PgEventEndpointBuilderImpl(String path) {
super(componentName, path);
}
}
return new PgEventEndpointBuilderImpl(path);
}
} | apache-2.0 |
romankagan/DDBWorkbench | python/psi-api/src/com/jetbrains/python/psi/PyParenthesizedExpression.java | 801 | /*
* Copyright 2000-2013 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.jetbrains.python.psi;
import org.jetbrains.annotations.Nullable;
public interface PyParenthesizedExpression extends PyExpression {
@Nullable
PyExpression getContainedExpression();
}
| apache-2.0 |
robsoncardosoti/flowable-engine | modules/flowable-engine/src/main/java/org/flowable/engine/impl/variable/CacheableVariable.java | 802 | /* 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.flowable.engine.impl.variable;
/**
* Interface to abstract the JPA cacheable setting
*
* @author Tijs Rademakers
*
*/
public interface CacheableVariable {
public void setForceCacheable(boolean forceCachedValue);
}
| apache-2.0 |
mhurne/aws-sdk-java | aws-java-sdk-redshift/src/main/java/com/amazonaws/services/redshift/model/transform/RebootClusterRequestMarshaller.java | 1901 | /*
* Copyright 2010-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazonaws.services.redshift.model.transform;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.amazonaws.AmazonClientException;
import com.amazonaws.Request;
import com.amazonaws.DefaultRequest;
import com.amazonaws.internal.ListWithAutoConstructFlag;
import com.amazonaws.services.redshift.model.*;
import com.amazonaws.transform.Marshaller;
import com.amazonaws.util.StringUtils;
/**
* Reboot Cluster Request Marshaller
*/
public class RebootClusterRequestMarshaller implements Marshaller<Request<RebootClusterRequest>, RebootClusterRequest> {
public Request<RebootClusterRequest> marshall(RebootClusterRequest rebootClusterRequest) {
if (rebootClusterRequest == null) {
throw new AmazonClientException("Invalid argument passed to marshall(...)");
}
Request<RebootClusterRequest> request = new DefaultRequest<RebootClusterRequest>(rebootClusterRequest, "AmazonRedshift");
request.addParameter("Action", "RebootCluster");
request.addParameter("Version", "2012-12-01");
if (rebootClusterRequest.getClusterIdentifier() != null) {
request.addParameter("ClusterIdentifier", StringUtils.fromString(rebootClusterRequest.getClusterIdentifier()));
}
return request;
}
}
| apache-2.0 |
MikeThomsen/nifi | nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/command/nifi/params/SetInheritedParamContexts.java | 5213 | /*
* 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.toolkit.cli.impl.command.nifi.params;
import org.apache.commons.cli.MissingOptionException;
import org.apache.nifi.toolkit.cli.api.CommandException;
import org.apache.nifi.toolkit.cli.api.Context;
import org.apache.nifi.toolkit.cli.impl.client.nifi.NiFiClient;
import org.apache.nifi.toolkit.cli.impl.client.nifi.NiFiClientException;
import org.apache.nifi.toolkit.cli.impl.client.nifi.ParamContextClient;
import org.apache.nifi.toolkit.cli.impl.command.CommandOption;
import org.apache.nifi.toolkit.cli.impl.result.VoidResult;
import org.apache.nifi.web.api.dto.ParameterContextDTO;
import org.apache.nifi.web.api.dto.ParameterContextReferenceDTO;
import org.apache.nifi.web.api.entity.ParameterContextEntity;
import org.apache.nifi.web.api.entity.ParameterContextReferenceEntity;
import org.apache.nifi.web.api.entity.ParameterContextUpdateRequestEntity;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
public class SetInheritedParamContexts extends AbstractUpdateParamContextCommand<VoidResult> {
public SetInheritedParamContexts() {
super("set-inherited-param-contexts", VoidResult.class);
}
@Override
public String getDescription() {
return "Sets a list of parameter context ids from which the given parameter context should inherit parameters";
}
@Override
protected void doInitialize(Context context) {
super.doInitialize(context);
addOption(CommandOption.PARAM_CONTEXT_ID.createOption());
addOption(CommandOption.PARAM_CONTEXT_INHERITED_IDS.createOption());
}
@Override
public VoidResult doExecute(final NiFiClient client, final Properties properties)
throws NiFiClientException, IOException, MissingOptionException, CommandException {
// Required args...
final String paramContextId = getRequiredArg(properties, CommandOption.PARAM_CONTEXT_ID);
final String inheritedIds = getRequiredArg(properties, CommandOption.PARAM_CONTEXT_INHERITED_IDS);
// Ensure the context exists...
final ParamContextClient paramContextClient = client.getParamContextClient();
final ParameterContextEntity existingParameterContextEntity = paramContextClient.getParamContext(paramContextId, false);
final String[] inheritedIdArray = inheritedIds.split(",");
final List<ParameterContextReferenceEntity> referenceEntities = new ArrayList<>();
for(final String inheritedId : inheritedIdArray) {
final ParameterContextEntity existingInheritedEntity = paramContextClient.getParamContext(inheritedId, false);
final ParameterContextReferenceEntity parameterContextReferenceEntity = new ParameterContextReferenceEntity();
parameterContextReferenceEntity.setId(existingInheritedEntity.getId());
final ParameterContextReferenceDTO parameterContextReferenceDTO = new ParameterContextReferenceDTO();
parameterContextReferenceDTO.setName(existingInheritedEntity.getComponent().getName());
parameterContextReferenceDTO.setId(existingInheritedEntity.getComponent().getId());
parameterContextReferenceEntity.setComponent(parameterContextReferenceDTO);
referenceEntities.add(parameterContextReferenceEntity);
}
final ParameterContextDTO parameterContextDTO = new ParameterContextDTO();
parameterContextDTO.setId(existingParameterContextEntity.getId());
parameterContextDTO.setParameters(existingParameterContextEntity.getComponent().getParameters());
final ParameterContextEntity updatedParameterContextEntity = new ParameterContextEntity();
updatedParameterContextEntity.setId(paramContextId);
updatedParameterContextEntity.setComponent(parameterContextDTO);
updatedParameterContextEntity.setRevision(existingParameterContextEntity.getRevision());
parameterContextDTO.setInheritedParameterContexts(referenceEntities);
// Submit the update request...
final ParameterContextUpdateRequestEntity updateRequestEntity = paramContextClient.updateParamContext(updatedParameterContextEntity);
performUpdate(paramContextClient, updatedParameterContextEntity, updateRequestEntity);
if (isInteractive()) {
println();
}
return VoidResult.getInstance();
}
}
| apache-2.0 |
kierarad/gocd | base/src/main/java/com/thoughtworks/go/domain/BaseCollection.java | 1881 | /*
* Copyright 2019 ThoughtWorks, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.thoughtworks.go.domain;
import java.util.ArrayList;
import java.util.Collection;
import static java.util.Arrays.asList;
public class BaseCollection<T> extends ArrayList<T> {
public BaseCollection(Collection<T> elements) {
super(elements);
}
public BaseCollection() {
}
public BaseCollection(T... items) {
this(asList(items));
}
public T first() {
if (this.isEmpty()) {
return null;
}
return this.get(0);
}
public T last() {
if (this.isEmpty()) {
return null;
}
return this.get(this.size() - 1);
}
public void replace(T oldItem, T newItem) {
if (this.isEmpty()) {
return;
}
int indexOfOldItem = this.indexOf(oldItem);
replace(indexOfOldItem, newItem);
}
public void replace(int indexOfOldItem, T newItem) {
if (this.isEmpty()) {
return;
}
if(indexOfOldItem < 0 || indexOfOldItem >= this.size()) {
throw new IndexOutOfBoundsException(String.format("There is no object at index '%s' in this collection of %s", indexOfOldItem, this.first().getClass().getName()));
}
this.set(indexOfOldItem, newItem);
}
}
| apache-2.0 |
prateekm/samza | samza-core/src/main/java/org/apache/samza/checkpoint/kafka/KafkaChangelogSSPOffset.java | 3326 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.samza.checkpoint.kafka;
import java.util.Objects;
import org.apache.commons.lang3.StringUtils;
import org.apache.samza.annotation.InterfaceStability;
import org.apache.samza.checkpoint.CheckpointId;
/**
* Used in {@link org.apache.samza.checkpoint.CheckpointV1} for tracking the latest offset for store changelogs at
* the time of commit. Checkpointed changelog offset has the format: [checkpointId, offset], separated by a colon.
*/
@InterfaceStability.Unstable
public class KafkaChangelogSSPOffset {
public static final String SEPARATOR = ":";
private final CheckpointId checkpointId;
private final String changelogOffset;
public KafkaChangelogSSPOffset(CheckpointId checkpointId, String changelogOffset) {
this.checkpointId = checkpointId;
this.changelogOffset = changelogOffset;
}
public static KafkaChangelogSSPOffset fromString(String message) {
if (StringUtils.isBlank(message)) {
throw new IllegalArgumentException("Invalid checkpointed changelog message: " + message);
}
String[] checkpointIdAndOffset = message.split(SEPARATOR);
if (checkpointIdAndOffset.length != 2) {
throw new IllegalArgumentException("Invalid checkpointed changelog offset: " + message);
}
CheckpointId checkpointId = CheckpointId.deserialize(checkpointIdAndOffset[0]);
String offset = null;
if (!"null".equals(checkpointIdAndOffset[1])) {
offset = checkpointIdAndOffset[1];
}
return new KafkaChangelogSSPOffset(checkpointId, offset);
}
public CheckpointId getCheckpointId() {
return checkpointId;
}
public String getChangelogOffset() {
return changelogOffset;
}
/**
* WARNING: Do not change the toString() representation. It is used for serde'ing the store changelog offsets
* as part of task checkpoints, in conjunction with {@link #fromString(String)}.
* @return the String representation of this {@link KafkaChangelogSSPOffset}
*/
@Override
public String toString() {
return String.format("%s%s%s", checkpointId, SEPARATOR, changelogOffset);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
KafkaChangelogSSPOffset that = (KafkaChangelogSSPOffset) o;
return Objects.equals(checkpointId, that.checkpointId) &&
Objects.equals(changelogOffset, that.changelogOffset);
}
@Override
public int hashCode() {
return Objects.hash(checkpointId, changelogOffset);
}
}
| apache-2.0 |
apache/tinkerpop | gremlin-core/src/test/java/org/apache/tinkerpop/gremlin/process/computer/traversal/strategy/verifcation/VertexProgramRestrictionStrategyTest.java | 3482 | /*
* 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.tinkerpop.gremlin.process.computer.traversal.strategy.verifcation;
import org.apache.tinkerpop.gremlin.process.computer.traversal.strategy.verification.VertexProgramRestrictionStrategy;
import org.apache.tinkerpop.gremlin.process.traversal.Traversal;
import org.apache.tinkerpop.gremlin.structure.util.empty.EmptyGraph;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import java.util.Arrays;
import static org.junit.Assert.fail;
/**
* @author Marc de Lignie
*/
@RunWith(Parameterized.class)
public class VertexProgramRestrictionStrategyTest {
@Parameterized.Parameters(name = "{0}")
public static Iterable<Object[]> data() {
return Arrays.asList(new Object[][]{
// illegal
{"withComputer().withStrategies(VertexProgramRestrictionStrategy.instance()).V()",
EmptyGraph.instance().traversal().withComputer().withStrategies(VertexProgramRestrictionStrategy.instance()).V(), false},
{"withStrategies(VertexProgramRestrictionStrategy.instance()).withComputer().V()",
EmptyGraph.instance().traversal().withStrategies(VertexProgramRestrictionStrategy.instance()).withComputer().V(), false},
{"withStrategies(VertexProgramRestrictionStrategy.instance()).withComputer().V().connectedComponent()",
EmptyGraph.instance().traversal().withStrategies(VertexProgramRestrictionStrategy.instance()).withComputer().V().connectedComponent(), false},
{"withStrategies(VertexProgramRestrictionStrategy.instance()).withComputer().V().pageRank()",
EmptyGraph.instance().traversal().withStrategies(VertexProgramRestrictionStrategy.instance()).withComputer().V().pageRank(), false},
// legal
{"withStrategies(VertexProgramRestrictionStrategy.instance()).V()", EmptyGraph.instance().traversal().withStrategies(VertexProgramRestrictionStrategy.instance()).V(), true},
});
}
@Parameterized.Parameter(value = 0)
public String name;
@Parameterized.Parameter(value = 1)
public Traversal<?, ?> traversal;
@Parameterized.Parameter(value = 2)
public boolean legal;
@Test
public void shouldBeVerifiedIllegal() {
try {
this.traversal.asAdmin().applyStrategies();
if (!this.legal)
fail("The traversal should not be allowed: " + this.traversal);
} catch (final IllegalStateException ise) {
if (this.legal)
fail("The traversal should be allowed: " + this.traversal);
}
}
}
| apache-2.0 |
diydyq/velocity-engine | velocity-engine-core/src/test/java/org/apache/velocity/test/TextblockTestCase.java | 4818 | package org.apache.velocity.test;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import org.apache.velocity.runtime.parser.node.ASTTextblock;
/**
* This class tests the Textblock directive.
*/
public class TextblockTestCase extends BaseTestCase
{
// these are all here so that the test case adapts instantly
// to changes in the textblock start/end sequences
private static final String START = ASTTextblock.START;
private static final String END = ASTTextblock.END;
private static final String PARTIAL_START = START.substring(0, START.length() - 1);
private static final String PARTIAL_END = END.substring(1, END.length());
private static final String END_OF_START = START.substring(START.length() - 1, START.length());
private static final String START_OF_END = END.substring(0, 1);
public TextblockTestCase(String name)
{
super(name);
//DEBUG = true;
}
public String textblock(String s)
{
return START + s + END;
}
public void assertTextblockEvalEquals(String s) throws Exception
{
assertEvalEquals(s, textblock(s));
}
/**
* https://issues.apache.org/jira/browse/VELOCITY-661
*/
public void testTextblockAjaxcode() throws Exception
{
String s = "var myId = 'someID';$('#test).append($.template('<div id=\"${myId}\"></div>').apply({myId: myId}));";
assertEvalEquals(s + " 123", textblock(s)+" #foreach($i in [1..3])$i#end");
}
public void testLooseTextblockEnd() throws Exception
{
// just like a multi-line comment end (*#), this must be
// followed by a character. by itself, it bombs for some reason.
assertEvalEquals(END+" ", END+" ");
}
public void testTextblockStartInTextblock() throws Exception
{
assertTextblockEvalEquals(START);
}
public void testTextblockEndBetweenTwoTextblockHalves() throws Exception
{
// just like a multi-line comment end (*#), the end token
// in the middle must be followed by some character.
// by itself, it bombs. not sure why that is, but the
// same has been true of multi-line comments without complaints,
// so i'm not going to worry about it just yet.
assertEvalEquals(" "+END+" ", textblock(" ")+END+" "+textblock(" "));
}
public void testZerolengthTextblock() throws Exception
{
assertTextblockEvalEquals("");
}
public void testTextblockInsideForeachLoop() throws Exception
{
String s = "var myId = 'someID';$('#test).append($.template('<div id=\"${myId}\"></div>').apply({myId: myId}));";
assertEvalEquals("1 "+s+"2 "+s+"3 "+s, "#foreach($i in [1..3])$i "+ textblock(s) + "#end");
}
public void testSingleHashInsideTextblock() throws Exception
{
assertTextblockEvalEquals(" # ");
}
public void testDollarInsideTextblock() throws Exception
{
assertTextblockEvalEquals("$");
}
public void testTextblockInsideComment() throws Exception
{
String s = "FOOBAR";
assertEvalEquals("", "#* comment "+textblock(s) + " *#");
}
public void testPartialStartEndTokensInsideTextblock() throws Exception
{
assertTextblockEvalEquals(PARTIAL_START+"foo"+PARTIAL_END);
}
public void testDupeTokenChars() throws Exception
{
assertTextblockEvalEquals(END_OF_START+START_OF_END);
assertTextblockEvalEquals(END_OF_START+END_OF_START+START_OF_END+START_OF_END);
assertTextblockEvalEquals(END_OF_START+END_OF_START+"#"+START_OF_END+START_OF_END);
}
/**
* https://issues.apache.org/jira/browse/VELOCITY-584
*/
public void testServerSideIncludeEscaping() throws Exception
{
assertTextblockEvalEquals("<!--#include file=\"wisdom.inc\"--> ");
}
/**
* https://issues.apache.org/jira/browse/VELOCITY-676
*/
public void testLineCommentInsideTextblock() throws Exception
{
assertTextblockEvalEquals("##x");
}
}
| apache-2.0 |
apache/jackrabbit | jackrabbit-jcr-tests/src/main/java/org/apache/jackrabbit/test/api/version/VersionStorageTest.java | 3366 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.jackrabbit.test.api.version;
import java.util.GregorianCalendar;
import javax.jcr.Node;
import javax.jcr.RepositoryException;
import javax.jcr.Session;
import javax.jcr.nodetype.ConstraintViolationException;
/**
* <code>VersionStorageTest</code> provides tests regarding {@link
* javax.jcr.version.VersionHistory#addVersionLabel(String, String, boolean)}
*
*/
public class VersionStorageTest extends AbstractVersionTest {
// path to version storage
protected String versionStoragePath;
protected void setUp() throws Exception {
super.setUp();
// get versionStorage path
versionStoragePath = superuser.getNamespacePrefix(NS_JCR_URI) + ":system/" + superuser.getNamespacePrefix(NS_JCR_URI) + ":versionStorage";
}
/**
* Entire subtree is protected.
*/
public void testVersionStorageProtected() throws RepositoryException {
try {
versionableNode.getBaseVersion().setProperty(jcrCreated, GregorianCalendar.getInstance());
fail("It should not be possible to modify a subnode/version in version storage.");
} catch (ConstraintViolationException e) {
// success
}
}
/**
* The full set of version histories in the version storage, though stored
* in a single location in the repository, must be reflected in each
* workspace as a subtree below the node /jcr:system/jcr:versionStorage.
* Entire subtree must be identical across all workspaces and is protected.
*/
public void testVersionStorageIdenticalAcrossAllWorkspaces() throws RepositoryException {
// The superuser session for the second workspace
Session superuserW2 = getHelper().getSuperuserSession(workspaceName);
try {
// check path to version storage
assertTrue("Version strorage must be reflected as a subtree below the node '" + versionStoragePath + "'", superuserW2.getRootNode().hasNode(versionStoragePath));
// check if subnodes in versionStorage are protected
try {
// try to create a version node
Node versionStorageNodeW2 = superuserW2.getRootNode().getNode(versionStoragePath);
versionStorageNodeW2.addNode(nodeName1, ntVersion);
fail("It should not be possible to add a subnode/version in version storage.");
} catch (ConstraintViolationException e) {
// success
}
} finally {
superuserW2.logout();
}
}
}
| apache-2.0 |
ChrisCanCompute/assertj-core | src/test/java/org/assertj/core/api/charsequence/CharSequenceAssert_matches_String_Test.java | 1479 | /**
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*
* Copyright 2012-2017 the original author or authors.
*/
package org.assertj.core.api.charsequence;
import static org.assertj.core.test.TestData.matchAnything;
import static org.mockito.Mockito.verify;
import org.assertj.core.api.CharSequenceAssert;
import org.assertj.core.api.CharSequenceAssertBaseTest;
import org.junit.BeforeClass;
/**
* Tests for <code>{@link CharSequenceAssert#matches(CharSequence)}</code>.
*
* @author Alex Ruiz
*/
public class CharSequenceAssert_matches_String_Test extends CharSequenceAssertBaseTest {
private static CharSequence regex;
@BeforeClass
public static void setUpOnce() {
regex = matchAnything().pattern();
}
@Override
protected CharSequenceAssert invoke_api_method() {
return assertions.matches(regex);
}
@Override
protected void verify_internal_effects() {
verify(strings).assertMatches(getInfo(assertions), getActual(assertions), regex);
}
}
| apache-2.0 |
hello2009chen/spring-boot | spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/export/datadog/DatadogMetricsExportAutoConfiguration.java | 3241 | /*
* Copyright 2012-2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.boot.actuate.autoconfigure.metrics.export.datadog;
import io.micrometer.core.instrument.Clock;
import io.micrometer.core.ipc.http.HttpUrlConnectionSender;
import io.micrometer.datadog.DatadogConfig;
import io.micrometer.datadog.DatadogMeterRegistry;
import org.springframework.boot.actuate.autoconfigure.metrics.CompositeMeterRegistryAutoConfiguration;
import org.springframework.boot.actuate.autoconfigure.metrics.MetricsAutoConfiguration;
import org.springframework.boot.actuate.autoconfigure.metrics.export.simple.SimpleMetricsExportAutoConfiguration;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* {@link EnableAutoConfiguration Auto-configuration} for exporting metrics to Datadog.
*
* @author Jon Schneider
* @author Artsiom Yudovin
* @since 2.0.0
*/
@Configuration
@AutoConfigureBefore({ CompositeMeterRegistryAutoConfiguration.class,
SimpleMetricsExportAutoConfiguration.class })
@AutoConfigureAfter(MetricsAutoConfiguration.class)
@ConditionalOnBean(Clock.class)
@ConditionalOnClass(DatadogMeterRegistry.class)
@ConditionalOnProperty(prefix = "management.metrics.export.datadog", name = "enabled", havingValue = "true", matchIfMissing = true)
@EnableConfigurationProperties(DatadogProperties.class)
public class DatadogMetricsExportAutoConfiguration {
private final DatadogProperties properties;
public DatadogMetricsExportAutoConfiguration(DatadogProperties properties) {
this.properties = properties;
}
@Bean
@ConditionalOnMissingBean
public DatadogConfig datadogConfig() {
return new DatadogPropertiesConfigAdapter(this.properties);
}
@Bean
@ConditionalOnMissingBean
public DatadogMeterRegistry datadogMeterRegistry(DatadogConfig datadogConfig,
Clock clock) {
return DatadogMeterRegistry.builder(datadogConfig).clock(clock)
.httpClient(
new HttpUrlConnectionSender(this.properties.getConnectTimeout(),
this.properties.getReadTimeout()))
.build();
}
}
| apache-2.0 |
dougmsft/reef | lang/java/reef-wake/wake/src/main/java/org/apache/reef/wake/remote/impl/DefaultRemoteManagerImplementation.java | 9093 | /*
* 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.reef.wake.remote.impl;
import org.apache.reef.tang.annotations.Parameter;
import org.apache.reef.wake.EStage;
import org.apache.reef.wake.EventHandler;
import org.apache.reef.wake.impl.StageManager;
import org.apache.reef.wake.remote.*;
import org.apache.reef.wake.remote.address.LocalAddressProvider;
import org.apache.reef.wake.remote.ports.TcpPortProvider;
import org.apache.reef.wake.remote.transport.Transport;
import org.apache.reef.wake.remote.transport.TransportFactory;
import org.apache.reef.wake.remote.transport.netty.NettyMessagingTransport;
import javax.inject.Inject;
import java.net.InetSocketAddress;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* Default remote manager implementation.
*/
public final class DefaultRemoteManagerImplementation implements RemoteManager {
private static final Logger LOG = Logger.getLogger(HandlerContainer.class.getName());
private static final AtomicInteger COUNTER = new AtomicInteger(0);
/**
* The timeout used for the execute running in close().
*/
private static final long CLOSE_EXECUTOR_TIMEOUT = 10000; //ms
/**
* Indicates a hostname that isn't set or known.
*/
public static final String UNKNOWN_HOST_NAME = NettyMessagingTransport.UNKNOWN_HOST_NAME;
private final AtomicBoolean closed = new AtomicBoolean(false);
private final RemoteSeqNumGenerator seqGen = new RemoteSeqNumGenerator();
private final String name;
private final Transport transport;
private final RemoteSenderStage reSendStage;
private final EStage<TransportEvent> reRecvStage;
private final HandlerContainer handlerContainer;
private RemoteIdentifier myIdentifier;
@Inject
private <T> DefaultRemoteManagerImplementation(
@Parameter(RemoteConfiguration.ManagerName.class) final String name,
@Parameter(RemoteConfiguration.HostAddress.class) final String hostAddress,
@Parameter(RemoteConfiguration.Port.class) final int listeningPort,
@Parameter(RemoteConfiguration.MessageCodec.class) final Codec<T> codec,
@Parameter(RemoteConfiguration.ErrorHandler.class) final EventHandler<Throwable> errorHandler,
@Parameter(RemoteConfiguration.OrderingGuarantee.class) final boolean orderingGuarantee,
@Parameter(RemoteConfiguration.NumberOfTries.class) final int numberOfTries,
@Parameter(RemoteConfiguration.RetryTimeout.class) final int retryTimeout,
final LocalAddressProvider localAddressProvider,
final TransportFactory tpFactory,
final TcpPortProvider tcpPortProvider) {
this.name = name;
this.handlerContainer = new HandlerContainer<>(name, codec);
this.reRecvStage = orderingGuarantee ?
new OrderedRemoteReceiverStage(this.handlerContainer, errorHandler) :
new RemoteReceiverStage(this.handlerContainer, errorHandler, 10);
this.transport = tpFactory.newInstance(hostAddress, listeningPort,
this.reRecvStage, this.reRecvStage, numberOfTries, retryTimeout, tcpPortProvider);
this.handlerContainer.setTransport(this.transport);
this.myIdentifier = new SocketRemoteIdentifier((InetSocketAddress)this.transport.getLocalAddress());
this.reSendStage = new RemoteSenderStage(codec, this.transport, 10);
StageManager.instance().register(this);
final int counter = COUNTER.incrementAndGet();
LOG.log(Level.FINEST,
"RemoteManager {0} instantiated id {1} counter {2} listening on {3} Binding address provided by {4}",
new Object[] {this.name, this.myIdentifier, counter, this.transport.getLocalAddress(), localAddressProvider});
}
/**
* Returns a proxy event handler for a remote identifier and a message type.
*/
@Override
public <T> EventHandler<T> getHandler(
final RemoteIdentifier destinationIdentifier, final Class<? extends T> messageType) {
if (LOG.isLoggable(Level.FINE)) {
LOG.log(Level.FINE, "RemoteManager: {0} destinationIdentifier: {1} messageType: {2}",
new Object[] {this.name, destinationIdentifier, messageType.getCanonicalName()});
}
return new ProxyEventHandler<>(this.myIdentifier, destinationIdentifier,
"default", this.reSendStage.<T>getHandler(), this.seqGen);
}
/**
* Registers an event handler for a remote identifier and a message type and.
* returns a subscription
*/
@Override
public <T, U extends T> AutoCloseable registerHandler(
final RemoteIdentifier sourceIdentifier, final Class<U> messageType, final EventHandler<T> theHandler) {
if (LOG.isLoggable(Level.FINE)) {
LOG.log(Level.FINE, "RemoteManager: {0} remoteId: {1} messageType: {2} handler: {3}", new Object[] {
this.name, sourceIdentifier, messageType.getCanonicalName(), theHandler.getClass().getCanonicalName()});
}
return this.handlerContainer.registerHandler(sourceIdentifier, messageType, theHandler);
}
/**
* Registers an event handler for a message type and returns a subscription.
*/
@Override
public <T, U extends T> AutoCloseable registerHandler(
final Class<U> messageType, final EventHandler<RemoteMessage<T>> theHandler) {
if (LOG.isLoggable(Level.FINE)) {
LOG.log(Level.FINE, "RemoteManager: {0} messageType: {1} handler: {2}", new Object[] {
this.name, messageType.getCanonicalName(), theHandler.getClass().getCanonicalName()});
}
return this.handlerContainer.registerHandler(messageType, theHandler);
}
/**
* Returns my identifier.
*/
@Override
public RemoteIdentifier getMyIdentifier() {
return this.myIdentifier;
}
@Override
public void close() {
LOG.log(Level.FINE, "RemoteManager: {0} Closing remote manager id: {1}",
new Object[] {this.name, this.myIdentifier});
if (!this.closed.compareAndSet(false, true)) {
LOG.log(Level.FINE, "RemoteManager: {0} already closed", this.name);
return;
}
final Runnable closeRunnable = new Runnable() {
@Override
public void run() {
Thread.currentThread().setName(String.format("CLOSE:RemoteManager:%s:%s", name, myIdentifier));
try {
LOG.log(Level.FINE, "Closing sender stage {0}", myIdentifier);
reSendStage.close();
LOG.log(Level.FINE, "Closed the remote sender stage");
} catch (final Exception e) {
LOG.log(Level.SEVERE, "Unable to close the remote sender stage", e);
}
try {
LOG.log(Level.FINE, "Closing transport {0}", myIdentifier);
transport.close();
LOG.log(Level.FINE, "Closed the transport");
} catch (final Exception e) {
LOG.log(Level.SEVERE, "Unable to close the transport.", e);
}
try {
LOG.log(Level.FINE, "Closing receiver stage {0}", myIdentifier);
reRecvStage.close();
LOG.log(Level.FINE, "Closed the remote receiver stage");
} catch (final Exception e) {
LOG.log(Level.SEVERE, "Unable to close the remote receiver stage", e);
}
}
};
final ExecutorService closeExecutor = Executors.newSingleThreadExecutor();
closeExecutor.submit(closeRunnable);
closeExecutor.shutdown();
if (!closeExecutor.isShutdown()) {
LOG.log(Level.SEVERE, "close executor did not shutdown properly.");
}
final long endTime = System.currentTimeMillis() + CLOSE_EXECUTOR_TIMEOUT;
while (!closeExecutor.isTerminated()) {
try {
final long waitTime = endTime - System.currentTimeMillis();
closeExecutor.awaitTermination(waitTime, TimeUnit.MILLISECONDS);
} catch (final InterruptedException e) {
LOG.log(Level.FINE, "Interrupted", e);
}
}
if (closeExecutor.isTerminated()) {
LOG.log(Level.FINE, "Close executor terminated properly.");
} else {
LOG.log(Level.SEVERE, "Close executor did not terminate properly.");
}
}
@Override
public String toString() {
return String.format("RemoteManager: { id: %s handler: %s }", this.myIdentifier, this.handlerContainer);
}
}
| apache-2.0 |
r48patel/emodb | datacenter/src/main/java/com/bazaarvoice/emodb/datacenter/DataCenterConfiguration.java | 3312 | package com.bazaarvoice.emodb.datacenter;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.google.common.base.Objects;
import com.google.common.collect.ImmutableSet;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import java.net.URI;
import java.util.Set;
public class DataCenterConfiguration {
@Valid
@NotNull
private String _currentDataCenter;
/**
* The name of the current data center as configured in Cassandra's NetworkTopologyStrategy. Defaults to the
* current data center.
*/
@Valid
private String _cassandraDataCenter;
@Valid
@NotNull
private String _systemDataCenter;
@Valid
@NotNull
@JsonProperty("systemDataCenterServiceUri")
private URI _systemDataCenterServiceUri;
/** Load-balanced highly available base URL for the EmoDB service (eg. http://localhost:8080). */
@Valid
@NotNull
private URI _dataCenterServiceUri;
/** Load-balanced highly available base URL for the EmoDB administration tasks (eg. http://localhost:8081). */
@Valid
@NotNull
private URI _dataCenterAdminUri;
/**
* Data centers which should be ignored. This is uncommon and typically only applies when migrating or removing an
* an existing data center. This allows for a smooth transition from the old to the new data center without any
* downtime or fanout errors if either data center unreachable.
**/
@Valid
@NotNull
private Set<String> _ignoredDataCenters = ImmutableSet.of();
public boolean isSystemDataCenter() {
return _currentDataCenter.equals(_systemDataCenter);
}
public String getCurrentDataCenter() {
return _currentDataCenter;
}
public DataCenterConfiguration setCurrentDataCenter(String currentDataCenter) {
_currentDataCenter = currentDataCenter;
return this;
}
public String getCassandraDataCenter() {
return Objects.firstNonNull(_cassandraDataCenter, _currentDataCenter);
}
public DataCenterConfiguration setCassandraDataCenter(String cassandraDataCenter) {
_cassandraDataCenter = cassandraDataCenter;
return this;
}
public String getSystemDataCenter() {
return _systemDataCenter;
}
public DataCenterConfiguration setSystemDataCenter(String systemDataCenter) {
_systemDataCenter = systemDataCenter;
return this;
}
public URI getDataCenterServiceUri() {
return _dataCenterServiceUri;
}
public DataCenterConfiguration setDataCenterServiceUri(URI dataCenterServiceUri) {
_dataCenterServiceUri = dataCenterServiceUri;
return this;
}
public URI getDataCenterAdminUri() {
return _dataCenterAdminUri;
}
public DataCenterConfiguration setDataCenterAdminUri(URI dataCenterAdminUri) {
_dataCenterAdminUri = dataCenterAdminUri;
return this;
}
public URI getSystemDataCenterServiceUri() {
return _systemDataCenterServiceUri;
}
public DataCenterConfiguration setIgnoredDataCenters(Set<String> ignoredDataCenters) {
_ignoredDataCenters = ignoredDataCenters;
return this;
}
public Set<String> getIgnoredDataCenters() {
return _ignoredDataCenters;
}
}
| apache-2.0 |
wwzhe/dataworks-zeus | web/.externalToolBuilders/schedule/src/main/java/com/taobao/zeus/store/Super.java | 238 | package com.taobao.zeus.store;
import java.util.Arrays;
import java.util.List;
public class Super {
private static final List<String> supers = Arrays.asList("yangfei");
public static List<String> getSupers() {
return supers;
}
}
| apache-2.0 |
ok2c/httpclient | httpclient5-win/src/examples/org/apache/hc/client5/http/examples/client/win/ClientWinAuth.java | 2833 | /*
* ====================================================================
* 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.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.hc.client5.http.examples.client.win;
import org.apache.hc.client5.http.classic.methods.HttpGet;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse;
import org.apache.hc.client5.http.impl.win.WinHttpClients;
import org.apache.hc.core5.http.io.entity.EntityUtils;
/**
* This example demonstrates how to create HttpClient pre-configured
* with support for integrated Windows authentication.
*/
public class ClientWinAuth {
public final static void main(String[] args) throws Exception {
if (!WinHttpClients.isWinAuthAvailable()) {
System.out.println("Integrated Win auth is not supported!!!");
}
CloseableHttpClient httpclient = WinHttpClients.createDefault();
// There is no need to provide user credentials
// HttpClient will attempt to access current user security context through
// Windows platform specific methods via JNI.
try {
HttpGet httpget = new HttpGet("http://winhost/");
System.out.println("Executing request " + httpget.getMethod() + " " + httpget.getUri());
CloseableHttpResponse response = httpclient.execute(httpget);
try {
System.out.println("----------------------------------------");
System.out.println(response.getCode() + " " + response.getReasonPhrase());
EntityUtils.consume(response.getEntity());
} finally {
response.close();
}
} finally {
httpclient.close();
}
}
}
| apache-2.0 |
sormuras/google-java-format | core/src/main/java/com/google/googlejavaformat/java/CommandLineOptions.java | 7851 | /*
* Copyright 2016 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.googlejavaformat.java;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableRangeSet;
import java.util.Optional;
/**
* Command line options for google-java-format.
*
* <p>google-java-format doesn't depend on AutoValue, to allow AutoValue to depend on
* google-java-format.
*/
final class CommandLineOptions {
private final ImmutableList<String> files;
private final boolean inPlace;
private final ImmutableRangeSet<Integer> lines;
private final ImmutableList<Integer> offsets;
private final ImmutableList<Integer> lengths;
private final boolean aosp;
private final boolean version;
private final boolean help;
private final boolean stdin;
private final boolean fixImportsOnly;
private final boolean sortImports;
private final boolean removeUnusedImports;
private final boolean dryRun;
private final boolean setExitIfChanged;
private final Optional<String> assumeFilename;
private final boolean reflowLongStrings;
private final boolean formatJavadoc;
CommandLineOptions(
ImmutableList<String> files,
boolean inPlace,
ImmutableRangeSet<Integer> lines,
ImmutableList<Integer> offsets,
ImmutableList<Integer> lengths,
boolean aosp,
boolean version,
boolean help,
boolean stdin,
boolean fixImportsOnly,
boolean sortImports,
boolean removeUnusedImports,
boolean dryRun,
boolean setExitIfChanged,
Optional<String> assumeFilename,
boolean reflowLongStrings,
boolean formatJavadoc) {
this.files = files;
this.inPlace = inPlace;
this.lines = lines;
this.offsets = offsets;
this.lengths = lengths;
this.aosp = aosp;
this.version = version;
this.help = help;
this.stdin = stdin;
this.fixImportsOnly = fixImportsOnly;
this.sortImports = sortImports;
this.removeUnusedImports = removeUnusedImports;
this.dryRun = dryRun;
this.setExitIfChanged = setExitIfChanged;
this.assumeFilename = assumeFilename;
this.reflowLongStrings = reflowLongStrings;
this.formatJavadoc = formatJavadoc;
}
/** The files to format. */
ImmutableList<String> files() {
return files;
}
/** Format files in place. */
boolean inPlace() {
return inPlace;
}
/** Line ranges to format. */
ImmutableRangeSet<Integer> lines() {
return lines;
}
/** Character offsets for partial formatting, paired with {@code lengths}. */
ImmutableList<Integer> offsets() {
return offsets;
}
/** Partial formatting region lengths, paired with {@code offsets}. */
ImmutableList<Integer> lengths() {
return lengths;
}
/** Use AOSP style instead of Google Style (4-space indentation). */
boolean aosp() {
return aosp;
}
/** Print the version. */
boolean version() {
return version;
}
/** Print usage information. */
boolean help() {
return help;
}
/** Format input from stdin. */
boolean stdin() {
return stdin;
}
/** Fix imports, but do no formatting. */
boolean fixImportsOnly() {
return fixImportsOnly;
}
/** Sort imports. */
boolean sortImports() {
return sortImports;
}
/** Remove unused imports. */
boolean removeUnusedImports() {
return removeUnusedImports;
}
/**
* Print the paths of the files whose contents would change if the formatter were run normally.
*/
boolean dryRun() {
return dryRun;
}
/** Return exit code 1 if there are any formatting changes. */
boolean setExitIfChanged() {
return setExitIfChanged;
}
/** Return the name to use for diagnostics when formatting standard input. */
Optional<String> assumeFilename() {
return assumeFilename;
}
boolean reflowLongStrings() {
return reflowLongStrings;
}
/** Returns true if partial formatting was selected. */
boolean isSelection() {
return !lines().isEmpty() || !offsets().isEmpty() || !lengths().isEmpty();
}
boolean formatJavadoc() {
return formatJavadoc;
}
static Builder builder() {
return new Builder();
}
static class Builder {
private final ImmutableList.Builder<String> files = ImmutableList.builder();
private final ImmutableRangeSet.Builder<Integer> lines = ImmutableRangeSet.builder();
private final ImmutableList.Builder<Integer> offsets = ImmutableList.builder();
private final ImmutableList.Builder<Integer> lengths = ImmutableList.builder();
private boolean inPlace = false;
private boolean aosp = false;
private boolean version = false;
private boolean help = false;
private boolean stdin = false;
private boolean fixImportsOnly = false;
private boolean sortImports = true;
private boolean removeUnusedImports = true;
private boolean dryRun = false;
private boolean setExitIfChanged = false;
private Optional<String> assumeFilename = Optional.empty();
private boolean reflowLongStrings = true;
private boolean formatJavadoc = true;
ImmutableList.Builder<String> filesBuilder() {
return files;
}
Builder inPlace(boolean inPlace) {
this.inPlace = inPlace;
return this;
}
ImmutableRangeSet.Builder<Integer> linesBuilder() {
return lines;
}
Builder addOffset(Integer offset) {
offsets.add(offset);
return this;
}
Builder addLength(Integer length) {
lengths.add(length);
return this;
}
Builder aosp(boolean aosp) {
this.aosp = aosp;
return this;
}
Builder version(boolean version) {
this.version = version;
return this;
}
Builder help(boolean help) {
this.help = help;
return this;
}
Builder stdin(boolean stdin) {
this.stdin = stdin;
return this;
}
Builder fixImportsOnly(boolean fixImportsOnly) {
this.fixImportsOnly = fixImportsOnly;
return this;
}
Builder sortImports(boolean sortImports) {
this.sortImports = sortImports;
return this;
}
Builder removeUnusedImports(boolean removeUnusedImports) {
this.removeUnusedImports = removeUnusedImports;
return this;
}
Builder dryRun(boolean dryRun) {
this.dryRun = dryRun;
return this;
}
Builder setExitIfChanged(boolean setExitIfChanged) {
this.setExitIfChanged = setExitIfChanged;
return this;
}
Builder assumeFilename(String assumeFilename) {
this.assumeFilename = Optional.of(assumeFilename);
return this;
}
Builder reflowLongStrings(boolean reflowLongStrings) {
this.reflowLongStrings = reflowLongStrings;
return this;
}
Builder formatJavadoc(boolean formatJavadoc) {
this.formatJavadoc = formatJavadoc;
return this;
}
CommandLineOptions build() {
return new CommandLineOptions(
files.build(),
inPlace,
lines.build(),
offsets.build(),
lengths.build(),
aosp,
version,
help,
stdin,
fixImportsOnly,
sortImports,
removeUnusedImports,
dryRun,
setExitIfChanged,
assumeFilename,
reflowLongStrings,
formatJavadoc);
}
}
}
| apache-2.0 |
twitter/zipkin | zipkin-storage/elasticsearch/src/test/java/zipkin2/elasticsearch/ElasticsearchSpanConsumerTest.java | 10618 | /*
* Copyright 2015-2020 The OpenZipkin 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 zipkin2.elasticsearch;
import com.linecorp.armeria.client.WebClient;
import com.linecorp.armeria.common.AggregatedHttpRequest;
import com.linecorp.armeria.common.AggregatedHttpResponse;
import com.linecorp.armeria.common.HttpData;
import com.linecorp.armeria.common.HttpStatus;
import com.linecorp.armeria.common.MediaType;
import com.linecorp.armeria.common.ResponseHeaders;
import com.linecorp.armeria.testing.junit5.server.mock.MockWebServerExtension;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import zipkin2.Endpoint;
import zipkin2.Span;
import zipkin2.Span.Kind;
import zipkin2.codec.SpanBytesEncoder;
import zipkin2.storage.SpanConsumer;
import static java.util.Arrays.asList;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.failBecauseExceptionWasNotThrown;
import static zipkin2.TestObjects.TODAY;
import static zipkin2.TestObjects.UTF_8;
class ElasticsearchSpanConsumerTest {
static final Endpoint WEB_ENDPOINT = Endpoint.newBuilder().serviceName("web").build();
static final Endpoint APP_ENDPOINT = Endpoint.newBuilder().serviceName("app").build();
final AggregatedHttpResponse SUCCESS_RESPONSE =
AggregatedHttpResponse.of(ResponseHeaders.of(HttpStatus.OK), HttpData.empty());
@RegisterExtension static MockWebServerExtension server = new MockWebServerExtension();
ElasticsearchStorage storage;
SpanConsumer spanConsumer;
@BeforeEach void setUp() throws Exception {
storage = ElasticsearchStorage.newBuilder(() -> WebClient.of(server.httpUri()))
.autocompleteKeys(asList("environment"))
.build();
ensureIndexTemplate();
}
@AfterEach void tearDown() throws IOException {
storage.close();
}
void ensureIndexTemplate() throws Exception {
// gets the index template so that each test doesn't have to
ensureIndexTemplates(storage);
spanConsumer = storage.spanConsumer();
}
private void ensureIndexTemplates(ElasticsearchStorage storage) throws InterruptedException {
server.enqueue(AggregatedHttpResponse.of(HttpStatus.OK, MediaType.JSON_UTF_8,
"{\"version\":{\"number\":\"6.0.0\"}}"));
server.enqueue(SUCCESS_RESPONSE); // get span template
server.enqueue(SUCCESS_RESPONSE); // get dependency template
server.enqueue(SUCCESS_RESPONSE); // get tags template
storage.ensureIndexTemplates();
server.takeRequest(); // get version
server.takeRequest(); // get span template
server.takeRequest(); // get dependency template
server.takeRequest(); // get tags template
}
@Test void addsTimestamp_millisIntoJson() throws Exception {
server.enqueue(SUCCESS_RESPONSE);
Span span =
Span.newBuilder().traceId("20").id("20").name("get").timestamp(TODAY * 1000).build();
accept(span);
assertThat(server.takeRequest().request().contentUtf8())
.contains("\n{\"timestamp_millis\":" + TODAY + ",\"traceId\":");
}
@Test void writesSpanNaturallyWhenNoTimestamp() throws Exception {
server.enqueue(SUCCESS_RESPONSE);
Span span = Span.newBuilder().traceId("1").id("1").name("foo").build();
accept(Span.newBuilder().traceId("1").id("1").name("foo").build());
assertThat(server.takeRequest().request().contentUtf8())
.contains("\n" + new String(SpanBytesEncoder.JSON_V2.encode(span), UTF_8) + "\n");
}
@Test void traceIsSearchableByServerServiceName() throws Exception {
server.enqueue(SUCCESS_RESPONSE);
Span clientSpan =
Span.newBuilder()
.traceId("20")
.id("22")
.name("")
.parentId("21")
.timestamp(1000L)
.kind(Kind.CLIENT)
.localEndpoint(WEB_ENDPOINT)
.build();
Span serverSpan =
Span.newBuilder()
.traceId("20")
.id("22")
.name("get")
.parentId("21")
.timestamp(2000L)
.kind(Kind.SERVER)
.localEndpoint(APP_ENDPOINT)
.build();
accept(serverSpan, clientSpan);
// make sure that both timestamps are in the index
assertThat(server.takeRequest().request().contentUtf8())
.contains("{\"timestamp_millis\":2")
.contains("{\"timestamp_millis\":1");
}
@Test void addsPipelineId() throws Exception {
storage.close();
storage = ElasticsearchStorage.newBuilder(() -> WebClient.of(server.httpUri()))
.pipeline("zipkin")
.build();
ensureIndexTemplate();
server.enqueue(SUCCESS_RESPONSE);
accept(Span.newBuilder().traceId("1").id("1").name("foo").build());
AggregatedHttpRequest request = server.takeRequest().request();
assertThat(request.path()).isEqualTo("/_bulk?pipeline=zipkin");
}
@Test void choosesTypeSpecificIndex() throws Exception {
server.enqueue(SUCCESS_RESPONSE);
Span span =
Span.newBuilder()
.traceId("1")
.id("2")
.parentId("1")
.name("s")
.localEndpoint(APP_ENDPOINT)
.addAnnotation(TimeUnit.DAYS.toMicros(365) /* 1971-01-01 */, "foo")
.build();
// sanity check data
assertThat(span.timestamp()).isNull();
accept(span);
// index timestamp is the server timestamp, not current time!
assertThat(server.takeRequest().request().contentUtf8())
.startsWith("{\"index\":{\"_index\":\"zipkin:span-1971-01-01\",\"_type\":\"span\"");
}
/** Much simpler template which doesn't write the timestamp_millis field */
@Test void searchDisabled_simplerIndexTemplate() throws Exception {
storage.close();
storage = ElasticsearchStorage.newBuilder(() -> WebClient.of(server.httpUri()))
.searchEnabled(false)
.build();
server.enqueue(AggregatedHttpResponse.of(HttpStatus.OK, MediaType.JSON_UTF_8,
"{\"version\":{\"number\":\"6.0.0\"}}"));
server.enqueue(AggregatedHttpResponse.of(HttpStatus.NOT_FOUND)); // get span template
server.enqueue(SUCCESS_RESPONSE); // put span template
server.enqueue(SUCCESS_RESPONSE); // get dependency template
server.enqueue(SUCCESS_RESPONSE); // get tags template
storage.ensureIndexTemplates();
server.takeRequest(); // get version
server.takeRequest(); // get span template
assertThat(server.takeRequest().request().contentUtf8()) // put span template
.contains(
""
+ " \"mappings\": {\n"
+ " \"span\": {\n"
+ " \"properties\": {\n"
+ " \"traceId\": { \"type\": \"keyword\", \"norms\": false },\n"
+ " \"annotations\": { \"enabled\": false },\n"
+ " \"tags\": { \"enabled\": false }\n"
+ " }\n"
+ " }\n"
+ " }\n");
}
/** Less overhead as a span json isn't rewritten to include a millis timestamp */
@Test
void searchDisabled_doesntAddTimestampMillis() throws Exception {
storage.close();
storage = ElasticsearchStorage.newBuilder(() -> WebClient.of(server.httpUri()))
.searchEnabled(false)
.build();
ensureIndexTemplates(storage);
server.enqueue(SUCCESS_RESPONSE); // for the bulk request
Span span =
Span.newBuilder().traceId("20").id("20").name("get").timestamp(TODAY * 1000).build();
storage.spanConsumer().accept(asList(span)).execute();
assertThat(server.takeRequest().request().contentUtf8()).doesNotContain("timestamp_millis");
}
@Test void addsAutocompleteValue() throws Exception {
server.enqueue(SUCCESS_RESPONSE);
accept(Span.newBuilder().traceId("1").id("1").timestamp(1).putTag("environment", "A").build());
assertThat(server.takeRequest().request().contentUtf8())
.endsWith(""
+ "{\"index\":{\"_index\":\"zipkin:autocomplete-1970-01-01\",\"_type\":\"autocomplete\",\"_id\":\"environment=A\"}}\n"
+ "{\"tagKey\":\"environment\",\"tagValue\":\"A\"}\n");
}
@Test void addsAutocompleteValue_suppressesWhenSameDay() throws Exception {
server.enqueue(SUCCESS_RESPONSE);
server.enqueue(SUCCESS_RESPONSE);
Span s = Span.newBuilder().traceId("1").id("1").timestamp(1).putTag("environment", "A").build();
accept(s);
accept(s.toBuilder().id(2).build());
server.takeRequest(); // skip first
// the tag is in the same date range as the other, so it should not write the tag again
assertThat(server.takeRequest().request().contentUtf8())
.doesNotContain("autocomplete");
}
@Test void addsAutocompleteValue_differentDays() throws Exception {
server.enqueue(SUCCESS_RESPONSE);
server.enqueue(SUCCESS_RESPONSE);
Span s = Span.newBuilder().traceId("1").id("1").timestamp(1).putTag("environment", "A").build();
accept(s);
accept(s.toBuilder().id(2).timestamp(1 + TimeUnit.DAYS.toMicros(1)).build());
server.takeRequest(); // skip first
// different day == different context
assertThat(server.takeRequest().request().contentUtf8())
.endsWith(""
+ "{\"index\":{\"_index\":\"zipkin:autocomplete-1970-01-02\",\"_type\":\"autocomplete\",\"_id\":\"environment=A\"}}\n"
+ "{\"tagKey\":\"environment\",\"tagValue\":\"A\"}\n");
}
@Test void addsAutocompleteValue_revertsSuppressionOnFailure() throws Exception {
server.enqueue(AggregatedHttpResponse.of(HttpStatus.INTERNAL_SERVER_ERROR));
server.enqueue(SUCCESS_RESPONSE);
Span s = Span.newBuilder().traceId("1").id("1").timestamp(1).putTag("environment", "A").build();
try {
accept(s);
failBecauseExceptionWasNotThrown(RuntimeException.class);
} catch (RuntimeException expected) {
}
accept(s);
// We only cache when there was no error.. the second request should be same as the first
assertThat(server.takeRequest().request().contentUtf8())
.isEqualTo(server.takeRequest().request().contentUtf8());
}
void accept(Span... spans) throws Exception {
spanConsumer.accept(asList(spans)).execute();
}
}
| apache-2.0 |
gradle/gradle | subprojects/persistent-cache/src/main/java/org/gradle/cache/internal/DefaultGlobalCacheLocations.java | 1590 | /*
* Copyright 2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gradle.cache.internal;
import org.gradle.cache.GlobalCache;
import org.gradle.cache.GlobalCacheLocations;
import org.gradle.internal.file.FileHierarchySet;
import java.io.File;
import java.util.List;
public class DefaultGlobalCacheLocations implements GlobalCacheLocations {
private final FileHierarchySet globalCacheRoots;
public DefaultGlobalCacheLocations(List<GlobalCache> globalCaches) {
FileHierarchySet globalCacheRoots = FileHierarchySet.empty();
for (GlobalCache globalCache : globalCaches) {
for (File file : globalCache.getGlobalCacheRoots()) {
globalCacheRoots = globalCacheRoots.plus(file);
}
}
this.globalCacheRoots = globalCacheRoots;
}
@Override
public boolean isInsideGlobalCache(String path) {
return globalCacheRoots.contains(path);
}
@Override
public String toString() {
return globalCacheRoots.toString();
}
}
| apache-2.0 |
jOOQ/jOOX | jOOX/src/main/java/org/joox/selector/Selector.java | 3743 | package org.joox.selector;
import java.util.List;
/**
* Represents a selector.
* <p/>
* A selector has a tag name, a combinator and a list of {@linkplain Specifier specifiers}.
*
* @see <a href="http://www.w3.org/TR/css3-selectors/#selector-syntax">Selector syntax description</a>
*
* @author Christer Sandberg
*/
class Selector {
/** The universal tag name (i.e. {@code *}). */
public static final String UNIVERSAL_TAG = "*";
/**
* Combinators
*
* @see <a href="http://www.w3.org/TR/css3-selectors/#combinators">Combinators description</a>
*/
public static enum Combinator {
DESCENDANT, CHILD, ADJACENT_SIBLING, GENERAL_SIBLING
};
/** Tag name. */
private final String tagName;
/** Combinator */
private final Combinator combinator;
/** A list of {@linkplain Specifier specifiers}. */
private final List<Specifier> specifiers;
/**
* Create a new instance with the tag name set to the value of {@link #UNIVERSAL_TAG},
* and with the combinator set to {@link Combinator#DESCENDANT}. The list of
* {@linkplain #specifiers specifiers} will be set to {@code null}.
*/
public Selector() {
this.tagName = UNIVERSAL_TAG;
this.combinator = Combinator.DESCENDANT;
this.specifiers = null;
}
/**
* Create a new instance with the specified tag name and combinator.
* <p/>
* The list of {@linkplain #specifiers specifiers} will be set to {@code null}.
*
* @param tagName The tag name to set.
* @param combinator The combinator to set.
*/
public Selector(String tagName, Combinator combinator) {
Assert.notNull(tagName, "tagName is null!");
Assert.notNull(combinator, "combinator is null!");
this.tagName = tagName;
this.combinator = combinator;
this.specifiers = null;
}
/**
* Create a new instance with the specified tag name and list of specifiers.
* <p/>
* The combinator will be set to {@link Combinator#DESCENDANT}.
*
* @param tagName The tag name to set.
* @param specifiers The list of specifiers to set.
*/
public Selector(String tagName, List<Specifier> specifiers) {
Assert.notNull(tagName, "tagName is null!");
this.tagName = tagName;
this.combinator = Combinator.DESCENDANT;
this.specifiers = specifiers;
}
/**
* Create a new instance with the specified tag name, combinator and
* list of specifiers.
*
* @param tagName The tag name to set.
* @param combinator The combinator to set.
* @param specifiers The list of specifiers to set.
*/
public Selector(String tagName, Combinator combinator, List<Specifier> specifiers) {
Assert.notNull(tagName, "tagName is null!");
Assert.notNull(combinator, "combinator is null!");
this.tagName = tagName;
this.combinator = combinator;
this.specifiers = specifiers;
}
/**
* Get the tag name.
*
* @return The tag name.
*/
public String getTagName() {
return tagName;
}
/**
* Get the combinator.
*
* @return The combinator.
*/
public Combinator getCombinator() {
return combinator;
}
/**
* Get the list of specifiers.
*
* @return The list of specifiers or {@code null}.
*/
public List<Specifier> getSpecifiers() {
return specifiers;
}
/**
* Returns whether this selector has any specifiers or not.
*
* @return <code>true</code> or <code>false</code>.
*/
public boolean hasSpecifiers() {
return specifiers != null && !specifiers.isEmpty();
}
}
| apache-2.0 |
ciandt-dev/tech-gallery | src/main/java/com/ciandt/techgallery/persistence/dao/StorageDAO.java | 936 | package com.ciandt.techgallery.persistence.dao;
import java.io.IOException;
import java.io.InputStream;
import java.security.GeneralSecurityException;
/**
* Class to acess the storage of the application.
*
* @author <a href="mailto:joaom@ciandt.com"> João Felipe de Medeiros Moreira </a>
* @since 13/10/2015
*
*/
public interface StorageDAO {
/**
* Method to insert a image into the bucket of the cloud storage.
*
* @author <a href="mailto:joaom@ciandt.com"> João Felipe de Medeiros Moreira </a>
* @since 13/10/2015
*
* @param name of the image.
* @param contentType of the image.
* @param stream to be converted.
*
* @return the self link of the image.
*
* @throws IOException in case a IO problem.
* @throws GeneralSecurityException in case a security problem.
*/
public String insertImage(String name, InputStream stream)
throws IOException, GeneralSecurityException;
}
| apache-2.0 |
grzesuav/jpf-core | src/main/gov/nasa/jpf/vm/PriorityRunnablesSyncPolicy.java | 2306 | /*
* Copyright (C) 2014, United States Government, as represented by the
* Administrator of the National Aeronautics and Space Administration.
* All rights reserved.
*
* The Java Pathfinder core (jpf-core) platform is 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 gov.nasa.jpf.vm;
import gov.nasa.jpf.Config;
/**
* a AllRunnablesSyncPolicy that only considers the runnables with the highest
* priority as choices
*
* 2do - it doesn't make much sense to compare priorities across process
* boundaries (unless we model distributed apps running on the same machine)
*/
public class PriorityRunnablesSyncPolicy extends AllRunnablesSyncPolicy {
public PriorityRunnablesSyncPolicy(Config config) {
super(config);
}
@Override
protected ThreadInfo[] getTimeoutRunnables (ApplicationContext appCtx){
ThreadInfo[] allRunnables = super.getTimeoutRunnables(appCtx);
int maxPrio = Integer.MIN_VALUE;
int n=0;
for (int i=0; i<allRunnables.length; i++){
ThreadInfo ti = allRunnables[i];
if (ti != null){
int prio = ti.getPriority();
if (prio > maxPrio){
maxPrio = prio;
for (int j=0; j<i; j++){
allRunnables[j]= null;
}
n = 1;
} else if (prio < maxPrio){
allRunnables[i] = null;
} else { // prio == maxPrio
n++;
}
}
}
if (n < allRunnables.length){
ThreadInfo[] prioRunnables = new ThreadInfo[n];
for (int i=0, j=0; j<n; j++, i++){
if (allRunnables[i] != null){
prioRunnables[j++] = allRunnables[i];
}
}
return prioRunnables;
} else { // all runnables had the same prio
return allRunnables;
}
}
}
| apache-2.0 |
stoksey69/googleads-java-lib | examples/dfp_axis/src/main/java/dfp/axis/v201408/labelservice/DeactivateLabels.java | 4168 | // 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 dfp.axis.v201408.labelservice;
import com.google.api.ads.common.lib.auth.OfflineCredentials;
import com.google.api.ads.common.lib.auth.OfflineCredentials.Api;
import com.google.api.ads.dfp.axis.factory.DfpServices;
import com.google.api.ads.dfp.axis.utils.v201408.StatementBuilder;
import com.google.api.ads.dfp.axis.v201408.Label;
import com.google.api.ads.dfp.axis.v201408.LabelPage;
import com.google.api.ads.dfp.axis.v201408.LabelServiceInterface;
import com.google.api.ads.dfp.axis.v201408.UpdateResult;
import com.google.api.ads.dfp.lib.client.DfpSession;
import com.google.api.client.auth.oauth2.Credential;
/**
* This example deactivates a label.
*
* Credentials and properties in {@code fromFile()} are pulled from the
* "ads.properties" file. See README for more info.
*
* Tags: LabelService.getLabelsByStatement
* Tags: LabelService.performLabelAction
*
* @author Adam Rogal
*/
public class DeactivateLabels {
// Set the ID of the label to deactivate.
private static final String LABEL_ID = "INSERT_LABEL_ID_HERE";
public static void runExample(DfpServices dfpServices, DfpSession session, long labelId)
throws Exception {
// Get the LabelService.
LabelServiceInterface labelService =
dfpServices.get(session, LabelServiceInterface.class);
// Create a statement to select a label.
StatementBuilder statementBuilder = new StatementBuilder()
.where("WHERE id = :id")
.orderBy("id ASC")
.limit(StatementBuilder.SUGGESTED_PAGE_LIMIT)
.withBindVariableValue("id", labelId);
// Default for total result set size.
int totalResultSetSize = 0;
do {
// Get labels by statement.
LabelPage page =
labelService.getLabelsByStatement(statementBuilder.toStatement());
if (page.getResults() != null) {
totalResultSetSize = page.getTotalResultSetSize();
int i = page.getStartIndex();
for (Label label : page.getResults()) {
System.out.printf("%d) Label with ID \"%d\" will be deactivated.\n", i++, label.getId());
}
}
statementBuilder.increaseOffsetBy(StatementBuilder.SUGGESTED_PAGE_LIMIT);
} while (statementBuilder.getOffset() < totalResultSetSize);
System.out.printf("Number of labels to be deactivated: %d\n", totalResultSetSize);
if (totalResultSetSize > 0) {
// Remove limit and offset from statement.
statementBuilder.removeLimitAndOffset();
// Create action.
com.google.api.ads.dfp.axis.v201408.DeactivateLabels action =
new com.google.api.ads.dfp.axis.v201408.DeactivateLabels();
// Perform action.
UpdateResult result = labelService.performLabelAction(
action, statementBuilder.toStatement());
if (result != null && result.getNumChanges() > 0) {
System.out.printf("Number of labels deactivated: %d\n", result.getNumChanges());
} else {
System.out.println("No labels were deactivated.");
}
}
}
public static void main(String[] args) throws Exception {
// Generate a refreshable OAuth2 credential.
Credential oAuth2Credential = new OfflineCredentials.Builder()
.forApi(Api.DFP)
.fromFile()
.build()
.generateCredential();
// Construct a DfpSession.
DfpSession session = new DfpSession.Builder()
.fromFile()
.withOAuth2Credential(oAuth2Credential)
.build();
DfpServices dfpServices = new DfpServices();
runExample(dfpServices, session, Long.parseLong(LABEL_ID));
}
}
| apache-2.0 |
dell-oss/Doradus | doradus-server/src/main/java/com/dell/doradus/search/builder/BuilderLinkCountRange.java | 1858 | /*
* Copyright (C) 2014 Dell, 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.dell.doradus.search.builder;
import com.dell.doradus.common.FieldDefinition;
import com.dell.doradus.common.Utils;
import com.dell.doradus.search.FilteredIterable;
import com.dell.doradus.search.QueryExecutor;
import com.dell.doradus.search.filter.Filter;
import com.dell.doradus.search.filter.FilterLinkCountRange;
import com.dell.doradus.search.query.LinkCountRangeQuery;
import com.dell.doradus.search.query.Query;
public class BuilderLinkCountRange extends SearchBuilder {
@Override public FilteredIterable search(Query query) {
return null;
}
@Override public Filter filter(Query query) {
LinkCountRangeQuery qu = (LinkCountRangeQuery)query;
FieldDefinition fieldDef = m_table.getFieldDef(qu.link);
Utils.require(fieldDef != null, qu.link + " not found in " + m_table.getTableName());
Utils.require(fieldDef.isLinkField(), qu.link + " is not a link field");
Filter inner = null;
if(qu.filter != null) {
QueryExecutor qe = new QueryExecutor(fieldDef.getTableDef().getLinkExtentTableDef(fieldDef));
inner = qe.filter(qu.filter);
}
FilterLinkCountRange condition = new FilterLinkCountRange(qu.link, qu.range, inner);
return condition;
}
}
| apache-2.0 |
hasinitg/airavata | modules/credential-store/credential-store-webapp/src/main/java/org/apache/airavata/credentialstore/local/LocalUserStore.java | 10664 | /*
*
* 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.airavata.credentialstore.local;
import java.security.NoSuchAlgorithmException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import javax.servlet.ServletContext;
import org.apache.airavata.common.utils.DBUtil;
import org.apache.airavata.common.utils.SecurityUtil;
import org.apache.airavata.common.utils.ServerSettings;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* User store to maintain internal DB database.
*/
public class LocalUserStore {
protected static Logger log = LoggerFactory.getLogger(LocalUserStore.class);
private DBUtil dbUtil;
private String hashMethod;
public LocalUserStore(ServletContext servletContext) throws Exception {
// Properties properties = WebAppUtil.getAiravataProperties(servletContext);
hashMethod = ServerSettings.getSetting("default.registry.password.hash.method");
dbUtil = new DBUtil(ServerSettings.getSetting("registry.jdbc.url"),
ServerSettings.getSetting("registry.jdbc.user"),
ServerSettings.getSetting("registry.jdbc.password"),
ServerSettings.getSetting("registry.jdbc.driver"));
}
public LocalUserStore(DBUtil db) {
dbUtil = db;
}
public void addUser(String userName, String password) {
String sql = "insert into Users values (?, ?)";
Connection connection = null;
PreparedStatement preparedStatement = null;
try {
connection = dbUtil.getConnection();
preparedStatement = connection.prepareStatement(sql);
preparedStatement.setString(1, userName);
preparedStatement.setString(2, SecurityUtil.digestString(password, hashMethod));
preparedStatement.executeUpdate();
connection.commit();
log.debug("User " + userName + " successfully added.");
} catch (SQLException e) {
StringBuilder stringBuilder = new StringBuilder("Error persisting user information.");
stringBuilder.append(" user - ").append(userName);
log.error(stringBuilder.toString(), e);
throw new RuntimeException(stringBuilder.toString(), e);
} catch (NoSuchAlgorithmException e) {
String stringBuilder = "Error creating hash value for password.";
log.error(stringBuilder, e);
throw new RuntimeException(stringBuilder, e);
} finally {
dbUtil.cleanup(preparedStatement, connection);
}
}
protected String getPassword(String userName, Connection connection) {
String sql = "select password from Users where user_name = ?";
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
try {
preparedStatement = connection.prepareStatement(sql);
preparedStatement.setString(1, userName);
resultSet = preparedStatement.executeQuery();
if (resultSet.next()) {
return resultSet.getString("password");
}
} catch (SQLException e) {
StringBuilder stringBuilder = new StringBuilder("Error retrieving credentials for user.");
stringBuilder.append("name - ").append(userName);
log.error(stringBuilder.toString(), e);
throw new RuntimeException(stringBuilder.toString(), e);
} finally {
if (resultSet != null) {
try {
resultSet.close();
} catch (SQLException e) {
log.error("Error closing result set", e);
}
}
if (preparedStatement != null) {
try {
preparedStatement.close();
} catch (SQLException e) {
log.error("Error closing prepared statement", e);
}
}
}
return null;
}
public void changePassword(String userName, String oldPassword, String newPassword) {
Connection connection = null;
PreparedStatement preparedStatement = null;
try {
connection = dbUtil.getConnection();
String storedPassword = getPassword(userName, connection);
String oldDigestedPassword = SecurityUtil.digestString(oldPassword, hashMethod);
if (storedPassword != null) {
if (!storedPassword.equals(oldDigestedPassword)) {
throw new RuntimeException("Previous password did not match correctly. Please specify old password"
+ " correctly.");
}
}
String sql = "update Users set password = ? where user_name = ?";
preparedStatement = connection.prepareStatement(sql);
preparedStatement.setString(1, SecurityUtil.digestString(newPassword, hashMethod));
preparedStatement.setString(2, userName);
preparedStatement.executeUpdate();
connection.commit();
log.debug("Password changed for user " + userName);
} catch (SQLException e) {
StringBuilder stringBuilder = new StringBuilder("Error updating credentials.");
stringBuilder.append(" user - ").append(userName);
log.error(stringBuilder.toString(), e);
throw new RuntimeException(stringBuilder.toString(), e);
} catch (NoSuchAlgorithmException e) {
String stringBuilder = "Error creating hash value for password.";
log.error(stringBuilder, e);
throw new RuntimeException(stringBuilder, e);
} finally {
dbUtil.cleanup(preparedStatement, connection);
}
}
public void changePasswordByAdmin(String userName, String newPassword) {
Connection connection = null;
PreparedStatement preparedStatement = null;
try {
connection = dbUtil.getConnection();
String sql = "update Users set password = ? where user_name = ?";
preparedStatement = connection.prepareStatement(sql);
preparedStatement.setString(1, SecurityUtil.digestString(newPassword, hashMethod));
preparedStatement.setString(2, userName);
preparedStatement.executeUpdate();
connection.commit();
log.debug("Admin changed password of user " + userName);
} catch (SQLException e) {
StringBuilder stringBuilder = new StringBuilder("Error updating credentials.");
stringBuilder.append(" user - ").append(userName);
log.error(stringBuilder.toString(), e);
throw new RuntimeException(stringBuilder.toString(), e);
} catch (NoSuchAlgorithmException e) {
String stringBuilder = "Error creating hash value for password.";
log.error(stringBuilder, e);
throw new RuntimeException(stringBuilder, e);
} finally {
dbUtil.cleanup(preparedStatement, connection);
}
}
public void deleteUser(String userName) {
String sql = "delete from Users where user_name=?";
Connection connection = null;
PreparedStatement preparedStatement = null;
try {
connection = dbUtil.getConnection();
preparedStatement = connection.prepareStatement(sql);
preparedStatement.setString(1, userName);
preparedStatement.executeUpdate();
connection.commit();
log.debug("User " + userName + " deleted.");
} catch (SQLException e) {
StringBuilder stringBuilder = new StringBuilder("Error deleting user.");
stringBuilder.append("user - ").append(userName);
log.error(stringBuilder.toString(), e);
throw new RuntimeException(stringBuilder.toString(), e);
} finally {
dbUtil.cleanup(preparedStatement, connection);
}
}
public List<String> getUsers() {
List<String> userList = new ArrayList<String>();
String sql = "select user_name from Users";
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
Connection connection = null;
try {
connection = dbUtil.getConnection();
preparedStatement = connection.prepareStatement(sql);
resultSet = preparedStatement.executeQuery();
while (resultSet.next()) {
userList.add(resultSet.getString("user_name"));
}
} catch (SQLException e) {
String errorString = "Error retrieving Users.";
log.error(errorString, e);
throw new RuntimeException(errorString, e);
} finally {
if (resultSet != null) {
try {
resultSet.close();
} catch (SQLException e) {
log.error("Error closing result set", e);
}
}
if (preparedStatement != null) {
try {
preparedStatement.close();
} catch (SQLException e) {
log.error("Error closing prepared statement", e);
}
}
if (connection != null) {
try {
connection.close();
} catch (SQLException e) {
log.error("Error closing connection", e);
}
}
}
Collections.sort(userList);
return userList;
}
public static String getPasswordRegularExpression() {
return "'^[a-zA-Z0-9_-]{6,15}$'";
}
}
| apache-2.0 |
planetakshay/wiremock | src/main/java/com/github/tomakehurst/wiremock/global/GlobalSettings.java | 1918 | /*
* Copyright (C) 2011 Thomas Akehurst
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.tomakehurst.wiremock.global;
import com.github.tomakehurst.wiremock.http.DelayDistribution;
import java.util.Objects;
public class GlobalSettings {
private Integer fixedDelay;
private DelayDistribution delayDistribution;
public Integer getFixedDelay() {
return fixedDelay;
}
public void setFixedDelay(Integer fixedDelay) {
this.fixedDelay = fixedDelay;
}
public DelayDistribution getDelayDistribution() {
return delayDistribution;
}
public void setDelayDistribution(DelayDistribution distribution) {
delayDistribution = distribution;
}
public GlobalSettings copy() {
GlobalSettings newSettings = new GlobalSettings();
newSettings.setFixedDelay(fixedDelay);
newSettings.setDelayDistribution(delayDistribution);
return newSettings;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
GlobalSettings that = (GlobalSettings) o;
return Objects.equals(fixedDelay, that.fixedDelay)
&& Objects.equals(delayDistribution, that.delayDistribution);
}
@Override
public int hashCode() {
return Objects.hash(fixedDelay, delayDistribution);
}
}
| apache-2.0 |
tcmoore32/sheer-madness | idea-gosu-plugin/src/main/java/gw/plugin/ij/util/XmlLocation.java | 1188 | /*
* Copyright 2014 Guidewire Software, Inc.
*/
package gw.plugin.ij.util;
import com.google.common.collect.ImmutableList;
import java.util.List;
import static com.google.common.base.Preconditions.checkNotNull;
public class XmlLocation {
public static class Segment {
public final String tag;
public final int index;
public Segment(String tag, int index) {
this.tag = tag;
this.index = index;
}
}
public final String rootTag;
public final List<Segment> path;
public final String attribute;
public XmlLocation(String rootTag, List<Segment> path) {
this(rootTag, path, null);
}
public XmlLocation(String rootTag, List<Segment> path, String attribute) {
this.rootTag = checkNotNull(rootTag);
this.path = ImmutableList.copyOf(checkNotNull(path));
this.attribute = attribute;
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder(rootTag);
for (Segment segment : path) {
sb.append("_");
sb.append(segment.tag);
sb.append(segment.index);
}
if (attribute != null) {
sb.append("__");
sb.append(attribute);
}
return sb.toString();
}
}
| apache-2.0 |
google/error-prone | core/src/test/java/com/google/errorprone/bugpatterns/CatchAndPrintStackTraceTest.java | 2260 | /*
* Copyright 2018 The Error Prone 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.errorprone.bugpatterns;
import com.google.errorprone.CompilationTestHelper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** {@link CatchAndPrintStackTrace}Test */
@RunWith(JUnit4.class)
public class CatchAndPrintStackTraceTest {
private final CompilationTestHelper testHelper =
CompilationTestHelper.newInstance(CatchAndPrintStackTrace.class, getClass());
@Test
public void positive() {
testHelper
.addSourceLines(
"Test.java",
"class Test {",
" void f() {",
" try {",
" System.err.println();",
" } catch (Throwable t) {",
" // BUG: Diagnostic contains:",
" t.printStackTrace();",
" }",
" try {",
" System.err.println();",
" } catch (Throwable t) {",
" // BUG: Diagnostic contains:",
" t.printStackTrace(System.err);",
" }",
" }",
"}")
.doTest();
}
@Test
public void negative() {
testHelper
.addSourceLines(
"Test.java",
"class Test {",
" void f() {",
" try {",
" System.err.println();",
" } catch (Throwable t) {}",
" try {",
" System.err.println();",
" } catch (Throwable t) {",
" t.printStackTrace();",
" t.printStackTrace();",
" }",
" }",
"}")
.doTest();
}
}
| apache-2.0 |
vlsi/calcite | core/src/main/java/org/apache/calcite/rel/convert/NoneConverter.java | 2086 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to you under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.calcite.rel.convert;
import org.apache.calcite.plan.Convention;
import org.apache.calcite.plan.ConventionTraitDef;
import org.apache.calcite.plan.RelOptCluster;
import org.apache.calcite.plan.RelOptPlanner;
import org.apache.calcite.plan.RelTraitSet;
import org.apache.calcite.rel.RelNode;
import org.apache.calcite.util.Util;
import java.util.List;
/**
* <code>NoneConverter</code> converts a plan from <code>inConvention</code> to
* {@link org.apache.calcite.plan.Convention#NONE}.
*/
public class NoneConverter extends ConverterImpl {
//~ Constructors -----------------------------------------------------------
public NoneConverter(
RelOptCluster cluster,
RelNode child) {
super(
cluster,
ConventionTraitDef.INSTANCE,
cluster.traitSetOf(Convention.NONE),
child);
}
//~ Methods ----------------------------------------------------------------
public RelNode copy(RelTraitSet traitSet, List<RelNode> inputs) {
assert traitSet.comprises(Convention.NONE);
return new NoneConverter(
getCluster(),
sole(inputs));
}
public static void init(RelOptPlanner planner) {
// we can't convert from any conventions, therefore no rules to register
Util.discard(planner);
}
}
| apache-2.0 |
eug48/hapi-fhir | hapi-fhir-structures-dstu2.1/src/main/java/org/hl7/fhir/dstu2016may/terminologies/ValueSetCheckerSimple.java | 4875 | package org.hl7.fhir.dstu2016may.terminologies;
import java.util.List;
import org.hl7.fhir.dstu2016may.model.CodeSystem;
import org.hl7.fhir.dstu2016may.model.CodeSystem.ConceptDefinitionComponent;
import org.hl7.fhir.dstu2016may.model.UriType;
import org.hl7.fhir.dstu2016may.model.ValueSet;
import org.hl7.fhir.dstu2016may.model.ValueSet.ConceptReferenceComponent;
import org.hl7.fhir.dstu2016may.model.ValueSet.ConceptSetComponent;
import org.hl7.fhir.dstu2016may.model.ValueSet.ConceptSetFilterComponent;
import org.hl7.fhir.dstu2016may.model.ValueSet.ValueSetExpansionContainsComponent;
import org.hl7.fhir.dstu2016may.terminologies.ValueSetExpander.ValueSetExpansionOutcome;
import org.hl7.fhir.dstu2016may.utils.EOperationOutcome;
import org.hl7.fhir.dstu2016may.utils.IWorkerContext;
import org.hl7.fhir.dstu2016may.utils.IWorkerContext.ValidationResult;
public class ValueSetCheckerSimple implements ValueSetChecker {
private ValueSet valueset;
private ValueSetExpanderFactory factory;
private IWorkerContext context;
public ValueSetCheckerSimple(ValueSet source, ValueSetExpanderFactory factory, IWorkerContext context) {
this.valueset = source;
this.factory = factory;
this.context = context;
}
@Override
public boolean codeInValueSet(String system, String code) throws EOperationOutcome, Exception {
if (valueset.hasCompose()) {
boolean ok = false;
for (UriType uri : valueset.getCompose().getImport()) {
ok = ok || inImport(uri.getValue(), system, code);
}
for (ConceptSetComponent vsi : valueset.getCompose().getInclude()) {
ok = ok || inComponent(vsi, system, code);
}
for (ConceptSetComponent vsi : valueset.getCompose().getExclude()) {
ok = ok && !inComponent(vsi, system, code);
}
}
return false;
}
private boolean inImport(String uri, String system, String code) throws EOperationOutcome, Exception {
ValueSet vs = context.fetchResource(ValueSet.class, uri);
if (vs == null)
return false ; // we can't tell
return codeInExpansion(factory.getExpander().expand(vs), system, code);
}
private boolean codeInExpansion(ValueSetExpansionOutcome vso, String system, String code) throws EOperationOutcome, Exception {
if (vso.getService() != null) {
return vso.getService().codeInValueSet(system, code);
} else {
for (ValueSetExpansionContainsComponent c : vso.getValueset().getExpansion().getContains()) {
if (code.equals(c.getCode()) && (system == null || system.equals(c.getSystem())))
return true;
if (codeinExpansion(c, system, code))
return true;
}
}
return false;
}
private boolean codeinExpansion(ValueSetExpansionContainsComponent cnt, String system, String code) {
for (ValueSetExpansionContainsComponent c : cnt.getContains()) {
if (code.equals(c.getCode()) && system.equals(c.getSystem().toString()))
return true;
if (codeinExpansion(c, system, code))
return true;
}
return false;
}
private boolean inComponent(ConceptSetComponent vsi, String system, String code) {
if (!vsi.getSystem().equals(system))
return false;
// whether we know the system or not, we'll accept the stated codes at face value
for (ConceptReferenceComponent cc : vsi.getConcept())
if (cc.getCode().equals(code)) {
return true;
}
CodeSystem def = context.fetchCodeSystem(system);
if (def != null) {
if (!def.getCaseSensitive()) {
// well, ok, it's not case sensitive - we'll check that too now
for (ConceptReferenceComponent cc : vsi.getConcept())
if (cc.getCode().equalsIgnoreCase(code)) {
return false;
}
}
if (vsi.getConcept().isEmpty() && vsi.getFilter().isEmpty()) {
return codeInDefine(def.getConcept(), code, def.getCaseSensitive());
}
for (ConceptSetFilterComponent f: vsi.getFilter())
throw new Error("not done yet: "+f.getValue());
return false;
} else if (context.supportsSystem(system)) {
ValidationResult vv = context.validateCode(system, code, null, vsi);
return vv.isOk();
} else
// we don't know this system, and can't resolve it
return false;
}
private boolean codeInDefine(List<ConceptDefinitionComponent> concepts, String code, boolean caseSensitive) {
for (ConceptDefinitionComponent c : concepts) {
if (caseSensitive && code.equals(c.getCode()))
return true;
if (!caseSensitive && code.equalsIgnoreCase(c.getCode()))
return true;
if (codeInDefine(c.getConcept(), code, caseSensitive))
return true;
}
return false;
}
}
| apache-2.0 |
buildscientist/greenmail | greenmail-core/src/main/java/com/icegreen/greenmail/pop3/commands/UidlCommand.java | 2003 | /*
* Copyright (c) 2014 Wael Chatila / Icegreen Technologies. All Rights Reserved.
* This software is released under the Apache license 2.0
* This file has been used and modified.
* Original file can be found on http://foedus.sourceforge.net
*/
package com.icegreen.greenmail.pop3.commands;
import com.icegreen.greenmail.foedus.util.MsgRangeFilter;
import com.icegreen.greenmail.pop3.Pop3Connection;
import com.icegreen.greenmail.pop3.Pop3State;
import com.icegreen.greenmail.store.FolderException;
import com.icegreen.greenmail.store.MailFolder;
import com.icegreen.greenmail.store.StoredMessage;
import java.util.List;
public class UidlCommand
extends Pop3Command {
@Override
public boolean isValidForState(Pop3State state) {
return state.isAuthenticated();
}
@Override
public void execute(Pop3Connection conn, Pop3State state,
String cmd) {
try {
MailFolder inbox = state.getFolder();
String[] cmdLine = cmd.split(" ");
List<StoredMessage> messages;
if (cmdLine.length > 1) {
String msgNumStr = cmdLine[1];
List<StoredMessage> msgList = inbox.getMessages(new MsgRangeFilter(msgNumStr, false));
if (msgList.size() != 1) {
conn.println("-ERR no such message");
return;
}
StoredMessage msg = msgList.get(0);
conn.println("+OK " + msgNumStr + " " + msg.getUid());
} else {
messages = inbox.getNonDeletedMessages();
conn.println("+OK");
for (StoredMessage msg : messages) {
conn.println(inbox.getMsn(msg.getUid()) + " " + msg.getUid());
}
conn.println(".");
}
} catch (FolderException me) {
conn.println("-ERR " + me);
}
}
} | apache-2.0 |
lritter/gnutch | src/java/org/apache/nutch/crawl/FetchScheduleFactory.java | 2003 | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.nutch.crawl;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.conf.Configuration;
import org.apache.nutch.util.ObjectCache;
/** Creates and caches a {@link FetchSchedule} implementation. */
public class FetchScheduleFactory {
public static final Log LOG = LogFactory.getLog(FetchScheduleFactory.class);
private FetchScheduleFactory() {} // no public ctor
/** Return the FetchSchedule implementation. */
public static FetchSchedule getFetchSchedule(Configuration conf) {
String clazz = conf.get("db.fetch.schedule.class", DefaultFetchSchedule.class.getName());
ObjectCache objectCache = ObjectCache.get(conf);
FetchSchedule impl = (FetchSchedule)objectCache.getObject(clazz);
if (impl == null) {
try {
LOG.info("Using FetchSchedule impl: " + clazz);
Class implClass = Class.forName(clazz);
impl = (FetchSchedule)implClass.newInstance();
impl.setConf(conf);
objectCache.setObject(clazz, impl);
} catch (Exception e) {
throw new RuntimeException("Couldn't create " + clazz, e);
}
}
return impl;
}
}
| apache-2.0 |
massakam/pulsar | pulsar-broker/src/main/java/org/apache/pulsar/broker/web/ProcessHandlerFilter.java | 2392 | /**
* 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.pulsar.broker.web;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.ws.rs.core.MediaType;
import org.apache.commons.lang3.StringUtils;
import org.apache.pulsar.broker.PulsarService;
import org.apache.pulsar.broker.intercept.BrokerInterceptor;
public class ProcessHandlerFilter implements Filter {
private final BrokerInterceptor interceptor;
private final boolean interceptorEnabled;
public ProcessHandlerFilter(PulsarService pulsar) {
this.interceptor = pulsar.getBrokerInterceptor();
this.interceptorEnabled = !pulsar.getConfig().getBrokerInterceptors().isEmpty();
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
if (interceptorEnabled
&& !StringUtils.containsIgnoreCase(request.getContentType(), MediaType.MULTIPART_FORM_DATA)
&& !StringUtils.containsIgnoreCase(request.getContentType(), MediaType.APPLICATION_OCTET_STREAM)) {
interceptor.onFilter(request, response, chain);
} else {
chain.doFilter(request, response);
}
}
@Override
public void init(FilterConfig arg) throws ServletException {
// No init necessary.
}
@Override
public void destroy() {
// No state to clean up.
}
}
| apache-2.0 |
yonzhang/incubator-eagle | eagle-core/eagle-query/eagle-entity-base/src/main/java/org/apache/eagle/log/entity/GenericMetricEntityDecompactionStreamReader.java | 4016 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.eagle.log.entity;
import org.apache.eagle.log.base.taggedlog.TaggedLogAPIEntity;
import org.apache.eagle.log.entity.meta.EntityDefinition;
import org.apache.eagle.log.entity.meta.EntityDefinitionManager;
import org.apache.eagle.common.DateTimeUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.text.ParseException;
public class GenericMetricEntityDecompactionStreamReader extends StreamReader
implements EntityCreationListener {
@SuppressWarnings("unused")
private static final Logger LOG = LoggerFactory
.getLogger(GenericMetricEntityDecompactionStreamReader.class);
private GenericEntityStreamReader reader;
private EntityDefinition ed;
private String serviceName = GenericMetricEntity.GENERIC_METRIC_SERVICE;
private long start;
private long end;
private GenericMetricShadowEntity single = new GenericMetricShadowEntity();
/**
* it makes sense that serviceName should not be provided while metric name should be provided as prefix
*
* @param metricName
* @param condition
* @throws InstantiationException
* @throws IllegalAccessException
* @throws ParseException
*/
public GenericMetricEntityDecompactionStreamReader(String metricName, SearchCondition condition)
throws InstantiationException, IllegalAccessException, ParseException {
ed = EntityDefinitionManager.getEntityByServiceName(serviceName);
checkIsMetric(ed);
reader = new GenericEntityStreamReader(serviceName, condition, metricName);
start = condition.getStartTime();
end = condition.getEndTime();
}
private void checkIsMetric(EntityDefinition ed) {
if (ed.getMetricDefinition() == null) {
throw new IllegalArgumentException("Only metric entity comes here");
}
}
@Override
public void entityCreated(TaggedLogAPIEntity entity) throws Exception {
GenericMetricEntity e = (GenericMetricEntity)entity;
double[] value = e.getValue();
if (value != null) {
int count = value.length;
@SuppressWarnings("unused")
Class<?> cls = ed.getMetricDefinition().getSingleTimestampEntityClass();
for (int i = 0; i < count; i++) {
long ts = entity.getTimestamp() + i * ed.getMetricDefinition().getInterval();
// exclude those entity which is not within the time range in search condition. [start, end)
if (ts < start || ts >= end) {
continue;
}
single.setTimestamp(ts);
single.setTags(entity.getTags());
single.setValue(e.getValue()[i]);
for (EntityCreationListener l : listeners) {
l.entityCreated(single);
}
}
}
}
@Override
public void readAsStream() throws Exception {
reader.register(this);
reader.readAsStream();
}
@Override
public long getLastTimestamp() {
return reader.getLastTimestamp();
}
@Override
public long getFirstTimestamp() {
return reader.getFirstTimestamp();
}
}
| apache-2.0 |
jhrcek/kie-wb-common | kie-wb-common-stunner/kie-wb-common-stunner-core/kie-wb-common-stunner-commons/kie-wb-common-stunner-client-common/src/main/java/org/kie/workbench/common/stunner/core/client/definition/adapter/binding/ClientBindablePropertySetAdapter.java | 3093 | /*
* Copyright 2016 Red Hat, Inc. and/or its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.kie.workbench.common.stunner.core.client.definition.adapter.binding;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import org.kie.workbench.common.stunner.core.definition.adapter.binding.BindableAdapterUtils;
import org.kie.workbench.common.stunner.core.definition.adapter.binding.BindablePropertySetAdapter;
import org.kie.workbench.common.stunner.core.i18n.StunnerTranslationService;
class ClientBindablePropertySetAdapter extends AbstractClientBindableAdapter<Object> implements BindablePropertySetAdapter<Object> {
private Map<Class, String> propertyNameFieldNames;
private Map<Class, Set<String>> propertiesFieldNames;
public ClientBindablePropertySetAdapter(StunnerTranslationService translationService) {
super(translationService);
}
@Override
public void setBindings(final Map<Class, String> propertyNameFieldNames,
final Map<Class, Set<String>> propertiesFieldNames) {
this.propertyNameFieldNames = propertyNameFieldNames;
this.propertiesFieldNames = propertiesFieldNames;
}
@Override
public String getId(final Object pojo) {
return BindableAdapterUtils.getPropertySetId(pojo.getClass());
}
@Override
public String getName(final Object pojo) {
String name = translationService.getPropertySetName(pojo.getClass().getName());
if (name != null) {
return name;
}
return getProxiedValue(pojo,
getPropertyNameFieldNames().get(pojo.getClass()));
}
@Override
public Set<?> getProperties(final Object pojo) {
return getProxiedSet(pojo,
getPropertiesFieldNames().get(pojo.getClass()));
}
@Override
public Optional<?> getProperty(Object pojo, String propertyName) {
return getPropertiesFieldNames().get(pojo.getClass()).stream()
.filter(name -> Objects.equals(name, propertyName))
.findFirst()
.map(prop -> getProxiedValue(pojo, prop));
}
@Override
public boolean accepts(final Class<?> pojoClass) {
return getPropertiesFieldNames().containsKey(pojoClass);
}
private Map<Class, String> getPropertyNameFieldNames() {
return propertyNameFieldNames;
}
private Map<Class, Set<String>> getPropertiesFieldNames() {
return propertiesFieldNames;
}
}
| apache-2.0 |
samolisov/ci.maven | liberty-maven-plugin/src/main/java/net/wasdev/wlp/maven/plugins/BasicSupport.java | 14098 | /**
* (C) Copyright IBM Corporation 2014.
*
* 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.wasdev.wlp.maven.plugins;
import java.io.File;
import java.io.IOException;
import java.text.MessageFormat;
import java.util.Enumeration;
import java.util.ResourceBundle;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import net.wasdev.wlp.ant.install.InstallLibertyTask;
import org.apache.maven.artifact.Artifact;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.settings.Server;
import org.apache.tools.ant.taskdefs.Chmod;
import org.apache.tools.ant.taskdefs.Expand;
import org.codehaus.mojo.pluginsupport.util.ArtifactItem;
import org.codehaus.plexus.util.FileUtils;
/**
* Basic Liberty Mojo Support
*
*
*/
public class BasicSupport extends AbstractLibertySupport {
//Note these next two are regular expressions, not just the code.
protected static final String START_APP_MESSAGE_REGEXP = "CWWKZ0001I.*";
protected static final ResourceBundle messages = ResourceBundle.getBundle("net.wasdev.wlp.maven.plugins.MvnMessages");
/**
* Skips the specific goal
*
* @parameter expression="${skip}" default-value="false"
*/
protected boolean skip = false;
/**
* Enable forced install refresh.
*
* @parameter expression="${refresh}" default-value="false"
*/
protected boolean refresh = false;
/**
* Set the false to skip the installation of the assembly, re-using anything
* that is already there.
*
* @parameter expression="${isInstall}" default-value="true"
*/
protected boolean isInstall = true;
/**
* Server Install Directory
*
* @parameter expression="${assemblyInstallDirectory}" default-value="${project.build.directory}/liberty"
*/
protected File assemblyInstallDirectory;
/**
* Installation directory of Liberty profile.
*
* @parameter expression="${installDirectory}"
*/
protected File installDirectory;
/**
* @deprecated Use installDirectory parameter instead.
* @parameter expression="${serverHome}"
*/
private File serverHome;
/**
* Liberty server name, default is defaultServer
*
* @parameter expression="${serverName}" default-value="defaultServer"
*/
protected String serverName = null;
/**
* Liberty user directory (<tT>WLP_USER_DIR</tt>).
*
* @parameter expression="${userDirectory}"
*/
protected File userDirectory = null;
/**
* Liberty output directory (<tT>WLP_OUTPUT_DIR</tt>).
*
* @parameter expression="${outputDirectory}"
*/
protected File outputDirectory = null;
/**
* Server Directory: ${installDirectory}/usr/servers/${serverName}/
*/
protected File serverDirectory;
protected static enum InstallType {
FROM_FILE, ALREADY_EXISTS, FROM_ARCHIVE
}
protected InstallType installType;
/**
* A file which points to a specific assembly ZIP archive. If this parameter
* is set, then it will install server from archive
*
* @parameter expression="${assemblyArchive}"
*/
protected File assemblyArchive;
/**
* Maven coordinates of a server assembly. This is best listed as a dependency, in which case the version can
* be omitted.
*
* @parameter
*/
protected ArtifactItem assemblyArtifact;
/**
* Liberty install option. If set, Liberty will be downloaded and installed from the WASdev repository or
* the given URL.
*
* @parameter
*/
protected Install install;
@Override
protected void init() throws MojoExecutionException, MojoFailureException {
if (skip) {
return;
}
super.init();
// for backwards compatibility
if (installDirectory == null) {
installDirectory = serverHome;
}
try {
// First check if installDirectory is set, if it is, then we can skip this
if (installDirectory != null) {
installDirectory = installDirectory.getCanonicalFile();
// Quick sanity check
File file = new File(installDirectory, "lib/ws-launch.jar");
if (!file.exists()) {
throw new MojoExecutionException(MessageFormat.format(messages.getString("error.server.home.validate"), ""));
}
log.info(MessageFormat.format(messages.getString("info.variable.set"), "pre-installed assembly", installDirectory));
installType = InstallType.ALREADY_EXISTS;
} else if (assemblyArchive != null) {
log.info(MessageFormat.format(messages.getString("info.variable.set"), "non-artifact based assembly archive", assemblyArchive));
assemblyArchive = assemblyArchive.getCanonicalFile();
installType = InstallType.FROM_FILE;
installDirectory = checkServerHome(assemblyArchive);
log.info(MessageFormat.format(messages.getString("info.variable.set"), "installDirectory", installDirectory));
} else if (assemblyArtifact != null) {
Artifact artifact = getArtifact(assemblyArtifact);
assemblyArchive = artifact.getFile();
if (assemblyArchive == null) {
throw new MojoExecutionException(MessageFormat.format(messages.getString("error.server.assembly.validate"), "artifact based assembly archive", ""));
}
log.info(MessageFormat.format(messages.getString("info.variable.set"), "artifact based assembly archive", assemblyArtifact));
assemblyArchive = assemblyArchive.getCanonicalFile();
installType = InstallType.FROM_FILE;
installDirectory = checkServerHome(assemblyArchive);
log.info(MessageFormat.format(messages.getString("info.variable.set"), "installDirectory", installDirectory));
} else {
if (install == null) {
install = new Install();
}
installType = InstallType.FROM_ARCHIVE;
installDirectory = new File(assemblyInstallDirectory, "wlp");
log.info(MessageFormat.format(messages.getString("info.variable.set"), "installDirectory", installDirectory));
}
// set server name
if (serverName == null) {
serverName = "defaultServer";
}
log.info(MessageFormat.format(messages.getString("info.variable.set"), "serverName", serverName));
// Set user directory
if (userDirectory == null) {
userDirectory = new File(installDirectory, "usr");
}
File serversDirectory = new File(userDirectory, "servers");
// Set server directory
serverDirectory = new File(serversDirectory, serverName);
log.info(MessageFormat.format(messages.getString("info.variable.set"), "serverDirectory", serverDirectory));
// Set output directory
if (outputDirectory == null) {
outputDirectory = serversDirectory;
}
} catch (IOException e) {
throw new MojoExecutionException(e.getMessage(), e);
}
}
protected void checkServerHomeExists() throws MojoExecutionException {
if (!installDirectory.exists()) {
throw new MojoExecutionException(MessageFormat.format(messages.getString("error.server.home.noexist"), installDirectory));
}
}
protected void checkServerDirectoryExists() throws MojoExecutionException {
if (!serverDirectory.exists()) {
throw new MojoExecutionException(MessageFormat.format(messages.getString("error.server.noexist"), serverName));
}
}
private File checkServerHome(final File archive) throws IOException,
MojoExecutionException {
log.debug(MessageFormat.format(messages.getString("debug.discover.server.home"), ""));
File dir = null;
ZipFile zipFile = null;
try {
zipFile = new ZipFile(archive);
Enumeration<?> n = zipFile.entries();
while (n.hasMoreElements()) {
ZipEntry entry = (ZipEntry) n.nextElement();
if (entry.getName().endsWith("lib/ws-launch.jar")) {
File file = new File(assemblyInstallDirectory, entry.getName());
dir = file.getParentFile().getParentFile();
break;
}
}
} catch (IOException e) {
throw new MojoExecutionException(MessageFormat.format(messages.getString("error.discover.server.home.fail"), archive), e);
} finally {
try {
zipFile.close();
} catch (Exception e) {
//Ignore it.
}
}
if (dir == null) {
throw new MojoExecutionException(MessageFormat.format(messages.getString("error.archive.not.contain.server"), archive));
}
return dir.getCanonicalFile();
}
/**
* Performs assembly installation unless the install type is pre-existing.
*
* @throws Exception
*/
protected void installServerAssembly() throws Exception {
if (installType == InstallType.ALREADY_EXISTS) {
log.info(MessageFormat.format(messages.getString("info.install.type.preexisting"), ""));
} else if (installType == InstallType.FROM_ARCHIVE) {
installFromArchive();
} else {
installFromFile();
}
}
protected void installFromFile() throws Exception {
// Check if there is a newer archive or missing marker to trigger assembly install
File installMarker = new File(installDirectory, ".installed");
if (!refresh) {
if (!installMarker.exists()) {
refresh = true;
} else if (assemblyArchive.lastModified() > installMarker.lastModified()) {
log.debug(MessageFormat.format(messages.getString("debug.detect.assembly.archive"), ""));
refresh = true;
}
} else {
log.debug(MessageFormat.format(messages.getString("debug.request.refresh"), ""));
}
if (refresh) {
if (installDirectory.exists()) {
log.info(MessageFormat.format(messages.getString("info.uninstalling.server.home"), installDirectory));
FileUtils.forceDelete(installDirectory);
}
}
// Install the assembly
if (!installMarker.exists()) {
log.info("Installing assembly...");
FileUtils.forceMkdir(installDirectory);
Expand unzip = (Expand) ant.createTask("unzip");
unzip.setSrc(assemblyArchive);
unzip.setDest(assemblyInstallDirectory.getCanonicalFile());
unzip.execute();
// Make scripts executable, since Java unzip ignores perms
Chmod chmod = (Chmod) ant.createTask("chmod");
chmod.setPerm("ugo+rx");
chmod.setDir(installDirectory);
chmod.setIncludes("bin/*");
chmod.setExcludes("bin/*.bat");
chmod.execute();
// delete installMarker first in case it was packaged with the assembly
installMarker.delete();
installMarker.createNewFile();
} else {
log.info(MessageFormat.format(messages.getString("info.reuse.installed.assembly"), ""));
}
}
protected void installFromArchive() throws Exception {
InstallLibertyTask installTask = (InstallLibertyTask) ant.createTask("antlib:net/wasdev/wlp/ant:install-liberty");
if (installTask == null) {
throw new NullPointerException("install-liberty task not found");
}
installTask.setBaseDir(assemblyInstallDirectory.getAbsolutePath());
installTask.setLicenseCode(install.getLicenseCode());
installTask.setVersion(install.getVersion());
installTask.setRuntimeUrl(install.getRuntimeUrl());
installTask.setVerbose(install.isVerbose());
installTask.setMaxDownloadTime(install.getMaxDownloadTime());
installTask.setType(install.getType());
installTask.setOffline(settings.isOffline());
String cacheDir = install.getCacheDirectory();
if (cacheDir == null) {
File dir = new File(artifactRepository.getBasedir(), "wlp-cache");
installTask.setCacheDir(dir.getAbsolutePath());
} else {
installTask.setCacheDir(cacheDir);
}
String serverId = install.getServerId();
if (serverId != null) {
Server server = settings.getServer(serverId);
if (server == null) {
throw new MojoExecutionException("Server id not found: " + serverId);
}
installTask.setUsername(server.getUsername());
installTask.setPassword(server.getPassword());
} else {
installTask.setUsername(install.getUsername());
installTask.setPassword(install.getPassword());
}
installTask.execute();
}
}
| apache-2.0 |
Cloudyle/hapi-fhir | hapi-fhir-structures-dstu3/src/main/java/org/hl7/fhir/dstu3/validation/ExtensionLocatorService.java | 2075 | package org.hl7.fhir.dstu3.validation;
import org.hl7.fhir.dstu3.exceptions.DefinitionException;
import org.hl7.fhir.dstu3.model.StructureDefinition;
/**
* This interface is used to provide extension location services for the validator
*
* when it encounters an extension, it asks this server to locate it, or tell it
* whether to ignore the extension, or mark it as invalid
*
* @author Grahame
*
*/
public interface ExtensionLocatorService {
public enum Status {
Located, NotAllowed, Unknown
}
public class ExtensionLocationResponse {
private Status status;
private StructureDefinition definition;
private String message;
private String url;
public ExtensionLocationResponse(String url, Status status, StructureDefinition definition, String message) {
super();
this.url = url;
this.status = status;
this.definition = definition;
this.message = message;
}
public Status getStatus() {
return status;
}
public StructureDefinition getDefinition() {
return definition;
}
public String getMessage() {
return message;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
/**
* This routine is used when walking into a complex extension.
* the non-tail part of the relative URL matches the end of the
* exiting URL
* @param url - the relative URL
* @return
* @throws DefinitionException
* @
*/
public ExtensionLocationResponse clone(String url) throws DefinitionException {
if (!this.url.endsWith(url.substring(0, url.lastIndexOf("."))))
throw new DefinitionException("the relative URL "+url+" cannot be used in the context "+this.url);
return new ExtensionLocationResponse(this.url+"."+url.substring(url.lastIndexOf(".")+1), status, definition, message);
}
}
public ExtensionLocationResponse locateExtension(String uri);
}
| apache-2.0 |
jimengliu/cattle | code/iaas/allocator/src/main/java/io/cattle/platform/allocator/service/AllocatorServiceImpl.java | 21171 | package io.cattle.platform.allocator.service;
import static io.cattle.platform.core.model.tables.ServiceTable.*;
import io.cattle.platform.allocator.constraint.AffinityConstraintDefinition;
import io.cattle.platform.allocator.constraint.AffinityConstraintDefinition.AffinityOps;
import io.cattle.platform.allocator.constraint.Constraint;
import io.cattle.platform.allocator.constraint.ContainerAffinityConstraint;
import io.cattle.platform.allocator.constraint.ContainerLabelAffinityConstraint;
import io.cattle.platform.allocator.constraint.HostAffinityConstraint;
import io.cattle.platform.allocator.dao.AllocatorDao;
import io.cattle.platform.allocator.lock.AllocateConstraintLock;
import io.cattle.platform.core.constants.InstanceConstants;
import io.cattle.platform.core.dao.InstanceDao;
import io.cattle.platform.core.dao.LabelsDao;
import io.cattle.platform.core.model.Host;
import io.cattle.platform.core.model.Instance;
import io.cattle.platform.core.model.Service;
import io.cattle.platform.json.JsonMapper;
import io.cattle.platform.lock.definition.LockDefinition;
import io.cattle.platform.object.ObjectManager;
import io.cattle.platform.object.util.DataAccessor;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.inject.Inject;
import org.jooq.tools.StringUtils;
public class AllocatorServiceImpl implements AllocatorService {
private static final String SERVICE_NAME_MACRO = "${service_name}";
private static final String STACK_NAME_MACRO = "${stack_name}";
// LEGACY: Temporarily support ${project_name} but this has become ${stack_name} now
private static final String PROJECT_NAME_MACRO = "${project_name}";
// TODO: We should refactor since these are defined in ServiceDiscoveryConstants too
private static final String LABEL_STACK_NAME = "io.rancher.stack.name";
private static final String LABEL_STACK_SERVICE_NAME = "io.rancher.stack_service.name";
private static final String LABEL_PROJECT_SERVICE_NAME = "io.rancher.project_service.name";
private static final String LABEL_SERVICE_LAUNCH_CONFIG = "io.rancher.service.launch.config";
private static final String PRIMARY_LAUNCH_CONFIG_NAME = "io.rancher.service.primary.launch.config";
@Inject
LabelsDao labelsDao;
@Inject
AllocatorDao allocatorDao;
@Inject
InstanceDao instanceDao;
@Inject
ObjectManager objectManager;
@Inject
JsonMapper jsonMapper;
@Override
public List<Long> getAllHostsSatisfyingHostAffinity(Long accountId, Map<String, String> labelConstraints) {
return getHostsSatisfyingHostAffinityInternal(true, accountId, labelConstraints);
}
@Override
public List<Long> getHostsSatisfyingHostAffinity(Long accountId, Map<String, String> labelConstraints) {
return getHostsSatisfyingHostAffinityInternal(false, accountId, labelConstraints);
}
protected List<Long> getHostsSatisfyingHostAffinityInternal(boolean includeRemoved, Long accountId, Map<String, String> labelConstraints) {
List<? extends Host> hosts = includeRemoved ? allocatorDao.getNonPurgedHosts(accountId) : allocatorDao.getActiveHosts(accountId);
List<Constraint> hostAffinityConstraints = getHostAffinityConstraintsFromLabels(labelConstraints);
List<Long> acceptableHostIds = new ArrayList<Long>();
for (Host host : hosts) {
if (hostSatisfiesHostAffinity(host.getId(), hostAffinityConstraints)) {
acceptableHostIds.add(host.getId());
}
}
return acceptableHostIds;
}
@Override
public boolean hostChangesAffectsHostAffinityRules(long hostId, Map<String, String> labelConstraints) {
List<Constraint> hostAffinityConstraints = getHostAffinityConstraintsFromLabels(labelConstraints);
// NOTE: There is a bug since the current check does not detect the converse.
// For example, if the host currently satisfies the hostAffinityConstraints but the
// change causes it to no longer satisfy the condition. This is fine for now since
// we currently do not want to remove containers for the user.
return hostSatisfiesHostAffinity(hostId, hostAffinityConstraints);
}
private List<Constraint> getHostAffinityConstraintsFromLabels(Map<String, String> labelConstraints) {
List<Constraint> constraints = extractConstraintsFromLabels(labelConstraints, null);
List<Constraint> hostConstraints = new ArrayList<Constraint>();
for (Constraint constraint : constraints) {
if (constraint instanceof HostAffinityConstraint) {
hostConstraints.add(constraint);
}
}
return hostConstraints;
}
private boolean hostSatisfiesHostAffinity(long hostId, List<Constraint> hostAffinityConstraints) {
for (Constraint constraint: hostAffinityConstraints) {
AllocationCandidate candidate = new AllocationCandidate();
candidate.setHost(hostId);
if (!constraint.matches(candidate)) {
return false;
}
}
return true;
}
@Override
public void normalizeLabels(long stackId, Map<String, String> systemLabels, Map<String, String> serviceUserLabels) {
String stackName = systemLabels.get(LABEL_STACK_NAME);
String stackServiceNameWithLaunchConfig = systemLabels.get(LABEL_STACK_SERVICE_NAME);
String launchConfig = systemLabels.get(LABEL_SERVICE_LAUNCH_CONFIG);
Set<String> serviceNamesInStack = getServiceNamesInStack(stackId);
for (Map.Entry<String, String> entry : serviceUserLabels.entrySet()) {
String labelValue = entry.getValue();
if (entry.getKey().startsWith(ContainerLabelAffinityConstraint.LABEL_HEADER_AFFINITY_CONTAINER_LABEL) &&
labelValue != null) {
String userEnteredServiceName = null;
if (labelValue.startsWith(LABEL_STACK_SERVICE_NAME)) {
userEnteredServiceName = labelValue.substring(LABEL_STACK_SERVICE_NAME.length() + 1);
} else if (labelValue.startsWith(LABEL_PROJECT_SERVICE_NAME)) {
userEnteredServiceName = labelValue.substring(LABEL_PROJECT_SERVICE_NAME.length() + 1);
}
if (userEnteredServiceName != null) {
String[] components = userEnteredServiceName.split("/");
if (components.length == 1 &&
stackServiceNameWithLaunchConfig != null) {
if (serviceNamesInStack.contains(userEnteredServiceName.toLowerCase())) {
// prepend stack name
userEnteredServiceName = stackName + "/" + userEnteredServiceName;
}
}
if (!PRIMARY_LAUNCH_CONFIG_NAME.equals(launchConfig) &&
stackServiceNameWithLaunchConfig.startsWith(userEnteredServiceName)) {
// automatically append secondary launchConfig
userEnteredServiceName = userEnteredServiceName + "/" + launchConfig;
}
entry.setValue(LABEL_STACK_SERVICE_NAME + "=" + userEnteredServiceName);
}
}
}
}
// TODO: Fix repeated DB call even if DB's cache no longer hits the disk
private Set<String> getServiceNamesInStack(long stackId) {
Set<String> servicesInEnv = new HashSet<String>();
List<? extends Service> services = objectManager.find(Service.class, SERVICE.STACK_ID, stackId, SERVICE.REMOVED,
null);
for (Service service : services) {
servicesInEnv.add(service.getName().toLowerCase());
}
return servicesInEnv;
}
@Override
public void mergeLabels(Map<String, String> srcMap, Map<String, String> destMap) {
if (srcMap == null || destMap == null) {
return;
}
for (Map.Entry<String, String> entry : srcMap.entrySet()) {
String key = entry.getKey();
if (key.toLowerCase().startsWith("io.rancher")) {
key = key.toLowerCase();
}
String value = entry.getValue();
if (key.startsWith("io.rancher.scheduler.affinity")) {
// merge labels
String destValue = destMap.get(key);
if (StringUtils.isEmpty(destValue)) {
destMap.put(key, value);
} else if (StringUtils.isEmpty(value)) {
continue;
} else if (!destValue.toLowerCase().contains(value.toLowerCase())) {
destMap.put(key, destValue + "," + value);
}
} else {
// overwrite label value
destMap.put(key, value);
}
}
}
@Override
@SuppressWarnings({ "unchecked", "rawtypes" })
public List<Constraint> extractConstraintsFromEnv(Map env) {
List<Constraint> constraints = new ArrayList<Constraint>();
if (env != null) {
Set<String> affinityDefinitions = env.keySet();
for (String affinityDef : affinityDefinitions) {
if (affinityDef == null) {
continue;
}
if (affinityDef.startsWith(ContainerAffinityConstraint.ENV_HEADER_AFFINITY_CONTAINER)) {
affinityDef = affinityDef.substring(ContainerAffinityConstraint.ENV_HEADER_AFFINITY_CONTAINER.length());
AffinityConstraintDefinition def = extractAffinitionConstraintDefinitionFromEnv(affinityDef);
if (def != null && !StringUtils.isEmpty(def.getValue())) {
constraints.add(new ContainerAffinityConstraint(def, objectManager, instanceDao));
}
} else if (affinityDef.startsWith(HostAffinityConstraint.ENV_HEADER_AFFINITY_HOST_LABEL)) {
affinityDef = affinityDef.substring(HostAffinityConstraint.ENV_HEADER_AFFINITY_HOST_LABEL.length());
AffinityConstraintDefinition def = extractAffinitionConstraintDefinitionFromEnv(affinityDef);
if (def != null && !StringUtils.isEmpty(def.getKey())) {
constraints.add(new HostAffinityConstraint(def, allocatorDao));
}
} else if (affinityDef.startsWith(ContainerLabelAffinityConstraint.ENV_HEADER_AFFINITY_CONTAINER_LABEL)) {
affinityDef = affinityDef.substring(ContainerLabelAffinityConstraint.ENV_HEADER_AFFINITY_CONTAINER_LABEL.length());
AffinityConstraintDefinition def = extractAffinitionConstraintDefinitionFromEnv(affinityDef);
if (def != null && !StringUtils.isEmpty(def.getKey())) {
constraints.add(new ContainerLabelAffinityConstraint(def, allocatorDao));
}
}
}
}
return constraints;
}
@Override
@SuppressWarnings({ "unchecked", "rawtypes" })
public List<Constraint> extractConstraintsFromLabels(Map labels, Instance instance) {
List<Constraint> constraints = new ArrayList<Constraint>();
if (labels == null) {
return constraints;
}
Iterator<Map.Entry> iter = labels.entrySet().iterator();
while (iter.hasNext()) {
Map.Entry affinityDef = iter.next();
String key = ((String)affinityDef.getKey()).toLowerCase();
String valueStr = (String)affinityDef.getValue();
valueStr = valueStr == null ? "" : valueStr.toLowerCase();
if (instance != null) {
// TODO: Possibly memoize the macros so we don't need to redo the queries for Service and Environment
valueStr = evaluateMacros(valueStr, instance);
}
String opStr = "";
if (key.startsWith(ContainerLabelAffinityConstraint.LABEL_HEADER_AFFINITY_CONTAINER_LABEL)) {
opStr = key.substring(ContainerLabelAffinityConstraint.LABEL_HEADER_AFFINITY_CONTAINER_LABEL.length());
List<AffinityConstraintDefinition> defs = extractAffinityConstraintDefinitionFromLabel(opStr, valueStr, true);
for (AffinityConstraintDefinition def: defs) {
constraints.add(new ContainerLabelAffinityConstraint(def, allocatorDao));
}
} else if (key.startsWith(ContainerAffinityConstraint.LABEL_HEADER_AFFINITY_CONTAINER)) {
opStr = key.substring(ContainerAffinityConstraint.LABEL_HEADER_AFFINITY_CONTAINER.length());
List<AffinityConstraintDefinition> defs = extractAffinityConstraintDefinitionFromLabel(opStr, valueStr, false);
for (AffinityConstraintDefinition def: defs) {
constraints.add(new ContainerAffinityConstraint(def, objectManager, instanceDao));
}
} else if (key.startsWith(HostAffinityConstraint.LABEL_HEADER_AFFINITY_HOST_LABEL)) {
opStr = key.substring(HostAffinityConstraint.LABEL_HEADER_AFFINITY_HOST_LABEL.length());
List<AffinityConstraintDefinition> defs = extractAffinityConstraintDefinitionFromLabel(opStr, valueStr, true);
for (AffinityConstraintDefinition def: defs) {
constraints.add(new HostAffinityConstraint(def, allocatorDao));
}
}
}
return constraints;
}
/**
* Supported macros
* ${service_name}
* ${stack_name}
* LEGACY:
* ${project_name}
*
* @param valueStr
* @param instance
* @return
*/
@SuppressWarnings("unchecked")
private String evaluateMacros(String valueStr, Instance instance) {
if (valueStr.indexOf(SERVICE_NAME_MACRO) != -1 ||
valueStr.indexOf(STACK_NAME_MACRO) != -1 ||
valueStr.indexOf(PROJECT_NAME_MACRO) != -1) {
Map<String, String> labels = DataAccessor.fields(instance).withKey(InstanceConstants.FIELD_LABELS).as(Map.class);
String serviceLaunchConfigName = "";
String stackName = "";
if (labels != null && !labels.isEmpty()) {
for (Map.Entry<String, String> label : labels.entrySet()) {
if (LABEL_STACK_NAME.equals(label.getKey())) {
stackName = label.getValue();
} else if (LABEL_STACK_SERVICE_NAME.equals(label.getKey())) {
if (label.getValue() != null) {
int i = label.getValue().indexOf('/');
if (i != -1) {
serviceLaunchConfigName = label.getValue().substring(i + 1);
}
}
}
}
}
if (!StringUtils.isBlank(stackName)) {
valueStr = valueStr.replace(STACK_NAME_MACRO, stackName);
// LEGACY: ${project_name} rename ${stack_name}
valueStr = valueStr.replace(PROJECT_NAME_MACRO, stackName);
}
if (!StringUtils.isBlank(serviceLaunchConfigName)) {
valueStr = valueStr.replace(SERVICE_NAME_MACRO, serviceLaunchConfigName);
}
}
return valueStr;
}
private AffinityConstraintDefinition extractAffinitionConstraintDefinitionFromEnv(String definitionString) {
for (AffinityOps op : AffinityOps.values()) {
int i = definitionString.indexOf(op.getEnvSymbol());
if (i != -1) {
String key = definitionString.substring(0, i);
String value = definitionString.substring(i + op.getEnvSymbol().length());
return new AffinityConstraintDefinition(op, key, value);
}
}
return null;
}
private List<AffinityConstraintDefinition> extractAffinityConstraintDefinitionFromLabel(String opStr, String valueStr, boolean keyValuePairs) {
List<AffinityConstraintDefinition> defs = new ArrayList<AffinityConstraintDefinition>();
AffinityOps affinityOp = null;
for (AffinityOps op : AffinityOps.values()) {
if (op.getLabelSymbol().equals(opStr)) {
affinityOp = op;
break;
}
}
if (affinityOp == null) {
return defs;
}
if (StringUtils.isEmpty(valueStr)) {
return defs;
}
String[] values = valueStr.split(",");
for (String value : values) {
if (StringUtils.isEmpty(value)) {
continue;
}
if (keyValuePairs && value.indexOf('=') != -1) {
String[] pair = value.split("=");
defs.add(new AffinityConstraintDefinition(affinityOp, pair[0], pair[1]));
} else {
defs.add(new AffinityConstraintDefinition(affinityOp, null, value));
}
}
return defs;
}
@Override
@SuppressWarnings({ "unchecked", "rawtypes" })
public List<LockDefinition> extractAllocationLockDefinitions(Instance instance) {
Map env = DataAccessor.fields(instance).withKey(InstanceConstants.FIELD_ENVIRONMENT).as(jsonMapper, Map.class);
List<LockDefinition> lockDefs = extractAllocationLockDefinitionsFromEnv(env);
Map labels = DataAccessor.fields(instance).withKey(InstanceConstants.FIELD_LABELS).as(jsonMapper, Map.class);
if (labels == null) {
return lockDefs;
}
Iterator<Map.Entry> iter = labels.entrySet().iterator();
while (iter.hasNext()) {
Map.Entry affinityDef = iter.next();
String key = ((String)affinityDef.getKey()).toLowerCase();
String valueStr = (String)affinityDef.getValue();
valueStr = valueStr == null ? "" : valueStr.toLowerCase();
if (instance != null) {
valueStr = evaluateMacros(valueStr, instance);
}
String opStr = "";
if (key.startsWith(ContainerLabelAffinityConstraint.LABEL_HEADER_AFFINITY_CONTAINER_LABEL)) {
opStr = key.substring(ContainerLabelAffinityConstraint.LABEL_HEADER_AFFINITY_CONTAINER_LABEL.length());
List<AffinityConstraintDefinition> defs = extractAffinityConstraintDefinitionFromLabel(opStr, valueStr, true);
for (AffinityConstraintDefinition def: defs) {
lockDefs.add(new AllocateConstraintLock(AllocateConstraintLock.Type.AFFINITY, def.getValue()));
}
} else if (key.startsWith(ContainerAffinityConstraint.LABEL_HEADER_AFFINITY_CONTAINER)) {
opStr = key.substring(ContainerAffinityConstraint.LABEL_HEADER_AFFINITY_CONTAINER.length());
List<AffinityConstraintDefinition> defs = extractAffinityConstraintDefinitionFromLabel(opStr, valueStr, false);
for (AffinityConstraintDefinition def: defs) {
lockDefs.add(new AllocateConstraintLock(AllocateConstraintLock.Type.AFFINITY, def.getValue()));
}
}
}
return lockDefs;
}
@SuppressWarnings({ "unchecked", "rawtypes" })
private List<LockDefinition> extractAllocationLockDefinitionsFromEnv(Map env) {
List<LockDefinition> constraints = new ArrayList<LockDefinition>();
if (env != null) {
Set<String> affinityDefinitions = env.keySet();
for (String affinityDef : affinityDefinitions) {
if (affinityDef == null) {
continue;
}
if (affinityDef.startsWith(ContainerAffinityConstraint.ENV_HEADER_AFFINITY_CONTAINER)) {
affinityDef = affinityDef.substring(ContainerAffinityConstraint.ENV_HEADER_AFFINITY_CONTAINER.length());
AffinityConstraintDefinition def = extractAffinitionConstraintDefinitionFromEnv(affinityDef);
if (def != null && !StringUtils.isEmpty(def.getValue())) {
constraints.add(new AllocateConstraintLock(AllocateConstraintLock.Type.AFFINITY, def.getValue()));
}
} else if (affinityDef.startsWith(ContainerLabelAffinityConstraint.ENV_HEADER_AFFINITY_CONTAINER_LABEL)) {
affinityDef = affinityDef.substring(ContainerLabelAffinityConstraint.ENV_HEADER_AFFINITY_CONTAINER_LABEL.length());
AffinityConstraintDefinition def = extractAffinitionConstraintDefinitionFromEnv(affinityDef);
if (def != null && !StringUtils.isEmpty(def.getKey())) {
constraints.add(new AllocateConstraintLock(AllocateConstraintLock.Type.AFFINITY, def.getValue()));
}
}
}
}
return constraints;
}
}
| apache-2.0 |
flofreud/aws-sdk-java | aws-java-sdk-ec2/src/main/java/com/amazonaws/services/ec2/model/VpnGateway.java | 16230 | /*
* Copyright 2010-2016 Amazon.com, Inc. or its affiliates. All Rights
* Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazonaws.services.ec2.model;
import java.io.Serializable;
/**
* <p>
* Describes a virtual private gateway.
* </p>
*/
public class VpnGateway implements Serializable, Cloneable {
/**
* <p>
* The ID of the virtual private gateway.
* </p>
*/
private String vpnGatewayId;
/**
* <p>
* The current state of the virtual private gateway.
* </p>
*/
private String state;
/**
* <p>
* The type of VPN connection the virtual private gateway supports.
* </p>
*/
private String type;
/**
* <p>
* The Availability Zone where the virtual private gateway was created, if
* applicable. This field may be empty or not returned.
* </p>
*/
private String availabilityZone;
/**
* <p>
* Any VPCs attached to the virtual private gateway.
* </p>
*/
private com.amazonaws.internal.SdkInternalList<VpcAttachment> vpcAttachments;
/**
* <p>
* Any tags assigned to the virtual private gateway.
* </p>
*/
private com.amazonaws.internal.SdkInternalList<Tag> tags;
/**
* <p>
* The ID of the virtual private gateway.
* </p>
*
* @param vpnGatewayId
* The ID of the virtual private gateway.
*/
public void setVpnGatewayId(String vpnGatewayId) {
this.vpnGatewayId = vpnGatewayId;
}
/**
* <p>
* The ID of the virtual private gateway.
* </p>
*
* @return The ID of the virtual private gateway.
*/
public String getVpnGatewayId() {
return this.vpnGatewayId;
}
/**
* <p>
* The ID of the virtual private gateway.
* </p>
*
* @param vpnGatewayId
* The ID of the virtual private gateway.
* @return Returns a reference to this object so that method calls can be
* chained together.
*/
public VpnGateway withVpnGatewayId(String vpnGatewayId) {
setVpnGatewayId(vpnGatewayId);
return this;
}
/**
* <p>
* The current state of the virtual private gateway.
* </p>
*
* @param state
* The current state of the virtual private gateway.
* @see VpnState
*/
public void setState(String state) {
this.state = state;
}
/**
* <p>
* The current state of the virtual private gateway.
* </p>
*
* @return The current state of the virtual private gateway.
* @see VpnState
*/
public String getState() {
return this.state;
}
/**
* <p>
* The current state of the virtual private gateway.
* </p>
*
* @param state
* The current state of the virtual private gateway.
* @return Returns a reference to this object so that method calls can be
* chained together.
* @see VpnState
*/
public VpnGateway withState(String state) {
setState(state);
return this;
}
/**
* <p>
* The current state of the virtual private gateway.
* </p>
*
* @param state
* The current state of the virtual private gateway.
* @see VpnState
*/
public void setState(VpnState state) {
this.state = state.toString();
}
/**
* <p>
* The current state of the virtual private gateway.
* </p>
*
* @param state
* The current state of the virtual private gateway.
* @return Returns a reference to this object so that method calls can be
* chained together.
* @see VpnState
*/
public VpnGateway withState(VpnState state) {
setState(state);
return this;
}
/**
* <p>
* The type of VPN connection the virtual private gateway supports.
* </p>
*
* @param type
* The type of VPN connection the virtual private gateway supports.
* @see GatewayType
*/
public void setType(String type) {
this.type = type;
}
/**
* <p>
* The type of VPN connection the virtual private gateway supports.
* </p>
*
* @return The type of VPN connection the virtual private gateway supports.
* @see GatewayType
*/
public String getType() {
return this.type;
}
/**
* <p>
* The type of VPN connection the virtual private gateway supports.
* </p>
*
* @param type
* The type of VPN connection the virtual private gateway supports.
* @return Returns a reference to this object so that method calls can be
* chained together.
* @see GatewayType
*/
public VpnGateway withType(String type) {
setType(type);
return this;
}
/**
* <p>
* The type of VPN connection the virtual private gateway supports.
* </p>
*
* @param type
* The type of VPN connection the virtual private gateway supports.
* @see GatewayType
*/
public void setType(GatewayType type) {
this.type = type.toString();
}
/**
* <p>
* The type of VPN connection the virtual private gateway supports.
* </p>
*
* @param type
* The type of VPN connection the virtual private gateway supports.
* @return Returns a reference to this object so that method calls can be
* chained together.
* @see GatewayType
*/
public VpnGateway withType(GatewayType type) {
setType(type);
return this;
}
/**
* <p>
* The Availability Zone where the virtual private gateway was created, if
* applicable. This field may be empty or not returned.
* </p>
*
* @param availabilityZone
* The Availability Zone where the virtual private gateway was
* created, if applicable. This field may be empty or not returned.
*/
public void setAvailabilityZone(String availabilityZone) {
this.availabilityZone = availabilityZone;
}
/**
* <p>
* The Availability Zone where the virtual private gateway was created, if
* applicable. This field may be empty or not returned.
* </p>
*
* @return The Availability Zone where the virtual private gateway was
* created, if applicable. This field may be empty or not returned.
*/
public String getAvailabilityZone() {
return this.availabilityZone;
}
/**
* <p>
* The Availability Zone where the virtual private gateway was created, if
* applicable. This field may be empty or not returned.
* </p>
*
* @param availabilityZone
* The Availability Zone where the virtual private gateway was
* created, if applicable. This field may be empty or not returned.
* @return Returns a reference to this object so that method calls can be
* chained together.
*/
public VpnGateway withAvailabilityZone(String availabilityZone) {
setAvailabilityZone(availabilityZone);
return this;
}
/**
* <p>
* Any VPCs attached to the virtual private gateway.
* </p>
*
* @return Any VPCs attached to the virtual private gateway.
*/
public java.util.List<VpcAttachment> getVpcAttachments() {
if (vpcAttachments == null) {
vpcAttachments = new com.amazonaws.internal.SdkInternalList<VpcAttachment>();
}
return vpcAttachments;
}
/**
* <p>
* Any VPCs attached to the virtual private gateway.
* </p>
*
* @param vpcAttachments
* Any VPCs attached to the virtual private gateway.
*/
public void setVpcAttachments(
java.util.Collection<VpcAttachment> vpcAttachments) {
if (vpcAttachments == null) {
this.vpcAttachments = null;
return;
}
this.vpcAttachments = new com.amazonaws.internal.SdkInternalList<VpcAttachment>(
vpcAttachments);
}
/**
* <p>
* Any VPCs attached to the virtual private gateway.
* </p>
* <p>
* <b>NOTE:</b> This method appends the values to the existing list (if
* any). Use {@link #setVpcAttachments(java.util.Collection)} or
* {@link #withVpcAttachments(java.util.Collection)} if you want to override
* the existing values.
* </p>
*
* @param vpcAttachments
* Any VPCs attached to the virtual private gateway.
* @return Returns a reference to this object so that method calls can be
* chained together.
*/
public VpnGateway withVpcAttachments(VpcAttachment... vpcAttachments) {
if (this.vpcAttachments == null) {
setVpcAttachments(new com.amazonaws.internal.SdkInternalList<VpcAttachment>(
vpcAttachments.length));
}
for (VpcAttachment ele : vpcAttachments) {
this.vpcAttachments.add(ele);
}
return this;
}
/**
* <p>
* Any VPCs attached to the virtual private gateway.
* </p>
*
* @param vpcAttachments
* Any VPCs attached to the virtual private gateway.
* @return Returns a reference to this object so that method calls can be
* chained together.
*/
public VpnGateway withVpcAttachments(
java.util.Collection<VpcAttachment> vpcAttachments) {
setVpcAttachments(vpcAttachments);
return this;
}
/**
* <p>
* Any tags assigned to the virtual private gateway.
* </p>
*
* @return Any tags assigned to the virtual private gateway.
*/
public java.util.List<Tag> getTags() {
if (tags == null) {
tags = new com.amazonaws.internal.SdkInternalList<Tag>();
}
return tags;
}
/**
* <p>
* Any tags assigned to the virtual private gateway.
* </p>
*
* @param tags
* Any tags assigned to the virtual private gateway.
*/
public void setTags(java.util.Collection<Tag> tags) {
if (tags == null) {
this.tags = null;
return;
}
this.tags = new com.amazonaws.internal.SdkInternalList<Tag>(tags);
}
/**
* <p>
* Any tags assigned to the virtual private gateway.
* </p>
* <p>
* <b>NOTE:</b> This method appends the values to the existing list (if
* any). Use {@link #setTags(java.util.Collection)} or
* {@link #withTags(java.util.Collection)} if you want to override the
* existing values.
* </p>
*
* @param tags
* Any tags assigned to the virtual private gateway.
* @return Returns a reference to this object so that method calls can be
* chained together.
*/
public VpnGateway withTags(Tag... tags) {
if (this.tags == null) {
setTags(new com.amazonaws.internal.SdkInternalList<Tag>(tags.length));
}
for (Tag ele : tags) {
this.tags.add(ele);
}
return this;
}
/**
* <p>
* Any tags assigned to the virtual private gateway.
* </p>
*
* @param tags
* Any tags assigned to the virtual private gateway.
* @return Returns a reference to this object so that method calls can be
* chained together.
*/
public VpnGateway withTags(java.util.Collection<Tag> tags) {
setTags(tags);
return this;
}
/**
* Returns a string representation of this object; useful for testing and
* debugging.
*
* @return A string representation of this object.
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{");
if (getVpnGatewayId() != null)
sb.append("VpnGatewayId: " + getVpnGatewayId() + ",");
if (getState() != null)
sb.append("State: " + getState() + ",");
if (getType() != null)
sb.append("Type: " + getType() + ",");
if (getAvailabilityZone() != null)
sb.append("AvailabilityZone: " + getAvailabilityZone() + ",");
if (getVpcAttachments() != null)
sb.append("VpcAttachments: " + getVpcAttachments() + ",");
if (getTags() != null)
sb.append("Tags: " + getTags());
sb.append("}");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof VpnGateway == false)
return false;
VpnGateway other = (VpnGateway) obj;
if (other.getVpnGatewayId() == null ^ this.getVpnGatewayId() == null)
return false;
if (other.getVpnGatewayId() != null
&& other.getVpnGatewayId().equals(this.getVpnGatewayId()) == false)
return false;
if (other.getState() == null ^ this.getState() == null)
return false;
if (other.getState() != null
&& other.getState().equals(this.getState()) == false)
return false;
if (other.getType() == null ^ this.getType() == null)
return false;
if (other.getType() != null
&& other.getType().equals(this.getType()) == false)
return false;
if (other.getAvailabilityZone() == null
^ this.getAvailabilityZone() == null)
return false;
if (other.getAvailabilityZone() != null
&& other.getAvailabilityZone().equals(
this.getAvailabilityZone()) == false)
return false;
if (other.getVpcAttachments() == null
^ this.getVpcAttachments() == null)
return false;
if (other.getVpcAttachments() != null
&& other.getVpcAttachments().equals(this.getVpcAttachments()) == false)
return false;
if (other.getTags() == null ^ this.getTags() == null)
return false;
if (other.getTags() != null
&& other.getTags().equals(this.getTags()) == false)
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
hashCode = prime
* hashCode
+ ((getVpnGatewayId() == null) ? 0 : getVpnGatewayId()
.hashCode());
hashCode = prime * hashCode
+ ((getState() == null) ? 0 : getState().hashCode());
hashCode = prime * hashCode
+ ((getType() == null) ? 0 : getType().hashCode());
hashCode = prime
* hashCode
+ ((getAvailabilityZone() == null) ? 0 : getAvailabilityZone()
.hashCode());
hashCode = prime
* hashCode
+ ((getVpcAttachments() == null) ? 0 : getVpcAttachments()
.hashCode());
hashCode = prime * hashCode
+ ((getTags() == null) ? 0 : getTags().hashCode());
return hashCode;
}
@Override
public VpnGateway clone() {
try {
return (VpnGateway) super.clone();
} catch (CloneNotSupportedException e) {
throw new IllegalStateException(
"Got a CloneNotSupportedException from Object.clone() "
+ "even though we're Cloneable!", e);
}
}
}
| apache-2.0 |
nmirasch/kie-wb-common | kie-wb-common-screens/kie-wb-common-server-ui/kie-wb-common-server-ui-api/src/main/java/org/kie/workbench/common/screens/server/management/model/impl/ScannerOperationResult.java | 1497 | /*
* Copyright 2015 JBoss Inc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.kie.workbench.common.screens.server.management.model.impl;
import org.jboss.errai.common.client.api.annotations.Portable;
import org.kie.workbench.common.screens.server.management.model.ScannerStatus;
@Portable
public class ScannerOperationResult {
private ScannerStatus scannerStatus;
private String message;
private Long pollInterval;
public ScannerOperationResult() {
}
public ScannerOperationResult( final ScannerStatus scannerStatus,
final String message,
final Long pollInterval ) {
this.scannerStatus = scannerStatus;
this.message = message;
this.pollInterval = pollInterval;
}
public ScannerStatus getScannerStatus() {
return scannerStatus;
}
public String getMessage() {
return message;
}
public Long getPollInterval() {
return pollInterval;
}
}
| apache-2.0 |
this/carbon-uuf | components/uuf-renderablecreator-hbs/src/main/java/org/wso2/carbon/uuf/renderablecreator/hbs/helpers/runtime/MenuHelper.java | 3562 | /*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.wso2.carbon.uuf.renderablecreator.hbs.helpers.runtime;
import com.github.jknack.handlebars.Context;
import com.github.jknack.handlebars.Handlebars;
import com.github.jknack.handlebars.Helper;
import com.github.jknack.handlebars.Options;
import org.wso2.carbon.uuf.api.config.Configuration;
import org.wso2.carbon.uuf.core.Lookup;
import org.wso2.carbon.uuf.renderablecreator.hbs.core.HbsRenderable;
import java.io.IOException;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
public class MenuHelper implements Helper<Object> {
public static final String HELPER_NAME = "menu";
@Override
@SuppressWarnings("unchecked")
public CharSequence apply(Object context, Options options) throws IOException {
if (Handlebars.Utils.isEmpty(context)) {
return "";
}
List<Configuration.MenuItem> menuItems;
if (context instanceof String) {
String menuName = (String) context;
Lookup lookup = options.data(HbsRenderable.DATA_KEY_LOOKUP);
menuItems = lookup.getConfiguration().getMenu(menuName);
} else if (context instanceof Configuration.MenuItem[]) {
menuItems = Arrays.asList((Configuration.MenuItem[]) context);
} else if (context instanceof List) {
List<?> rawList = (List) context;
for (Object item : rawList) {
if (!(item instanceof Configuration.MenuItem)) {
throw new IllegalArgumentException(
"List parsed as the context of the menu helper must be a List<Configuration.MenuItem>. " +
"Instead found a '" + context.getClass().getName() + "'.");
}
}
menuItems = (List<Configuration.MenuItem>) rawList;
} else {
throw new IllegalArgumentException(
"Menu helper context must be either a string (menu name) or a Configuration.MenuItem[] or a " +
"List<Configuration.MenuItem>. Instead found a '" + context.getClass().getName() + "'.");
}
Iterator<Configuration.MenuItem> iterator = menuItems.iterator();
Context parentContext = options.context;
boolean isFirstIteration = true;
while (iterator.hasNext()) {
Configuration.MenuItem menuItem = iterator.next();
boolean isLeaf = menuItem.getSubMenus().isEmpty();
Context iterationContext = Context.newContext(parentContext, menuItem)
.combine("@first", isFirstIteration)
.combine("@last", !iterator.hasNext())
.combine("@leaf", isLeaf)
.combine("@nested", !isLeaf);
options.buffer().append(options.fn(iterationContext));
isFirstIteration = false;
}
return options.buffer();
}
}
| apache-2.0 |
cosmoharrigan/rl-viz | projects/rlVizLibJava/src/org/rlcommunity/rlviz/dynamicloading/SharedLibraryFileFilter.java | 986 | /*
Copyright 2007 Brian Tanner
brian@tannerpages.com
http://brian.tannerpages.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.rlcommunity.rlviz.dynamicloading;
import java.io.File;
import java.io.FileFilter;
/**
*
* @author Brian Tanner
*/
public class SharedLibraryFileFilter implements FileFilter {
public boolean accept(File pathName) {
String stringPath=pathName.getPath();
return stringPath.endsWith(".dylib")||stringPath.endsWith(".so");
}
}
| apache-2.0 |
Selventa/model-builder | tools/groovy/src/src/main/org/codehaus/groovy/transform/sc/transformers/CompareToNullExpression.java | 3190 | /*
* Copyright 2003-2009 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.codehaus.groovy.transform.sc.transformers;
import org.codehaus.groovy.ast.ClassHelper;
import org.codehaus.groovy.ast.ClassNode;
import org.codehaus.groovy.ast.GroovyCodeVisitor;
import org.codehaus.groovy.ast.expr.BinaryExpression;
import org.codehaus.groovy.ast.expr.ConstantExpression;
import org.codehaus.groovy.ast.expr.Expression;
import org.codehaus.groovy.ast.expr.ExpressionTransformer;
import org.codehaus.groovy.classgen.AsmClassGenerator;
import org.codehaus.groovy.classgen.asm.WriterController;
import org.codehaus.groovy.syntax.Token;
import org.codehaus.groovy.syntax.Types;
import org.objectweb.asm.Label;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.Opcodes;
public class CompareToNullExpression extends BinaryExpression implements Opcodes {
private final boolean equalsNull;
private final Expression objectExpression;
public CompareToNullExpression(final Expression objectExpression, final boolean compareToNull) {
super(objectExpression, new Token(Types.COMPARE_TO, compareToNull ? "==" : "!=", -1, -1), ConstantExpression.NULL);
this.objectExpression = objectExpression;
this.equalsNull = compareToNull;
}
public Expression getObjectExpression() {
return objectExpression;
}
@Override
public Expression transformExpression(final ExpressionTransformer transformer) {
return this;
}
@Override
public void visit(final GroovyCodeVisitor visitor) {
if (visitor instanceof AsmClassGenerator) {
AsmClassGenerator acg = (AsmClassGenerator) visitor;
WriterController controller = acg.getController();
MethodVisitor mv = controller.getMethodVisitor();
objectExpression.visit(acg);
ClassNode top = controller.getOperandStack().getTopOperand();
if (ClassHelper.isPrimitiveType(top)) {
controller.getOperandStack().pop();
mv.visitInsn(ICONST_0);
controller.getOperandStack().push(ClassHelper.boolean_TYPE);
return;
}
Label zero = new Label();
mv.visitJumpInsn(equalsNull ? IFNONNULL : IFNULL, zero);
mv.visitInsn(ICONST_1);
Label end = new Label();
mv.visitJumpInsn(GOTO, end);
mv.visitLabel(zero);
mv.visitInsn(ICONST_0);
mv.visitLabel(end);
controller.getOperandStack().replace(ClassHelper.boolean_TYPE);
} else {
super.visit(visitor);
}
}
}
| apache-2.0 |
maliqq/netty | codec-http/src/main/java/io/netty/handler/codec/http/HttpRequestEncoder.java | 2933 | /*
* 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.
*/
package io.netty.handler.codec.http;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufUtil;
import io.netty.util.AsciiString;
import io.netty.util.CharsetUtil;
import static io.netty.handler.codec.http.HttpConstants.SP;
/**
* Encodes an {@link HttpRequest} or an {@link HttpContent} into
* a {@link ByteBuf}.
*/
public class HttpRequestEncoder extends HttpObjectEncoder<HttpRequest> {
private static final char SLASH = '/';
private static final char QUESTION_MARK = '?';
@Override
public boolean acceptOutboundMessage(Object msg) throws Exception {
return super.acceptOutboundMessage(msg) && !(msg instanceof HttpResponse);
}
@Override
protected void encodeInitialLine(ByteBuf buf, HttpRequest request) throws Exception {
AsciiString method = request.method().asciiName();
ByteBufUtil.copy(method, method.arrayOffset(), buf, method.length());
buf.writeByte(SP);
// Add / as absolute path if no is present.
// See http://tools.ietf.org/html/rfc2616#section-5.1.2
String uri = request.uri();
if (uri.length() == 0) {
uri += SLASH;
} else {
int start = uri.indexOf("://");
if (start != -1 && uri.charAt(0) != SLASH) {
int startIndex = start + 3;
// Correctly handle query params.
// See https://github.com/netty/netty/issues/2732
int index = uri.indexOf(QUESTION_MARK, startIndex);
if (index == -1) {
if (uri.lastIndexOf(SLASH) <= startIndex) {
uri += SLASH;
}
} else {
if (uri.lastIndexOf(SLASH, index) <= startIndex) {
int len = uri.length();
StringBuilder sb = new StringBuilder(len + 1);
sb.append(uri, 0, index)
.append(SLASH)
.append(uri, index, len);
uri = sb.toString();
}
}
}
}
buf.writeBytes(uri.getBytes(CharsetUtil.UTF_8));
buf.writeByte(SP);
request.protocolVersion().encode(buf);
buf.writeBytes(CRLF);
}
}
| apache-2.0 |
jayantgolhar/Hadoop-0.21.0 | mapred/src/test/mapred/org/apache/hadoop/mapreduce/security/token/TestDelegationTokenRenewal.java | 11145 | /**
* 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.mapreduce.security.token;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.hdfs.DFSConfigKeys;
import org.apache.hadoop.hdfs.DistributedFileSystem;
import org.apache.hadoop.hdfs.security.token.delegation.DelegationTokenIdentifier;
import org.apache.hadoop.hdfs.security.token.delegation.DelegationTokenSecretManager;
import org.apache.hadoop.security.token.delegation.DelegationKey;
import org.apache.hadoop.hdfs.server.namenode.FSNamesystem;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.JobID;
import org.apache.hadoop.security.TokenStorage;
import org.apache.hadoop.security.token.Token;
import org.apache.hadoop.security.token.SecretManager.InvalidToken;
import org.apache.hadoop.util.StringUtils;
import org.junit.BeforeClass;
import org.junit.Test;
/**
* unit test -
* tests addition/deletion/cancelation of renewals of delegation tokens
*
*/
public class TestDelegationTokenRenewal {
private static final Log LOG =
LogFactory.getLog(TestDelegationTokenRenewal.class);
private static Configuration conf;
@BeforeClass
public static void setUp() throws Exception {
conf = new Configuration();
// create a fake FileSystem (MyFS) and assosiate it
// with "hdfs" schema.
URI uri = new URI(DelegationTokenRenewal.SCHEME+"://localhost:0");
System.out.println("scheme is : " + uri.getScheme());
conf.setClass("fs." + uri.getScheme() + ".impl", MyFS.class, DistributedFileSystem.class);
FileSystem.setDefaultUri(conf, uri);
System.out.println("filesystem uri = " + FileSystem.getDefaultUri(conf).toString());
}
private static class MyDelegationTokenSecretManager extends DelegationTokenSecretManager {
public MyDelegationTokenSecretManager(long delegationKeyUpdateInterval,
long delegationTokenMaxLifetime, long delegationTokenRenewInterval,
long delegationTokenRemoverScanInterval, FSNamesystem namesystem) {
super(delegationKeyUpdateInterval, delegationTokenMaxLifetime,
delegationTokenRenewInterval, delegationTokenRemoverScanInterval,
namesystem);
}
@Override //DelegationTokenSecretManager
public void logUpdateMasterKey(DelegationKey key) throws IOException {
return;
}
}
/**
* add some extra functionality for testing
* 1. toString();
* 2. cancel() and isCanceled()
*/
private static class MyToken extends Token<DelegationTokenIdentifier> {
public String status = "GOOD";
public static final String CANCELED = "CANCELED";
public MyToken(DelegationTokenIdentifier dtId1,
MyDelegationTokenSecretManager sm) {
super(dtId1, sm);
status = "GOOD";
}
public boolean isCanceled() {return status.equals(CANCELED);}
public void cancelToken() {this.status=CANCELED;}
public String toString() {
StringBuilder sb = new StringBuilder(1024);
sb.append("id=");
String id = StringUtils.byteToHexString(this.getIdentifier());
int idLen = id.length();
sb.append(id.substring(idLen-6));
sb.append(";k=");
sb.append(this.getKind());
sb.append(";s=");
sb.append(this.getService());
return sb.toString();
}
}
/**
* fake FileSystem
* overwrites three methods
* 1. getDelegationToken() - generates a token
* 2. renewDelegataionToken - counts number of calls, and remembers
* most recently renewed token.
* 3. cancelToken -cancels token (subsequent renew will cause IllegalToken
* exception
*/
static class MyFS extends DistributedFileSystem {
int counter=0;
MyToken token;
MyToken tokenToRenewIn2Sec;
public MyFS() {}
public void close() {}
@Override
public void initialize(URI uri, Configuration conf) throws IOException {}
@Override
public long renewDelegationToken(Token<DelegationTokenIdentifier> t)
throws InvalidToken, IOException {
MyToken token = (MyToken)t;
if(token.isCanceled()) {
throw new InvalidToken("token has been canceled");
}
counter ++;
this.token = (MyToken)token;
System.out.println("Called MYDFS.renewdelegationtoken " + token);
if(tokenToRenewIn2Sec == token) {
// this token first renewal in 2 seconds
System.out.println("RENEW in 2 seconds");
tokenToRenewIn2Sec=null;
return 2*1000 + System.currentTimeMillis();
} else {
return 86400*1000 + System.currentTimeMillis();
}
}
@Override
public MyToken getDelegationToken(Text renewer)
throws IOException {
System.out.println("Called MYDFS.getdelegationtoken");
return createTokens(renewer);
}
@Override
public void cancelDelegationToken(Token<DelegationTokenIdentifier> t)
throws IOException {
MyToken token = (MyToken)t;
token.cancelToken();
}
public void setTokenToRenewIn2Sec(MyToken t) {tokenToRenewIn2Sec=t;}
public int getCounter() {return counter; }
public MyToken getToken() {return token;}
}
/**
* auxilary - create token
* @param renewer
* @return
* @throws IOException
*/
static MyToken createTokens(Text renewer)
throws IOException {
Text user1= new Text("user1");
MyDelegationTokenSecretManager sm = new MyDelegationTokenSecretManager(
DFSConfigKeys.DFS_NAMENODE_DELEGATION_KEY_UPDATE_INTERVAL_DEFAULT,
DFSConfigKeys.DFS_NAMENODE_DELEGATION_KEY_UPDATE_INTERVAL_DEFAULT,
DFSConfigKeys.DFS_NAMENODE_DELEGATION_TOKEN_MAX_LIFETIME_DEFAULT,
3600000, null);
sm.startThreads();
DelegationTokenIdentifier dtId1 =
new DelegationTokenIdentifier(user1, renewer, user1);
MyToken token1 = new MyToken(dtId1, sm);
token1.setService(new Text("localhost:0"));
return token1;
}
/**
* Basic idea of the test:
* 1. create tokens.
* 2. Mark one of them to be renewed in 2 seconds (istead of
* 24 hourse)
* 3. register them for renewal
* 4. sleep for 3 seconds
* 5. count number of renewals (should 3 initial ones + one extra)
* 6. register another token for 2 seconds
* 7. cancel it immediately
* 8. Sleep and check that the 2 seconds renew didn't happen
* (totally 5 reneals)
* 9. check cancelation
* @throws IOException
* @throws URISyntaxException
*/
@Test
public void testDTRenewal () throws IOException, URISyntaxException {
MyFS dfs = (MyFS)FileSystem.get(conf);
System.out.println("dfs="+(Object)dfs);
// Test 1. - add three tokens - make sure exactly one get's renewed
// get the delegation tokens
MyToken token1, token2, token3;
token1 = dfs.getDelegationToken(new Text("user1"));
token2 = dfs.getDelegationToken(new Text("user2"));
token3 = dfs.getDelegationToken(new Text("user3"));
//to cause this one to be set for renew in 2 secs
dfs.setTokenToRenewIn2Sec(token1);
System.out.println("token="+token1+" should be renewed for 2 secs");
// two distinct Namenodes
String nn1 = DelegationTokenRenewal.SCHEME + "://host1:0";
String nn2 = DelegationTokenRenewal.SCHEME + "://host2:0";
String nn3 = DelegationTokenRenewal.SCHEME + "://host3:0";
TokenStorage ts = new TokenStorage();
// register the token for renewal
ts.addToken(new Text(nn1), token1);
ts.addToken(new Text(nn2), token2);
ts.addToken(new Text(nn3), token3);
// register the tokens for renewal
DelegationTokenRenewal.registerDelegationTokensForRenewal(
new JobID("job1", 1), ts, conf);
// first 3 initial renewals + 1 real
int numberOfExpectedRenewals = 3+1;
int attempts = 4;
while(attempts-- > 0) {
try {
Thread.sleep(3*1000); // sleep 3 seconds, so it has time to renew
} catch (InterruptedException e) {}
// since we cannot guarantee timely execution - let's give few chances
if(dfs.getCounter()==numberOfExpectedRenewals)
break;
}
System.out.println("Counter = " + dfs.getCounter() + ";t="+
dfs.getToken());
assertEquals("renew wasn't called as many times as expected(4):",
numberOfExpectedRenewals, dfs.getCounter());
assertEquals("most recently renewed token mismatch", dfs.getToken(),
token1);
// Test 2.
// add another token ( that expires in 2 secs). Then remove it, before
// time is up.
// Wait for 3 secs , and make sure no renews were called
ts = new TokenStorage();
MyToken token4 = dfs.getDelegationToken(new Text("user4"));
//to cause this one to be set for renew in 2 secs
dfs.setTokenToRenewIn2Sec(token4);
System.out.println("token="+token4+" should be renewed for 2 secs");
String nn4 = DelegationTokenRenewal.SCHEME + "://host4:0";
ts.addToken(new Text(nn4), token4);
JobID jid2 = new JobID("job2",1);
DelegationTokenRenewal.registerDelegationTokensForRenewal(jid2, ts, conf);
DelegationTokenRenewal.removeDelegationTokenRenewalForJob(jid2);
numberOfExpectedRenewals++; // one more initial renewal
attempts = 4;
while(attempts-- > 0) {
try {
Thread.sleep(3*1000); // sleep 3 seconds, so it has time to renew
} catch (InterruptedException e) {}
// since we cannot guarantee timely execution - let's give few chances
if(dfs.getCounter()==numberOfExpectedRenewals)
break;
}
System.out.println("Counter = " + dfs.getCounter() + ";t="+dfs.getToken());
// counter and the token should stil be the old ones
assertEquals("renew wasn't called as many times as expected",
numberOfExpectedRenewals, dfs.getCounter());
// also renewing of the cancelled token should fail
boolean exception=false;
try {
dfs.renewDelegationToken(token4);
} catch (InvalidToken ite) {
//expected
exception = true;
}
assertTrue("Renew of canceled token didn't fail", exception);
}
}
| apache-2.0 |
rogerioalves21/batch-processing | batch-processing/src/br/com/sicoob/cro/cop/util/MandatoryFieldException.java | 627 | /*
* 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 br.com.sicoob.cro.cop.util;
/**
* Campo obrigatorio.
*
* Classe para o lancamento de erros de runtime do tipo campo obrigatorio.
*
* @author Rogerio Alves Rodrigues
*/
public class MandatoryFieldException extends RuntimeException {
/**
* Recebe uma mensagem e envia o erro.
*
* @param message String da mensagem.
*/
public MandatoryFieldException(String message) {
super(message);
}
}
| apache-2.0 |
GerritCodeReview/gerrit | java/com/google/gerrit/metrics/proc/OperatingSystemMXBeanReflectionBased.java | 1770 | // Copyright (C) 2019 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.metrics.proc;
import java.lang.management.OperatingSystemMXBean;
import java.lang.reflect.Method;
class OperatingSystemMXBeanReflectionBased implements OperatingSystemMXBeanInterface {
private final OperatingSystemMXBean sys;
private final Method getProcessCpuTime;
private final Method getOpenFileDescriptorCount;
OperatingSystemMXBeanReflectionBased(OperatingSystemMXBean sys)
throws ReflectiveOperationException {
this.sys = sys;
getProcessCpuTime = sys.getClass().getMethod("getProcessCpuTime");
getProcessCpuTime.setAccessible(true);
getOpenFileDescriptorCount = sys.getClass().getMethod("getOpenFileDescriptorCount");
getOpenFileDescriptorCount.setAccessible(true);
}
@Override
public long getProcessCpuTime() {
try {
return (long) getProcessCpuTime.invoke(sys, new Object[] {});
} catch (ReflectiveOperationException e) {
return -1;
}
}
@Override
public long getOpenFileDescriptorCount() {
try {
return (long) getOpenFileDescriptorCount.invoke(sys, new Object[] {});
} catch (ReflectiveOperationException e) {
return -1;
}
}
}
| apache-2.0 |
ketan/gocd | server/src/main/java/com/thoughtworks/go/server/service/plugins/processor/elasticagent/v1/AgentMetadataConverterV1.java | 1403 | /*
* Copyright 2020 ThoughtWorks, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.thoughtworks.go.server.service.plugins.processor.elasticagent.v1;
import com.thoughtworks.go.plugin.access.elastic.DataConverter;
import com.thoughtworks.go.plugin.access.elastic.models.AgentMetadata;
class AgentMetadataConverterV1 implements DataConverter<AgentMetadata, AgentMetadataDTO> {
@Override
public AgentMetadata fromDTO(AgentMetadataDTO agentMetadataDTO) {
return new AgentMetadata(agentMetadataDTO.elasticAgentId(), agentMetadataDTO.agentState(), agentMetadataDTO.buildState(), agentMetadataDTO.configState());
}
@Override
public AgentMetadataDTO toDTO(AgentMetadata agentMetadata) {
return new AgentMetadataDTO(agentMetadata.elasticAgentId(), agentMetadata.agentState(), agentMetadata.buildState(), agentMetadata.configState());
}
}
| apache-2.0 |
cyhhao/Genius-Android | caprice/library-ui/src/main/java/net/qiujuer/genius/ui/widget/attribute/BaseAttributes.java | 7330 | /*
* Copyright (C) 2014 Qiujuer <qiujuer@live.cn>
* WebSite http://www.qiujuer.net
* Created 02/09/2015
* Changed 02/16/2015
* Version 2.0.0
* GeniusEditText
*
* 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.qiujuer.genius.ui.widget.attribute;
import android.content.Context;
import android.content.res.Resources;
import android.content.res.TypedArray;
import android.util.AttributeSet;
import net.qiujuer.genius.ui.GeniusUi;
public class BaseAttributes extends Attributes {
public static final String[] DEFAULT_FONT_FAMILY = new String[]{"roboto", "opensans"};
public static final String[] DEFAULT_FONT_WEIGHT = new String[]{"bold", "extrabold", "extralight", "light", "regular"};
public static final String DEFAULT_FONT_EXTENSION = "ttf";
public static final int DEFAULT_TEXT_APPEARANCE = 0;
public static final int DEFAULT_RADIUS = 0;
public static final int DEFAULT_BORDER_WIDTH = 0;
/**
* Font related fields
*/
private String fontFamily = DEFAULT_FONT_FAMILY[0];
private String fontWeight = DEFAULT_FONT_WEIGHT[3];
private String fontExtension = DEFAULT_FONT_EXTENSION;
private int textAppearance = DEFAULT_TEXT_APPEARANCE;
/**
* Size related fields
*/
private float radius = DEFAULT_RADIUS;
private float[] radiusArray = null;
private int borderWidth = DEFAULT_BORDER_WIDTH;
/**
* Is has own set
*/
private boolean hasOwnTextColor;
private boolean hasOwnBackground;
private boolean hasHintTextColor;
public BaseAttributes(AttributeChangeListener attributeChangeListener, Resources resources) {
super(attributeChangeListener, resources);
}
public void initHasOwnAttrs(Context context, AttributeSet attrs) {
// getting android default tags for textColor and textColorHint
String textColorAttribute = attrs.getAttributeValue(GeniusUi.androidStyleNameSpace, "textColor");
if (textColorAttribute == null) {
int styleId = attrs.getStyleAttribute();
int[] attributesArray = new int[]{android.R.attr.textColor};
try {
TypedArray styleTextColorTypedArray = context.obtainStyledAttributes(styleId, attributesArray);
// color might have values from the entire integer range, so to find out if there is any color set,
// checking if default value is returned is not enough. Thus we get color with two different
// default values - if returned value is the same, it means color is set
int styleTextColor1 = styleTextColorTypedArray.getColor(0, -1);
int styleTextColor2 = styleTextColorTypedArray.getColor(0, 1);
hasOwnTextColor = styleTextColor1 == styleTextColor2;
styleTextColorTypedArray.recycle();
} catch (Resources.NotFoundException e) {
hasOwnTextColor = false;
}
} else {
hasOwnTextColor = true;
}
// getting android default tags for background
String backgroundAttribute = attrs.getAttributeValue(GeniusUi.androidStyleNameSpace, "background");
hasOwnBackground = backgroundAttribute != null;
// getting android default tags for textColorHint
hasHintTextColor = attrs.getAttributeValue(GeniusUi.androidStyleNameSpace, "textColorHint") != null;
}
public void initCornerRadius(TypedArray a, int indexRadius, int indexRadiiA, int indexRadiiB, int indexRadiiC, int indexRadiiD) {
// Set Radius
setRadius(a.getDimension(indexRadius, DEFAULT_RADIUS));
// Set Radii[] array
float rA, rB, rC, rD, r = getRadius();
rA = a.getDimension(indexRadiiA, r);
rB = a.getDimension(indexRadiiB, r);
rC = a.getDimension(indexRadiiC, r);
rD = a.getDimension(indexRadiiD, r);
if (rA == r && rB == r && rC == r && rD == r)
return;
setRadii(new float[]{rA, rA, rB, rB, rC, rC, rD, rD});
}
public String getFontFamily() {
return fontFamily;
}
public void setFontFamily(String fontFamily) {
if (fontFamily != null && !fontFamily.equals("") && !fontFamily.equals("null"))
this.fontFamily = fontFamily;
}
public String getFontWeight() {
return fontWeight;
}
public void setFontWeight(String fontWeight) {
if (fontWeight != null && !fontWeight.equals("") && !fontWeight.equals("null"))
this.fontWeight = fontWeight;
}
public String getFontExtension() {
return fontExtension;
}
public void setFontExtension(String fontExtension) {
if (fontExtension != null && !fontExtension.equals("") && !fontExtension.equals("null"))
this.fontExtension = fontExtension;
}
public void setRadii(float[] radii) {
radiusArray = radii;
if (radii == null) {
radius = 0;
}
}
public float getRadius() {
return radius;
}
public void setRadius(float radius) {
if (radius < 0) {
radius = 0;
}
this.radius = radius;
this.radiusArray = null;
}
public float[] getOuterRadii() {
if (radiusArray != null)
return radiusArray;
return new float[]{radius, radius, radius, radius, radius, radius, radius, radius};
}
public boolean isOuterRadiiZero() {
if (radiusArray == null)
return radius == 0;
else {
boolean isZero = true;
for (float i : radiusArray) {
if (i != 0) {
isZero = false;
break;
}
}
return isZero;
}
}
public float[] getOuterRadiiNull() {
if (isOuterRadiiZero())
return null;
else
return getOuterRadii();
}
public int getBorderWidth() {
return borderWidth;
}
public void setBorderWidth(int borderWidth) {
this.borderWidth = borderWidth;
}
public int getTextAppearance() {
return textAppearance;
}
public void setTextAppearance(int textAppearance) {
this.textAppearance = textAppearance;
}
public boolean isHasOwnBackground() {
return hasOwnBackground;
}
public void setHasOwnBackground(boolean isHave) {
hasOwnBackground = isHave;
}
public boolean isHasOwnTextColor() {
return hasOwnTextColor;
}
public void setHasOwnTextColor(boolean isHave) {
hasOwnTextColor = isHave;
}
public boolean isHasOwnHintTextColor() {
return hasHintTextColor;
}
public void setHasOwnHintTextColor(boolean isHave) {
hasHintTextColor = isHave;
}
}
| apache-2.0 |
DariusX/camel | components/camel-hdfs/src/test/java/org/apache/camel/component/hdfs/HdfsConsumerTest.java | 10348 | /*
* 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.hdfs;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import org.apache.camel.CamelContext;
import org.apache.camel.Exchange;
import org.apache.camel.Processor;
import org.apache.camel.impl.DefaultCamelContext;
import org.apache.camel.support.DefaultExchange;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FSDataInputStream;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.junit.Before;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
import static org.apache.camel.component.hdfs.HdfsConstants.DEFAULT_OPENED_SUFFIX;
import static org.apache.camel.component.hdfs.HdfsConstants.DEFAULT_READ_SUFFIX;
import static org.apache.camel.component.hdfs.HdfsTestSupport.CWD;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.notNullValue;
import static org.hamcrest.CoreMatchers.startsWith;
import static org.junit.Assert.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
public class HdfsConsumerTest {
private HdfsEndpoint endpoint;
private Processor processor;
private HdfsConfiguration endpointConfig;
private HdfsInfoFactory hdfsInfoFactory;
private CamelContext context;
private FileSystem fileSystem;
private Configuration configuration;
private HdfsConsumer underTest;
@Before
public void setUp() throws Exception {
endpoint = mock(HdfsEndpoint.class);
processor = mock(Processor.class);
endpointConfig = mock(HdfsConfiguration.class);
hdfsInfoFactory = mock(HdfsInfoFactory.class);
HdfsInfo hdfsInfo = mock(HdfsInfo.class);
fileSystem = mock(FileSystem.class);
configuration = mock(Configuration.class);
Path path = mock(Path.class);
when(hdfsInfoFactory.newHdfsInfo(anyString())).thenReturn(hdfsInfo);
when(hdfsInfoFactory.getEndpointConfig()).thenReturn(endpointConfig);
when(hdfsInfoFactory.newHdfsInfo(anyString())).thenReturn(hdfsInfo);
when(hdfsInfo.getFileSystem()).thenReturn(fileSystem);
when(hdfsInfo.getConfiguration()).thenReturn(configuration);
when(hdfsInfo.getPath()).thenReturn(path);
when(endpointConfig.getReadSuffix()).thenReturn(DEFAULT_READ_SUFFIX);
when(endpointConfig.getOpenedSuffix()).thenReturn(DEFAULT_OPENED_SUFFIX);
context = new DefaultCamelContext();
}
@Test
public void doStartWithoutHdfsSetup() throws Exception {
// given
String hdfsPath = "hdfs://localhost/target/test/multiple-consumers";
when(endpointConfig.getFileSystemType()).thenReturn(HdfsFileSystemType.LOCAL);
when(endpointConfig.getPath()).thenReturn(hdfsPath);
when(endpointConfig.isConnectOnStartup()).thenReturn(false);
when(endpoint.getCamelContext()).thenReturn(context);
when(endpoint.getEndpointUri()).thenReturn(hdfsPath);
underTest = new HdfsConsumer(endpoint, processor, endpointConfig, hdfsInfoFactory, new StringBuilder(hdfsPath));
// when
underTest.doStart();
// then
verify(hdfsInfoFactory, times(0)).newHdfsInfo(anyString());
}
@Test
public void doStartWithHdfsSetup() throws Exception {
// given
String hdfsPath = "hdfs://localhost/target/test/multiple-consumers";
when(endpointConfig.getFileSystemType()).thenReturn(HdfsFileSystemType.LOCAL);
when(endpointConfig.getPath()).thenReturn(hdfsPath);
when(endpointConfig.isConnectOnStartup()).thenReturn(true);
when(endpointConfig.getFileSystemLabel(anyString())).thenReturn("TEST_FS_LABEL");
when(endpoint.getCamelContext()).thenReturn(context);
when(endpoint.getEndpointUri()).thenReturn(hdfsPath);
underTest = new HdfsConsumer(endpoint, processor, endpointConfig, hdfsInfoFactory, new StringBuilder(hdfsPath));
// when
underTest.doStart();
// then
verify(hdfsInfoFactory, times(1)).newHdfsInfo(hdfsPath);
}
@Test
public void doPollFromExistingLocalFile() throws Exception {
// given
String hdfsPath = "hdfs://localhost/target/test/multiple-consumers";
when(endpointConfig.getFileSystemType()).thenReturn(HdfsFileSystemType.LOCAL);
when(endpointConfig.getFileType()).thenReturn(HdfsFileType.NORMAL_FILE);
when(endpointConfig.getPath()).thenReturn(hdfsPath);
when(endpointConfig.getOwner()).thenReturn("spiderman");
when(endpointConfig.isConnectOnStartup()).thenReturn(true);
when(endpointConfig.getFileSystemLabel(anyString())).thenReturn("TEST_FS_LABEL");
when(endpointConfig.getChunkSize()).thenReturn(100 * 1000);
when(endpointConfig.getMaxMessagesPerPoll()).thenReturn(10);
when(endpoint.getCamelContext()).thenReturn(context);
when(endpoint.createExchange()).thenReturn(new DefaultExchange(context));
when(endpoint.getEndpointUri()).thenReturn(hdfsPath);
when(fileSystem.isFile(any(Path.class))).thenReturn(true);
FileStatus[] fileStatuses = new FileStatus[1];
FileStatus fileStatus = mock(FileStatus.class);
fileStatuses[0] = fileStatus;
when(fileSystem.globStatus(any(Path.class))).thenReturn(fileStatuses);
when(fileStatus.getPath()).thenReturn(new Path(hdfsPath));
when(fileStatus.isFile()).thenReturn(true);
when(fileStatus.isDirectory()).thenReturn(false);
when(fileStatus.getOwner()).thenReturn("spiderman");
String normalFile = CWD.getAbsolutePath() + "/src/test/resources/hdfs/normal_file.txt";
FSDataInputStream fsDataInputStream = new FSDataInputStream(new MockDataInputStream(normalFile));
when(fileSystem.rename(any(Path.class), any(Path.class))).thenReturn(true);
when(fileSystem.open(any(Path.class))).thenReturn(fsDataInputStream);
ArgumentCaptor<Exchange> exchangeCaptor = ArgumentCaptor.forClass(Exchange.class);
underTest = new HdfsConsumer(endpoint, processor, endpointConfig, hdfsInfoFactory, new StringBuilder(hdfsPath));
// when
int actual = underTest.doPoll();
// then
assertThat(actual, is(1));
verify(processor, times(1)).process(exchangeCaptor.capture());
Exchange exchange = exchangeCaptor.getValue();
assertThat(exchange, notNullValue());
ByteArrayOutputStream body = exchange.getIn().getBody(ByteArrayOutputStream.class);
assertThat(body, notNullValue());
assertThat(body.toString(), startsWith("Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam eget fermentum arcu, vel dignissim ipsum."));
}
@Test
public void doPollFromExistingLocalFileWithStreamDownload() throws Exception {
// given
String hdfsPath = "hdfs://localhost/target/test/multiple-consumers";
when(endpointConfig.getFileSystemType()).thenReturn(HdfsFileSystemType.LOCAL);
when(endpointConfig.getFileType()).thenReturn(HdfsFileType.NORMAL_FILE);
when(endpointConfig.getPath()).thenReturn(hdfsPath);
when(endpointConfig.getOwner()).thenReturn("spiderman");
when(endpointConfig.isConnectOnStartup()).thenReturn(true);
when(endpointConfig.getFileSystemLabel(anyString())).thenReturn("TEST_FS_LABEL");
when(endpointConfig.getChunkSize()).thenReturn(100 * 1000);
when(endpointConfig.isStreamDownload()).thenReturn(true);
when(endpointConfig.getMaxMessagesPerPoll()).thenReturn(10);
when(endpoint.getCamelContext()).thenReturn(context);
when(endpoint.createExchange()).thenReturn(new DefaultExchange(context));
when(endpoint.getEndpointUri()).thenReturn(hdfsPath);
when(fileSystem.isFile(any(Path.class))).thenReturn(true);
FileStatus[] fileStatuses = new FileStatus[1];
FileStatus fileStatus = mock(FileStatus.class);
fileStatuses[0] = fileStatus;
when(fileSystem.globStatus(any(Path.class))).thenReturn(fileStatuses);
when(fileStatus.getPath()).thenReturn(new Path(hdfsPath));
when(fileStatus.isFile()).thenReturn(true);
when(fileStatus.isDirectory()).thenReturn(false);
when(fileStatus.getOwner()).thenReturn("spiderman");
String normalFile = CWD.getAbsolutePath() + "/src/test/resources/hdfs/normal_file.txt";
FSDataInputStream fsDataInputStream = new FSDataInputStream(new MockDataInputStream(normalFile));
when(fileSystem.rename(any(Path.class), any(Path.class))).thenReturn(true);
when(fileSystem.open(any(Path.class))).thenReturn(fsDataInputStream);
ArgumentCaptor<Exchange> exchangeCaptor = ArgumentCaptor.forClass(Exchange.class);
underTest = new HdfsConsumer(endpoint, processor, endpointConfig, hdfsInfoFactory, new StringBuilder(hdfsPath));
// when
int actual = underTest.doPoll();
// then
assertThat(actual, is(1));
verify(processor, times(1)).process(exchangeCaptor.capture());
Exchange exchange = exchangeCaptor.getValue();
assertThat(exchange, notNullValue());
InputStream body = (InputStream) exchange.getIn().getBody();
assertThat(body, notNullValue());
}
}
| apache-2.0 |
xiaguangme/sharding-jdbc-how2work | sharding-jdbc-core/src/test/java/com/dangdang/ddframe/rdb/integrate/tbl/SelectGroupByShardingTablesOnlyTest.java | 3242 | /**
* Copyright 1999-2015 dangdang.com.
* <p>
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* </p>
*/
package com.dangdang.ddframe.rdb.integrate.tbl;
import java.sql.SQLException;
import org.dbunit.DatabaseUnitException;
import org.junit.Before;
import org.junit.Test;
import com.dangdang.ddframe.rdb.sharding.api.ShardingDataSource;
public final class SelectGroupByShardingTablesOnlyTest extends AbstractShardingTablesOnlyDBUnitTest {
private ShardingDataSource shardingDataSource;
@Before
public void init() throws SQLException {
shardingDataSource = getShardingDataSource();
}
@Test
public void assertSelectSum() throws SQLException, DatabaseUnitException {
String sql = "SELECT SUM(order_id) AS `orders_sum`, `user_id` FROM `t_order` GROUP BY `user_id`";
assertDataset("integrate/dataset/tbl/expect/select_groupby/SelectSum.xml", shardingDataSource.getConnection(), "t_order", sql);
}
@Test
public void assertSelectCount() throws SQLException, DatabaseUnitException {
String sql = "SELECT COUNT(order_id) AS `orders_count`, `user_id` FROM `t_order` GROUP BY `user_id`";
assertDataset("integrate/dataset/tbl/expect/select_groupby/SelectCount.xml", shardingDataSource.getConnection(), "t_order", sql);
}
@Test
public void assertSelectMax() throws SQLException, DatabaseUnitException {
String sql = "SELECT MAX(order_id) AS `max_order_id`, `user_id` FROM `t_order` GROUP BY `user_id`";
assertDataset("integrate/dataset/tbl/expect/select_groupby/SelectMax.xml", shardingDataSource.getConnection(), "t_order", sql);
}
@Test
public void assertSelectMin() throws SQLException, DatabaseUnitException {
String sql = "SELECT MIN(order_id) AS `min_order_id`, `user_id` FROM `t_order` GROUP BY `user_id`";
assertDataset("integrate/dataset/tbl/expect/select_groupby/SelectMin.xml", shardingDataSource.getConnection(), "t_order", sql);
}
@Test
public void assertSelectAvg() throws SQLException, DatabaseUnitException {
String sql = "SELECT AVG(order_id) AS `orders_avg`, `user_id` FROM `t_order` GROUP BY `user_id`";
assertDataset("integrate/dataset/tbl/expect/select_groupby/SelectAvg.xml", shardingDataSource.getConnection(), "t_order", sql);
}
@Test
public void assertSelectOrderByDesc() throws SQLException, DatabaseUnitException {
String sql = "SELECT SUM(order_id) AS `orders_sum`, `user_id` FROM `t_order` GROUP BY `user_id` ORDER BY orders_sum DESC";
assertDataset("integrate/dataset/tbl/expect/select_groupby/SelectOrderByDesc.xml", shardingDataSource.getConnection(), "t_order", sql);
}
}
| apache-2.0 |
MikeThomsen/nifi | nifi-nar-bundles/nifi-elasticsearch-bundle/nifi-elasticsearch-restapi-processors/src/main/java/org/apache/nifi/processors/elasticsearch/JsonQueryElasticsearch.java | 5383 | /*
* 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.processors.elasticsearch;
import org.apache.nifi.annotation.behavior.DynamicProperty;
import org.apache.nifi.annotation.behavior.EventDriven;
import org.apache.nifi.annotation.behavior.InputRequirement;
import org.apache.nifi.annotation.behavior.WritesAttribute;
import org.apache.nifi.annotation.behavior.WritesAttributes;
import org.apache.nifi.annotation.documentation.CapabilityDescription;
import org.apache.nifi.annotation.documentation.Tags;
import org.apache.nifi.elasticsearch.SearchResponse;
import org.apache.nifi.expression.ExpressionLanguageScope;
import org.apache.nifi.flowfile.FlowFile;
import org.apache.nifi.processor.ProcessContext;
import org.apache.nifi.processor.ProcessSession;
import org.apache.nifi.processors.elasticsearch.api.JsonQueryParameters;
import org.apache.nifi.util.StopWatch;
import java.io.IOException;
import java.util.List;
import java.util.concurrent.TimeUnit;
@WritesAttributes({
@WritesAttribute(attribute = "mime.type", description = "application/json"),
@WritesAttribute(attribute = "aggregation.name", description = "The name of the aggregation whose results are in the output flowfile"),
@WritesAttribute(attribute = "aggregation.number", description = "The number of the aggregation whose results are in the output flowfile"),
@WritesAttribute(attribute = "hit.count", description = "The number of hits that are in the output flowfile"),
@WritesAttribute(attribute = "elasticsearch.query.error", description = "The error message provided by Elasticsearch if there is an error querying the index.")
})
@InputRequirement(InputRequirement.Requirement.INPUT_ALLOWED)
@EventDriven
@Tags({"elasticsearch", "elasticsearch5", "elasticsearch6", "elasticsearch7", "query", "read", "get", "json"})
@CapabilityDescription("A processor that allows the user to run a query (with aggregations) written with the " +
"Elasticsearch JSON DSL. It does not automatically paginate queries for the user. If an incoming relationship is added to this " +
"processor, it will use the flowfile's content for the query. Care should be taken on the size of the query because the entire response " +
"from Elasticsearch will be loaded into memory all at once and converted into the resulting flowfiles.")
@DynamicProperty(
name = "The name of a URL query parameter to add",
value = "The value of the URL query parameter",
expressionLanguageScope = ExpressionLanguageScope.FLOWFILE_ATTRIBUTES,
description = "Adds the specified property name/value as a query parameter in the Elasticsearch URL used for processing. " +
"These parameters will override any matching parameters in the query request body")
public class JsonQueryElasticsearch extends AbstractJsonQueryElasticsearch<JsonQueryParameters> {
@Override
JsonQueryParameters buildJsonQueryParameters(final FlowFile input, final ProcessContext context, final ProcessSession session)
throws IOException {
final JsonQueryParameters jsonQueryParameters = new JsonQueryParameters();
populateCommonJsonQueryParameters(jsonQueryParameters, input, context, session);
return jsonQueryParameters;
}
@Override
SearchResponse doQuery(final JsonQueryParameters queryJsonParameters, final List<FlowFile> hitsFlowFiles,
final ProcessSession session, final ProcessContext context, final FlowFile input,
final StopWatch stopWatch) throws IOException {
final SearchResponse response = clientService.get().search(
queryJsonParameters.getQuery(),
queryJsonParameters.getIndex(),
queryJsonParameters.getType(),
getUrlQueryParameters(context, input)
);
if (input != null) {
session.getProvenanceReporter().send(
input,
clientService.get().getTransitUrl(queryJsonParameters.getIndex(), queryJsonParameters.getType()),
stopWatch.getElapsed(TimeUnit.MILLISECONDS)
);
}
handleResponse(response, true, queryJsonParameters, hitsFlowFiles, session, input, stopWatch);
return response;
}
@Override
void finishQuery(final FlowFile input, final JsonQueryParameters jsonQueryParameters, final ProcessSession session,
final ProcessContext context, final SearchResponse response) {
if (input != null) {
session.transfer(input, REL_ORIGINAL);
}
}
}
| apache-2.0 |
antoinesd/weld-core | impl/src/main/java/org/jboss/weld/interceptor/proxy/SecurityActions.java | 1728 | /*
* JBoss, Home of Professional Open Source
* Copyright 2014, Red Hat, Inc., and individual contributors
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jboss.weld.interceptor.proxy;
import java.lang.reflect.AccessibleObject;
import java.security.AccessController;
import java.security.PrivilegedAction;
import org.jboss.weld.security.SetAccessibleAction;
/**
*
* @author Martin Kouba
*/
final class SecurityActions {
private SecurityActions() {
}
/**
* Set the {@code accessible} flag for this accessible object. Does not perform {@link PrivilegedAction} unless necessary.
*
* @param accessibleObject
*/
static void ensureAccessible(AccessibleObject accessibleObject) {
if (accessibleObject != null) {
if (!accessibleObject.isAccessible()) {
if (System.getSecurityManager() != null) {
AccessController.doPrivileged(SetAccessibleAction.of(accessibleObject));
} else {
accessibleObject.setAccessible(true);
}
}
}
}
}
| apache-2.0 |
mbiarnes/dashbuilder | dashbuilder-shared/dashbuilder-dataset-api/src/main/java/org/dashbuilder/dataprovider/SQLProviderType.java | 1320 | /*
* Copyright 2016 Red Hat, Inc. and/or its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.dashbuilder.dataprovider;
import org.dashbuilder.dataset.def.SQLDataSetDef;
import org.dashbuilder.dataset.json.DataSetDefJSONMarshallerExt;
import org.dashbuilder.dataset.json.SQLDefJSONMarshaller;
/**
* For accessing data sets defined as an SQL query over an existing data source.
*/
public class SQLProviderType extends AbstractProviderType<SQLDataSetDef> {
@Override
public String getName() {
return "SQL";
}
@Override
public SQLDataSetDef createDataSetDef() {
return new SQLDataSetDef();
}
@Override
public DataSetDefJSONMarshallerExt<SQLDataSetDef> getJsonMarshaller() {
return SQLDefJSONMarshaller.INSTANCE;
}
}
| apache-2.0 |
ty1er/incubator-asterixdb | hyracks-fullstack/hyracks/hyracks-tests/hyracks-storage-am-lsm-btree-test/src/test/java/org/apache/hyracks/storage/am/lsm/btree/perf/BTreePageSizePerf.java | 4584 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.hyracks.storage.am.lsm.btree.perf;
import java.util.Enumeration;
import java.util.logging.Level;
import java.util.logging.LogManager;
import java.util.logging.Logger;
import org.apache.hyracks.api.dataflow.value.IBinaryComparatorFactory;
import org.apache.hyracks.api.dataflow.value.ISerializerDeserializer;
import org.apache.hyracks.api.dataflow.value.ITypeTraits;
import org.apache.hyracks.dataflow.common.data.marshalling.IntegerSerializerDeserializer;
import org.apache.hyracks.dataflow.common.utils.SerdeUtils;
import org.apache.hyracks.storage.am.common.datagen.DataGenThread;
public class BTreePageSizePerf {
public static void main(String[] args) throws Exception {
// Disable logging so we can better see the output times.
Enumeration<String> loggers = LogManager.getLogManager().getLoggerNames();
while(loggers.hasMoreElements()) {
String loggerName = loggers.nextElement();
Logger logger = LogManager.getLogManager().getLogger(loggerName);
logger.setLevel(Level.OFF);
}
int numTuples = 1000000;
int batchSize = 10000;
int numBatches = numTuples / batchSize;
ISerializerDeserializer[] fieldSerdes = new ISerializerDeserializer[] { IntegerSerializerDeserializer.INSTANCE };
ITypeTraits[] typeTraits = SerdeUtils.serdesToTypeTraits(fieldSerdes, 30);
IBinaryComparatorFactory[] cmpFactories = SerdeUtils.serdesToComparatorFactories(fieldSerdes, fieldSerdes.length);
runExperiment(numBatches, batchSize, 1024, 100000, fieldSerdes, cmpFactories, typeTraits);
runExperiment(numBatches, batchSize, 2048, 100000, fieldSerdes, cmpFactories, typeTraits);
runExperiment(numBatches, batchSize, 4096, 25000, fieldSerdes, cmpFactories, typeTraits);
runExperiment(numBatches, batchSize, 8192, 12500, fieldSerdes, cmpFactories, typeTraits);
runExperiment(numBatches, batchSize, 16384, 6250, fieldSerdes, cmpFactories, typeTraits);
runExperiment(numBatches, batchSize, 32768, 3125, fieldSerdes, cmpFactories, typeTraits);
runExperiment(numBatches, batchSize, 65536, 1564, fieldSerdes, cmpFactories, typeTraits);
runExperiment(numBatches, batchSize, 131072, 782, fieldSerdes, cmpFactories, typeTraits);
runExperiment(numBatches, batchSize, 262144, 391, fieldSerdes, cmpFactories, typeTraits);
}
private static void runExperiment(int numBatches, int batchSize, int pageSize, int numPages, ISerializerDeserializer[] fieldSerdes, IBinaryComparatorFactory[] cmpFactories, ITypeTraits[] typeTraits) throws Exception {
System.out.println("PAGE SIZE: " + pageSize);
System.out.println("NUM PAGES: " + numPages);
System.out.println("MEMORY: " + (pageSize * numPages));
int repeats = 5;
long[] times = new long[repeats];
//BTreeRunner runner = new BTreeRunner(numTuples, pageSize, numPages, typeTraits, cmp);
InMemoryBTreeRunner runner = new InMemoryBTreeRunner(numBatches, pageSize, numPages, typeTraits, cmpFactories);
runner.init();
int numThreads = 1;
for (int i = 0; i < repeats; i++) {
DataGenThread dataGen = new DataGenThread(numThreads, numBatches, batchSize, fieldSerdes, 30, 50, 10, false);
dataGen.start();
times[i] = runner.runExperiment(dataGen, numThreads);
System.out.println("TIME " + i + ": " + times[i] + "ms");
}
runner.deinit();
long avgTime = 0;
for (int i = 0; i < repeats; i++) {
avgTime += times[i];
}
avgTime /= repeats;
System.out.println("AVG TIME: " + avgTime + "ms");
System.out.println("-------------------------------");
}
}
| apache-2.0 |
googlecodelabs/android-tv-leanback | checkpoint_5/src/main/java/com/android/example/leanback/BlurTransform.java | 2467 | /*
* 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.android.example.leanback;
import android.content.Context;
import android.graphics.Bitmap;
import android.renderscript.Allocation;
import android.renderscript.Element;
import android.renderscript.RenderScript;
import android.renderscript.ScriptIntrinsicBlur;
import com.squareup.picasso.Transformation;
public class BlurTransform implements Transformation {
static BlurTransform blurTransform;
RenderScript rs;
protected BlurTransform() {
// Exists only to defeat instantiation.
}
private BlurTransform(Context context) {
super();
rs = RenderScript.create(context);
}
public static BlurTransform getInstance(Context context) {
if (blurTransform == null) {
blurTransform = new BlurTransform(context);
}
return blurTransform;
}
@Override
public Bitmap transform(Bitmap bitmap) {
// Create another bitmap that will hold the results of the filter.
Bitmap blurredBitmap = Bitmap.createBitmap(bitmap);
// Allocate memory for Renderscript to work with
Allocation input = Allocation.createFromBitmap(rs, bitmap, Allocation.MipmapControl.MIPMAP_FULL, Allocation.USAGE_SHARED);
Allocation output = Allocation.createTyped(rs, input.getType());
// Load up an instance of the specific script that we want to use.
ScriptIntrinsicBlur script = ScriptIntrinsicBlur.create(rs, Element.U8_4(rs));
script.setInput(input);
// Set the blur radius
script.setRadius(20);
// Start the ScriptIntrinisicBlur
script.forEach(output);
// Copy the output to the blurred bitmap
output.copyTo(blurredBitmap);
bitmap.recycle();
return blurredBitmap;
}
@Override
public String key() {
return "blur";
}
}
| apache-2.0 |
zdary/intellij-community | plugins/lombok/src/main/java/de/plushnikov/intellij/plugin/processor/AbstractProcessor.java | 5666 | package de.plushnikov.intellij.plugin.processor;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.psi.*;
import com.intellij.util.containers.ContainerUtil;
import de.plushnikov.intellij.plugin.LombokClassNames;
import de.plushnikov.intellij.plugin.lombokconfig.ConfigDiscovery;
import de.plushnikov.intellij.plugin.lombokconfig.ConfigKey;
import de.plushnikov.intellij.plugin.psi.LombokLightModifierList;
import de.plushnikov.intellij.plugin.thirdparty.LombokCopyableAnnotations;
import de.plushnikov.intellij.plugin.util.LombokProcessorUtil;
import de.plushnikov.intellij.plugin.util.PsiAnnotationSearchUtil;
import de.plushnikov.intellij.plugin.util.PsiAnnotationUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.Collection;
import java.util.List;
import java.util.Map;
/**
* Base lombok processor class
*
* @author Plushnikov Michail
*/
public abstract class AbstractProcessor implements Processor {
/**
* Annotation classes this processor supports
*/
private final String[] supportedAnnotationClasses;
/**
* Kind of output elements this processor supports
*/
private final Class<? extends PsiElement> supportedClass;
/**
* Instance of config discovery service to access lombok.config informations
*/
protected final ConfigDiscovery configDiscovery;
/**
* Constructor for all Lombok-Processors
*
* @param supportedClass kind of output elements this processor supports
* @param supportedAnnotationClasses annotations this processor supports
*/
protected AbstractProcessor(@NotNull Class<? extends PsiElement> supportedClass,
@NotNull String... supportedAnnotationClasses) {
this.configDiscovery = ConfigDiscovery.getInstance();
this.supportedClass = supportedClass;
this.supportedAnnotationClasses = supportedAnnotationClasses;
}
@Override
public final @NotNull String @NotNull [] getSupportedAnnotationClasses() {
return supportedAnnotationClasses;
}
@NotNull
@Override
public final Class<? extends PsiElement> getSupportedClass() {
return supportedClass;
}
@NotNull
public abstract Collection<PsiAnnotation> collectProcessedAnnotations(@NotNull PsiClass psiClass);
protected boolean supportAnnotationVariant(@NotNull PsiAnnotation psiAnnotation) {
return true;
}
protected void filterToleratedElements(@NotNull Collection<? extends PsiModifierListOwner> definedMethods) {
definedMethods.removeIf(definedMethod -> PsiAnnotationSearchUtil.isAnnotatedWith(definedMethod, LombokClassNames.TOLERATE));
}
protected boolean readAnnotationOrConfigProperty(@NotNull PsiAnnotation psiAnnotation, @NotNull PsiClass psiClass,
@NotNull String annotationParameter, @NotNull ConfigKey configKey) {
final boolean result;
final Boolean declaredAnnotationValue = PsiAnnotationUtil.getDeclaredBooleanAnnotationValue(psiAnnotation, annotationParameter);
if (null == declaredAnnotationValue) {
result = configDiscovery.getBooleanLombokConfigProperty(configKey, psiClass);
}
else {
result = declaredAnnotationValue;
}
return result;
}
protected static void copyOnXAnnotations(@Nullable PsiAnnotation processedAnnotation,
@NotNull PsiModifierList modifierList,
@NotNull String onXParameterName) {
if (processedAnnotation == null) {
return;
}
Iterable<String> annotationsToAdd = LombokProcessorUtil.getOnX(processedAnnotation, onXParameterName);
annotationsToAdd.forEach(modifierList::addAnnotation);
}
protected static @NotNull List<PsiAnnotation> copyableAnnotations(@NotNull PsiField psiField,
@NotNull LombokCopyableAnnotations copyableAnnotations) {
final Map<String, String> fullQualifiedToShortNames = copyableAnnotations.getFullQualifiedToShortNames();
final PsiClass containingClass = psiField.getContainingClass();
// append only for BASE_COPYABLE
if (LombokCopyableAnnotations.BASE_COPYABLE.equals(copyableAnnotations) && null != containingClass) {
Collection<String> configuredCopyableAnnotations =
ConfigDiscovery.getInstance().getMultipleValueLombokConfigProperty(ConfigKey.COPYABLE_ANNOTATIONS, containingClass);
configuredCopyableAnnotations.forEach(fqn->fullQualifiedToShortNames.put(fqn, StringUtil.getShortName(fqn)));
}
final Collection<String> existedShortAnnotationNames = ContainerUtil.map(psiField.getAnnotations(), PsiAnnotationSearchUtil::getShortNameOf);
// reduce copyableAnnotations to only matching existed annotations by shortName
fullQualifiedToShortNames.values().retainAll(existedShortAnnotationNames);
// collect existing annotations to copy
return PsiAnnotationSearchUtil.findAllAnnotations(psiField, fullQualifiedToShortNames.keySet());
}
protected static void copyCopyableAnnotations(@NotNull PsiField fromPsiElement,
@NotNull LombokLightModifierList toModifierList,
@NotNull LombokCopyableAnnotations copyableAnnotations) {
List<PsiAnnotation> annotationsToAdd = copyableAnnotations(fromPsiElement, copyableAnnotations);
annotationsToAdd.forEach(toModifierList::withAnnotation);
}
@Override
public LombokPsiElementUsage checkFieldUsage(@NotNull PsiField psiField, @NotNull PsiAnnotation psiAnnotation) {
return LombokPsiElementUsage.NONE;
}
}
| apache-2.0 |
papicella/snappy-store | gemfire-core/src/main/java/com/gemstone/gemfire/internal/tools/gfsh/app/cache/index/LookupServiceException.java | 2814 | /*
* Copyright (c) 2010-2015 Pivotal Software, 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. See accompanying
* LICENSE file.
*/
package com.gemstone.gemfire.internal.tools.gfsh.app.cache.index;
/**
* LookupService throws LookupServiceException if it encounters
* an error from the underlying GemFire communications mechanism.
*/
class LookupServiceException extends RuntimeException
{
private static final long serialVersionUID = 1L;
/**
* Constructs a new LookupServiceException.
*/
LookupServiceException()
{
super();
}
/**
* Constructs a new LookupServiceException exception with the specified detail message.
*
* @param message the detail message (which is saved for later retrieval
* by the {@link #getMessage()} method).
*/
public LookupServiceException(String message)
{
super(message, null);
}
/**
* Constructs a new LookupServiceException exception with the specified detail message and
* cause.
* <p>Note that the detail message associated with
* <code>cause</code> is <i>not</i> automatically incorporated in
* this exception's detail message.
*
* @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 <tt>null</tt> value is
* permitted, and indicates that the cause is nonexistent or
* unknown.)
*/
public LookupServiceException(String message, Throwable cause)
{
super(message, cause);
}
/**
* Constructs a new LookupServiceException exception with the specified cause.
* <p>Note that the detail message associated with
* <code>cause</code> is <i>not</i> automatically incorporated in
* this exception's detail message.
*
* @param cause the cause (which is saved for later retrieval by the
* {@link #getCause()} method). (A <tt>null</tt> value is
* permitted, and indicates that the cause is nonexistent or
* unknown.)
*/
public LookupServiceException(Throwable cause)
{
super(cause);
}
}
| apache-2.0 |
kanayo/izpack | src/lib/com/izforge/izpack/util/os/Unix_Shortcut.java | 43876 | /*
* IzPack - Copyright 2001-2008 Julien Ponge, All Rights Reserved.
*
* http://www.izforge.com/izpack/
* http://izpack.codehaus.org/
*
* Copyright 2003 Marc Eppelmann
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* This represents a Implementation of the KDE/GNOME DesktopEntry.
* which is standard from
* "Desktop Entry Standard"
* "The format of .desktop files, supported by KDE and GNOME."
* http://www.freedesktop.org/standards/desktop-entry-spec/
*
* [Desktop Entry]
// Comment=$Comment
// Comment[de]=
// Encoding=$UTF-8
// Exec=$'/home/marc/CPS/tomcat/bin/catalina.sh' run
// GenericName=$
// GenericName[de]=$
// Icon=$inetd
// MimeType=$
// Name=$Start Tomcat
// Name[de]=$Start Tomcat
// Path=$/home/marc/CPS/tomcat/bin/
// ServiceTypes=$
// SwallowExec=$
// SwallowTitle=$
// Terminal=$true
// TerminalOptions=$
// Type=$Application
// X-KDE-SubstituteUID=$false
// X-KDE-Username=$
*
*/
package com.izforge.izpack.util.os;
import com.izforge.izpack.installer.AutomatedInstallData;
import com.izforge.izpack.installer.ResourceManager;
import com.izforge.izpack.installer.ResourceNotFoundException;
import com.izforge.izpack.util.Debug;
import com.izforge.izpack.util.FileExecutor;
import com.izforge.izpack.util.OsVersion;
import com.izforge.izpack.util.StringTool;
import com.izforge.izpack.util.os.unix.ShellScript;
import com.izforge.izpack.util.os.unix.UnixHelper;
import com.izforge.izpack.util.os.unix.UnixUser;
import com.izforge.izpack.util.os.unix.UnixUsers;
//import com.sun.corba.se.impl.orbutil.closure.Constant;
import java.io.*;
import java.util.*;
/**
* This is the Implementation of the RFC-Based Desktop-Link. Used in KDE and GNOME.
*
* @author marc.eppelmann@reddot.de
*/
public class Unix_Shortcut extends Shortcut implements Unix_ShortcutConstants
{
// ~ Static fields/initializers
// *******************************************************************************************************************************
/**
* version = "$Id$"
*/
private static String version = "$Id$";
/**
* rev = "$Revision$"
*/
private static String rev = "$Revision$";
/**
* DESKTOP_EXT = ".desktop"
*/
private static String DESKTOP_EXT = ".desktop";
/**
* template = ""
*/
private static String template = "";
/**
* N = "\n"
*/
private final static String N = "\n";
/**
* H = "#"
*/
private final static String H = "#";
/**
* S = " "
*/
private final static String S = " ";
/**
* C = Comment = H+S = "# "
*/
private final static String C = H + S;
/**
* QM = "\"" : <b>Q</b>uotation<b>M</b>ark
*/
private final static String QM = "\"";
private int ShortcutType;
private static ShellScript rootScript = null;
private static ShellScript uninstallScript = null;
private List users;
// private static ArrayList tempfiles = new ArrayList();
// ~ Instance fields
// ******************************************************************************************************************************************
/**
* internal String createdDirectory
*/
private String createdDirectory;
/**
* internal int itsUserType
*/
private int itsUserType;
/**
* internal String itsGroupName
*/
private String itsGroupName;
/**
* internal String itsName
*/
private String itsName;
/**
* internal String itsFileName
*/
private String itsFileName;
/**
* internal String itsApplnkFolder = "applnk"
*/
private String itsApplnkFolder = "applnk";
/**
* internal Properties Set
*/
private Properties props;
/**
* forAll = new Boolean(false): A flag to indicate that this should created for all users.
*/
private Boolean forAll = Boolean.FALSE;
/**
* Internal Help Buffer
*/
public StringBuffer hlp;
/** my Install ShellScript **/
public ShellScript myInstallScript;
/** Internal Constant: FS = File.separator // **/
public final String FS = File.separator;
/** Internal Constant: myHome = System.getProperty("user.home") **/
public final String myHome = System.getProperty("user.home");
/** Internal Constant: su = UnixHelper.getSuCommand() **/
public final String su = UnixHelper.getSuCommand();
/** Internal Constant: xdgDesktopIconCmd = UnixHelper.getCustomCommand("xdg-desktop-icon") **/
public final String xdgDesktopIconCmd = UnixHelper.getCustomCommand("xdg-desktop-icon");
public String myXdgDesktopIconScript;
public String myXdgDesktopIconCmd;
// ~ Constructors ***********************************************************************
// ~ Constructors
// *********************************************************************************************************************************************
/**
* Creates a new Unix_Shortcut object.
*/
public Unix_Shortcut()
{
hlp = new StringBuffer();
String userLanguage = System.getProperty("user.language", "en");
hlp.append("[Desktop Entry]" + N);
// TODO implement Attribute: X-KDE-StartupNotify=true
hlp.append("Categories=" + $Categories + N);
hlp.append("Comment=" + $Comment + N);
hlp.append("Comment[").append(userLanguage).append("]=" + $Comment + N);
hlp.append("Encoding=" + $Encoding + N);
// this causes too many problems
// hlp.append("TryExec=" + $E_QUOT + $Exec + $E_QUOT + S + $Arguments + N);
hlp.append("Exec=" + $E_QUOT + $Exec + $E_QUOT + S + $Arguments + N);
hlp.append("GenericName=" + $GenericName + N);
hlp.append("GenericName[").append(userLanguage).append("]=" + $GenericName + N);
hlp.append("Icon=" + $Icon + N);
hlp.append("MimeType=" + $MimeType + N);
hlp.append("Name=" + $Name + N);
hlp.append("Name[").append(userLanguage).append("]=" + $Name + N);
hlp.append("Path=" + $P_QUOT + $Path + $P_QUOT + N);
hlp.append("ServiceTypes=" + $ServiceTypes + N);
hlp.append("SwallowExec=" + $SwallowExec + N);
hlp.append("SwallowTitle=" + $SwallowTitle + N);
hlp.append("Terminal=" + $Terminal + N);
hlp.append("TerminalOptions=" + $Options_For_Terminal + N);
hlp.append("Type=" + $Type + N);
hlp.append("URL=" + $URL + N);
hlp.append("X-KDE-SubstituteUID=" + $X_KDE_SubstituteUID + N);
hlp.append("X-KDE-Username=" + $X_KDE_Username + N);
hlp.append(N);
hlp.append(C + "created by" + S).append(getClass().getName()).append(S).append(rev).append(
N);
hlp.append(C).append(version);
template = hlp.toString();
props = new Properties();
initProps();
if (rootScript == null)
{
rootScript = new ShellScript();
}
if (uninstallScript == null)
{
uninstallScript = new ShellScript();
}
if (myInstallScript == null)
{
myInstallScript = new ShellScript();
}
}
// ~ Methods ****************************************************************************
// ~ Methods
// **************************************************************************************************************************************************
/**
* This initialisizes all Properties Values with "".
*/
private void initProps()
{
String[] propsArray = { $Comment, $$LANG_Comment, $Encoding, $Exec, $Arguments,
$GenericName, $$LANG_GenericName, $MimeType, $Name, $$LANG_Name, $Path,
$ServiceTypes, $SwallowExec, $SwallowTitle, $Terminal, $Options_For_Terminal,
$Type, $X_KDE_SubstituteUID, $X_KDE_Username, $Icon, $URL, $E_QUOT, $P_QUOT,
$Categories, $TryExec};
for (String aPropsArray : propsArray)
{
props.put(aPropsArray, "");
}
}
/**
* Overridden Method
*
* @see com.izforge.izpack.util.os.Shortcut#initialize(int, java.lang.String)
*/
public void initialize(int aType, String aName) throws Exception
{
this.itsName = aName;
props.put($Name, aName);
}
/**
* This indicates that Unix will be supported.
*
* @see com.izforge.izpack.util.os.Shortcut#supported()
*/
public boolean supported()
{
return true;
}
/**
* Dummy
*
* @see com.izforge.izpack.util.os.Shortcut#getDirectoryCreated()
*/
public String getDirectoryCreated()
{
return this.createdDirectory; // while not stored...
}
/**
* Dummy
*
* @see com.izforge.izpack.util.os.Shortcut#getFileName()
*/
public String getFileName()
{
return (this.itsFileName);
}
/**
* Overridden compatibility method. Returns all directories in $USER/.kde/share/applink.
*
* @see com.izforge.izpack.util.os.Shortcut#getProgramGroups(int)
*/
public Vector<String> getProgramGroups(int userType)
{
Vector<String> groups = new Vector<String>();
File kdeShareApplnk = getKdeShareApplnkFolder(userType);
try
{
File[] listing = kdeShareApplnk.listFiles();
for (File aListing : listing)
{
if (aListing.isDirectory())
{
groups.add(aListing.getName());
}
}
}
catch (Exception e)
{
// ignore and return an empty vector.
}
return (groups);
}
/**
* Gets the Programsfolder for the given User (non-Javadoc).
*
* @see com.izforge.izpack.util.os.Shortcut#getProgramsFolder(int)
*/
public String getProgramsFolder(int current_user)
{
String result = "";
//
result = getKdeShareApplnkFolder(current_user).toString();
return result;
}
/**
* Gets the XDG path to place the menu shortcuts
*
* @param userType to get for.
* @return handle to the directory
*/
private File getKdeShareApplnkFolder(int userType)
{
if (userType == Shortcut.ALL_USERS)
{
return new File(File.separator + "usr" + File.separator + "share" + File.separator
+ "applications");
}
else
{
return new File(System.getProperty("user.home") + File.separator + ".local"
+ File.separator + "share" + File.separator + "applications");
}
}
/**
* Gets the name of the applink folder for the currently used distribution. Currently
* "applnk-redhat for RedHat, "applnk-mdk" for Mandrake, and simply "applnk" for all others.
*
* @return result
*/
private String getKdeApplinkFolderName()
{
String applinkFolderName = "applnk";
if (OsVersion.IS_REDHAT_LINUX)
{
applinkFolderName = "applnk-redhat";
}
if (OsVersion.IS_MANDRAKE_LINUX)
{
applinkFolderName = "applnk-mdk";
}
return applinkFolderName;
}
/**
* Gets the KDEBasedir for the given User.
*
* @param userType one of root or regular user
* @return the basedir
*/
private File getKdeBase(int userType)
{
File result = null;
if (userType == Shortcut.ALL_USERS)
{
FileExecutor fe = new FileExecutor();
String[] execOut = new String[2];
int execResult = fe.executeCommand(new String[] { "/usr/bin/env", "kde-config",
"--prefix"}, execOut);
result = new File(execOut[0].trim());
}
else
{
result = new File(System.getProperty("user.home") + File.separator + ".kde");
}
return result;
}
/**
* overridden method
*
* @return true
* @see com.izforge.izpack.util.os.Shortcut#multipleUsers()
*/
public boolean multipleUsers()
{
// EVER true for UNIXes ;-)
return (true);
}
/**
* Creates and stores the shortcut-files.
*
* @see com.izforge.izpack.util.os.Shortcut#save()
*/
public void save() throws Exception
{
String target = null;
String shortCutDef = this.replace();
boolean rootUser4All = this.getUserType() == Shortcut.ALL_USERS;
boolean create4All = this.getCreateForAll();
// Create The Desktop Shortcuts
if ("".equals(this.itsGroupName) && (this.getLinkType() == Shortcut.DESKTOP))
{
this.itsFileName = target;
AutomatedInstallData idata;
idata = AutomatedInstallData.getInstance();
// read the userdefined / overridden / wished Shortcut Location
// This can be an absolute Path name or a relative Path to the InstallPath
File shortCutLocation = null;
File ApplicationShortcutPath;
String ApplicationShortcutPathName = idata.getVariable("ApplicationShortcutPath"/**
* TODO
* <-- Put in Docu and in Un/InstallerConstantsClass
*/
);
if (null != ApplicationShortcutPathName && !ApplicationShortcutPathName.equals(""))
{
ApplicationShortcutPath = new File(ApplicationShortcutPathName);
if (ApplicationShortcutPath.isAbsolute())
{
// I know :-) Can be m"ORed" elegant :)
if (!ApplicationShortcutPath.exists() && ApplicationShortcutPath.mkdirs()
&& ApplicationShortcutPath.canWrite())
shortCutLocation = ApplicationShortcutPath;
if (ApplicationShortcutPath.exists() && ApplicationShortcutPath.isDirectory()
&& ApplicationShortcutPath.canWrite())
shortCutLocation = ApplicationShortcutPath;
}
else
{
File relativePath = new File(idata.getInstallPath() + FS
+ ApplicationShortcutPath);
relativePath.mkdirs();
shortCutLocation = new File(relativePath.toString());
}
}
else
shortCutLocation = new File(idata.getInstallPath());
// write the App ShortCut
File writtenDesktopFile = writeAppShortcutWithOutSpace(shortCutLocation.toString(),
this.itsName, shortCutDef);
uninstaller.addFile(writtenDesktopFile.toString(), true);
// Now install my Own with xdg-if available // Note the The reverse Uninstall-Task is on
// TODO: "WHICH another place"
if (xdgDesktopIconCmd != null)
{
createExtXdgDesktopIconCmd(shortCutLocation);
// / TODO: DELETE the ScriptFiles
myInstallScript.appendln(new String[] { myXdgDesktopIconCmd, "install",
"--novendor", StringTool.escapeSpaces(writtenDesktopFile.toString())});
ShellScript myUninstallScript = new ShellScript();
myUninstallScript.appendln(new String[] { myXdgDesktopIconCmd, "uninstall",
"--novendor", StringTool.escapeSpaces(writtenDesktopFile.toString())});
uninstaller.addUninstallScript(myUninstallScript.getContentAsString());
}
else
{
// otherwise copy to my desktop and add to uninstaller
File myDesktopFile;
do
{
myDesktopFile = new File(myHome + FS + "Desktop" + writtenDesktopFile.getName()
+ "-" + System.currentTimeMillis() + DESKTOP_EXT);
}
while (myDesktopFile.exists());
copyTo(writtenDesktopFile, myDesktopFile);
uninstaller.addFile(myDesktopFile.toString(), true);
}
// If I'm root and this Desktop.ShortCut should be for all other users
if (rootUser4All && create4All)
{
if (xdgDesktopIconCmd != null)
{
installDesktopFileToAllUsersDesktop(writtenDesktopFile);
}
else
// OLD ( Backward-Compatible/hardwired-"Desktop"-Foldername Styled Mechanic )
{
copyDesktopFileToAllUsersDesktop(writtenDesktopFile);
}
}
}
// This is - or should be only a Link in the [K?]-Menu
else
{
// the following is for backwards compatibility to older versions of KDE!
// on newer versions of KDE the icons will appear duplicated unless you set
// the category=""
// removed because of compatibility issues
/*
* Object categoryobject = props.getProperty($Categories); if(categoryobject != null &&
* ((String)categoryobject).length()>0) { File kdeHomeShareApplnk =
* getKdeShareApplnkFolder(this.getUserType()); target = kdeHomeShareApplnk.toString() +
* FS + this.itsGroupName + FS + this.itsName + DESKTOP_EXT; this.itsFileName = target;
* File kdemenufile = writeShortCut(target, shortCutDef);
*
* uninstaller.addFile(kdemenufile.toString(), true); }
*/
if (rootUser4All && create4All)
{
{
// write the icon pixmaps into /usr/share/pixmaps
File theIcon = new File(this.getIconLocation());
File commonIcon = new File("/usr/share/pixmaps/" + theIcon.getName());
try
{
copyTo(theIcon, commonIcon);
uninstaller.addFile(commonIcon.toString(), true);
}
catch (Exception cnc)
{
Debug.log("Could Not Copy: " + theIcon + " to " + commonIcon + "( "
+ cnc.getMessage() + " )");
}
// write *.desktop
this.itsFileName = target;
File writtenFile = writeAppShortcut("/usr/share/applications/", this.itsName,
shortCutDef);
setWrittenFileName(writtenFile.getName());
uninstaller.addFile(writtenFile.toString(), true);
}
}
else
// create local XDG shortcuts
{
// System.out.println("Creating gnome shortcut");
String localApps = myHome + "/.local/share/applications/";
String localPixmaps = myHome + "/.local/share/pixmaps/";
// System.out.println("Creating "+localApps);
try
{
java.io.File f = new java.io.File(localApps);
f.mkdirs();
f = new java.io.File(localPixmaps);
f.mkdirs();
}
catch (Exception ignore)
{
// System.out.println("Failed creating "+localApps + " or " + localPixmaps);
Debug.log("Failed creating " + localApps + " or " + localPixmaps);
}
// write the icon pixmaps into ~/share/pixmaps
File theIcon = new File(this.getIconLocation());
File commonIcon = new File(localPixmaps + theIcon.getName());
try
{
copyTo(theIcon, commonIcon);
uninstaller.addFile(commonIcon.toString(), true);
}
catch (Exception cnc)
{
Debug.log("Could Not Copy: " + theIcon + " to " + commonIcon + "( "
+ cnc.getMessage() + " )");
}
// write *.desktop in the local folder
this.itsFileName = target;
File writtenFile = writeAppShortcut(localApps, this.itsName, shortCutDef);
setWrittenFileName(writtenFile.getName());
uninstaller.addFile(writtenFile.toString(), true);
}
}
}
/**
* Ceates Extended Locale Enabled XdgDesktopIcon Command script.
* Fills the File myXdgDesktopIconScript with the content of
* com/izforge/izpack/util/os/unix/xdgscript.sh and uses this to
* creates User Desktop icons
*
* @param shortCutLocation in which folder should this stored.
* @throws IOException
* @throws ResourceNotFoundException
*/
public void createExtXdgDesktopIconCmd(File shortCutLocation) throws IOException,
ResourceNotFoundException
{
ShellScript myXdgDesktopIconScript = new ShellScript(null);
String lines = "";
ResourceManager m = ResourceManager.getInstance();
m.setDefaultOrResourceBasePath("");
lines = m.getTextResource("/com/izforge/izpack/util/os/unix/xdgdesktopiconscript.sh");
m.setDefaultOrResourceBasePath(null);
myXdgDesktopIconScript.append(lines);
myXdgDesktopIconCmd = new String(shortCutLocation + FS
+ "IzPackLocaleEnabledXdgDesktopIconScript.sh" );
myXdgDesktopIconScript.write(myXdgDesktopIconCmd);
FileExecutor.getExecOutput( new String [] { UnixHelper.getCustomCommand("chmod"),"+x", myXdgDesktopIconCmd },true );
}
/**
* Calls and creates the Install/Unistall Script which installs Desktop Icons using
* xdgDesktopIconCmd un-/install
*
* @param writtenDesktopFile An applications desktop file, which should be installed.
*/
private void installDesktopFileToAllUsersDesktop(File writtenDesktopFile)
{
for (Object user1 : getUsers())
{
UnixUser user = ((UnixUser) user1);
if (user.getHome().equals(myHome))
{
Debug.log("need not to copy for itself: " + user.getHome() + "==" + myHome);
continue;
}
try
{
// / THE Following does such as #> su username -c "xdg-desktopicon install
// --novendor /Path/to/Filename\ with\ or\ without\ Space.desktop"
rootScript.append(new String[] { su, user.getName(), "-c" });
rootScript.appendln(new String[] { "\"" + myXdgDesktopIconCmd, "install", "--novendor",
StringTool.escapeSpaces(writtenDesktopFile.toString()) + "\"" });
uninstallScript.append(new String[] { su, user.getName(), "-c" });
uninstallScript
.appendln(new String[] { "\"" + myXdgDesktopIconCmd, "uninstall", "--novendor",
StringTool.escapeSpaces(writtenDesktopFile.toString()) + "\""});
}
catch (Exception e)
{
Debug.log(e.getMessage());
Debug.log(e.toString());
}
}
Debug.log("==============================");
Debug.log(rootScript.getContentAsString());
}
/**
* @param writtenDesktopFile
* @throws IOException
*/
private void copyDesktopFileToAllUsersDesktop(File writtenDesktopFile) throws IOException
{
String chmod = UnixHelper.getCustomCommand("chmod");
String chown = UnixHelper.getCustomCommand("chown");
String rm = UnixHelper.getRmCommand();
String copy = UnixHelper.getCpCommand();
File dest = null;
// Create a tempFileName of this ShortCut
File tempFile = File.createTempFile(this.getClass().getName(), Long.toString(System
.currentTimeMillis())
+ ".tmp");
copyTo(writtenDesktopFile, tempFile);
// Debug.log("Wrote Tempfile: " + tempFile.toString());
FileExecutor.getExecOutput(new String[] { chmod, "uga+rwx", tempFile.toString()});
// su marc.eppelmann -c "/bin/cp /home/marc.eppelmann/backup.job.out.txt
// /home/marc.eppelmann/backup.job.out2.txt"
for (Object user1 : getUsers())
{
UnixUser user = ((UnixUser) user1);
if (user.getHome().equals(myHome))
{
Debug.log("need not to copy for itself: " + user.getHome() + "==" + myHome);
continue;
}
try
{
// aHomePath = userHomesList[idx];
dest = new File(user.getHome() + FS + "Desktop" + FS + writtenDesktopFile.getName());
//
// I'm root and cannot write into Users Home as root;
// But I'm Root and I can slip in every users skin :-)
//
// by# su username
//
// This works as well
// su $username -c "cp /tmp/desktopfile $HOME/Desktop/link.desktop"
// chown $username $HOME/Desktop/link.desktop
// Debug.log("Will Copy: " + tempFile.toString() + " to " + dest.toString());
rootScript.append(su);
rootScript.append(S);
rootScript.append(user.getName());
rootScript.append(S);
rootScript.append("-c");
rootScript.append(S);
rootScript.append('"');
rootScript.append(copy);
rootScript.append(S);
rootScript.append(tempFile.toString());
rootScript.append(S);
rootScript.append(StringTool.replace(dest.toString(), " ", "\\ "));
rootScript.appendln('"');
rootScript.append('\n');
// Debug.log("Will exec: " + script.toString());
rootScript.append(chown);
rootScript.append(S);
rootScript.append(user.getName());
rootScript.append(S);
rootScript.appendln(StringTool.replace(dest.toString(), " ", "\\ "));
rootScript.append('\n');
rootScript.append('\n');
// Debug.log("Will exec: " + script.toString());
uninstallScript.append(su);
uninstallScript.append(S);
uninstallScript.append(user.getName());
uninstallScript.append(S);
uninstallScript.append("-c");
uninstallScript.append(S);
uninstallScript.append('"');
uninstallScript.append(rm);
uninstallScript.append(S);
uninstallScript.append(StringTool.replace(dest.toString(), " ", "\\ "));
uninstallScript.appendln('"');
uninstallScript.appendln();
// Debug.log("Uninstall will exec: " + uninstallScript.toString());
}
catch (Exception rex)
{
System.out.println("Error while su Copy: " + rex.getLocalizedMessage() + "\n\n");
rex.printStackTrace();
/* ignore */
// most distros does not allow root to access any user
// home (ls -la /home/user drwx------)
// But try it anyway...
}
}
rootScript.append(rm);
rootScript.append(S);
rootScript.appendln(tempFile.toString());
rootScript.appendln();
}
/**
* Post Exec Action especially for the Unix Root User. which executes the Root ShortCut
* Shellscript. to copy all ShellScripts to the users Desktop.
*/
public void execPostAction()
{
Debug.log("Call of Impl. execPostAction Method in " + this.getClass().getName());
String pseudoUnique = this.getClass().getName() + Long.toString(System.currentTimeMillis());
String scriptFilename = null;
try
{
scriptFilename = File.createTempFile(pseudoUnique, ".sh").toString();
}
catch (IOException e)
{
scriptFilename = System.getProperty("java.io.tmpdir", "/tmp") + "/" + pseudoUnique
+ ".sh";
e.printStackTrace();
}
rootScript.write(scriptFilename);
rootScript.exec();
rootScript.delete();
Debug.log(rootScript);
// Quick an dirty copy & paste code - will be cleanup in one of 4.1.1++
pseudoUnique = this.getClass().getName() + Long.toString(System.currentTimeMillis());
try
{
scriptFilename = File.createTempFile(pseudoUnique, ".sh").toString();
}
catch (IOException e)
{
scriptFilename = System.getProperty("java.io.tmpdir", "/tmp") + "/" + pseudoUnique
+ ".sh";
e.printStackTrace();
}
myInstallScript.write(scriptFilename);
myInstallScript.exec();
myInstallScript.delete();
Debug.log(myInstallScript);
// End OF Quick AND Dirty
Debug.log(uninstallScript);
uninstaller.addUninstallScript(uninstallScript.getContentAsString());
}
/**
* Copies the inFile file to outFile using cbuff as buffer.
*
* @param inFile The File to read from.
* @param outFile The targetFile to write to.
* @throws IOException If an IO Error occurs
*/
public static void copyTo(File inFile, File outFile) throws IOException
{
char[] cbuff = new char[32768];
BufferedReader reader = new BufferedReader(new FileReader(inFile));
BufferedWriter writer = new BufferedWriter(new FileWriter(outFile));
int readedBytes = 0;
long absWrittenBytes = 0;
while ((readedBytes = reader.read(cbuff, 0, cbuff.length)) != -1)
{
writer.write(cbuff, 0, readedBytes);
absWrittenBytes += readedBytes;
}
reader.close();
writer.close();
}
private String writtenFileName;
public String getWrittenFileName()
{
return writtenFileName;
}
protected void setWrittenFileName(String s)
{
writtenFileName = s;
}
/**
* Write the given ShortDefinition in a File $ShortcutName-$timestamp.desktop in the given
* TargetPath.
*
* @param targetPath The Path in which the files should be written.
* @param shortcutName The Name for the File
* @param shortcutDef The Shortcut FileContent
*
* @return The written File
*/
private File writeAppShortcut(String targetPath, String shortcutName, String shortcutDef)
{
return writeAppShortcutWithSimpleSpacehandling(targetPath, shortcutName, shortcutDef, false);
}
/**
* Write the given ShortDefinition in a File $ShortcutName-$timestamp.desktop in the given
* TargetPath. ALSO all WhiteSpaces in the ShortCutName will be repalced with "-"
*
* @param targetPath The Path in which the files should be written.
* @param shortcutName The Name for the File
* @param shortcutDef The Shortcut FileContent
*
* @return The written File
*/
private File writeAppShortcutWithOutSpace(String targetPath, String shortcutName,
String shortcutDef)
{
return writeAppShortcutWithSimpleSpacehandling(targetPath, shortcutName, shortcutDef, true);
}
/**
* Write the given ShortDefinition in a File $ShortcutName-$timestamp.desktop in the given
* TargetPath. If the given replaceSpaces was true ALSO all WhiteSpaces in the ShortCutName will
* be replaced with "-"
*
* @param targetPath The Path in which the files should be written.
* @param shortcutName The Name for the File
* @param shortcutDef The Shortcut FileContent
* @return The written File
*/
private File writeAppShortcutWithSimpleSpacehandling(String targetPath, String shortcutName,
String shortcutDef, boolean replaceSpacesWithMinus)
{
if (!(targetPath.endsWith("/") || targetPath.endsWith("\\")))
{
targetPath += File.separatorChar;
}
File shortcutFile;
do
{
shortcutFile = new File(targetPath
+ (replaceSpacesWithMinus == true ? StringTool
.replaceSpacesWithMinus(shortcutName) : shortcutName) + "-"
+ System.currentTimeMillis() + DESKTOP_EXT);
}
while (shortcutFile.exists());
FileWriter fileWriter = null;
try
{
fileWriter = new FileWriter(shortcutFile);
}
catch (IOException e1)
{
System.out.println(e1.getMessage());
}
try
{
fileWriter.write(shortcutDef);
}
catch (IOException e)
{
e.printStackTrace();
}
try
{
fileWriter.close();
}
catch (IOException e2)
{
e2.printStackTrace();
}
return shortcutFile;
}
/**
* Writes the given Shortcutdefinition to the given Target. Returns the written File.
*
* @param target
* @param shortCutDef
* @return the File of the written shortcut.
*/
private File writeShortCut(String target, String shortCutDef)
{
File targetPath = new File(target.substring(0, target.lastIndexOf(File.separatorChar)));
if (!targetPath.exists())
{
targetPath.mkdirs();
this.createdDirectory = targetPath.toString();
}
File targetFileName = new File(target);
File backupFile = new File(targetPath + File.separator + "." + targetFileName.getName()
+ System.currentTimeMillis());
if (targetFileName.exists())
{
try
{
// create a hidden backup.file of the existing shortcut with a timestamp name.
copyTo(targetFileName, backupFile); // + System.e );
targetFileName.delete();
}
catch (IOException e3)
{
System.out.println("cannot create backup file " + backupFile + " of "
+ targetFileName); // e3.printStackTrace();
}
}
FileWriter fileWriter = null;
try
{
fileWriter = new FileWriter(targetFileName);
}
catch (IOException e1)
{
System.out.println(e1.getMessage());
}
try
{
fileWriter.write(shortCutDef);
}
catch (IOException e)
{
e.printStackTrace();
}
try
{
fileWriter.close();
}
catch (IOException e2)
{
e2.printStackTrace();
}
return targetFileName;
}
/**
* Set the Commandline Arguments
*
* @see com.izforge.izpack.util.os.Shortcut#setArguments(java.lang.String)
*/
public void setArguments(String args)
{
props.put($Arguments, args);
}
/**
* Sets the Description
*
* @see com.izforge.izpack.util.os.Shortcut#setDescription(java.lang.String)
*/
public void setDescription(String description)
{
props.put($Comment, description);
}
/**
* Sets The Icon Path
*
* @see com.izforge.izpack.util.os.Shortcut#setIconLocation(java.lang.String, int)
*/
public void setIconLocation(String path, int index)
{
props.put($Icon, path);
}
/**
* Sets the Name of this Shortcut
*
* @see com.izforge.izpack.util.os.Shortcut#setLinkName(java.lang.String)
*/
public void setLinkName(String aName)
{
this.itsName = aName;
props.put($Name, aName);
}
/**
* Sets the type of this Shortcut
*
* @see com.izforge.izpack.util.os.Shortcut#setLinkType(int)
*/
public void setLinkType(int aType) throws IllegalArgumentException,
UnsupportedEncodingException
{
ShortcutType = aType;
}
/**
* Sets the ProgramGroup
*
* @see com.izforge.izpack.util.os.Shortcut#setProgramGroup(java.lang.String)
*/
public void setProgramGroup(String aGroupName)
{
this.itsGroupName = aGroupName;
}
/**
* Sets the ShowMode
*
* @see com.izforge.izpack.util.os.Shortcut#setShowCommand(int)
*/
public void setShowCommand(int show)
{
}
/**
* Sets The TargetPath
*
* @see com.izforge.izpack.util.os.Shortcut#setTargetPath(java.lang.String)
*/
public void setTargetPath(String aPath)
{
StringTokenizer whiteSpaceTester = new StringTokenizer(aPath);
if (whiteSpaceTester.countTokens() > 1)
{
props.put($E_QUOT, QM);
}
props.put($Exec, aPath);
}
/**
* Sets the usertype.
*
* @see com.izforge.izpack.util.os.Shortcut#setUserType(int)
*/
public void setUserType(int aUserType)
{
this.itsUserType = aUserType;
}
/**
* Sets the working-directory
*
* @see com.izforge.izpack.util.os.Shortcut#setWorkingDirectory(java.lang.String)
*/
public void setWorkingDirectory(String aDirectory)
{
StringTokenizer whiteSpaceTester = new StringTokenizer(aDirectory);
if (whiteSpaceTester.countTokens() > 1)
{
props.put($P_QUOT, QM);
}
props.put($Path, aDirectory);
}
/**
* Dumps the Name to console.
*
* @see java.lang.Object#toString()
*/
public String toString()
{
return this.itsName + N + template;
}
/**
* Creates the Shortcut String which will be stored as File.
*
* @return contents of the shortcut file
*/
public String replace()
{
String result = template;
Enumeration enumeration = props.keys();
while (enumeration.hasMoreElements())
{
String key = (String) enumeration.nextElement();
result = StringTool.replace(result, key, props.getProperty(key));
}
return result;
}
/**
* Test Method
*
* @param args
* @throws IOException
* @throws ResourceNotFoundException
*/
public static void main(String[] args) throws IOException, ResourceNotFoundException
{
Unix_Shortcut aSample = new Unix_Shortcut();
System.out.println(">>" + aSample.getClass().getName() + "- Test Main Program\n\n");
try
{
aSample.initialize(APPLICATIONS, "Start Tomcat");
}
catch (Exception exc)
{
System.err.println("Could not init Unix_Shourtcut");
}
aSample.replace();
System.out.println(aSample);
//
//
//
// File targetFileName = new File(System.getProperty("user.home") + File.separator
// + "Start Tomcat" + DESKTOP_EXT);
// FileWriter fileWriter = null;
//
// try
// {
// fileWriter = new FileWriter(targetFileName);
// }
// catch (IOException e1)
// {
// e1.printStackTrace();
// }
//
// try
// {
// fileWriter.write( aSample.toString() );
// }
// catch (IOException e)
// {
// e.printStackTrace();
// }
//
// try
// {
// fileWriter.close();
// }
// catch (IOException e2)
// {
// e2.printStackTrace();
// }
aSample.createExtXdgDesktopIconCmd(new File(System.getProperty("user.home")));
System.out.println("DONE.\n");
}
/**
* Sets The Encoding
*
* @see com.izforge.izpack.util.os.Shortcut#setEncoding(java.lang.String)
*/
public void setEncoding(String aEncoding)
{
props.put($Encoding, aEncoding);
}
/**
* Sets The KDE Specific subst UID property
*
* @see com.izforge.izpack.util.os.Shortcut#setKdeSubstUID(java.lang.String)
*/
public void setKdeSubstUID(String trueFalseOrNothing)
{
props.put($X_KDE_SubstituteUID, trueFalseOrNothing);
}
/**
* Sets The KDE Specific subst UID property
*
* @see com.izforge.izpack.util.os.Shortcut#setKdeSubstUID(java.lang.String)
*/
public void setKdeUserName(String aUserName)
{
props.put($X_KDE_Username, aUserName);
}
/**
* Sets the MimeType
*
* @see com.izforge.izpack.util.os.Shortcut#setMimetype(java.lang.String)
*/
public void setMimetype(String aMimetype)
{
props.put($MimeType, aMimetype);
}
/**
* Sets the terminal
*
* @see com.izforge.izpack.util.os.Shortcut#setTerminal(java.lang.String)
*/
public void setTerminal(String trueFalseOrNothing)
{
props.put($Terminal, trueFalseOrNothing);
}
/**
* Sets the terminal options
*
* @see com.izforge.izpack.util.os.Shortcut#setTerminalOptions(java.lang.String)
*/
public void setTerminalOptions(String someTerminalOptions)
{
props.put($Options_For_Terminal, someTerminalOptions);
}
/**
* Sets the Shortcut type (one of Application, Link or Device)
*
* @see com.izforge.izpack.util.os.Shortcut#setType(java.lang.String)
*/
public void setType(String aType)
{
props.put($Type, aType);
}
/**
* Sets the Url for type Link. Can be also a apsolute file/path
*
* @see com.izforge.izpack.util.os.Shortcut#setURL(java.lang.String)
*/
public void setURL(String anUrl)
{
props.put($URL, anUrl);
}
/**
* Gets the Usertype of the Shortcut.
*
* @see com.izforge.izpack.util.os.Shortcut#getUserType()
*/
public int getUserType()
{
return itsUserType;
}
/**
* Sets the Categories Field
*
* @param theCategories the categories
*/
public void setCategories(String theCategories)
{
props.put($Categories, theCategories);
}
/**
* Sets the TryExecField.
*
* @param aTryExec the try exec command
*/
public void setTryExec(String aTryExec)
{
props.put($TryExec, aTryExec);
}
public int getLinkType()
{
return ShortcutType;
// return Shortcut.DESKTOP;
}
private List getUsers() {
if (users == null) {
users = UnixUsers.getUsersWithValidShellsExistingHomesAndDesktops();
}
return users;
}
}
| apache-2.0 |
sap-production/hudson-3.x | hudson-utils/src/test/java/org/hudsonci/utils/marshal/xref/XReferenceTest.java | 1671 | /*******************************************************************************
*
* Copyright (c) 2010-2011 Sonatype, Inc.
*
* 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
*
* Contributors:
*
*
*
*
*******************************************************************************/
package org.hudsonci.utils.marshal.xref;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.annotations.XStreamAlias;
import org.hudsonci.utils.marshal.xref.XReference;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.util.Date;
/**
* Tests for {@link XReference}.
*/
public class XReferenceTest
{
private XStream xs;
@Before
public void setUp() throws Exception {
xs = new XStream();
xs.autodetectAnnotations(true);
}
@After
public void tearDown() throws Exception {
xs = null;
}
@Test
public void testMarshal() throws Exception {
Date value1 = new Date();
TestRef ref1 = new TestRef(value1, "a");
String xml = xs.toXML(ref1);
System.out.println("XML:\n" + xml);
}
@XStreamAlias("test-ref")
private static class TestRef
extends XReference
{
private String path;
private TestRef(Object value, String path) {
super(value);
this.path = path;
}
@Override
public String getPath() {
return path;
}
}
}
| apache-2.0 |
papicella/snappy-store | gemfire-core/src/main/java/com/gemstone/gemfire/internal/jta/TransactionImpl.java | 10374 | /*
* Copyright (c) 2010-2015 Pivotal Software, 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. See accompanying
* LICENSE file.
*/
package com.gemstone.gemfire.internal.jta;
/**
* TransactionImpl implements the JTA Transaction interface.
*
*/
import javax.transaction.xa.*;
import javax.transaction.*;
import com.gemstone.gemfire.i18n.LogWriterI18n;
import com.gemstone.gemfire.internal.i18n.LocalizedStrings;
import java.util.*;
public class TransactionImpl implements Transaction {
/**
* The Global Transaction to which this Transaction belongs.
*/
private GlobalTransaction gtx = null;
/**
* A Synchronization object.
*/
private Synchronization sync = null;
/**
* The transaction manager that owns this transaction.
*/
private TransactionManagerImpl tm = TransactionManagerImpl
.getTransactionManager();
/**
* List of registered Synchronization objects.
*/
private List syncList = new ArrayList();
/**
* Constructs an instance of a Transaction
*/
public TransactionImpl() {
}
/**
* Calls the commit() of the TransactionManager that owns the current
* Transaction
*
* @throws RollbackException - Thrown to indicate that the transaction has
* been rolled back rather than committed.
* @throws HeuristicMixedException - Thrown to indicate that a heuristic
* decision was made and that some relevant updates have been
* committed while others have been rolled back.
* @throws HeuristicRollbackException - Thrown to indicate that a heuristic
* decision was made and that all relevant updates have been
* rolled back.
* @throws java.lang.SecurityException - Thrown to indicate that the thread
* is not allowed to commit the transaction.
* @throws java.lang.IllegalStateException - Thrown if the current thread is
* not associated with a transaction.
* @throws SystemException - Thrown if the transaction manager encounters an
* unexpected error condition.
*
* @see javax.transaction.Transaction#commit()
*/
public void commit() throws RollbackException, HeuristicMixedException,
HeuristicRollbackException, SecurityException, SystemException {
tm.commit();
}
/**
* Calls the rollback() of the TransactionManager that owns the current
* Transaction
*
* @throws java.lang.SecurityException - Thrown to indicate that the thread
* is not allowed to commit the transaction.
* @throws java.lang.IllegalStateException - Thrown if the current thread is
* not associated with a transaction.
* @throws SystemException - Thrown if the transaction manager encounters an
* unexpected error condition.
*
* @see javax.transaction.Transaction#rollback()
*/
public void rollback() throws IllegalStateException, SystemException {
tm.rollback();
}
/**
* Sets the status of the Global Transaction associated with this transaction
* to be RollBack only
*
* @see javax.transaction.Transaction#setRollbackOnly()
*/
public void setRollbackOnly() throws IllegalStateException, SystemException {
gtx = tm.getGlobalTransaction();
if (gtx == null) {
String exception = LocalizedStrings.TransactionImpl_TRANSACTIONIMPL_SETROLLBACKONLY_NO_GLOBAL_TRANSACTION_EXISTS.toLocalizedString();
LogWriterI18n writer = TransactionUtils.getLogWriterI18n();
if (writer.fineEnabled()) writer.fine(exception);
throw new SystemException(exception);
}
gtx.setRollbackOnly();
}
/**
* Get the status of the Global Transaction associated with this local
* transaction
*
* @see javax.transaction.Transaction#getStatus()
*/
public int getStatus() throws SystemException {
gtx = tm.getGlobalTransaction();
if (gtx == null) {
return Status.STATUS_NO_TRANSACTION;
}
return gtx.getStatus();
}
/**
* not supported
*/
public void setTransactionTimeout(int seconds) throws SystemException {
String exception = LocalizedStrings.TransactionImpl_SETTRANSACTIONTIMEOUT_IS_NOT_SUPPORTED.toLocalizedString();
LogWriterI18n writer = TransactionUtils.getLogWriterI18n();
if (writer.fineEnabled()) writer.fine(exception);
throw new SystemException(exception);
}
/**
* Enlist the XAResource specified to the Global Transaction associated with
* this transaction.
*
* @param xaRes XAResource to be enlisted
* @return true, if resource was enlisted successfully, otherwise false.
* @throws SystemException Thrown if the transaction manager encounters an
* unexpected error condition.
* @throws IllegalStateException Thrown if the transaction in the target
* object is in the prepared state or the transaction is
* inactive.
* @throws RollbackException Thrown to indicate that the transaction has been
* marked for rollback only.
*
* @see javax.transaction.Transaction#enlistResource(javax.transaction.xa.XAResource)
*/
public boolean enlistResource(XAResource xaRes) throws RollbackException,
IllegalStateException, SystemException {
gtx = tm.getGlobalTransaction();
if (gtx == null) {
String exception = LocalizedStrings.TransactionImpl_TRANSACTIONIMPL_ENLISTRESOURCE_NO_GLOBAL_TRANSACTION_EXISTS.toLocalizedString();
LogWriterI18n writer = TransactionUtils.getLogWriterI18n();
if (writer.fineEnabled()) writer.fine(exception);
throw new SystemException(exception);
}
return gtx.enlistResource(xaRes);
}
/**
* Disassociate the resource specified from the global transaction.
* associated with this transaction
*
* @param xaRes XAResource to be delisted
* @param flag One of the values of TMSUCCESS, TMSUSPEND, or TMFAIL.
* @return true, if resource was delisted successfully, otherwise false.
* @throws SystemException Thrown if the transaction manager encounters an
* unexpected error condition.
* @throws IllegalStateException Thrown if the transaction in the target
* object is not active.
*
* @see javax.transaction.Transaction#delistResource(javax.transaction.xa.XAResource,
* int)
*/
public boolean delistResource(XAResource xaRes, int flag)
throws IllegalStateException, SystemException {
gtx = tm.getGlobalTransaction();
if (gtx == null) {
String exception = LocalizedStrings.TransactionImpl_TRANSACTIONIMPL_DELISTRESOURCE_NO_GLOBAL_TRANSACTION_EXISTS.toLocalizedString();
LogWriterI18n writer = TransactionUtils.getLogWriterI18n();
if (writer.fineEnabled()) writer.fine(exception);
throw new SystemException(exception);
}
return gtx.delistResource(xaRes, flag);
}
/**
* Register the Synchronizations by adding the synchronization object to a
* list of synchronizations
*
* @param synchronisation Synchronization the Synchronization which needs to
* be registered
*
* @see javax.transaction.Transaction#registerSynchronization(javax.transaction.Synchronization)
*/
public void registerSynchronization(Synchronization synchronisation)
throws SystemException, IllegalStateException, RollbackException {
{
LogWriterI18n writer = TransactionUtils.getLogWriterI18n();
if (writer.fineEnabled()) {
writer.fine("registering JTA synchronization: " + synchronisation);
}
}
if (synchronisation == null)
throw new SystemException(LocalizedStrings.TransactionImpl_TRANSACTIONIMPLREGISTERSYNCHRONIZATIONSYNCHRONIZATION_IS_NULL.toLocalizedString());
gtx = tm.getGlobalTransaction();
if (gtx == null) {
throw new SystemException(LocalizedStrings.TransactionManagerImpl_NO_TRANSACTION_PRESENT.toLocalizedString());
}
synchronized (gtx) {
int status = -1;
if ((status = gtx.getStatus()) == Status.STATUS_MARKED_ROLLBACK) {
String exception = LocalizedStrings.TransactionImpl_TRANSACTIONIMPL_REGISTERSYNCHRONIZATION_SYNCHRONIZATION_CANNOT_BE_REGISTERED_BECAUSE_THE_TRANSACTION_HAS_BEEN_MARKED_FOR_ROLLBACK.toLocalizedString();
LogWriterI18n writer = TransactionUtils.getLogWriterI18n();
if (writer.fineEnabled()) writer.fine(exception);
throw new RollbackException(exception);
} else if (status != Status.STATUS_ACTIVE) {
String exception = LocalizedStrings.TransactionImpl_TRANSACTIONIMPL_REGISTERSYNCHRONIZATION_SYNCHRONIZATION_CANNOT_BE_REGISTERED_ON_A_TRANSACTION_WHICH_IS_NOT_ACTIVE.toLocalizedString();
LogWriterI18n writer = TransactionUtils.getLogWriterI18n();
if (writer.fineEnabled()) writer.fine(exception);
throw new IllegalStateException(exception);
}
syncList.add(synchronisation);
}
}
/**
* Iterate over the list of Synchronizations to complete all the methods to
* be performed before completion
*/
boolean notifyBeforeCompletion() {
Iterator iterator = syncList.iterator();
boolean result = true;
while (iterator.hasNext()) {
sync = ((Synchronization) iterator.next());
sync.beforeCompletion();
}
return result;
}
/**
* Iterate over the list of Synchronizations to complete all the methods to
* be performed after completion
*
* @param status int The status of the Global transaction associated with the
* transaction
*/
void notifyAfterCompletion(int status) throws SystemException {
Iterator iterator = syncList.iterator();
while (iterator.hasNext()) {
sync = ((Synchronization) iterator.next());
sync.afterCompletion(status);
}
}
//This method is to be used only for test validation
List getSyncList() {
return syncList;
}
}
| apache-2.0 |
Darsstar/framework | uitest/src/main/java/com/vaadin/tests/requesthandlers/CommunicationError.java | 4043 | /*
* Copyright 2000-2016 Vaadin Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.vaadin.tests.requesthandlers;
import java.io.IOException;
import java.io.PrintWriter;
import com.vaadin.launcher.ApplicationRunnerServlet;
import com.vaadin.server.CustomizedSystemMessages;
import com.vaadin.server.SystemMessages;
import com.vaadin.server.UIClassSelectionEvent;
import com.vaadin.server.UIProvider;
import com.vaadin.server.VaadinRequest;
import com.vaadin.server.VaadinService;
import com.vaadin.server.VaadinServletRequest;
import com.vaadin.tests.components.AbstractReindeerTestUI;
import com.vaadin.ui.Button;
import com.vaadin.ui.Label;
import com.vaadin.ui.UI;
/**
* Test UI provider to check communication error json object null values.
*
* @author Vaadin Ltd
*/
public class CommunicationError extends UIProvider {
@Override
public Class<? extends UI> getUIClass(UIClassSelectionEvent event) {
VaadinServletRequest request = (VaadinServletRequest) event
.getRequest();
String currentUrl = request.getRequestURL().toString();
StringBuilder redirectClass = new StringBuilder(
CommunicationError.class.getSimpleName());
redirectClass.append('$');
redirectClass.append(RedirectedUI.class.getSimpleName());
String restartApplication = "?restartApplication";
if (!currentUrl.contains(restartApplication)) {
redirectClass.append(restartApplication);
}
final String url = currentUrl.replace(
CommunicationError.class.getSimpleName(), redirectClass);
request.setAttribute(
ApplicationRunnerServlet.CUSTOM_SYSTEM_MESSAGES_PROPERTY,
createSystemMessages(url));
return CommunicationErrorUI.class;
}
public static class CommunicationErrorUI extends AbstractReindeerTestUI {
@Override
protected void setup(VaadinRequest request) {
Button button = new Button("Send bad request",
event -> {
try {
// An unparseable response will cause
// communication error
PrintWriter writer = VaadinService
.getCurrentResponse().getWriter();
writer.write("for(;;)[{FOOBAR}]");
writer.flush();
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
});
addComponent(button);
}
@Override
protected Integer getTicketNumber() {
return 14594;
}
@Override
protected String getTestDescription() {
return "Null values should be wrapped into JsonNull objects.";
}
}
public static class RedirectedUI extends UI {
@Override
protected void init(VaadinRequest request) {
Label label = new Label("redirected");
label.addStyleName("redirected");
setContent(label);
}
}
private SystemMessages createSystemMessages(String url) {
CustomizedSystemMessages messages = new CustomizedSystemMessages();
messages.setCommunicationErrorCaption(null);
messages.setCommunicationErrorMessage(null);
messages.setCommunicationErrorURL(url);
return messages;
}
}
| apache-2.0 |
papicella/snappy-store | gemfirexd/core/src/main/java/com/pivotal/gemfirexd/internal/impl/sql/compile/DefaultVTIModDeferPolicy.java | 3304 | /*
Derby - Class com.pivotal.gemfirexd.internal.impl.sql.compile.DefaultVTIModDeferPolicy
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.pivotal.gemfirexd.internal.impl.sql.compile;
import com.pivotal.gemfirexd.internal.vti.DeferModification;
/**
* This class implements the default policy for defering modifications to virtual
* tables.
*/
class DefaultVTIModDeferPolicy implements DeferModification
{
private final String targetVTIClassName;
private final boolean VTIResultSetIsSensitive;
DefaultVTIModDeferPolicy( String targetVTIClassName,
boolean VTIResultSetIsSensitive)
{
this.targetVTIClassName = targetVTIClassName;
this.VTIResultSetIsSensitive = VTIResultSetIsSensitive;
}
/**
* @see com.pivotal.gemfirexd.internal.vti.DeferModification#alwaysDefer
*/
public boolean alwaysDefer( int statementType)
{
return false;
}
/**
* @see com.pivotal.gemfirexd.internal.vti.DeferModification#columnRequiresDefer
*/
public boolean columnRequiresDefer( int statementType,
String columnName,
boolean inWhereClause)
{
switch( statementType)
{
case DeferModification.INSERT_STATEMENT:
return false;
case DeferModification.UPDATE_STATEMENT:
return VTIResultSetIsSensitive && inWhereClause;
case DeferModification.DELETE_STATEMENT:
return false;
}
return false; // Should not get here.
} // end of columnRequiresDefer
/**
* @see com.pivotal.gemfirexd.internal.vti.DeferModification#subselectRequiresDefer(int,String,String)
*/
public boolean subselectRequiresDefer( int statementType,
String schemaName,
String tableName)
{
return false;
} // end of subselectRequiresDefer( statementType, schemaName, tableName)
/**
* @see com.pivotal.gemfirexd.internal.vti.DeferModification#subselectRequiresDefer(int, String)
*/
public boolean subselectRequiresDefer( int statementType,
String VTIClassName)
{
return targetVTIClassName.equals( VTIClassName);
} // end of subselectRequiresDefer( statementType, VTIClassName)
public void modificationNotify( int statementType,
boolean deferred)
{}
}
| apache-2.0 |
Darsstar/framework | testbench-api/src/main/java/com/vaadin/testbench/elements/TableElement.java | 5994 | /*
* Copyright 2000-2016 Vaadin Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.vaadin.testbench.elements;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.WebDriverException;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.interactions.Actions;
import com.vaadin.testbench.By;
import com.vaadin.testbench.TestBenchElement;
import com.vaadin.testbench.elementsbase.AbstractElement;
import com.vaadin.testbench.elementsbase.ServerClass;
@ServerClass("com.vaadin.ui.Table")
@Deprecated
public class TableElement extends AbstractSelectElement {
/**
* Function to find a Table cell. Looking for a cell that is currently not
* visible will throw NoSuchElementException
*
* @param row
* 0 based row index
* @param column
* 0 based column index
* @return TestBenchElement containing wanted cell.
* @throws NoSuchElementException
* if the cell (row, column) is not found.
*/
public TestBenchElement getCell(int row, int column) {
TestBenchElement cell = wrapElement(
findElement(By.vaadin("#row[" + row + "]/col[" + column + "]")),
getCommandExecutor());
return cell;
}
/**
* Return table row element by zero-based index.
*
* @return table row element by zero-based index
*/
public TableRowElement getRow(int row) {
TestBenchElement rowElem = wrapElement(
findElement(By.vaadin("#row[" + row + "]")),
getCommandExecutor());
return rowElem.wrap(TableRowElement.class);
}
/**
* Returns the header cell with the given column index.
*
* @param column
* 0 based column index
* @return TableHeaderElement containing the wanted header cell
*/
public TableHeaderElement getHeaderCell(int column) {
TestBenchElement headerCell = wrapElement(
findElement(By.vaadin("#header[" + column + "]")),
getCommandExecutor());
return headerCell.wrap(TableHeaderElement.class);
}
/**
* Function to get footer cell with given column index.
*
* @param column
* 0 based column index
* @return TestBenchElement containing wanted footer cell
*/
public TestBenchElement getFooterCell(int column) {
TestBenchElement footerCell = wrapElement(
findElement(By.vaadin("#footer[" + column + "]")),
getCommandExecutor());
return footerCell;
}
@Override
public void scroll(int scrollTop) {
((TestBenchElement) findElement(By.className("v-scrollable")))
.scroll(scrollTop);
}
@Override
public void scrollLeft(int scrollLeft) {
((TestBenchElement) findElement(By.className("v-scrollable")))
.scrollLeft(scrollLeft);
}
@Override
public void contextClick() {
WebElement tbody = findElement(By.className("v-table-body"));
// There is a problem in with phantomjs driver, just calling
// contextClick() doesn't work. We have to use javascript.
if (isPhantomJS()) {
JavascriptExecutor js = getCommandExecutor();
String scr = "var element=arguments[0];"
+ "var ev = document.createEvent('HTMLEvents');"
+ "ev.initEvent('contextmenu', true, false);"
+ "element.dispatchEvent(ev);";
js.executeScript(scr, tbody);
} else {
new Actions(getDriver()).contextClick(tbody).build().perform();
}
}
public static class ContextMenuElement extends AbstractElement {
public WebElement getItem(int index) {
return findElement(
By.xpath(".//table//tr[" + (index + 1) + "]//td/*"));
}
}
/**
* Fetches the context menu for the table.
*
* @return {@link com.vaadin.testbench.elements.TableElement.ContextMenuElement}
* @throws java.util.NoSuchElementException
* if the menu isn't open
*/
public ContextMenuElement getContextMenu() {
try {
WebElement cm = getDriver()
.findElement(By.className("v-contextmenu"));
return wrapElement(cm, getCommandExecutor())
.wrap(ContextMenuElement.class);
} catch (WebDriverException e) {
throw new NoSuchElementException("Context menu not found", e);
}
}
/**
* Opens the collapse menu of this table and returns the element for it.
*
* @return collapse menu element
*/
public CollapseMenuElement openCollapseMenu() {
getCollapseMenuToggle().click();
WebElement cm = getDriver()
.findElement(By.xpath("//*[@id='PID_VAADIN_CM']"));
return wrapElement(cm, getCommandExecutor())
.wrap(CollapseMenuElement.class);
}
/**
* Element representing a collapse menu of a Table.
*/
public static class CollapseMenuElement extends ContextMenuElement {
}
/**
* Gets the button that shows or hides the collapse menu.
*
* @return button for opening collapse menu
*/
public WebElement getCollapseMenuToggle() {
return findElement(By.className("v-table-column-selector"));
}
}
| apache-2.0 |
bgroenks96/nifty-gui | nifty-examples-libgdx/desktop/src/main/java/de/lessvoid/nifty/examples/libgdx/defaultcontrols/ControlsDemoMain.java | 1139 | package de.lessvoid.nifty.examples.libgdx.defaultcontrols;
import com.badlogic.gdx.backends.lwjgl.LwjglApplication;
import com.badlogic.gdx.backends.lwjgl.LwjglApplicationConfiguration;
import de.lessvoid.nifty.examples.defaultcontrols.ControlsDemo;
import de.lessvoid.nifty.examples.libgdx.LibgdxExampleApplication;
import de.lessvoid.nifty.examples.libgdx.resolution.GdxResolutionControl;
import de.lessvoid.nifty.examples.libgdx.resolution.GdxResolutionControl.Resolution;
/**
* @author Aaron Mahan <aaron@forerunnergames.com>
*/
public class ControlsDemoMain {
public static void main(String[] args) {
LwjglApplicationConfiguration config = new LwjglApplicationConfiguration();
config.useGL30 = false;
config.vSyncEnabled = true;
config.width = 1024;
config.height = 768;
config.title = "Nifty LibGDX Desktop Examples: Default Controls";
config.resizable = true;
final int atlasWidth = 2048;
final int atlasHeight = 2048;
new LwjglApplication(new LibgdxExampleApplication(new ControlsDemo<Resolution>(new GdxResolutionControl()),
atlasWidth, atlasHeight), config);
}
}
| bsd-2-clause |
NoChanceSD/DarkBot | src/main/protocols/org/darkstorm/darkbot/minecraftbot/protocol/v61/packets/Packet11PlayerPosition.java | 779 | package org.darkstorm.darkbot.minecraftbot.protocol.v61.packets;
import java.io.*;
import org.darkstorm.darkbot.minecraftbot.protocol.WriteablePacket;
public class Packet11PlayerPosition extends Packet10Flying implements WriteablePacket {
public double x;
public double y;
public double z;
public double stance;
public Packet11PlayerPosition() {
}
public Packet11PlayerPosition(double par1, double par3, double par5, double par7, boolean par9) {
super(par9);
x = par1;
y = par3;
stance = par5;
z = par7;
}
@Override
public void writeData(DataOutputStream out) throws IOException {
out.writeDouble(x);
out.writeDouble(y);
out.writeDouble(stance);
out.writeDouble(z);
super.writeData(out);
}
@Override
public int getId() {
return 11;
}
}
| bsd-2-clause |
samlanning/pebble | src/main/java/com/mitchellbosecke/pebble/extension/debug/PrettyPrintNodeVisitor.java | 6311 | /*******************************************************************************
* This file is part of Pebble.
*
* Copyright (c) 2014 by Mitchell Bösecke
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
******************************************************************************/
package com.mitchellbosecke.pebble.extension.debug;
import com.mitchellbosecke.pebble.extension.AbstractNodeVisitor;
import com.mitchellbosecke.pebble.node.ArgumentsNode;
import com.mitchellbosecke.pebble.node.BlockNode;
import com.mitchellbosecke.pebble.node.BodyNode;
import com.mitchellbosecke.pebble.node.FlushNode;
import com.mitchellbosecke.pebble.node.ForNode;
import com.mitchellbosecke.pebble.node.IfNode;
import com.mitchellbosecke.pebble.node.ImportNode;
import com.mitchellbosecke.pebble.node.IncludeNode;
import com.mitchellbosecke.pebble.node.NamedArgumentNode;
import com.mitchellbosecke.pebble.node.Node;
import com.mitchellbosecke.pebble.node.ParallelNode;
import com.mitchellbosecke.pebble.node.PrintNode;
import com.mitchellbosecke.pebble.node.RootNode;
import com.mitchellbosecke.pebble.node.SetNode;
import com.mitchellbosecke.pebble.node.TestInvocationExpression;
import com.mitchellbosecke.pebble.node.TextNode;
import com.mitchellbosecke.pebble.node.expression.BinaryExpression;
import com.mitchellbosecke.pebble.node.expression.ContextVariableExpression;
import com.mitchellbosecke.pebble.node.expression.FilterInvocationExpression;
import com.mitchellbosecke.pebble.node.expression.FunctionOrMacroInvocationExpression;
import com.mitchellbosecke.pebble.node.expression.GetAttributeExpression;
import com.mitchellbosecke.pebble.node.expression.ParentFunctionExpression;
import com.mitchellbosecke.pebble.node.expression.TernaryExpression;
import com.mitchellbosecke.pebble.node.expression.UnaryExpression;
public class PrettyPrintNodeVisitor extends AbstractNodeVisitor {
private StringBuilder output = new StringBuilder();
private int level = 0;
private void write(String message) {
for (int i = 0; i < level - 1; i++) {
output.append("| ");
}
if (level > 0) {
output.append("|-");
}
output.append(message.toUpperCase()).append("\n");
}
public String toString() {
return output.toString();
}
/**
* Default method used for unknown nodes such as nodes from a user provided
* extension.
*/
@Override
public void visit(Node node) {
write("unknown");
level++;
super.visit(node);
level--;
}
@Override
public void visit(BodyNode node) {
write("body");
level++;
super.visit(node);
level--;
}
@Override
public void visit(IfNode node) {
write("if");
level++;
super.visit(node);
level--;
}
@Override
public void visit(ForNode node) {
write("for");
level++;
super.visit(node);
level--;
}
public void visit(BinaryExpression<?> node) {
write("binary");
level++;
super.visit(node);
level--;
}
public void visit(UnaryExpression node) {
write("unary");
level++;
super.visit(node);
level--;
}
public void visit(ContextVariableExpression node) {
write(String.format("context variable [%s]", node.getName()));
level++;
super.visit(node);
level--;
}
public void visit(FilterInvocationExpression node) {
write("filter");
level++;
super.visit(node);
level--;
}
public void visit(FunctionOrMacroInvocationExpression node) {
write("function or macro");
level++;
super.visit(node);
level--;
}
public void visit(GetAttributeExpression node) {
write("get attribute");
level++;
super.visit(node);
level--;
}
@Override
public void visit(NamedArgumentNode node) {
write("named argument");
level++;
super.visit(node);
level--;
}
@Override
public void visit(ArgumentsNode node) {
write("named arguments");
level++;
super.visit(node);
level--;
}
public void visit(ParentFunctionExpression node) {
write("parent function");
level++;
super.visit(node);
level--;
}
public void visit(TernaryExpression node) {
write("ternary");
level++;
super.visit(node);
level--;
}
public void visit(TestInvocationExpression node) {
write("test");
level++;
super.visit(node);
level--;
}
@Override
public void visit(BlockNode node) {
write(String.format("block [%s]", node.getName()));
level++;
super.visit(node);
level--;
}
@Override
public void visit(FlushNode node) {
write("flush");
level++;
super.visit(node);
level--;
}
@Override
public void visit(ImportNode node) {
write("import");
level++;
super.visit(node);
level--;
}
@Override
public void visit(IncludeNode node) {
write("include");
level++;
super.visit(node);
level--;
}
@Override
public void visit(ParallelNode node) {
write("parallel");
level++;
super.visit(node);
level--;
}
@Override
public void visit(PrintNode node) {
write("print");
level++;
super.visit(node);
level--;
}
@Override
public void visit(RootNode node) {
write("root");
level++;
super.visit(node);
level--;
}
@Override
public void visit(SetNode node) {
write("set");
level++;
super.visit(node);
level--;
}
@Override
public void visit(TextNode node) {
String text = new String(node.getData());
String preview = text.length() > 10 ? text.substring(0, 10) + "..." : text;
write(String.format("text [%s]", preview));
level++;
super.visit(node);
level--;
}
}
| bsd-3-clause |
motech-implementations/mim | testing/src/main/java/org/motechproject/nms/testing/tracking/repository/DepartmentDataService.java | 263 | package org.motechproject.nms.testing.tracking.repository;
import org.motechproject.mds.service.MotechDataService;
import org.motechproject.nms.testing.tracking.domain.Department;
public interface DepartmentDataService extends MotechDataService<Department> {
}
| bsd-3-clause |
steffeli/inf5750-tracker-capture | dhis-support/dhis-support-commons/src/main/java/org/hisp/dhis/commons/sqlfunc/OneIfZeroOrPositiveSqlFunction.java | 2234 | package org.hisp.dhis.commons.sqlfunc;
/*
* Copyright (c) 2004-2015, University of Oslo
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 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.
* Neither the name of the HISP project 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.
*/
/**
* Function which evaluates numerical values to one if zero or positive, zero
* if negative or null.
*
* @author Lars Helge Overland
*/
public class OneIfZeroOrPositiveSqlFunction
implements SqlFunction
{
public static final String KEY = "oizp";
@Override
public String evaluate( String... args )
{
if ( args == null || args.length != 1 )
{
throw new IllegalArgumentException( "Illegal arguments, expected 1 argument: value" );
}
String value = args[0];
return "coalesce(case when " + value + " >= 0 then 1 else 0 end, 0)";
}
}
| bsd-3-clause |
samlanning/pebble | src/main/java/com/mitchellbosecke/pebble/operator/Associativity.java | 465 | /*******************************************************************************
* This file is part of Pebble.
*
* Copyright (c) 2014 by Mitchell Bösecke
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
******************************************************************************/
package com.mitchellbosecke.pebble.operator;
public enum Associativity {
LEFT, RIGHT;
}
| bsd-3-clause |
ngs-doo/dsl-json | library/src/test/java/com/dslplatform/json/generated/types/Long/NullableListOfOneLongsDefaultValueTurtle.java | 2720 | package com.dslplatform.json.generated.types.Long;
import com.dslplatform.json.generated.types.StaticJson;
import com.dslplatform.json.generated.ocd.javaasserts.LongAsserts;
import java.io.IOException;
public class NullableListOfOneLongsDefaultValueTurtle {
private static StaticJson.JsonSerialization jsonSerialization;
@org.junit.BeforeClass
public static void initializeJsonSerialization() throws IOException {
jsonSerialization = StaticJson.getSerialization();
}
@org.junit.Test
public void testDefaultValueEquality() throws IOException {
final java.util.List<Long> defaultValue = null;
final StaticJson.Bytes defaultValueJsonSerialized = jsonSerialization.serialize(defaultValue);
final java.util.List<Long> defaultValueJsonDeserialized = jsonSerialization.deserializeList(Long.class, defaultValueJsonSerialized.content, defaultValueJsonSerialized.length);
LongAsserts.assertNullableListOfOneEquals(defaultValue, defaultValueJsonDeserialized);
}
@org.junit.Test
public void testBorderValue1Equality() throws IOException {
final java.util.List<Long> borderValue1 = new java.util.ArrayList<Long>(java.util.Arrays.asList(0L));
final StaticJson.Bytes borderValue1JsonSerialized = jsonSerialization.serialize(borderValue1);
final java.util.List<Long> borderValue1JsonDeserialized = jsonSerialization.deserializeList(Long.class, borderValue1JsonSerialized.content, borderValue1JsonSerialized.length);
LongAsserts.assertNullableListOfOneEquals(borderValue1, borderValue1JsonDeserialized);
}
@org.junit.Test
public void testBorderValue2Equality() throws IOException {
final java.util.List<Long> borderValue2 = new java.util.ArrayList<Long>(java.util.Arrays.asList(Long.MAX_VALUE));
final StaticJson.Bytes borderValue2JsonSerialized = jsonSerialization.serialize(borderValue2);
final java.util.List<Long> borderValue2JsonDeserialized = jsonSerialization.deserializeList(Long.class, borderValue2JsonSerialized.content, borderValue2JsonSerialized.length);
LongAsserts.assertNullableListOfOneEquals(borderValue2, borderValue2JsonDeserialized);
}
@org.junit.Test
public void testBorderValue3Equality() throws IOException {
final java.util.List<Long> borderValue3 = new java.util.ArrayList<Long>(java.util.Arrays.asList(0L, 1L, 1000000000000000000L, -1000000000000000000L, Long.MIN_VALUE, Long.MAX_VALUE));
final StaticJson.Bytes borderValue3JsonSerialized = jsonSerialization.serialize(borderValue3);
final java.util.List<Long> borderValue3JsonDeserialized = jsonSerialization.deserializeList(Long.class, borderValue3JsonSerialized.content, borderValue3JsonSerialized.length);
LongAsserts.assertNullableListOfOneEquals(borderValue3, borderValue3JsonDeserialized);
}
}
| bsd-3-clause |
KingBowser/hatter-source-code | tools/winstone/src/java/javax/servlet/GenericServlet.java | 1733 | /*
* Copyright 2003-2006 Rick Knowles <winstone-devel at lists sourceforge net>
* Distributed under the terms of either:
* - the common development and distribution license (CDDL), v1.0; or
* - the GNU Lesser General Public License, v2.1 or later
*/
package javax.servlet;
import java.io.IOException;
import java.io.Serializable;
import java.util.Enumeration;
/**
* The base class from which all servlets extend.
*
* @author <a href="mailto:rick_knowles@hotmail.com">Rick Knowles</a>
*/
public abstract class GenericServlet implements Servlet, ServletConfig,
Serializable {
private ServletConfig config;
public GenericServlet() {
}
public String getInitParameter(String name) {
return config.getInitParameter(name);
}
public Enumeration getInitParameterNames() {
return config.getInitParameterNames();
}
public ServletConfig getServletConfig() {
return this.config;
}
public void init(ServletConfig config) throws ServletException {
this.config = config;
init();
}
public void init() throws ServletException {
}
public void destroy() {
}
public ServletContext getServletContext() {
return config.getServletContext();
}
public String getServletInfo() {
return "";
}
public String getServletName() {
return config.getServletName();
}
public void log(String msg) {
config.getServletContext().log(msg);
}
public void log(String message, Throwable t) {
config.getServletContext().log(message, t);
}
public abstract void service(ServletRequest req, ServletResponse res)
throws IOException, ServletException;
}
| bsd-3-clause |
hzhao/galago-git | core/src/main/java/org/lemurproject/galago/core/links/pagerank/TypeFileWriter.java | 2596 | /*
* BSD License (http://lemurproject.org/galago-license)
*/
package org.lemurproject.galago.core.links.pagerank;
import java.io.File;
import java.io.IOException;
import org.lemurproject.galago.tupleflow.CompressionType;
import org.lemurproject.galago.utility.debug.Counter;
import org.lemurproject.galago.tupleflow.runtime.FileOrderedWriter;
import org.lemurproject.galago.tupleflow.Order;
import org.lemurproject.galago.utility.Parameters;
import org.lemurproject.galago.tupleflow.Processor;
import org.lemurproject.galago.tupleflow.TupleFlowParameters;
import org.lemurproject.galago.tupleflow.Type;
import org.lemurproject.galago.tupleflow.execution.ErrorStore;
import org.lemurproject.galago.tupleflow.execution.Verification;
import org.lemurproject.galago.tupleflow.execution.Verified;
/**
*
* @author sjh
*/
@Verified
public class TypeFileWriter<T> implements Processor<T> {
Processor<T> writer;
Counter counter;
long count;
private final File outFile;
public TypeFileWriter(TupleFlowParameters p) throws Exception {
String outputClass = p.getJSON().get("class", "");
String[] orderSpec = p.getJSON().get("order", "").split(" ");
CompressionType c = CompressionType.fromString(p.getJSON().get("compression", "GZIP"));
Type output = (Type) Class.forName(outputClass).getConstructor().newInstance();
Order order = output.getOrder(orderSpec);
outFile = new File(p.getJSON().getString("outputFile") + p.getInstanceId());
writer = new FileOrderedWriter(outFile.getAbsolutePath(), order, c);
counter = p.getCounter("Objects Written");
count = 0;
}
@Override
public void process(T t) throws IOException {
writer.process(t);
count += 1;
counter.increment();
}
@Override
public void close() throws IOException {
writer.close();
// ensure we don't leave empty files around.
if (count == 0) {
outFile.delete();
}
}
public static String getInputClass(TupleFlowParameters parameters) {
return parameters.getJSON().get("class", "");
}
public static void verify(TupleFlowParameters fullParameters, ErrorStore store) {
Parameters parameters = fullParameters.getJSON();
String[] requiredParameters = {"class", "order", "outputFile"};
if (!Verification.requireParameters(requiredParameters, parameters, store)) {
return;
}
String className = parameters.getString("class");
String[] orderSpec = parameters.getString("order").split(" ");
Verification.requireClass(className, store);
Verification.requireOrder(className, orderSpec, store);
}
}
| bsd-3-clause |
jenkinsci/jaxen | src/java/main/org/jaxen/expr/iter/IterablePrecedingAxis.java | 2839 | /*
* $Header$
* $Revision: 1162 $
* $Date: 2006-06-03 13:52:26 -0700 (Sat, 03 Jun 2006) $
*
* ====================================================================
*
* Copyright 2000-2002 bob mcwhirter & James Strachan.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * 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.
*
* * Neither the name of the Jaxen Project 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.
*
* ====================================================================
* This software consists of voluntary contributions made by many
* individuals on behalf of the Jaxen Project and was originally
* created by bob mcwhirter <bob@werken.com> and
* James Strachan <jstrachan@apache.org>. For more information on the
* Jaxen Project, please see <http://www.jaxen.org/>.
*
* $Id: IterablePrecedingAxis.java 1162 2006-06-03 20:52:26Z elharo $
*/
package org.jaxen.expr.iter;
import java.util.Iterator;
import org.jaxen.ContextSupport;
import org.jaxen.UnsupportedAxisException;
public class IterablePrecedingAxis extends IterableAxis
{
/**
*
*/
private static final long serialVersionUID = 587333938258540052L;
public IterablePrecedingAxis(int value)
{
super( value );
}
public Iterator iterator(Object contextNode,
ContextSupport support) throws UnsupportedAxisException
{
return support.getNavigator().getPrecedingAxisIterator( contextNode );
}
}
| bsd-3-clause |
codeaudit/Foundry | Components/LearningCore/Source/gov/sandia/cognition/learning/function/scalar/LinearVectorScalarFunction.java | 5201 | /*
* File: LinearVectorScalarFunction.java
* Authors: Justin Basilico
* Company: Sandia National Laboratories
* Project: Cognitive Foundry
*
* Copyright November 30, 2007, Sandia Corporation. Under the terms of Contract
* DE-AC04-94AL85000, there is a non-exclusive license for use of this work by
* or on behalf of the U.S. Government. Export of this program may require a
* license from the United States Government. See CopyrightHistory.txt for
* complete details.
*
*/
package gov.sandia.cognition.learning.function.scalar;
import gov.sandia.cognition.learning.function.regression.AbstractRegressor;
import gov.sandia.cognition.annotation.CodeReview;
import gov.sandia.cognition.math.matrix.Vector;
import gov.sandia.cognition.math.matrix.Vectorizable;
import gov.sandia.cognition.util.ObjectUtil;
/**
* The <code>LinearVectorScalarFunction</code> class implements a scalar
* function that is implemented by a linear function. More formally, the
* scalar function is parameterized by a weight vector (w) and a bias (b) and
* computes the output for a given input (x) as:
*
* f(x) = w * x + b
*
* @author Justin Basilico
* @since 2.0
*/
@CodeReview(
reviewer="Kevin R. Dixon",
date="2009-07-06",
changesNeeded=false,
comments={
"Made clone() call super.clone().",
"Otherwise, class looks fine."
}
)
public class LinearVectorScalarFunction
extends AbstractRegressor<Vectorizable>
{
/** The default bias is 0.0. */
public static final double DEFAULT_BIAS = 0.0;
/** The weight vector. */
private Vector weights;
/** The bias term. */
private double bias;
/**
* Creates a new instance of LinearVectorScalarFunction.
*/
public LinearVectorScalarFunction()
{
this((Vector) null);
}
/**
* Creates a new instance of LinearVectorScalarFunction.
* @param weights The weight vector.
*/
public LinearVectorScalarFunction(
final Vector weights)
{
this(weights, DEFAULT_BIAS);
}
/**
* Creates a new instance of LinearVectorScalarFunction with the given
* weights and bias.
*
* @param weights The weight vector.
* @param bias The bias term.
*/
public LinearVectorScalarFunction(
final Vector weights,
final double bias)
{
super();
this.setWeights(weights);
this.setBias(bias);
}
/**
* Creates a new copy of a LinearVectorScalarFunction.
*
* @param other The LinearVectorScalarFunction to copy.
*/
public LinearVectorScalarFunction(
final LinearVectorScalarFunction other)
{
this(ObjectUtil.cloneSafe(other.getWeights()), other.getBias());
}
@Override
public LinearVectorScalarFunction clone()
{
LinearVectorScalarFunction clone =
(LinearVectorScalarFunction) super.clone();
clone.setWeights( ObjectUtil.cloneSafe(this.getWeights()) );
return clone;
}
/**
* Evaluate the given input vector as a double by:
*
* weights * input + bias
*
* @param input The input vector to evaluate.
* @return Evaluated input.
*/
@Override
public double evaluateAsDouble(
final Vectorizable input)
{
return this.evaluateAsDouble(input.convertToVector());
}
/**
* A convenience method for evaluating a Vector object as a double, thus
* avoiding the convertToVector call from Vectorizable. It calculates:
*
* weights * input + bias
*
* @param input
* The input value to convert to a vector.
* @return
* The double result of multiplying the weight vector times the given
* vector and adding the bias. If the weight vector is null, bias is
* returned.
*/
public double evaluateAsDouble(
final Vector input)
{
if (this.weights == null)
{
// In the case the weights are uninitialized the result is the bias.
return this.bias;
}
else
{
return input.dotProduct(this.weights) + this.bias;
}
}
/**
* Gets the weight vector.
*
* @return The weight vector.
*/
public Vector getWeights()
{
return this.weights;
}
/**
* Sets the weight vector.
*
* @param weights The weight vector.
*/
public void setWeights(
final Vector weights)
{
this.weights = weights;
}
/**
* Gets the bias term.
*
* @return The bias term.
*/
public double getBias()
{
return this.bias;
}
/**
* Sets the bias term.
*
* @param bias The bias term.
*/
public void setBias(
final double bias)
{
this.bias = bias;
}
@Override
public String toString()
{
return "Linear Vector Scalar Function "
+ "(weights = " + this.getWeights() + ", "
+ "bias = " + this.getBias() + ")";
}
}
| bsd-3-clause |
dhis2/dhis2-core | dhis-2/dhis-services/dhis-service-dxf2/src/main/java/org/hisp/dhis/dxf2/events/event/TestSkipLockedProvider.java | 1879 | /*
* Copyright (c) 2004-2022, University of Oslo
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 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.
* Neither the name of the HISP project 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.hisp.dhis.dxf2.events.event;
import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Service;
@Service
@Profile( "test" )
public class TestSkipLockedProvider implements SkipLockedProvider
{
@Override
public String getSkipLocked()
{
return "";
}
}
| bsd-3-clause |
codeaudit/Foundry | Components/LearningCore/Source/gov/sandia/cognition/learning/algorithm/minimization/line/interpolator/AbstractLineBracketInterpolatorPolynomial.java | 3565 | /*
* File: AbstractLineBracketInterpolatorPolynomial.java
* Authors: Kevin R. Dixon
* Company: Sandia National Laboratories
* Project: Cognitive Foundry
*
* Copyright Jun 17, 2008, Sandia Corporation.
* Under the terms of Contract DE-AC04-94AL85000, there is a non-exclusive
* license for use of this work by or on behalf of the U.S. Government.
* Export of this program may require a license from the United States
* Government. See CopyrightHistory.txt for complete details.
*
*/
package gov.sandia.cognition.learning.algorithm.minimization.line.interpolator;
import gov.sandia.cognition.evaluator.Evaluator;
import gov.sandia.cognition.learning.algorithm.minimization.line.LineBracket;
import gov.sandia.cognition.learning.function.scalar.PolynomialFunction;
/**
* Partial implementation of a LineBracketInterpolator based on a closed-form
* polynomial function.
* @param <EvaluatorType> Type of Evaluator to consider
* @author Kevin R. Dixon
* @since 2.2
*/
public abstract class AbstractLineBracketInterpolatorPolynomial<EvaluatorType extends Evaluator<Double,Double>>
extends AbstractLineBracketInterpolator<EvaluatorType>
{
/**
* Creates a new instance of AbstractLineBracketInterpolatorPolynomial
* @param tolerance
* Collinear tolerance of the algorithm.
*/
public AbstractLineBracketInterpolatorPolynomial(
double tolerance )
{
super( tolerance );
}
public double findMinimum(
LineBracket bracket,
double minx,
double maxx,
EvaluatorType function )
{
// Compute the interpolating polynomial first
PolynomialFunction.ClosedForm interpolator =
this.computePolynomial( bracket, function );
//Find the optimal stationary point within the required interval
double fstar = Double.POSITIVE_INFINITY;
double xstar = 0.0;
Double[] stationaryPoints = interpolator.stationaryPoints();
for( int i = 0; i < stationaryPoints.length; i++ )
{
double x = stationaryPoints[i];
if( (minx <= x) && (x <= maxx) )
{
double f = interpolator.evaluate( x );
if( fstar > f )
{
fstar = f;
xstar = x;
}
}
}
// Find the lowest-value bound on the interval
double bestBoundx;
double bestBoundfx;
double fminx = interpolator.evaluate( minx );
double fmaxx = interpolator.evaluate( maxx );
if( fminx < fmaxx )
{
bestBoundx = minx;
bestBoundfx = fminx;
}
else
{
bestBoundx = maxx;
bestBoundfx = fmaxx;
}
// return the best of the stationary points OR the interval bound
double bestx;
if( fstar <= bestBoundfx )
{
bestx = xstar;
}
else
{
bestx = bestBoundx;
}
return bestx;
}
/**
* Fits the interpolating polynomial to the given LineBracket
* @param bracket
* LineBracket to consider
* @param function
* Function to use to fill in missing information
* @return
* Interpolating polynomial
*/
public abstract PolynomialFunction.ClosedForm computePolynomial(
LineBracket bracket,
EvaluatorType function );
}
| bsd-3-clause |
xdv/ripple-lib-java | ripple-bouncycastle/src/main/java/org/ripple/bouncycastle/jcajce/provider/asymmetric/ecgost/KeyPairGeneratorSpi.java | 6733 | package org.ripple.bouncycastle.jcajce.provider.asymmetric.ecgost;
import java.math.BigInteger;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidParameterException;
import java.security.KeyPair;
import java.security.SecureRandom;
import java.security.spec.AlgorithmParameterSpec;
import java.security.spec.ECGenParameterSpec;
import org.ripple.bouncycastle.asn1.cryptopro.ECGOST3410NamedCurves;
import org.ripple.bouncycastle.crypto.AsymmetricCipherKeyPair;
import org.ripple.bouncycastle.crypto.generators.ECKeyPairGenerator;
import org.ripple.bouncycastle.crypto.params.ECDomainParameters;
import org.ripple.bouncycastle.crypto.params.ECKeyGenerationParameters;
import org.ripple.bouncycastle.crypto.params.ECPrivateKeyParameters;
import org.ripple.bouncycastle.crypto.params.ECPublicKeyParameters;
import org.ripple.bouncycastle.jcajce.provider.asymmetric.util.EC5Util;
import org.ripple.bouncycastle.jce.provider.BouncyCastleProvider;
import org.ripple.bouncycastle.jce.spec.ECNamedCurveGenParameterSpec;
import org.ripple.bouncycastle.jce.spec.ECNamedCurveSpec;
import org.ripple.bouncycastle.jce.spec.ECParameterSpec;
import org.ripple.bouncycastle.math.ec.ECCurve;
import org.ripple.bouncycastle.math.ec.ECPoint;
public class KeyPairGeneratorSpi
extends java.security.KeyPairGenerator
{
Object ecParams = null;
ECKeyPairGenerator engine = new ECKeyPairGenerator();
String algorithm = "ECGOST3410";
ECKeyGenerationParameters param;
int strength = 239;
SecureRandom random = null;
boolean initialised = false;
public KeyPairGeneratorSpi()
{
super("ECGOST3410");
}
public void initialize(
int strength,
SecureRandom random)
{
this.strength = strength;
this.random = random;
if (ecParams != null)
{
try
{
initialize((ECGenParameterSpec)ecParams, random);
}
catch (InvalidAlgorithmParameterException e)
{
throw new InvalidParameterException("key size not configurable.");
}
}
else
{
throw new InvalidParameterException("unknown key size.");
}
}
public void initialize(
AlgorithmParameterSpec params,
SecureRandom random)
throws InvalidAlgorithmParameterException
{
if (params instanceof ECParameterSpec)
{
ECParameterSpec p = (ECParameterSpec)params;
this.ecParams = params;
param = new ECKeyGenerationParameters(new ECDomainParameters(p.getCurve(), p.getG(), p.getN()), random);
engine.init(param);
initialised = true;
}
else if (params instanceof java.security.spec.ECParameterSpec)
{
java.security.spec.ECParameterSpec p = (java.security.spec.ECParameterSpec)params;
this.ecParams = params;
ECCurve curve = EC5Util.convertCurve(p.getCurve());
ECPoint g = EC5Util.convertPoint(curve, p.getGenerator(), false);
param = new ECKeyGenerationParameters(new ECDomainParameters(curve, g, p.getOrder(), BigInteger.valueOf(p.getCofactor())), random);
engine.init(param);
initialised = true;
}
else if (params instanceof ECGenParameterSpec || params instanceof ECNamedCurveGenParameterSpec)
{
String curveName;
if (params instanceof ECGenParameterSpec)
{
curveName = ((ECGenParameterSpec)params).getName();
}
else
{
curveName = ((ECNamedCurveGenParameterSpec)params).getName();
}
ECDomainParameters ecP = ECGOST3410NamedCurves.getByName(curveName);
if (ecP == null)
{
throw new InvalidAlgorithmParameterException("unknown curve name: " + curveName);
}
this.ecParams = new ECNamedCurveSpec(
curveName,
ecP.getCurve(),
ecP.getG(),
ecP.getN(),
ecP.getH(),
ecP.getSeed());
java.security.spec.ECParameterSpec p = (java.security.spec.ECParameterSpec)ecParams;
ECCurve curve = EC5Util.convertCurve(p.getCurve());
ECPoint g = EC5Util.convertPoint(curve, p.getGenerator(), false);
param = new ECKeyGenerationParameters(new ECDomainParameters(curve, g, p.getOrder(), BigInteger.valueOf(p.getCofactor())), random);
engine.init(param);
initialised = true;
}
else if (params == null && BouncyCastleProvider.CONFIGURATION.getEcImplicitlyCa() != null)
{
ECParameterSpec p = BouncyCastleProvider.CONFIGURATION.getEcImplicitlyCa();
this.ecParams = params;
param = new ECKeyGenerationParameters(new ECDomainParameters(p.getCurve(), p.getG(), p.getN()), random);
engine.init(param);
initialised = true;
}
else if (params == null && BouncyCastleProvider.CONFIGURATION.getEcImplicitlyCa() == null)
{
throw new InvalidAlgorithmParameterException("null parameter passed but no implicitCA set");
}
else
{
throw new InvalidAlgorithmParameterException("parameter object not a ECParameterSpec: " + params.getClass().getName());
}
}
public KeyPair generateKeyPair()
{
if (!initialised)
{
throw new IllegalStateException("EC Key Pair Generator not initialised");
}
AsymmetricCipherKeyPair pair = engine.generateKeyPair();
ECPublicKeyParameters pub = (ECPublicKeyParameters)pair.getPublic();
ECPrivateKeyParameters priv = (ECPrivateKeyParameters)pair.getPrivate();
if (ecParams instanceof ECParameterSpec)
{
ECParameterSpec p = (ECParameterSpec)ecParams;
BCECGOST3410PublicKey pubKey = new BCECGOST3410PublicKey(algorithm, pub, p);
return new KeyPair(pubKey,
new BCECGOST3410PrivateKey(algorithm, priv, pubKey, p));
}
else if (ecParams == null)
{
return new KeyPair(new BCECGOST3410PublicKey(algorithm, pub),
new BCECGOST3410PrivateKey(algorithm, priv));
}
else
{
java.security.spec.ECParameterSpec p = (java.security.spec.ECParameterSpec)ecParams;
BCECGOST3410PublicKey pubKey = new BCECGOST3410PublicKey(algorithm, pub, p);
return new KeyPair(pubKey, new BCECGOST3410PrivateKey(algorithm, priv, pubKey, p));
}
}
}
| isc |
joda17/Diorite-API | src/main/java/org/diorite/cfg/annotations/CfgFooterCommentsArray.java | 525 | package org.diorite.cfg.annotations;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Used by {@link CfgFooterComment} for {@link java.lang.annotation.Repeatable} annotations.
*/
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD, ElementType.TYPE})
public @interface CfgFooterCommentsArray
{
/**
* @return all single comments annotations.
*/
CfgFooterComment[] value();
}
| mit |
devgateway/oc-explorer | persistence-mongodb/src/main/java/org/devgateway/ocds/persistence/mongo/spring/ReflectionsConfiguration.java | 1204 | /**
*
*/
package org.devgateway.ocds.persistence.mongo.spring;
import org.reflections.Reflections;
import org.reflections.scanners.FieldAnnotationsScanner;
import org.reflections.scanners.MethodParameterScanner;
import org.reflections.scanners.SubTypesScanner;
import org.reflections.util.ClasspathHelper;
import org.reflections.util.ConfigurationBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* @author mpostelnicu
*
*/
@Configuration
public class ReflectionsConfiguration {
protected static final Logger logger = LoggerFactory.getLogger(ReflectionsConfiguration.class);
@Bean
public Reflections reflections() {
logger.debug("Starting reflections scanners...");
Reflections reflections = new Reflections(new ConfigurationBuilder()
.setUrls(ClasspathHelper.forPackage("org.devgateway.ocds.persistence.mongo"))
.setScanners(new SubTypesScanner(), new FieldAnnotationsScanner(), new MethodParameterScanner()));
logger.debug("Configured reflections bean.");
return reflections;
}
}
| mit |
alexstyl/Memento-Calendar | android_mobile/src/main/java/com/alexstyl/specialdates/addevent/DiscardPromptDialog.java | 1330 | package com.alexstyl.specialdates.addevent;
import android.app.Activity;
import android.app.Dialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.app.AlertDialog;
import com.alexstyl.specialdates.R;
import com.alexstyl.specialdates.ui.base.MementoDialog;
import com.novoda.notils.caster.Classes;
public class DiscardPromptDialog extends MementoDialog {
interface Listener {
void onDiscardChangesSelected();
}
private Listener listener;
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
listener = Classes.from(activity);
}
@NonNull
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
return new AlertDialog.Builder(getActivity())
.setTitle(R.string.add_event_discard_changes_title)
.setPositiveButton(R.string.add_event_discard_changes_accept, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
listener.onDiscardChangesSelected();
}
})
.setNegativeButton(android.R.string.no, null)
.create();
}
}
| mit |
ronaldoWang/My_XDroidMvp | mvp/src/main/java/cn/droidlover/xdroidmvp/router/Router.java | 5792 | package cn.droidlover.xdroidmvp.router;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Parcelable;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.ActivityOptionsCompat;
import java.io.Serializable;
import java.util.ArrayList;
import cn.droidlover.xdroidmvp.XDroidConf;
/**
* Created by wanglei on 2016/11/29.
*/
public class Router {
private Intent intent;
private Activity from;
private Class<?> to;
private Bundle data;
private ActivityOptionsCompat options;
private int requestCode = -1;
private int enterAnim = XDroidConf.ROUTER_ANIM_ENTER;
private int exitAnim = XDroidConf.ROUTER_ANIM_EXIT;
public static final int RES_NONE = -1;
private static RouterCallback callback;
private Router() {
intent = new Intent();
}
public static Router newIntent(Activity context) {
Router router = new Router();
router.from = context;
return router;
}
public Router to(Class<?> to) {
this.to = to;
return this;
}
public Router addFlags(int flags) {
if (intent != null) {
intent.addFlags(flags);
}
return this;
}
public Router data(Bundle data) {
this.data = data;
return this;
}
public Router putByte(@Nullable String key, byte value) {
getBundleData().putByte(key, value);
return this;
}
public Router putChar(@Nullable String key, char value) {
getBundleData().putChar(key, value);
return this;
}
public Router putInt(@Nullable String key, int value) {
getBundleData().putInt(key, value);
return this;
}
public Router putString(@Nullable String key, String value) {
getBundleData().putString(key, value);
return this;
}
public Router putShort(@Nullable String key, short value) {
getBundleData().putShort(key, value);
return this;
}
public Router putFloat(@Nullable String key, float value) {
getBundleData().putFloat(key, value);
return this;
}
public Router putCharSequence(@Nullable String key, @Nullable CharSequence value) {
getBundleData().putCharSequence(key, value);
return this;
}
public Router putParcelable(@Nullable String key, @Nullable Parcelable value) {
getBundleData().putParcelable(key, value);
return this;
}
public Router putParcelableArray(@Nullable String key, @Nullable Parcelable[] value) {
getBundleData().putParcelableArray(key, value);
return this;
}
public Router putParcelableArrayList(@Nullable String key,
@Nullable ArrayList<? extends Parcelable> value) {
getBundleData().putParcelableArrayList(key, value);
return this;
}
public Router putIntegerArrayList(@Nullable String key, @Nullable ArrayList<Integer> value) {
getBundleData().putIntegerArrayList(key, value);
return this;
}
public Router putStringArrayList(@Nullable String key, @Nullable ArrayList<String> value) {
getBundleData().putStringArrayList(key, value);
return this;
}
public Router putCharSequenceArrayList(@Nullable String key,
@Nullable ArrayList<CharSequence> value) {
getBundleData().putCharSequenceArrayList(key, value);
return this;
}
public Router putSerializable(@Nullable String key, @Nullable Serializable value) {
getBundleData().putSerializable(key, value);
return this;
}
public Router options(ActivityOptionsCompat options) {
this.options = options;
return this;
}
public Router requestCode(int requestCode) {
this.requestCode = requestCode;
return this;
}
public Router anim(int enterAnim, int exitAnim) {
this.enterAnim = enterAnim;
this.exitAnim = exitAnim;
return this;
}
public void launch() {
try {
if (intent != null && from != null && to != null) {
if (callback != null) {
callback.onBefore(from, to);
}
intent.setClass(from, to);
intent.putExtras(getBundleData());
if (options == null) {
if (requestCode < 0) {
from.startActivity(intent);
} else {
from.startActivityForResult(intent, requestCode);
}
if (enterAnim > 0 && exitAnim > 0) {
from.overridePendingTransition(enterAnim, exitAnim);
}
} else {
if (requestCode < 0) {
ActivityCompat.startActivity(from, intent, options.toBundle());
} else {
ActivityCompat.startActivityForResult(from, intent, requestCode, options.toBundle());
}
}
if (callback != null) {
callback.onNext(from, to);
}
}
} catch (Throwable throwable) {
if (callback != null) {
callback.onError(from, to, throwable);
}
}
}
private Bundle getBundleData() {
if (data == null) {
data = new Bundle();
}
return data;
}
public static void pop(Activity activity) {
activity.finish();
}
public static void setCallback(RouterCallback callback) {
Router.callback = callback;
}
}
| mit |
dashorst/dea-code-examples | exercises/solid/1.SRP/src/main/java/nl/oose/dea/orderservice/withoutsrp/Item.java | 408 | package nl.oose.dea.orderservice.withoutsrp;
public class Item {
// SKU' A store's or catalog's product and service identification code, often portrayed as a
// machine-readable bar code that helps the item to be tracked for inventory.
public String sku;
public int quantity;
public Item(String sku, int quantity)
{
this.sku = sku;
this.quantity = quantity;
}
}
| mit |
stevenuray/XChange | xchange-bitfinex/src/main/java/org/knowm/xchange/bitfinex/v1/dto/trade/BitfinexActivePositionsResponse.java | 2393 | package org.knowm.xchange.bitfinex.v1.dto.trade;
import java.math.BigDecimal;
import org.knowm.xchange.dto.Order.OrderType;
import com.fasterxml.jackson.annotation.JsonProperty;
public class BitfinexActivePositionsResponse {
private final int id;
private final String symbol;
private final String status;
private final BigDecimal base;
private final BigDecimal amount;
private final BigDecimal timestamp;
private final BigDecimal swap;
private final BigDecimal pnl;
private final OrderType orderType;
public BitfinexActivePositionsResponse(@JsonProperty("id") int id, @JsonProperty("symbol") String symbol, @JsonProperty("status") String status,
@JsonProperty("base") BigDecimal base, @JsonProperty("amount") BigDecimal amount, @JsonProperty("timestamp") BigDecimal timestamp,
@JsonProperty("swap") BigDecimal swap, @JsonProperty("pl") BigDecimal pnl) {
this.id = id;
this.symbol = symbol;
this.status = status;
this.base = base;
this.amount = amount;
this.timestamp = timestamp;
this.swap = swap;
this.pnl = pnl;
this.orderType = amount.signum() < 0 ? OrderType.ASK : OrderType.BID;
}
public int getId() {
return id;
}
public String getSymbol() {
return symbol;
}
public String getStatus() {
return status;
}
public BigDecimal getBase() {
return base;
}
public BigDecimal getAmount() {
return amount;
}
public BigDecimal getTimestamp() {
return timestamp;
}
public BigDecimal getSwap() {
return swap;
}
public BigDecimal getPnl() {
return pnl;
}
public OrderType getOrderType() {
return orderType;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("BitfinexActivePositionsResponse [id=");
builder.append(id);
builder.append(", symbol=");
builder.append(symbol);
builder.append(", status=");
builder.append(status);
builder.append(", base=");
builder.append(base);
builder.append(", amount=");
builder.append(amount);
builder.append(", timestamp=");
builder.append(timestamp);
builder.append(", swap=");
builder.append(swap);
builder.append(", pnl=");
builder.append(pnl);
builder.append(", orderType=");
builder.append(orderType);
builder.append("]");
return builder.toString();
}
}
| mit |
drbgfc/mdht | cts2/plugins/org.openhealthtools.mdht.cts2.core/src/org/openhealthtools/mdht/cts2/core/Example.java | 1123 | /*******************************************************************************
* Copyright (c) 2012 David A Carlson.
* 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
*
* Contributors:
* David A Carlson (XMLmodeling.com) - initial API and implementation
*******************************************************************************/
package org.openhealthtools.mdht.cts2.core;
/**
* <!-- begin-user-doc -->
* A representation of the model object '<em><b>Example</b></em>'.
* <!-- end-user-doc -->
*
* <!-- begin-model-doc -->
* An example. See: <a href="//http://www.w3.org/TR/skos-reference/#L1693" xmlns="http://schema.omg.org/spec/CTS2/1.0/Core">skos:example</a>
*
* <!-- end-model-doc -->
*
*
* @see org.openhealthtools.mdht.cts2.core.CorePackage#getExample()
* @model extendedMetaData="name='Example' kind='elementOnly'"
* @generated
*/
public interface Example extends Note {
} // Example
| epl-1.0 |
sgilda/windup | rules-java/api/src/main/java/org/jboss/windup/rules/apps/java/ip/StaticIPLocationModel.java | 377 | package org.jboss.windup.rules.apps.java.ip;
import org.jboss.windup.reporting.model.InlineHintModel;
import com.tinkerpop.frames.modules.typedgraph.TypeValue;
/**
* Contains the location of a static ip within a file
*
*/
@TypeValue(StaticIPLocationModel.TYPE)
public interface StaticIPLocationModel extends InlineHintModel
{
String TYPE = "StaticIPLocationModel";
}
| epl-1.0 |
darionct/kura | kura/examples/org.eclipse.kura.example.eddystone.scanner/src/main/java/org/eclipse/kura/example/eddystone/scanner/EddystoneScannerOptions.java | 2583 | /*******************************************************************************
* Copyright (c) 2017, 2018 Eurotech and/or its affiliates
*
* 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.eclipse.kura.example.eddystone.scanner;
import static java.util.Objects.requireNonNull;
import java.util.Map;
public class EddystoneScannerOptions {
private static final String PROPERTY_ENABLE = "enable.scanning";
private static final String PROPERTY_INAME = "iname";
private static final String PROPERTY_PUBLISH_PERIOD = "publish.period";
private static final String PROPERTY_SCAN_DURATION = "scan.duration";
private static final boolean PROPERTY_ENABLE_DEFAULT = false;
private static final String PROPERTY_INAME_DEFAULT = "hci0";
private static final int PROPERTY_PUBLISH_PERIOD_DEFAULT = 10;
private static final int PROPERTY_SCAN_DURATION_DEFAULT = 60;
private final boolean enableScanning;
private final String adapterName;
private final int publishPeriod;
private final int scanDuration;
public EddystoneScannerOptions(Map<String, Object> properties) {
requireNonNull(properties, "Required not null");
this.enableScanning = getProperty(properties, PROPERTY_ENABLE, PROPERTY_ENABLE_DEFAULT);
this.adapterName = getProperty(properties, PROPERTY_INAME, PROPERTY_INAME_DEFAULT);
this.publishPeriod = getProperty(properties, PROPERTY_PUBLISH_PERIOD, PROPERTY_PUBLISH_PERIOD_DEFAULT);
this.scanDuration = getProperty(properties, PROPERTY_SCAN_DURATION, PROPERTY_SCAN_DURATION_DEFAULT);
}
public boolean isEnabled() {
return this.enableScanning;
}
public String getAdapterName() {
return this.adapterName;
}
public int getPublishPeriod() {
return this.publishPeriod;
}
public int getScanDuration() {
return this.scanDuration;
}
@SuppressWarnings("unchecked")
private <T> T getProperty(Map<String, Object> properties, String propertyName, T defaultValue) {
Object prop = properties.getOrDefault(propertyName, defaultValue);
if (prop != null && prop.getClass().isAssignableFrom(defaultValue.getClass())) {
return (T) prop;
} else {
return defaultValue;
}
}
}
| epl-1.0 |
drbgfc/mdht | hl7/plugins/org.openhealthtools.mdht.emf.hl7.mif2/src/org/openhealthtools/mdht/emf/hl7/mif2/ConceptDomain.java | 11963 | /*******************************************************************************
* Copyright (c) 2006, 2009 David A Carlson
* 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
*
* Contributors:
* David A Carlson (XMLmodeling.com) - initial API and implementation
*******************************************************************************/
package org.openhealthtools.mdht.emf.hl7.mif2;
import org.eclipse.emf.common.util.EList;
/**
* <!-- begin-user-doc -->
* A representation of the model object '<em><b>Concept Domain</b></em>'.
* <!-- end-user-doc -->
*
* <!-- begin-model-doc -->
* Information about a vocabulary domain that constrains the semantic values of one or more coded attributes or datatype properties.
* UML: Stereotype on package
* <!-- end-model-doc -->
*
* <p>
* The following features are supported:
* <ul>
* <li>{@link org.openhealthtools.mdht.emf.hl7.mif2.ConceptDomain#getBusinessName <em>Business Name</em>}</li>
* <li>{@link org.openhealthtools.mdht.emf.hl7.mif2.ConceptDomain#getAnnotations <em>Annotations</em>}</li>
* <li>{@link org.openhealthtools.mdht.emf.hl7.mif2.ConceptDomain#getSpecializesDomain <em>Specializes Domain</em>}</li>
* <li>{@link org.openhealthtools.mdht.emf.hl7.mif2.ConceptDomain#getExampleConcept <em>Example Concept</em>}</li>
* <li>{@link org.openhealthtools.mdht.emf.hl7.mif2.ConceptDomain#getProperty <em>Property</em>}</li>
* <li>{@link org.openhealthtools.mdht.emf.hl7.mif2.ConceptDomain#getSpecializedByDomain <em>Specialized By Domain</em>}</li>
* <li>{@link org.openhealthtools.mdht.emf.hl7.mif2.ConceptDomain#isIsBindable <em>Is Bindable</em>}</li>
* <li>{@link org.openhealthtools.mdht.emf.hl7.mif2.ConceptDomain#getName <em>Name</em>}</li>
* <li>{@link org.openhealthtools.mdht.emf.hl7.mif2.ConceptDomain#getSortKey <em>Sort Key</em>}</li>
* </ul>
* </p>
*
* @see org.openhealthtools.mdht.emf.hl7.mif2.Mif2Package#getConceptDomain()
* @model extendedMetaData="name='ConceptDomain' kind='elementOnly'"
* @generated
*/
public interface ConceptDomain extends ModelElement {
/**
* Returns the value of the '<em><b>Business Name</b></em>' containment reference list.
* The list contents are of type {@link org.openhealthtools.mdht.emf.hl7.mif2.BusinessName}.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* <!-- begin-model-doc -->
* The business names associated with the element. CURRENT- 0..1
* UML: Tag value inherited from ModelElement
* <!-- end-model-doc -->
* @return the value of the '<em>Business Name</em>' containment reference list.
* @see org.openhealthtools.mdht.emf.hl7.mif2.Mif2Package#getConceptDomain_BusinessName()
* @model containment="true"
* extendedMetaData="kind='element' name='businessName' namespace='##targetNamespace'"
* @generated
*/
EList<BusinessName> getBusinessName();
/**
* Returns the value of the '<em><b>Annotations</b></em>' containment reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* <!-- begin-model-doc -->
* Descriptive information about this vocabulary domain.
* UML: A collector for the comments and constraints associated with a concept domain. (Consider rendering the definition or description annotation into ModelElement.documentation)
* <!-- end-model-doc -->
* @return the value of the '<em>Annotations</em>' containment reference.
* @see #setAnnotations(ConceptDomainAnnotations)
* @see org.openhealthtools.mdht.emf.hl7.mif2.Mif2Package#getConceptDomain_Annotations()
* @model containment="true"
* extendedMetaData="kind='element' name='annotations' namespace='##targetNamespace'"
* @generated
*/
ConceptDomainAnnotations getAnnotations();
/**
* Sets the value of the '{@link org.openhealthtools.mdht.emf.hl7.mif2.ConceptDomain#getAnnotations <em>Annotations</em>}' containment reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Annotations</em>' containment reference.
* @see #getAnnotations()
* @generated
*/
void setAnnotations(ConceptDomainAnnotations value);
/**
* Returns the value of the '<em><b>Specializes Domain</b></em>' containment reference list.
* The list contents are of type {@link org.openhealthtools.mdht.emf.hl7.mif2.ConceptDomainRef}.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* <!-- begin-model-doc -->
* A reference to another domain that is a proper superset of this domain.
* UML: A stereotype on dependency
* <!-- end-model-doc -->
* @return the value of the '<em>Specializes Domain</em>' containment reference list.
* @see org.openhealthtools.mdht.emf.hl7.mif2.Mif2Package#getConceptDomain_SpecializesDomain()
* @model containment="true"
* extendedMetaData="kind='element' name='specializesDomain' namespace='##targetNamespace'"
* @generated
*/
EList<ConceptDomainRef> getSpecializesDomain();
/**
* Returns the value of the '<em><b>Example Concept</b></em>' attribute list.
* The list contents are of type {@link java.lang.String}.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* <!-- begin-model-doc -->
* A textual description of a concept considered to be part of the domain. Used when domains are not bound to a universal, representative or example value set
* UML: Tag on ConceptDomain stereotype
* <!-- end-model-doc -->
* @return the value of the '<em>Example Concept</em>' attribute list.
* @see org.openhealthtools.mdht.emf.hl7.mif2.Mif2Package#getConceptDomain_ExampleConcept()
* @model unique="false" dataType="org.openhealthtools.mdht.emf.hl7.mif2.ShortDescriptiveName"
* extendedMetaData="kind='element' name='exampleConcept' namespace='##targetNamespace'"
* @generated
*/
EList<String> getExampleConcept();
/**
* Returns the value of the '<em><b>Property</b></em>' containment reference list.
* The list contents are of type {@link org.openhealthtools.mdht.emf.hl7.mif2.ConceptDomainProperty}.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* <!-- begin-model-doc -->
* A reference to a property associated with the domain.
* UML: A stereotype on dependency
* <!-- end-model-doc -->
* @return the value of the '<em>Property</em>' containment reference list.
* @see org.openhealthtools.mdht.emf.hl7.mif2.Mif2Package#getConceptDomain_Property()
* @model containment="true"
* extendedMetaData="kind='element' name='property' namespace='##targetNamespace'"
* @generated
*/
EList<ConceptDomainProperty> getProperty();
/**
* Returns the value of the '<em><b>Specialized By Domain</b></em>' containment reference list.
* The list contents are of type {@link org.openhealthtools.mdht.emf.hl7.mif2.ConceptDomainRef}.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* <!-- begin-model-doc -->
* A reference to another domain that is a proper subset of this domain.
* UML: A stereotype on dependency
* Derive: Todo
* <!-- end-model-doc -->
* @return the value of the '<em>Specialized By Domain</em>' containment reference list.
* @see org.openhealthtools.mdht.emf.hl7.mif2.Mif2Package#getConceptDomain_SpecializedByDomain()
* @model containment="true"
* extendedMetaData="kind='element' name='specializedByDomain' namespace='##targetNamespace'"
* @generated
*/
EList<ConceptDomainRef> getSpecializedByDomain();
/**
* Returns the value of the '<em><b>Is Bindable</b></em>' attribute.
* The default value is <code>"true"</code>.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* <!-- begin-model-doc -->
* Indicates whether this domain can be bound to a value-set as part of a context binding. If false, the domain can't be bound directly, though specializations might be bound. Direct substitution with valuesets in derived static models is still possible.
* UML: tag on stereotype
* <!-- end-model-doc -->
* @return the value of the '<em>Is Bindable</em>' attribute.
* @see #isSetIsBindable()
* @see #unsetIsBindable()
* @see #setIsBindable(boolean)
* @see org.openhealthtools.mdht.emf.hl7.mif2.Mif2Package#getConceptDomain_IsBindable()
* @model default="true" unsettable="true" dataType="org.eclipse.emf.ecore.xml.type.Boolean"
* extendedMetaData="kind='attribute' name='isBindable'"
* @generated
*/
boolean isIsBindable();
/**
* Sets the value of the '{@link org.openhealthtools.mdht.emf.hl7.mif2.ConceptDomain#isIsBindable <em>Is Bindable</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Is Bindable</em>' attribute.
* @see #isSetIsBindable()
* @see #unsetIsBindable()
* @see #isIsBindable()
* @generated
*/
void setIsBindable(boolean value);
/**
* Unsets the value of the '{@link org.openhealthtools.mdht.emf.hl7.mif2.ConceptDomain#isIsBindable <em>Is Bindable</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #isSetIsBindable()
* @see #isIsBindable()
* @see #setIsBindable(boolean)
* @generated
*/
void unsetIsBindable();
/**
* Returns whether the value of the '{@link org.openhealthtools.mdht.emf.hl7.mif2.ConceptDomain#isIsBindable <em>Is Bindable</em>}' attribute is set.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return whether the value of the '<em>Is Bindable</em>' attribute is set.
* @see #unsetIsBindable()
* @see #isIsBindable()
* @see #setIsBindable(boolean)
* @generated
*/
boolean isSetIsBindable();
/**
* Returns the value of the '<em><b>Name</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* <!-- begin-model-doc -->
* The unique name of the concept domain
* UML: name attribute inherited from ModelElement
* <!-- end-model-doc -->
* @return the value of the '<em>Name</em>' attribute.
* @see #setName(String)
* @see org.openhealthtools.mdht.emf.hl7.mif2.Mif2Package#getConceptDomain_Name()
* @model dataType="org.openhealthtools.mdht.emf.hl7.mif2.FormalProperName" required="true"
* extendedMetaData="kind='attribute' name='name'"
* @generated
*/
String getName();
/**
* Sets the value of the '{@link org.openhealthtools.mdht.emf.hl7.mif2.ConceptDomain#getName <em>Name</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Name</em>' attribute.
* @see #getName()
* @generated
*/
void setName(String value);
/**
* Returns the value of the '<em><b>Sort Key</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* <!-- begin-model-doc -->
* A name used in determining the sort order of the model element within its siblings.
* Impl: This will usually be a sequential number, but could be something else.
* UML: tag value within ModelElement
* <!-- end-model-doc -->
* @return the value of the '<em>Sort Key</em>' attribute.
* @see #setSortKey(String)
* @see org.openhealthtools.mdht.emf.hl7.mif2.Mif2Package#getConceptDomain_SortKey()
* @model dataType="org.openhealthtools.mdht.emf.hl7.mif2.BasicFormalName"
* extendedMetaData="kind='attribute' name='sortKey'"
* @generated
*/
String getSortKey();
/**
* Sets the value of the '{@link org.openhealthtools.mdht.emf.hl7.mif2.ConceptDomain#getSortKey <em>Sort Key</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Sort Key</em>' attribute.
* @see #getSortKey()
* @generated
*/
void setSortKey(String value);
} // ConceptDomain
| epl-1.0 |
TypeFox/che | samples/sample-plugin-wizard/che-sample-plugin-wizard-ide/src/main/java/org/eclipse/che/plugin/sample/wizard/ide/SampleWizardExtension.java | 1977 | /*
* Copyright (c) 2012-2017 Red Hat, Inc.
* 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
*
* Contributors:
* Red Hat, Inc. - initial API and implementation
*/
package org.eclipse.che.plugin.sample.wizard.ide;
import static org.eclipse.che.ide.api.action.IdeActions.GROUP_FILE_NEW;
import static org.eclipse.che.ide.api.action.IdeActions.GROUP_HELP;
import com.google.inject.Inject;
import com.google.inject.name.Named;
import org.eclipse.che.ide.api.action.ActionManager;
import org.eclipse.che.ide.api.action.DefaultActionGroup;
import org.eclipse.che.ide.api.constraints.Constraints;
import org.eclipse.che.ide.api.extension.Extension;
import org.eclipse.che.ide.api.filetypes.FileType;
import org.eclipse.che.ide.api.filetypes.FileTypeRegistry;
import org.eclipse.che.plugin.sample.wizard.ide.action.NewXFileAction;
import org.eclipse.che.plugin.sample.wizard.ide.action.SampleAction;
/** */
@Extension(title = "Sample Wizard")
public class SampleWizardExtension {
public static String X_CATEGORY = "Sample Category";
@Inject
public SampleWizardExtension(
FileTypeRegistry fileTypeRegistry, @Named("XFileType") FileType xFile) {
fileTypeRegistry.registerFileType(xFile);
}
@Inject
private void prepareActions(
SampleAction sampleAction, NewXFileAction newXFileAction, ActionManager actionManager) {
DefaultActionGroup newGroup = (DefaultActionGroup) actionManager.getAction(GROUP_HELP);
DefaultActionGroup newFileGroup = (DefaultActionGroup) actionManager.getAction(GROUP_FILE_NEW);
actionManager.registerAction("sayHello", sampleAction);
actionManager.registerAction("newFileActon", newXFileAction);
newGroup.add(sampleAction, Constraints.FIRST);
newFileGroup.add(newXFileAction, Constraints.FIRST);
}
}
| epl-1.0 |
akervern/che | core/che-core-api-core/src/main/java/org/eclipse/che/api/core/util/UnixProcessManager.java | 5828 | /*
* Copyright (c) 2012-2018 Red Hat, Inc.
* This program and the accompanying materials are made
* available under the terms of the Eclipse Public License 2.0
* which is available at https://www.eclipse.org/legal/epl-2.0/
*
* SPDX-License-Identifier: EPL-2.0
*
* Contributors:
* Red Hat, Inc. - initial API and implementation
*/
package org.eclipse.che.api.core.util;
import com.sun.jna.Library;
import com.sun.jna.Native;
import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Process manager for *nix like system.
*
* @author andrew00x
*/
class UnixProcessManager extends ProcessManager {
/*
At the moment tested on linux only.
*/
private static final Logger LOG = LoggerFactory.getLogger(UnixProcessManager.class);
private static final CLibrary C_LIBRARY;
private static final Field PID_FIELD;
private static final Method PID_METHOD;
static {
CLibrary lib = null;
Field pidField = null;
Method pidMethod = null;
if (SystemInfo.isUnix()) {
try {
lib = ((CLibrary) Native.loadLibrary("c", CLibrary.class));
} catch (Exception e) {
LOG.error("Cannot load native library", e);
}
try {
pidField =
Thread.currentThread()
.getContextClassLoader()
.loadClass("java.lang.UNIXProcess")
.getDeclaredField("pid");
pidField.setAccessible(true);
} catch (Exception e) {
// try with Java9
try {
pidMethod = Process.class.getDeclaredMethod("pid");
} catch (NoSuchMethodException e1) {
LOG.error(e1.getMessage(), e1);
}
}
}
C_LIBRARY = lib;
PID_FIELD = pidField;
PID_METHOD = pidMethod;
}
private static interface CLibrary extends Library {
// kill -l
int SIGKILL = 9;
int SIGTERM = 15;
int kill(int pid, int signal);
String strerror(int errno);
int system(String cmd);
}
private static final Pattern UNIX_PS_TABLE_PATTERN = Pattern.compile("\\s+");
@Override
public void kill(Process process) {
if (C_LIBRARY != null) {
killTree(getPid(process));
} else {
throw new IllegalStateException("Can't kill process. Not unix system?");
}
}
private void killTree(int pid) {
final int[] children = getChildProcesses(pid);
LOG.debug("PID: {}, child PIDs: {}", pid, children);
if (children.length > 0) {
for (int cpid : children) {
killTree(cpid); // kill process tree recursively
}
}
int r = C_LIBRARY.kill(pid, CLibrary.SIGKILL); // kill origin process
LOG.debug("kill {}", pid);
if (r != 0) {
if (LOG.isDebugEnabled()) {
LOG.debug("kill for {} returns {}, strerror '{}'", pid, r, C_LIBRARY.strerror(r));
}
}
}
private int[] getChildProcesses(final int myPid) {
final String ps = "ps -e -o ppid,pid,comm"; /* PPID, PID, COMMAND */
final List<Integer> children = new ArrayList<>();
final StringBuilder error = new StringBuilder();
final LineConsumer stdout =
new LineConsumer() {
@Override
public void writeLine(String line) throws IOException {
if (line != null && !line.isEmpty()) {
final String[] tokens = UNIX_PS_TABLE_PATTERN.split(line.trim());
if (tokens.length == 3 /* PPID, PID, COMMAND */) {
int ppid;
try {
ppid = Integer.parseInt(tokens[0]);
} catch (NumberFormatException e) {
// May be first line from process table: 'PPID PID COMMAND'. Skip it.
return;
}
if (ppid == myPid) {
int pid = Integer.parseInt(tokens[1]);
children.add(pid);
}
}
}
}
@Override
public void close() throws IOException {}
};
final LineConsumer stderr =
new LineConsumer() {
@Override
public void writeLine(String line) throws IOException {
if (error.length() > 0) {
error.append('\n');
}
error.append(line);
}
@Override
public void close() throws IOException {}
};
try {
ProcessUtil.process(Runtime.getRuntime().exec(ps), stdout, stderr);
} catch (IOException e) {
throw new IllegalStateException(e);
}
if (error.length() > 0) {
throw new IllegalStateException("can't get child processes: " + error.toString());
}
final int size = children.size();
final int[] result = new int[size];
for (int i = 0; i < size; i++) {
result[i] = children.get(i);
}
return result;
}
@Override
public boolean isAlive(Process process) {
return process.isAlive();
}
int getPid(Process process) {
if (PID_FIELD != null) {
try {
return ((Number) PID_FIELD.get(process)).intValue();
} catch (IllegalAccessException e) {
throw new IllegalStateException("Can't get process' pid. Not unix system?", e);
}
} else if (PID_METHOD != null) {
try {
return ((Long) PID_METHOD.invoke(process)).intValue();
} catch (IllegalAccessException | InvocationTargetException e) {
throw new IllegalStateException("Can't get process' pid. Not unix system?", e);
}
} else {
throw new IllegalStateException("Can't get process' pid. Not unix system?");
}
}
@Override
int system(String command) {
return C_LIBRARY.system(command);
}
}
| epl-1.0 |
markuskeunecke/stendhal | tests/utilities/RPClass/SheepTestHelperTest.java | 1163 | /* $Id$ */
/***************************************************************************
* (C) Copyright 2003-2010 - Stendhal *
***************************************************************************
***************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
***************************************************************************/
package utilities.RPClass;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
import marauroa.common.game.RPClass;
public class SheepTestHelperTest {
@Test
public void testGenerateRPClasses() {
SheepTestHelper.generateRPClasses();
assertTrue(RPClass.hasRPClass("sheep"));
}
}
| gpl-2.0 |
ekummerfeld/GdistanceP | tetrad-gui/src/main/java/edu/cmu/tetradapp/model/datamanip/RemoveConstantColumnsWrapper.java | 3125 | ///////////////////////////////////////////////////////////////////////////////
// For information as to what this class does, see the Javadoc, below. //
// Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, //
// 2007, 2008, 2009, 2010, 2014, 2015 by Peter Spirtes, Richard Scheines, Joseph //
// Ramsey, and Clark Glymour. //
// //
// This program is free software; you can redistribute it and/or modify //
// it under the terms of the GNU General Public License as published by //
// the Free Software Foundation; either version 2 of the License, or //
// (at your option) any later version. //
// //
// This program is distributed in the hope that it will be useful, //
// but WITHOUT ANY WARRANTY; without even the implied warranty of //
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the //
// GNU General Public License for more details. //
// //
// You should have received a copy of the GNU General Public License //
// along with this program; if not, write to the Free Software //
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //
///////////////////////////////////////////////////////////////////////////////
package edu.cmu.tetradapp.model.datamanip;
import edu.cmu.tetrad.data.DataFilter;
import edu.cmu.tetrad.data.DataModel;
import edu.cmu.tetrad.data.DataSet;
import edu.cmu.tetrad.data.LogDataUtils;
import edu.cmu.tetrad.util.Parameters;
import edu.cmu.tetrad.util.TetradSerializableUtils;
import edu.cmu.tetradapp.model.DataWrapper;
import edu.cmu.tetradapp.model.PcRunner;
/**
* Tyler was lazy and didn't document this....
*
* @author Tyler Gibson
*/
public class RemoveConstantColumnsWrapper extends DataWrapper {
static final long serialVersionUID = 23L;
public RemoveConstantColumnsWrapper(DataWrapper data, Parameters params) {
if (data == null) {
throw new NullPointerException("The givan data must not be null");
}
DataModel model = data.getSelectedDataModel();
if ((!(model instanceof DataSet))) {
throw new IllegalArgumentException("Data must be tabular");
}
DataFilter interpolator = new RemoveConstantColumnsDataFilter();
this.setDataModel(interpolator.filter((DataSet)model));
this.setSourceGraph(data.getSourceGraph());
LogDataUtils.logDataModelList("Parent data in which constant columns have been removed.", getDataModelList());
}
/**
* Generates a simple exemplar of this class to test serialization.
*
* @see TetradSerializableUtils
*/
public static PcRunner serializableInstance() {
return PcRunner.serializableInstance();
}
}
| gpl-2.0 |
ekummerfeld/GdistanceP | tetrad-gui/src/main/java/edu/cmu/tetradapp/editor/IndependenceFactsEditor.java | 26738 | ///////////////////////////////////////////////////////////////////////////////
// For information as to what this class does, see the Javadoc, below. //
// Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, //
// 2007, 2008, 2009, 2010, 2014, 2015 by Peter Spirtes, Richard Scheines, Joseph //
// Ramsey, and Clark Glymour. //
// //
// This program is free software; you can redistribute it and/or modify //
// it under the terms of the GNU General Public License as published by //
// the Free Software Foundation; either version 2 of the License, or //
// (at your option) any later version. //
// //
// This program is distributed in the hope that it will be useful, //
// but WITHOUT ANY WARRANTY; without even the implied warranty of //
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the //
// GNU General Public License for more details. //
// //
// You should have received a copy of the GNU General Public License //
// along with this program; if not, write to the Free Software //
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //
///////////////////////////////////////////////////////////////////////////////
package edu.cmu.tetradapp.editor;
import edu.cmu.tetrad.graph.Node;
import edu.cmu.tetrad.search.IndTestDSep;
import edu.cmu.tetrad.search.IndependenceTest;
import edu.cmu.tetrad.util.ChoiceGenerator;
import edu.cmu.tetrad.util.DepthChoiceGenerator;
import edu.cmu.tetradapp.model.IndTestModel;
import edu.cmu.tetradapp.model.IndTestProducer;
import edu.cmu.tetradapp.model.IndependenceResult;
import edu.cmu.tetradapp.util.IntTextField;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.JTableHeader;
import java.awt.*;
import java.awt.event.*;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.*;
import java.util.List;
import java.util.prefs.Preferences;
/**
* Lists independence facts specified by user and allows the list to be sorted by independence fact or by p value.
*
* @author Joseph Ramsey
*/
public class IndependenceFactsEditor extends JPanel {
private IndTestModel model;
private LinkedList<String> vars;
private JTextField textField;
private List<IndTestProducer> indTestProducers;
private List<List<IndependenceResult>> results = new ArrayList<>();
private AbstractTableModel tableModel;
private int sortDir;
private int lastSortCol;
private final NumberFormat nf = new DecimalFormat("0.0000");
private boolean showPs = false;
public IndependenceFactsEditor(IndTestModel model) {
this.indTestProducers = model.getIndTestProducers();
this.model = model;
this.vars = new LinkedList<>();
this.textField = new JTextField(40);
this.textField.setEditable(false);
this.textField.setFont(new Font("Serif", Font.BOLD, 14));
this.textField.setBackground(new Color(250, 250, 250));
this.vars = model.getVars();
this.results = model.getResults();
if (this.results == null) {
this.results = new ArrayList<>();
}
resetText();
if (indTestProducers.isEmpty()) {
throw new IllegalArgumentException("At least one source must be specified");
}
List<String> names = indTestProducers.get(0).getIndependenceTest().getVariableNames();
for (int i = 1; i < indTestProducers.size(); i++) {
List<String> _names = indTestProducers.get(i).getIndependenceTest().getVariableNames();
if (!new HashSet<>(names).equals(new HashSet<>(_names))) {
throw new IllegalArgumentException("All sources must have the same variable names.");
}
}
buildGui();
}
//========================PUBLIC METHODS==========================//
/**
* Performs the action of opening a session from a file.
*/
private void buildGui() {
// this.independenceTest = getIndTestProducer().getIndependenceTest();
final List<String> varNames = new ArrayList<>();
varNames.add("VAR");
varNames.addAll(getDataVars());
varNames.add("?");
varNames.add("+");
final JComboBox variableBox = new JComboBox();
DefaultComboBoxModel aModel1 = new DefaultComboBoxModel(varNames.toArray(new String[varNames.size()]));
aModel1.setSelectedItem("VAR");
variableBox.setModel(aModel1);
variableBox.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JComboBox box = (JComboBox) e.getSource();
String var = (String) box.getSelectedItem();
LinkedList<String> vars = getVars();
int size = vars.size();
if ("VAR".equals(var)) {
return;
}
if ("?".equals(var)) {
if (size >= 0 && !vars.contains("+")) {
vars.addLast(var);
}
} else if ("+".equals(var)) {
if (size >= 2) {
vars.addLast(var);
}
} else if ((vars.indexOf("?") < 2) && !(vars.contains("+")) &&
!(vars.contains(var))) {
vars.add(var);
}
resetText();
// This is a workaround to an introduced bug in the JDK whereby
// repeated selections of the same item send out just one
// action event.
DefaultComboBoxModel aModel = new DefaultComboBoxModel(
varNames.toArray(new String[varNames.size()]));
aModel.setSelectedItem("VAR");
variableBox.setModel(aModel);
}
});
final JButton delete = new JButton("Delete");
delete.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (!getVars().isEmpty()) {
getVars().removeLast();
resetText();
}
}
});
textField.addKeyListener(new KeyAdapter() {
public void keyTyped(KeyEvent e) {
if ('?' == e.getKeyChar()) {
variableBox.setSelectedItem("?");
} else if ('+' == e.getKeyChar()) {
variableBox.setSelectedItem("+");
} else if ('\b' == e.getKeyChar()) {
vars.removeLast();
resetText();
}
e.consume();
}
});
delete.addKeyListener(new KeyAdapter() {
public void keyTyped(KeyEvent e) {
if ('?' == e.getKeyChar()) {
variableBox.setSelectedItem("?");
} else if ('+' == e.getKeyChar()) {
variableBox.setSelectedItem("+");
} else if ('\b' == e.getKeyChar()) {
vars.removeLast();
resetText();
}
}
});
variableBox.addKeyListener(new KeyAdapter() {
public void keyTyped(KeyEvent e) {
super.keyTyped(e);
if ('\b' == e.getKeyChar()) {
vars.removeLast();
resetText();
}
}
});
JButton list = new JButton("LIST");
list.setFont(new Font("Dialog", Font.BOLD, 14));
list.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
generateResults();
}
});
Box b1 = Box.createVerticalBox();
Box b2 = Box.createHorizontalBox();
b2.add(new JLabel("Compares conditional independence tests from the given sources: "));
b2.add(Box.createHorizontalGlue());
b1.add(b2);
for (int i = 0; i < indTestProducers.size(); i++) {
Box b2a = Box.createHorizontalBox();
b2a.add(new JLabel(indTestProducers.get(i).getName() + ": " + getIndependenceTest(i).toString()));
b2a.add(Box.createHorizontalGlue());
b1.add(b2a);
}
b1.add(Box.createVerticalStrut(5));
Box b3 = Box.createHorizontalBox();
b3.add(getTextField());
b3.add(variableBox);
b3.add(delete);
b1.add(b3);
b1.add(Box.createVerticalStrut(10));
tableModel = new AbstractTableModel() {
public String getColumnName(int column) {
if (column == 0) {
return "Index";
}
if (column == 1) {
return "Fact";
} else if (column >= 2) {
return indTestProducers.get(column - 2).getName();// "Judgment";
}
return null;
}
public int getColumnCount() {
return 2 + indTestProducers.size();
}
public int getRowCount() {
return results.size();
}
public Object getValueAt(int rowIndex, int columnIndex) {
if (rowIndex > results.size()) return null;
if (columnIndex == 0) {
return results.get(rowIndex).get(0).getIndex();
}
if (columnIndex == 1) {
return results.get(rowIndex).get(0).getFact();
}
IndependenceResult independenceResult = results.get(rowIndex).get(columnIndex - 2);
for (int i = 0; i < indTestProducers.size(); i++) {
if (columnIndex == i + 2) {
if (getIndependenceTest(i) instanceof IndTestDSep) {
if (independenceResult.getType() == IndependenceResult.Type.INDEPENDENT) {
return "D-SEPARATED";
} else if (independenceResult.getType() == IndependenceResult.Type.DEPENDENT) {
return "d-connected";
} else if (independenceResult.getType() == IndependenceResult.Type.UNDETERMINED) {
return "*";
}
} else {
if (isShowPs()) {
return nf.format(independenceResult.getpValue());
} else {
if (independenceResult.getType() == IndependenceResult.Type.INDEPENDENT) {
return "INDEPENDENT";
} else if (independenceResult.getType() == IndependenceResult.Type.DEPENDENT) {
return "dependent";
} else if (independenceResult.getType() == IndependenceResult.Type.UNDETERMINED) {
return "*";
}
}
}
}
}
return null;
}
public Class getColumnClass(int columnIndex) {
if (columnIndex == 0) {
return Number.class;
}
if (columnIndex == 1) {
return String.class;
} else if (columnIndex == 2) {
return Number.class;
} else {
return Number.class;
}
}
};
JTable table = new JTable(tableModel);
table.getColumnModel().getColumn(0).setMinWidth(40);
table.getColumnModel().getColumn(0).setMaxWidth(40);
table.getColumnModel().getColumn(1).setMinWidth(200);
table.getColumnModel().getColumn(1).setCellRenderer(new Renderer(this));
for (int i = 2; i < table.getColumnModel().getColumnCount(); i++) {
table.getColumnModel().getColumn(i).setMinWidth(100);
table.getColumnModel().getColumn(i).setMaxWidth(100);
table.getColumnModel().getColumn(i).setCellRenderer(new Renderer(this));
}
JTableHeader header = table.getTableHeader();
header.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
JTableHeader header = (JTableHeader) e.getSource();
Point point = e.getPoint();
int col = header.columnAtPoint(point);
int sortCol = header.getTable().convertColumnIndexToModel(col);
sortByColumn(sortCol, true);
}
});
JScrollPane scroll = new JScrollPane(table);
scroll.setPreferredSize(new Dimension(400, 400));
b1.add(scroll);
Box b4 = Box.createHorizontalBox();
b4.add(new JLabel("Limit list to "));
IntTextField field = new IntTextField(getListLimit(), 7);
field.setFilter(new IntTextField.Filter() {
public int filter(int value, int oldValue) {
try {
setListLimit(value);
return value;
} catch (Exception e) {
return oldValue;
}
}
});
b4.add(field);
b4.add(new JLabel(" items."));
b4.add(Box.createHorizontalStrut(10));
final JButton showPValues = new JButton("Show P Values");
showPValues.addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
toggleShowPs();
}
@Override
public void mouseReleased(MouseEvent e) {
toggleShowPs();
}
});
b4.add(showPValues);
b4.add(Box.createHorizontalGlue());
b4.add(list);
b1.add(b4);
b1.add(Box.createVerticalStrut(10));
JPanel panel = this;
panel.setLayout(new BorderLayout());
panel.add(b1, BorderLayout.CENTER);
panel.setBorder(new EmptyBorder(10, 10, 10, 10));
}
//=============================PRIVATE METHODS=======================//
private void sortByColumn(final int sortCol, boolean allowReverse) {
if (allowReverse && sortCol == getLastSortCol()) {
setSortDir(-1 * getSortDir());
} else {
setSortDir(1);
}
setLastSortCol(sortCol);
Collections.sort(results, new Comparator<List<IndependenceResult>>() {
public int compare(List<IndependenceResult> r1, List<IndependenceResult> r2) {
switch (sortCol) {
case 0:
return getSortDir() * (r1.get(0).getIndex() - r2.get(0).getIndex());
case 1:
return getSortDir() * (r1.get(0).getIndex() - r2.get(0).getIndex());
default:
int ind1, ind2;
int col = sortCol - 2;
if (r1.get(col).getType() == IndependenceResult.Type.UNDETERMINED) {
ind1 = 0;
} else if (r1.get(col).getType() == IndependenceResult.Type.DEPENDENT) {
ind1 = 1;
} else {
ind1 = 2;
}
if (r2.get(col).getType() == IndependenceResult.Type.UNDETERMINED) {
ind2 = 0;
} else if (r2.get(col).getType() == IndependenceResult.Type.DEPENDENT) {
ind2 = 1;
} else {
ind2 = 2;
}
return getSortDir() * (ind1 - ind2);
}
}
});
tableModel.fireTableDataChanged();
}
private boolean isShowPs() {
return showPs;
}
private void toggleShowPs() {
this.showPs = !this.showPs;
tableModel.fireTableDataChanged();
}
static class Renderer extends DefaultTableCellRenderer {
private final IndependenceFactsEditor editor;
private JTable table;
private int row;
private int col;
private boolean selected;
public Renderer(IndependenceFactsEditor editor) {
super();
this.editor = editor;
}
public void setValue(Object value) {
int indep = 0;
int numCols = table.getModel().getColumnCount();
if (selected) {
super.setForeground(table.getSelectionForeground());
super.setBackground(table.getSelectionBackground());
} else {
for (int i = 2; i < numCols; i++) {
Object _value = table.getModel().getValueAt(row, i);
if ("INDEPENDENT".equals(_value) || "D-SEPARATED".equals(_value)) {
indep++;
}
}
if (!editor.isShowPs()) {
if (!(indep == 0 || indep == numCols - 2)) {
setForeground(table.getForeground());
setBackground(Color.YELLOW);
} else {
setForeground(table.getForeground());
setBackground(table.getBackground());
}
}
else {
setForeground(table.getForeground());
setBackground(table.getBackground());
}
}
setText((String) value);
}
@Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
this.table = table;
this.row = row;
this.col = column;
this.selected = isSelected;
return super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
}
}
private List<String> getDataVars() {
return getIndependenceTest(0).getVariableNames();
}
private void resetText() {
StringBuilder buf = new StringBuilder();
if (getVars().size() == 0) {
buf.append("Choose variables and wildcards from dropdown-->");
}
if (getVars().size() > 0) {
buf.append(" ").append(getVars().get(0));
buf.append(" _||_ ");
}
if (getVars().size() > 1) {
buf.append(getVars().get(1));
}
if (getVars().size() > 2) {
buf.append(" | ");
}
for (int i = 2; i < getVars().size() - 1; i++) {
buf.append(getVars().get(i));
buf.append(", ");
}
if (getVars().size() > 2) {
buf.append(getVars().get(getVars().size() - 1));
}
model.setVars(getVars());
textField.setText(buf.toString());
}
private void generateResults() {
results = new ArrayList<>();
List<String> dataVars = getDataVars();
if (getVars().size() < 2) {
tableModel.fireTableDataChanged();
return;
}
// Need a choice generator over the ?'s, and a depth choice generator over the +'s. The +'s all have to come
// at the end at index >= 2.
int numQuestionMarksFirstTwo = 0;
int numQuestionMarksRest = 0;
int numPluses = 0;
int numFixed = 0;
for (int i = 0; i < vars.size(); i++) {
String var = vars.get(i);
if ("?".equals(var) && i < 2) numQuestionMarksFirstTwo++;
else if ("?".equals(var)) numQuestionMarksRest++;
else if ("+".equals(var)) numPluses++;
else numFixed++;
}
int[] questionMarkFirstTwoIndices = new int[numQuestionMarksFirstTwo];
int[] questionMarkRestIndices = new int[numQuestionMarksRest];
int[] plusIndices = new int[numPluses];
int[] fixedIndices = new int[numFixed];
String[] fixedVars = new String[numFixed];
int _i = -1;
int _j = -1;
int _k = -1;
int _l = -1;
for (int i = 0; i < vars.size(); i++) {
if ("?".equals(vars.get(i)) && i < 2) questionMarkFirstTwoIndices[++_i] = i;
else if ("?".equals(vars.get(i))) questionMarkRestIndices[++_j] = i;
else if ("+".equals(vars.get(i))) plusIndices[++_k] = i;
else {
fixedIndices[++_l] = i;
fixedVars[_l] = vars.get(i);
}
}
List<String> vars1 = new ArrayList<>(dataVars);
vars1.removeAll(vars);
ChoiceGenerator gen1 = new ChoiceGenerator(vars1.size(), questionMarkFirstTwoIndices.length);
int[] choice1;
LOOP:
while ((choice1 = gen1.next()) != null) {
List<String> s2 = asList(choice1, vars1);
List<String> vars2 = new ArrayList<>(vars1);
vars2.removeAll(s2);
ChoiceGenerator gen2 = new ChoiceGenerator(vars2.size(), questionMarkRestIndices.length);
int[] choice2;
while ((choice2 = gen2.next()) != null) {
List<String> s3 = asList(choice2, vars2);
List<String> vars3 = new ArrayList<>(vars2);
vars3.removeAll(s3);
DepthChoiceGenerator gen3 = new DepthChoiceGenerator(vars3.size(), plusIndices.length);
int[] choice3;
while ((choice3 = gen3.next()) != null) {
results.add(new ArrayList<IndependenceResult>());
for (int prod = 0; prod < indTestProducers.size(); prod++) {
String[] vars4 = new String[fixedIndices.length + questionMarkFirstTwoIndices.length
+ questionMarkRestIndices.length + choice3.length];
for (int i = 0; i < fixedIndices.length; i++) {
vars4[fixedIndices[i]] = fixedVars[i];
}
for (int i = 0; i < choice1.length; i++) {
vars4[questionMarkFirstTwoIndices[i]] = vars1.get(choice1[i]);
}
for (int i = 0; i < choice2.length; i++) {
vars4[questionMarkRestIndices[i]] = vars2.get(choice2[i]);
}
for (int i = 0; i < choice3.length; i++) {
vars4[plusIndices[i]] = vars3.get(choice3[i]);
}
IndependenceTest independenceTest = getIndependenceTest(prod);
Node x = independenceTest.getVariable(vars4[0]);
Node y = independenceTest.getVariable(vars4[1]);
List<Node> z = new ArrayList<>();
for (int i = 2; i < vars4.length; i++) {
z.add(independenceTest.getVariable(vars4[i]));
}
IndependenceResult.Type indep;
double pValue;
try {
indep = independenceTest.isIndependent(x, y, z) ? IndependenceResult.Type.INDEPENDENT : IndependenceResult.Type.DEPENDENT;
pValue = independenceTest.getPValue();
} catch (Exception e) {
indep = IndependenceResult.Type.UNDETERMINED;
pValue = Double.NaN;
}
results.get(results.size() - 1).add(new IndependenceResult(results.size(),
factString(x, y, z), indep, pValue));
}
if (results.size() > getListLimit()) break LOOP;
}
}
}
model.setResults(results);
tableModel.fireTableDataChanged();
}
private static List<String> asList(int[] indices, List<String> nodes) {
List<String> list = new LinkedList<>();
for (int i : indices) {
list.add(nodes.get(i));
}
return list;
}
private LinkedList<String> getVars() {
return vars;
}
private JTextField getTextField() {
return textField;
}
public IndependenceFactsEditor(LayoutManager layout, boolean isDoubleBuffered) {
super(layout, isDoubleBuffered);
}
private static String factString(Node x, Node y, List<Node> condSet) {
StringBuilder sb = new StringBuilder();
sb.append(x.getName());
sb.append(" _||_ ");
sb.append(y.getName());
Iterator<Node> it = condSet.iterator();
if (it.hasNext()) {
sb.append(" | ");
sb.append(it.next());
}
while (it.hasNext()) {
sb.append(", ");
sb.append(it.next());
}
return sb.toString();
}
private IndependenceTest getIndependenceTest(int i) {
return indTestProducers.get(i).getIndependenceTest();
}
private int getLastSortCol() {
return this.lastSortCol;
}
private void setLastSortCol(int lastSortCol) {
if (lastSortCol < 0 || lastSortCol > 4) {
throw new IllegalArgumentException();
}
this.lastSortCol = lastSortCol;
}
private int getSortDir() {
return this.sortDir;
}
private void setSortDir(int sortDir) {
if (!(sortDir == 1 || sortDir == -1)) {
throw new IllegalArgumentException();
}
this.sortDir = sortDir;
}
private int getListLimit() {
return Preferences.userRoot().getInt("indFactsListLimit", 10000);
}
private void setListLimit(int listLimit) {
if (listLimit < 1) {
throw new IllegalArgumentException();
}
Preferences.userRoot().putInt("indFactsListLimit", listLimit);
}
}
| gpl-2.0 |
davleopo/graal-core | graal/com.oracle.graal.salver/src/com/oracle/graal/salver/dumper/AbstractSerializerDumper.java | 2019 | /*
* Copyright (c) 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.
*/
package com.oracle.graal.salver.dumper;
import java.io.IOException;
import com.oracle.graal.salver.serialize.Serializer;
public abstract class AbstractSerializerDumper implements Dumper {
protected Serializer serializer;
public AbstractSerializerDumper() {
}
public AbstractSerializerDumper(Serializer serializer) {
this.serializer = serializer;
}
public Serializer getSerializer() {
return serializer;
}
public void setSerializer(Serializer serializer) {
this.serializer = serializer;
}
protected void serialize(Object obj) throws IOException {
if (serializer != null) {
serializer.serialize(obj);
}
}
protected void serializeAndFlush(Object obj) throws IOException {
if (serializer != null) {
serializer.serialize(obj);
serializer.flush();
}
}
@Override
public void close() throws IOException {
}
}
| gpl-2.0 |
FauxFaux/jdk9-jaxws | src/jdk.xml.bind/share/classes/com/sun/codemodel/internal/writer/ProgressCodeWriter.java | 2569 | /*
* Copyright (c) 1997, 2012, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.codemodel.internal.writer;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;
import java.io.Writer;
import com.sun.codemodel.internal.CodeWriter;
import com.sun.codemodel.internal.JPackage;
/**
* Filter CodeWriter that writes a progress message to the specified
* PrintStream.
*
* @author
* Kohsuke Kawaguchi (kohsuke.kawaguchi@sun.com)
*/
public class ProgressCodeWriter extends FilterCodeWriter {
public ProgressCodeWriter( CodeWriter output, PrintStream progress ) {
super(output);
this.progress = progress;
if(progress==null)
throw new IllegalArgumentException();
}
private final PrintStream progress;
public OutputStream openBinary(JPackage pkg, String fileName) throws IOException {
report(pkg, fileName);
return super.openBinary(pkg,fileName);
}
public Writer openSource(JPackage pkg, String fileName) throws IOException {
report(pkg, fileName);
return super.openSource(pkg,fileName);
}
private void report(JPackage pkg, String fileName) {
if(pkg.isUnnamed()) progress.println(fileName);
else
progress.println(
pkg.name().replace('.',File.separatorChar)
+File.separatorChar+fileName);
}
}
| gpl-2.0 |