hexsha
stringlengths 40
40
| size
int64 3
1.05M
| ext
stringclasses 1
value | lang
stringclasses 1
value | max_stars_repo_path
stringlengths 5
1.02k
| max_stars_repo_name
stringlengths 4
126
| max_stars_repo_head_hexsha
stringlengths 40
78
| max_stars_repo_licenses
list | max_stars_count
float64 1
191k
⌀ | max_stars_repo_stars_event_min_datetime
stringlengths 24
24
⌀ | max_stars_repo_stars_event_max_datetime
stringlengths 24
24
⌀ | max_issues_repo_path
stringlengths 5
1.02k
| max_issues_repo_name
stringlengths 4
114
| max_issues_repo_head_hexsha
stringlengths 40
78
| max_issues_repo_licenses
list | max_issues_count
float64 1
92.2k
⌀ | max_issues_repo_issues_event_min_datetime
stringlengths 24
24
⌀ | max_issues_repo_issues_event_max_datetime
stringlengths 24
24
⌀ | max_forks_repo_path
stringlengths 5
1.02k
| max_forks_repo_name
stringlengths 4
136
| max_forks_repo_head_hexsha
stringlengths 40
78
| max_forks_repo_licenses
list | max_forks_count
float64 1
105k
⌀ | max_forks_repo_forks_event_min_datetime
stringlengths 24
24
⌀ | max_forks_repo_forks_event_max_datetime
stringlengths 24
24
⌀ | avg_line_length
float64 2.55
99.9
| max_line_length
int64 3
1k
| alphanum_fraction
float64 0.25
1
| index
int64 0
1M
| content
stringlengths 3
1.05M
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
923f3564756a04f0b9c13e1d3269f319a83f0ba4
| 7,761 |
java
|
Java
|
hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-jobclient/src/test/java/org/apache/hadoop/mapred/TestMRCJCJobClient.java
|
dmgerman/hadoop
|
70c015914a8756c5440cd969d70dac04b8b6142b
|
[
"Apache-2.0"
] | null | null | null |
hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-jobclient/src/test/java/org/apache/hadoop/mapred/TestMRCJCJobClient.java
|
dmgerman/hadoop
|
70c015914a8756c5440cd969d70dac04b8b6142b
|
[
"Apache-2.0"
] | null | null | null |
hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-jobclient/src/test/java/org/apache/hadoop/mapred/TestMRCJCJobClient.java
|
dmgerman/hadoop
|
70c015914a8756c5440cd969d70dac04b8b6142b
|
[
"Apache-2.0"
] | null | null | null | 14.698864 | 814 | 0.803891 | 1,001,072 |
begin_unit|revision:0.9.5;language:Java;cregit-version:0.0.1
begin_comment
comment|/** * 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. */
end_comment
begin_package
DECL|package|org.apache.hadoop.mapred
package|package
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|mapred
package|;
end_package
begin_import
import|import
name|java
operator|.
name|io
operator|.
name|IOException
import|;
end_import
begin_import
import|import
name|java
operator|.
name|io
operator|.
name|OutputStream
import|;
end_import
begin_import
import|import
name|java
operator|.
name|io
operator|.
name|OutputStreamWriter
import|;
end_import
begin_import
import|import
name|java
operator|.
name|io
operator|.
name|Writer
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|conf
operator|.
name|Configuration
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|fs
operator|.
name|Path
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|io
operator|.
name|LongWritable
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|io
operator|.
name|Text
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|mapreduce
operator|.
name|TestMRJobClient
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|mapreduce
operator|.
name|tools
operator|.
name|CLI
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|util
operator|.
name|Tool
import|;
end_import
begin_import
import|import
name|org
operator|.
name|junit
operator|.
name|Ignore
import|;
end_import
begin_class
annotation|@
name|Ignore
DECL|class|TestMRCJCJobClient
specifier|public
class|class
name|TestMRCJCJobClient
extends|extends
name|TestMRJobClient
block|{
DECL|method|runJob ()
specifier|private
name|String
name|runJob
parameter_list|()
throws|throws
name|Exception
block|{
name|OutputStream
name|os
init|=
name|getFileSystem
argument_list|()
operator|.
name|create
argument_list|(
operator|new
name|Path
argument_list|(
name|getInputDir
argument_list|()
argument_list|,
literal|"text.txt"
argument_list|)
argument_list|)
decl_stmt|;
name|Writer
name|wr
init|=
operator|new
name|OutputStreamWriter
argument_list|(
name|os
argument_list|)
decl_stmt|;
name|wr
operator|.
name|write
argument_list|(
literal|"hello1\n"
argument_list|)
expr_stmt|;
name|wr
operator|.
name|write
argument_list|(
literal|"hello2\n"
argument_list|)
expr_stmt|;
name|wr
operator|.
name|write
argument_list|(
literal|"hello3\n"
argument_list|)
expr_stmt|;
name|wr
operator|.
name|close
argument_list|()
expr_stmt|;
name|JobConf
name|conf
init|=
name|createJobConf
argument_list|()
decl_stmt|;
name|conf
operator|.
name|setJobName
argument_list|(
literal|"mr"
argument_list|)
expr_stmt|;
name|conf
operator|.
name|setJobPriority
argument_list|(
name|JobPriority
operator|.
name|HIGH
argument_list|)
expr_stmt|;
name|conf
operator|.
name|setInputFormat
argument_list|(
name|TextInputFormat
operator|.
name|class
argument_list|)
expr_stmt|;
name|conf
operator|.
name|setMapOutputKeyClass
argument_list|(
name|LongWritable
operator|.
name|class
argument_list|)
expr_stmt|;
name|conf
operator|.
name|setMapOutputValueClass
argument_list|(
name|Text
operator|.
name|class
argument_list|)
expr_stmt|;
name|conf
operator|.
name|setOutputFormat
argument_list|(
name|TextOutputFormat
operator|.
name|class
argument_list|)
expr_stmt|;
name|conf
operator|.
name|setOutputKeyClass
argument_list|(
name|LongWritable
operator|.
name|class
argument_list|)
expr_stmt|;
name|conf
operator|.
name|setOutputValueClass
argument_list|(
name|Text
operator|.
name|class
argument_list|)
expr_stmt|;
name|conf
operator|.
name|setMapperClass
argument_list|(
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|mapred
operator|.
name|lib
operator|.
name|IdentityMapper
operator|.
name|class
argument_list|)
expr_stmt|;
name|conf
operator|.
name|setReducerClass
argument_list|(
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|mapred
operator|.
name|lib
operator|.
name|IdentityReducer
operator|.
name|class
argument_list|)
expr_stmt|;
name|FileInputFormat
operator|.
name|setInputPaths
argument_list|(
name|conf
argument_list|,
name|getInputDir
argument_list|()
argument_list|)
expr_stmt|;
name|FileOutputFormat
operator|.
name|setOutputPath
argument_list|(
name|conf
argument_list|,
name|getOutputDir
argument_list|()
argument_list|)
expr_stmt|;
return|return
name|JobClient
operator|.
name|runJob
argument_list|(
name|conf
argument_list|)
operator|.
name|getID
argument_list|()
operator|.
name|toString
argument_list|()
return|;
block|}
DECL|method|runTool (Configuration conf, Tool tool, String[] args, OutputStream out)
specifier|public
specifier|static
name|int
name|runTool
parameter_list|(
name|Configuration
name|conf
parameter_list|,
name|Tool
name|tool
parameter_list|,
name|String
index|[]
name|args
parameter_list|,
name|OutputStream
name|out
parameter_list|)
throws|throws
name|Exception
block|{
return|return
name|TestMRJobClient
operator|.
name|runTool
argument_list|(
name|conf
argument_list|,
name|tool
argument_list|,
name|args
argument_list|,
name|out
argument_list|)
return|;
block|}
DECL|method|verifyJobPriority (String jobId, String priority, JobConf conf)
specifier|static
name|void
name|verifyJobPriority
parameter_list|(
name|String
name|jobId
parameter_list|,
name|String
name|priority
parameter_list|,
name|JobConf
name|conf
parameter_list|)
throws|throws
name|Exception
block|{
name|TestMRCJCJobClient
name|test
init|=
operator|new
name|TestMRCJCJobClient
argument_list|()
decl_stmt|;
name|test
operator|.
name|verifyJobPriority
argument_list|(
name|jobId
argument_list|,
name|priority
argument_list|,
name|conf
argument_list|,
name|test
operator|.
name|createJobClient
argument_list|()
argument_list|)
expr_stmt|;
block|}
DECL|method|testJobClient ()
specifier|public
name|void
name|testJobClient
parameter_list|()
throws|throws
name|Exception
block|{
name|Configuration
name|conf
init|=
name|createJobConf
argument_list|()
decl_stmt|;
name|String
name|jobId
init|=
name|runJob
argument_list|()
decl_stmt|;
name|testGetCounter
argument_list|(
name|jobId
argument_list|,
name|conf
argument_list|)
expr_stmt|;
name|testAllJobList
argument_list|(
name|jobId
argument_list|,
name|conf
argument_list|)
expr_stmt|;
name|testChangingJobPriority
argument_list|(
name|jobId
argument_list|,
name|conf
argument_list|)
expr_stmt|;
block|}
DECL|method|createJobClient ()
specifier|protected
name|CLI
name|createJobClient
parameter_list|()
throws|throws
name|IOException
block|{
return|return
operator|new
name|JobClient
argument_list|()
return|;
block|}
block|}
end_class
end_unit
|
923f37b0df1ba9091fde8a3727184d95dfb55cdf
| 4,435 |
java
|
Java
|
texoo-entity-linking/src/main/java/de/datexis/nel/NamedEntityAnnotator.java
|
sebastianarnold/TeXoo
|
514860d96decdf3ff6613dfcf0d27d9845ddcf60
|
[
"Apache-2.0"
] | 15 |
2019-02-18T16:50:56.000Z
|
2022-02-02T10:13:09.000Z
|
texoo-entity-linking/src/main/java/de/datexis/nel/NamedEntityAnnotator.java
|
sebastianarnold/TeXoo
|
514860d96decdf3ff6613dfcf0d27d9845ddcf60
|
[
"Apache-2.0"
] | 23 |
2019-02-05T16:38:00.000Z
|
2021-06-04T19:29:13.000Z
|
texoo-entity-linking/src/main/java/de/datexis/nel/NamedEntityAnnotator.java
|
sebastianarnold/TeXoo
|
514860d96decdf3ff6613dfcf0d27d9845ddcf60
|
[
"Apache-2.0"
] | 3 |
2019-02-15T09:54:19.000Z
|
2020-06-23T12:46:20.000Z
| 32.445255 | 149 | 0.699438 | 1,001,073 |
package de.datexis.nel;
import com.google.common.collect.Lists;
import de.datexis.annotator.Annotator;
import de.datexis.ner.MentionAnnotator;
import de.datexis.common.Timer;
import de.datexis.encoder.Encoder;
import de.datexis.model.Document;
import de.datexis.ner.MentionAnnotation;
import de.datexis.model.Annotation;
import de.datexis.index.ArticleIndex;
import de.datexis.index.ArticleRef;
import de.datexis.index.impl.VectorArticleIndex;
import de.datexis.preprocess.DocumentFactory;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.NavigableMap;
import java.util.TreeMap;
import java.util.stream.Collectors;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* An Annotator that detects and links Named Entities.
* @author Sebastian Arnold <[email protected]>
*/
public class NamedEntityAnnotator extends Annotator {
protected final static Logger log = LoggerFactory.getLogger(NamedEntityAnnotator.class);
protected final MentionAnnotator ner;
protected final ArticleIndex index;
protected final Encoder encoder;
public NamedEntityAnnotator(MentionAnnotator recognize, ArticleIndex search, Encoder disambiguate) {
this.ner = recognize;
this.index = search;
this.encoder = disambiguate;
}
public NamedEntityAnnotator(MentionAnnotator recognize, ArticleIndex search) {
this.ner = recognize;
this.index = search;
this.encoder = null;
}
@Override
public Document annotate(String text) {
log.trace("Annotating document: " + text);
// update
Document doc = DocumentFactory.fromText(text);
if(doc.countTokens() == 0) return doc;
annotate(doc);
return doc;
}
@Override
public Document annotate(Document doc) {
annotate(Lists.newArrayList(doc));
return doc;
}
@Override
public void annotate(Collection<Document> docs) {
Timer timer = new Timer();
timer.start();
NavigableMap<Integer,NamedEntityAnnotation> result = new TreeMap<>();
// recognize
timer.resetSplit();
ner.annotate(docs);
timer.setSplit("NER");
// search & disambiguate
for(Document doc : docs) {
createSignature(doc);
disambiguateMentions(doc, Annotation.Source.PRED);
}
timer.setSplit("NED");
timer.stop();
log.debug("Annotated " + docs.size() + " documends [" + timer.get("NER") + " NER, " + timer.get("NED") + " NED, " + timer.get() + " total]");
}
public ArticleIndex getKnowlegeBase() {
return this.index;
}
/**
* Attaches MentonAnnotations to the Document
*/
protected void recognizeMentions(Document doc) {
ner.annotate(doc);
}
/**
* Attaches Vector to the Document
*/
protected void createSignature(Document doc) {
//INDArray sig = encoder.encode(doc);
//doc.putVector(encoder.getClass(), sig);
}
/**
* Attaches NamedEntityAnnotation to the Document
*/
public void disambiguateMentions(Document doc, Annotation.Source source) {
//INDArray context = doc.getVector(encoder.getClass());
List<MentionAnnotation> anns = doc.streamAnnotations(source, MentionAnnotation.class).collect(Collectors.toList());
for(MentionAnnotation mention : anns) {
NamedEntityAnnotation entity = new NamedEntityAnnotation(mention, new ArrayList<>());
//if(annotationExists(ner, doc.ge)) {
String entityMention = mention.getText();
String entityContext = doc.getSentenceAtPosition(mention.getBegin()).get().toTokenizedString();
List<ArticleRef> candidates;
if(index instanceof VectorArticleIndex) {
// get many top candidates from Lucene and rerank unsing vectors
candidates = ((VectorArticleIndex)index).querySimilarArticles(entityMention, entityContext, 1);
} else {
// get only top candidate from Lucene
candidates = index.queryNames(entityMention, 1);
}
if(candidates.size() > 0) {
// TODO: this piece of code should be part of NamedEntityAnnotation!
entity.setRefName(candidates.get(0).getTitle());
entity.setRefId(candidates.get(0).getId());
entity.setRefUrl(candidates.get(0).getUrl());
}
//log.trace("adding ner result: " + entity.getText() + " (" + entity.getBegin() + "," + entity.getLength() + ") with id " + entity.getRefId());
entity.setSource(Annotation.Source.PRED);
doc.addAnnotation(entity);
}
}
}
|
923f37eb2d8c7efcfa91ee703c469ae6f2d7605e
| 3,704 |
java
|
Java
|
cloud-backends/components/cloud-mgt/org.wso2.carbon.cloud.common/src/main/java/org/wso2/carbon/cloud/common/internal/CloudCommonServiceComponent.java
|
thiliniish/appcloud-testrepo
|
0b57dd411a1426f96543de36c901c3ad916ae946
|
[
"Apache-2.0"
] | null | null | null |
cloud-backends/components/cloud-mgt/org.wso2.carbon.cloud.common/src/main/java/org/wso2/carbon/cloud/common/internal/CloudCommonServiceComponent.java
|
thiliniish/appcloud-testrepo
|
0b57dd411a1426f96543de36c901c3ad916ae946
|
[
"Apache-2.0"
] | null | null | null |
cloud-backends/components/cloud-mgt/org.wso2.carbon.cloud.common/src/main/java/org/wso2/carbon/cloud/common/internal/CloudCommonServiceComponent.java
|
thiliniish/appcloud-testrepo
|
0b57dd411a1426f96543de36c901c3ad916ae946
|
[
"Apache-2.0"
] | null | null | null | 41.155556 | 113 | 0.729482 | 1,001,074 |
/*
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. 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.wso2.carbon.cloud.common.internal;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.osgi.framework.BundleContext;
import org.osgi.service.component.ComponentContext;
import org.wso2.carbon.cloud.common.CloudMgtConfiguration;
import org.wso2.carbon.cloud.common.CloudMgtConfigurationBuilder;
import org.wso2.carbon.cloud.common.CloudMgtConstants;
import org.wso2.carbon.securevault.SecretCallbackHandlerService;
import org.wso2.carbon.user.core.service.RealmService;
import org.wso2.carbon.utils.CarbonUtils;
import java.io.File;
/**
* @scr.component name="cloud.common.component" immediate=true
* @scr.reference name="user.realmservice.default"
* interface="org.wso2.carbon.user.core.service.RealmService"
* cardinality="1..1" policy="dynamic" bind="setRealmService"
* unbind="unsetRealmService"
* @scr.reference name="secret.callback.handler.service"
* interface="org.wso2.carbon.securevault.SecretCallbackHandlerService"
* cardinality="1..1" policy="dynamic"
* bind="setSecretCallbackHandlerService" unbind="unsetSecretCallbackHandlerService"
*/
public class CloudCommonServiceComponent {
private static Log log = LogFactory.getLog(CloudCommonServiceComponent.class);
protected void activate(ComponentContext ctxt) {
BundleContext bundleContext = ctxt.getBundleContext();
CloudMgtConfiguration configuration;
try {
String fileLocation = CarbonUtils.getCarbonConfigDirPath() +
File.separator + CloudMgtConstants.CONFIG_FOLDER +
File.separator + CloudMgtConstants.CONFIG_FILE_NAME;
configuration = new CloudMgtConfigurationBuilder(fileLocation).buildCloudMgtConfiguration();
bundleContext.registerService(CloudMgtConfiguration.class.getName(), configuration, null);
if (log.isDebugEnabled()) {
log.debug("Cloud common bundle is activated");
}
} catch (Throwable e) {
log.error("Error in creating cloud-mgt configuration", e);
}
}
protected void deactivate(ComponentContext ctxt) {
if (log.isDebugEnabled()) {
log.debug("Cloud Common bundle is deactivated ");
}
}
protected void setRealmService(RealmService rlmService) {
ServiceHolder.setRealmService(rlmService);
}
protected void unsetRealmService(RealmService realmService) {
ServiceHolder.setRealmService(null);
}
protected void setSecretCallbackHandlerService(SecretCallbackHandlerService secretCallbackHandlerService) {
if (log.isDebugEnabled()) {
log.debug("SecretCallbackHandlerService acquired");
}
ServiceHolder.setSecretCallbackHandlerService(secretCallbackHandlerService);
}
protected void unsetSecretCallbackHandlerService(SecretCallbackHandlerService secretCallbackHandlerService) {
ServiceHolder.setSecretCallbackHandlerService(null);
}
}
|
923f3853568d26486a5c8d28e46af68015a0295d
| 13,801 |
java
|
Java
|
modules/core/src/main/java/org/apache/ignite/marshaller/optimized/OptimizedMarshallerUtils.java
|
andyglick/apache-ignite
|
c864fe443284508c7eb1d2341d9fdc2a5a844c45
|
[
"CC0-1.0"
] | null | null | null |
modules/core/src/main/java/org/apache/ignite/marshaller/optimized/OptimizedMarshallerUtils.java
|
andyglick/apache-ignite
|
c864fe443284508c7eb1d2341d9fdc2a5a844c45
|
[
"CC0-1.0"
] | 1 |
2021-08-17T09:21:18.000Z
|
2021-08-17T09:21:18.000Z
|
modules/core/src/main/java/org/apache/ignite/marshaller/optimized/OptimizedMarshallerUtils.java
|
andyglick/apache-ignite
|
c864fe443284508c7eb1d2341d9fdc2a5a844c45
|
[
"CC0-1.0"
] | null | null | null | 25.092727 | 110 | 0.573147 | 1,001,075 |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.ignite.marshaller.optimized;
import java.io.IOException;
import java.io.ObjectStreamClass;
import java.io.Serializable;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.nio.charset.Charset;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HashSet;
import java.util.List;
import java.util.concurrent.ConcurrentMap;
import org.apache.ignite.IgniteCheckedException;
import org.apache.ignite.IgniteException;
import org.apache.ignite.internal.util.GridUnsafe;
import org.apache.ignite.internal.util.typedef.F;
import org.apache.ignite.marshaller.MarshallerContext;
import org.apache.ignite.marshaller.jdk.JdkMarshaller;
/**
* Miscellaneous utility methods to facilitate {@link OptimizedMarshaller}.
*/
class OptimizedMarshallerUtils {
/** */
static final long HASH_SET_MAP_OFF;
/** */
static final byte JDK = -2;
/** */
static final byte HANDLE = -1;
/** */
static final byte NULL = 0;
/** */
static final byte BYTE = 1;
/** */
static final byte SHORT = 2;
/** */
static final byte INT = 3;
/** */
static final byte LONG = 4;
/** */
static final byte FLOAT = 5;
/** */
static final byte DOUBLE = 6;
/** */
static final byte CHAR = 7;
/** */
static final byte BOOLEAN = 8;
/** */
static final byte BYTE_ARR = 9;
/** */
static final byte SHORT_ARR = 10;
/** */
static final byte INT_ARR = 11;
/** */
static final byte LONG_ARR = 12;
/** */
static final byte FLOAT_ARR = 13;
/** */
static final byte DOUBLE_ARR = 14;
/** */
static final byte CHAR_ARR = 15;
/** */
static final byte BOOLEAN_ARR = 16;
/** */
static final byte OBJ_ARR = 17;
/** */
static final byte STR = 18;
/** */
static final byte UUID = 19;
/** */
static final byte PROPS = 20;
/** */
static final byte ARRAY_LIST = 21;
/** */
static final byte HASH_MAP = 22;
/** */
static final byte HASH_SET = 23;
/** */
static final byte LINKED_LIST = 24;
/** */
static final byte LINKED_HASH_MAP = 25;
/** */
static final byte LINKED_HASH_SET = 26;
/** */
static final byte DATE = 27;
/** */
static final byte CLS = 28;
/** */
static final byte PROXY = 29;
/** */
static final byte ENUM = 100;
/** */
static final byte EXTERNALIZABLE = 101;
/** */
static final byte SERIALIZABLE = 102;
/** UTF-8 character name. */
static final Charset UTF_8 = Charset.forName("UTF-8");
/** JDK marshaller. */
static final JdkMarshaller JDK_MARSH = new JdkMarshaller();
static {
long mapOff;
try {
mapOff = GridUnsafe.objectFieldOffset(HashSet.class.getDeclaredField("map"));
}
catch (NoSuchFieldException e) {
try {
// Workaround for legacy IBM JRE.
mapOff = GridUnsafe.objectFieldOffset(HashSet.class.getDeclaredField("backingMap"));
}
catch (NoSuchFieldException e2) {
throw new IgniteException("Initialization failure.", e2);
}
}
HASH_SET_MAP_OFF = mapOff;
}
/**
*/
private OptimizedMarshallerUtils() {
// No-op.
}
/**
* Gets descriptor for provided class.
*
* @param clsMap Class descriptors by class map.
* @param cls Class.
* @param ctx Context.
* @param mapper ID mapper.
* @return Descriptor.
* @throws IOException In case of error.
*/
static OptimizedClassDescriptor classDescriptor(
ConcurrentMap<Class, OptimizedClassDescriptor> clsMap,
Class cls,
MarshallerContext ctx,
OptimizedMarshallerIdMapper mapper)
throws IOException
{
OptimizedClassDescriptor desc = clsMap.get(cls);
if (desc == null) {
int typeId = resolveTypeId(cls.getName(), mapper);
boolean registered;
try {
registered = ctx.registerClass(typeId, cls);
}
catch (IgniteCheckedException e) {
throw new IOException("Failed to register class: " + cls.getName(), e);
}
desc = new OptimizedClassDescriptor(cls, registered ? typeId : 0, clsMap, ctx, mapper);
if (registered) {
OptimizedClassDescriptor old = clsMap.putIfAbsent(cls, desc);
if (old != null)
desc = old;
}
}
return desc;
}
/**
* @param clsName Class name.
* @param mapper Mapper.
* @return Type ID.
*/
private static int resolveTypeId(String clsName, OptimizedMarshallerIdMapper mapper) {
int typeId;
if (mapper != null) {
typeId = mapper.typeId(clsName);
if (typeId == 0)
typeId = clsName.hashCode();
}
else
typeId = clsName.hashCode();
return typeId;
}
/**
* Gets descriptor for provided ID.
*
* @param clsMap Class descriptors by class map.
* @param id ID.
* @param ldr Class loader.
* @param ctx Context.
* @param mapper ID mapper.
* @return Descriptor.
* @throws IOException In case of error.
* @throws ClassNotFoundException If class was not found.
*/
static OptimizedClassDescriptor classDescriptor(
ConcurrentMap<Class, OptimizedClassDescriptor> clsMap,
int id,
ClassLoader ldr,
MarshallerContext ctx,
OptimizedMarshallerIdMapper mapper) throws IOException, ClassNotFoundException {
Class cls;
try {
cls = ctx.getClass(id, ldr);
}
catch (IgniteCheckedException e) {
throw new IOException("Failed to resolve class for ID: " + id, e);
}
OptimizedClassDescriptor desc = clsMap.get(cls);
if (desc == null) {
OptimizedClassDescriptor old = clsMap.putIfAbsent(cls, desc =
new OptimizedClassDescriptor(cls, resolveTypeId(cls.getName(), mapper), clsMap, ctx, mapper));
if (old != null)
desc = old;
}
return desc;
}
/**
* Computes the serial version UID value for the given class. The code is taken from {@link
* ObjectStreamClass#computeDefaultSUID(Class)}.
*
* @param cls A class.
* @param fields Fields.
* @return A serial version UID.
* @throws IOException If failed.
*/
@SuppressWarnings("ForLoopReplaceableByForEach")
static short computeSerialVersionUid(Class cls, List<Field> fields) throws IOException {
if (Serializable.class.isAssignableFrom(cls) && !Enum.class.isAssignableFrom(cls)) {
try {
Field field = cls.getDeclaredField("serialVersionUID");
if (field.getType() == long.class) {
int mod = field.getModifiers();
if (Modifier.isStatic(mod) && Modifier.isFinal(mod)) {
field.setAccessible(true);
return (short)field.getLong(null);
}
}
}
catch (NoSuchFieldException e) {
// No-op.
}
catch (IllegalAccessException e) {
throw new IOException(e);
}
if (OptimizedMarshaller.USE_DFLT_SUID)
return (short)ObjectStreamClass.lookup(cls).getSerialVersionUID();
}
MessageDigest md;
try {
md = MessageDigest.getInstance("SHA");
}
catch (NoSuchAlgorithmException e) {
throw new IOException("Failed to get digest for SHA.", e);
}
md.update(cls.getName().getBytes(UTF_8));
if (!F.isEmpty(fields)) {
for (int i = 0; i < fields.size(); i++) {
Field f = fields.get(i);
md.update(f.getName().getBytes(UTF_8));
md.update(f.getType().getName().getBytes(UTF_8));
}
}
byte[] hashBytes = md.digest();
long hash = 0;
// Composes a single-long hash from the byte[] hash.
for (int i = Math.min(hashBytes.length, 8) - 1; i >= 0; i--)
hash = (hash << 8) | (hashBytes[i] & 0xFF);
return (short)hash;
}
/**
* Gets byte field value.
*
* @param obj Object.
* @param off Field offset.
* @return Byte value.
*/
static byte getByte(Object obj, long off) {
return GridUnsafe.getByteField(obj, off);
}
/**
* Sets byte field value.
*
* @param obj Object.
* @param off Field offset.
* @param val Value.
*/
static void setByte(Object obj, long off, byte val) {
GridUnsafe.putByteField(obj, off, val);
}
/**
* Gets short field value.
*
* @param obj Object.
* @param off Field offset.
* @return Short value.
*/
static short getShort(Object obj, long off) {
return GridUnsafe.getShortField(obj, off);
}
/**
* Sets short field value.
*
* @param obj Object.
* @param off Field offset.
* @param val Value.
*/
static void setShort(Object obj, long off, short val) {
GridUnsafe.putShortField(obj, off, val);
}
/**
* Gets integer field value.
*
* @param obj Object.
* @param off Field offset.
* @return Integer value.
*/
static int getInt(Object obj, long off) {
return GridUnsafe.getIntField(obj, off);
}
/**
* Sets integer field value.
*
* @param obj Object.
* @param off Field offset.
* @param val Value.
*/
static void setInt(Object obj, long off, int val) {
GridUnsafe.putIntField(obj, off, val);
}
/**
* Gets long field value.
*
* @param obj Object.
* @param off Field offset.
* @return Long value.
*/
static long getLong(Object obj, long off) {
return GridUnsafe.getLongField(obj, off);
}
/**
* Sets long field value.
*
* @param obj Object.
* @param off Field offset.
* @param val Value.
*/
static void setLong(Object obj, long off, long val) {
GridUnsafe.putLongField(obj, off, val);
}
/**
* Gets float field value.
*
* @param obj Object.
* @param off Field offset.
* @return Float value.
*/
static float getFloat(Object obj, long off) {
return GridUnsafe.getFloatField(obj, off);
}
/**
* Sets float field value.
*
* @param obj Object.
* @param off Field offset.
* @param val Value.
*/
static void setFloat(Object obj, long off, float val) {
GridUnsafe.putFloatField(obj, off, val);
}
/**
* Gets double field value.
*
* @param obj Object.
* @param off Field offset.
* @return Double value.
*/
static double getDouble(Object obj, long off) {
return GridUnsafe.getDoubleField(obj, off);
}
/**
* Sets double field value.
*
* @param obj Object.
* @param off Field offset.
* @param val Value.
*/
static void setDouble(Object obj, long off, double val) {
GridUnsafe.putDoubleField(obj, off, val);
}
/**
* Gets char field value.
*
* @param obj Object.
* @param off Field offset.
* @return Char value.
*/
static char getChar(Object obj, long off) {
return GridUnsafe.getCharField(obj, off);
}
/**
* Sets char field value.
*
* @param obj Object.
* @param off Field offset.
* @param val Value.
*/
static void setChar(Object obj, long off, char val) {
GridUnsafe.putCharField(obj, off, val);
}
/**
* Gets boolean field value.
*
* @param obj Object.
* @param off Field offset.
* @return Boolean value.
*/
static boolean getBoolean(Object obj, long off) {
return GridUnsafe.getBooleanField(obj, off);
}
/**
* Sets boolean field value.
*
* @param obj Object.
* @param off Field offset.
* @param val Value.
*/
static void setBoolean(Object obj, long off, boolean val) {
GridUnsafe.putBooleanField(obj, off, val);
}
/**
* Gets field value.
*
* @param obj Object.
* @param off Field offset.
* @return Value.
*/
static Object getObject(Object obj, long off) {
return GridUnsafe.getObjectField(obj, off);
}
/**
* Sets field value.
*
* @param obj Object.
* @param off Field offset.
* @param val Value.
*/
static void setObject(Object obj, long off, Object val) {
GridUnsafe.putObjectField(obj, off, val);
}
}
|
923f38c7d692dbccba3d1d0d2997c407cb969abe
| 613 |
java
|
Java
|
src/main/java/com/yishuifengxiao/common/crawler/utils/LocalCrawler.java
|
yishuifengxiao/wind-bell
|
3691166407e9c1aab12f5262c0510c395972d30a
|
[
"Apache-2.0"
] | 5 |
2020-01-04T03:49:57.000Z
|
2021-12-11T04:31:42.000Z
|
src/main/java/com/yishuifengxiao/common/crawler/utils/LocalCrawler.java
|
yishuifengxiao/wind-bell
|
3691166407e9c1aab12f5262c0510c395972d30a
|
[
"Apache-2.0"
] | null | null | null |
src/main/java/com/yishuifengxiao/common/crawler/utils/LocalCrawler.java
|
yishuifengxiao/wind-bell
|
3691166407e9c1aab12f5262c0510c395972d30a
|
[
"Apache-2.0"
] | 4 |
2020-01-04T03:49:56.000Z
|
2020-07-01T03:22:22.000Z
| 14.595238 | 71 | 0.65416 | 1,001,076 |
package com.yishuifengxiao.common.crawler.utils;
import com.yishuifengxiao.common.crawler.Task;
/**
* 风铃虫任务信息线程缓存类
*
* @author yishui
* @date 2019年12月2日
* @version 1.0.0
*/
public final class LocalCrawler {
private volatile static ThreadLocal<Task> LOCAL = new ThreadLocal<>();
/**
* 放置一个风铃虫任务信息
*
* @param crawler
*/
public synchronized static void put(Task crawler) {
LOCAL.set(crawler);
}
/**
* 获取风铃虫任务信息
*
* @return
*/
public synchronized static Task get() {
return LOCAL.get();
}
/**
* 清理缓存
*/
public synchronized static void clear() {
LOCAL.remove();
}
}
|
923f396e37c0c7df267e4e8c76fa93a9a793c388
| 2,747 |
java
|
Java
|
src/main/java/com/thinkaurelius/titan/diskstorage/cassandra/thriftpool/UncheckedGenericKeyedObjectPool.java
|
marciosilva/titan
|
10c6186d0274d8576085a70e37192605216df4b8
|
[
"Apache-2.0"
] | 1 |
2019-02-27T00:14:40.000Z
|
2019-02-27T00:14:40.000Z
|
src/main/java/com/thinkaurelius/titan/diskstorage/cassandra/thriftpool/UncheckedGenericKeyedObjectPool.java
|
buka/titan
|
2c9ccf0dd9d1edfcb39a86ae08dd5fbf37916295
|
[
"Apache-2.0"
] | 1 |
2021-06-22T09:54:03.000Z
|
2021-06-22T09:54:03.000Z
|
src/main/java/com/thinkaurelius/titan/diskstorage/cassandra/thriftpool/UncheckedGenericKeyedObjectPool.java
|
buka/titan
|
2c9ccf0dd9d1edfcb39a86ae08dd5fbf37916295
|
[
"Apache-2.0"
] | 1 |
2021-06-22T09:34:08.000Z
|
2021-06-22T09:34:08.000Z
| 34.3625 | 82 | 0.744998 | 1,001,077 |
package com.thinkaurelius.titan.diskstorage.cassandra.thriftpool;
import com.thinkaurelius.titan.core.GraphStorageException;
import org.apache.commons.pool.KeyedPoolableObjectFactory;
import org.apache.commons.pool.impl.GenericKeyedObjectPool;
/**
* This class extends Apache Commons Pool's GenericKeyedObjectPool, adding
* two methods that support Java 5 generic type safety. However, a
* programmer can still cause RuntimeExceptions related to type errors
* by mixing calls to these additional methods with calls to the legacy
* "Object"-typed methods.
*
* <p>
* Unfortunately, GenericKeyedObjectPool is not actually generic in the
* type-system sense. All of its methods are typed to Object, forcing the
* client programmer to sprinkle code with casts. This class centralizes
* that casting to a single method.
*
* <p>
* As a corollary, this class is slightly less flexible than
* GenericKeyedObjectPool, as this class can only store keys and pooled
* objects each of a single type, whereas GenericKeyedObjectPool could
* theoretically contain heterogeneous types of each. However, I do not
* need the flexibility of heterogeneous types for pooling Thrift
* connections, the original work that precipitated writing this class.
*
* @author Dan LaRocque <[email protected]>
*
* @param <K> Key type
* @param <V> Pooled object type
*/
public class UncheckedGenericKeyedObjectPool<K,V> extends GenericKeyedObjectPool {
public UncheckedGenericKeyedObjectPool(KeyedPoolableObjectFactory factory) {
super(factory);
}
@Override
public Object borrowObject(Object key) {
try {
return super.borrowObject(key);
} catch (Exception e) {
throw new GraphStorageException(e);
}
}
@Override
public void returnObject(Object key, Object o) {
try {
super.returnObject(key, o);
} catch (Exception e) {
throw new GraphStorageException(e);
}
}
/**
* This method internally calls {@link #borrowObject(Object)}
* and casts the return value to type {@code V}. Be careful
* when mixing calls to this method with calls to superclass
* methods that allow the programmer to insert
* arbitrarily-typed objects. That is not recommended, because
* the cast in this method will fail if an object which is not
* of type V is retrieved by {@link #borrowObject(Object)}.
*
* @throws ClassCastException if the programmer permitted pooled
* objects of a type other than V to enter this object and
* tries to borrow one here.
* @param key the pool key
* @return the pooled object
*/
@SuppressWarnings("unchecked")
public V genericBorrowObject(K key) {
return (V)borrowObject(key);
}
public void genericReturnObject(K key, V o) {
returnObject(key, o);
}
}
|
923f3a326051d9325b0408228609bbacb3284182
| 2,578 |
java
|
Java
|
src/main/java/org/spongepowered/common/mixin/core/world/gen/populators/MixinWorldGenerator.java
|
Katrix/SpongeCommon
|
8cbb37305d6be39e6b4fbc3910df5191aa2c2730
|
[
"MIT"
] | null | null | null |
src/main/java/org/spongepowered/common/mixin/core/world/gen/populators/MixinWorldGenerator.java
|
Katrix/SpongeCommon
|
8cbb37305d6be39e6b4fbc3910df5191aa2c2730
|
[
"MIT"
] | null | null | null |
src/main/java/org/spongepowered/common/mixin/core/world/gen/populators/MixinWorldGenerator.java
|
Katrix/SpongeCommon
|
8cbb37305d6be39e6b4fbc3910df5191aa2c2730
|
[
"MIT"
] | null | null | null | 42.262295 | 113 | 0.752909 | 1,001,078 |
/*
* This file is part of Sponge, licensed under the MIT License (MIT).
*
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.spongepowered.common.mixin.core.world.gen.populators;
import net.minecraft.block.Block;
import net.minecraft.block.material.Material;
import net.minecraft.block.state.IBlockState;
import net.minecraft.init.Blocks;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
import net.minecraft.world.gen.feature.WorldGenerator;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
@Mixin(WorldGenerator.class)
public abstract class MixinWorldGenerator {
@Shadow public abstract void setDecorationDefaults();
//These are overridden in forge to call the forge added Block.isAir/isLeaves
public boolean isAir(IBlockState state, World worldIn, BlockPos pos) {
return state.getMaterial() == Material.AIR;
}
public boolean isLeaves(IBlockState state, World worldIn, BlockPos pos) {
return state.getMaterial() == Material.LEAVES;
}
public boolean isWood(IBlockState state, World worldIn, BlockPos pos) {
return state.getMaterial() == Material.WOOD;
}
public boolean canSustainPlant(Block block, World worldIn, BlockPos pos, EnumFacing direction, Block plant) {
return block == Blocks.GRASS || block == Blocks.DIRT || block == Blocks.FARMLAND;
}
}
|
923f3a330a4f94de88555c35d8235c509fa95934
| 2,504 |
java
|
Java
|
ksqldb-engine/src/test/java/io/confluent/ksql/function/udf/list/SliceTest.java
|
aculver28/ksql
|
42cffe268a61dbbf0e86a1d3c1b478058c89f812
|
[
"Apache-2.0"
] | 1 |
2019-05-03T19:31:00.000Z
|
2019-05-03T19:31:00.000Z
|
ksqldb-engine/src/test/java/io/confluent/ksql/function/udf/list/SliceTest.java
|
aculver28/ksql
|
42cffe268a61dbbf0e86a1d3c1b478058c89f812
|
[
"Apache-2.0"
] | null | null | null |
ksqldb-engine/src/test/java/io/confluent/ksql/function/udf/list/SliceTest.java
|
aculver28/ksql
|
42cffe268a61dbbf0e86a1d3c1b478058c89f812
|
[
"Apache-2.0"
] | null | null | null | 25.04 | 81 | 0.65655 | 1,001,079 |
/*
* Copyright 2019 Confluent Inc.
*
* Licensed under the Confluent Community License (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.confluent.io/confluent-community-license
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package io.confluent.ksql.function.udf.list;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.nullValue;
import com.google.common.collect.Lists;
import java.util.List;
import org.junit.Test;
public class SliceTest {
@Test
public void shouldOneIndexSlice() {
// Given:
final List<String> list = Lists.newArrayList("a", "b", "c");
// When:
final List<String> slice = new Slice().slice(list, 1, 2);
// Then:
assertThat(slice, is(Lists.newArrayList("a", "b")));
}
@Test
public void shouldFullListOnNullEndpoints() {
// Given:
final List<String> list = Lists.newArrayList("a", "b", "c");
// When:
final List<String> slice = new Slice().slice(list, null, null);
// Then:
assertThat(slice, is(Lists.newArrayList("a", "b", "c")));
}
@Test
public void shouldOneElementSlice() {
// Given:
final List<String> list = Lists.newArrayList("a", "b", "c");
// When:
final List<String> slice = new Slice().slice(list, 2, 2);
// Then:
assertThat(slice, is(Lists.newArrayList("b")));
}
@Test
public void shouldHandleIntegers() {
// Given:
final List<Integer> list = Lists.newArrayList(1, 2, 3);
// When:
final List<Integer> slice = new Slice().slice(list, 2, 2);
// Then:
assertThat(slice, is(Lists.newArrayList(2)));
}
@Test
public void shouldReturnNullOnIndexError() {
// Given:
final List<String> list = Lists.newArrayList("a", "b", "c");
// When:
final List<String> slice = new Slice().slice(list, 2, 5);
// Then:
assertThat(slice, nullValue());
}
@Test
public void shouldReturnNullOnNullInput() {
// Given:
final List<String> list = null;
// When:
final List<String> slice = new Slice().slice(list, 1, 2);
// Then:
assertThat(slice, nullValue());
}
}
|
923f3a58127b20edc3d13daaa9f11dc1b0387e31
| 6,988 |
java
|
Java
|
src/test/java/com/github/f4b6a3/uuid/factory/rfc4122/TimeOrderedFactoryTest.java
|
lbruun/uuid-creator
|
74018f0c5c193a404e22cdb16c2f189faeef7d86
|
[
"MIT"
] | 153 |
2019-04-20T22:48:01.000Z
|
2022-03-28T15:48:00.000Z
|
src/test/java/com/github/f4b6a3/uuid/factory/rfc4122/TimeOrderedFactoryTest.java
|
lbruun/uuid-creator
|
74018f0c5c193a404e22cdb16c2f189faeef7d86
|
[
"MIT"
] | 59 |
2019-04-14T08:14:29.000Z
|
2022-03-22T18:28:08.000Z
|
src/test/java/com/github/f4b6a3/uuid/factory/rfc4122/TimeOrderedFactoryTest.java
|
lbruun/uuid-creator
|
74018f0c5c193a404e22cdb16c2f189faeef7d86
|
[
"MIT"
] | 23 |
2019-04-13T21:18:17.000Z
|
2022-03-09T00:19:07.000Z
| 31.196429 | 99 | 0.736835 | 1,001,080 |
package com.github.f4b6a3.uuid.factory.rfc4122;
import org.junit.Test;
import com.github.f4b6a3.uuid.UuidCreator;
import com.github.f4b6a3.uuid.factory.UuidFactoryTest;
import com.github.f4b6a3.uuid.factory.function.ClockSeqFunction;
import com.github.f4b6a3.uuid.factory.function.NodeIdFunction;
import com.github.f4b6a3.uuid.factory.rfc4122.TimeOrderedFactory;
import com.github.f4b6a3.uuid.util.UuidTime;
import com.github.f4b6a3.uuid.util.UuidUtil;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.time.Instant;
import java.util.Random;
import java.util.UUID;
public class TimeOrderedFactoryTest extends UuidFactoryTest {
@Test
public void testTimeOrdered() {
boolean multicast = true;
testGetAbstractTimeBased(new TimeOrderedFactory(), multicast);
}
@Test
public void testTimeOrderedWithMac() {
boolean multicast = false;
testGetAbstractTimeBased(TimeOrderedFactory.builder().withMacNodeId().build(), multicast);
}
@Test
public void testTimeOrderedWithHash() {
boolean multicast = true;
testGetAbstractTimeBased(TimeOrderedFactory.builder().withHashNodeId().build(), multicast);
}
@Test
public void testGetTimeOrderedWithNodeIdFunction() {
long nodeid = NodeIdFunction.toExpectedRange(System.nanoTime());
NodeIdFunction nodeIdFunction = () -> nodeid;
long nodeIdentifier1 = nodeIdFunction.getAsLong();
UUID uuid = TimeOrderedFactory.builder().withNodeIdFunction(nodeIdFunction).build().create();
long nodeIdentifier2 = UuidUtil.getNodeIdentifier(uuid);
assertEquals(nodeIdentifier1, nodeIdentifier2);
}
@Test
public void testGetTimeOrderedWithClockSeqFunction() {
long clockSeq = ClockSeqFunction.toExpectedRange((int) System.nanoTime());
ClockSeqFunction clockSeqFunction = x -> clockSeq;
long clockseq1 = clockSeqFunction.applyAsLong(0);
UUID uuid = TimeOrderedFactory.builder().withClockSeqFunction(clockSeqFunction).build().create();
long clockseq2 = UuidUtil.getClockSequence(uuid);
assertEquals(clockseq1, clockseq2);
}
@Test
public void testGetTimeOrderedTimestampBitsAreTimeOrdered() {
UUID[] list = new UUID[DEFAULT_LOOP_MAX];
TimeOrderedFactory factory = new TimeOrderedFactory();
for (int i = 0; i < DEFAULT_LOOP_MAX; i++) {
list[i] = factory.create();
}
long oldTimestemp = 0;
for (int i = 0; i < DEFAULT_LOOP_MAX; i++) {
long newTimestamp = UuidUtil.getTimestamp(list[i]);
if (i > 0) {
assertTrue(newTimestamp >= oldTimestemp);
}
oldTimestemp = newTimestamp;
}
}
@Test
public void testGetTimeOrderedCheckTimestamp() {
for (int i = 0; i < DEFAULT_LOOP_MAX; i++) {
Instant instant1 = Instant.now();
UUID uuid = TimeOrderedFactory.builder().withInstant(instant1).build().create();
Instant instant2 = UuidUtil.getInstant(uuid);
long timestamp1 = UuidTime.toGregTimestamp(instant1);
long timestamp2 = UuidTime.toGregTimestamp(instant2);
assertEquals(timestamp1, timestamp2);
}
}
@Test
public void testGetTimeOrderedCheckOrder() {
UUID[] list = new UUID[DEFAULT_LOOP_MAX];
TimeOrderedFactory factory = new TimeOrderedFactory();
// Create list of UUIDs
for (int i = 0; i < DEFAULT_LOOP_MAX; i++) {
list[i] = factory.create();
}
// Check if the MSBs are ordered
long old = 0;
for (int i = 0; i < DEFAULT_LOOP_MAX; i++) {
long msb = list[i].getMostSignificantBits();
if (i > 0) {
assertTrue(msb > old);
}
old = msb;
}
}
@Test
public void testGetTimeOrderedCheckGreatestTimestamp() {
// Check if the greatest 60 bit timestamp corresponds to the date
long maxTimestamp = 0x0fffffffffffffffL;
Instant maxInstant = Instant.parse("5236-03-31T21:21:00.684697500Z");
UUID uuid = TimeOrderedFactory.builder().withInstant(maxInstant).build().create();
// Test the extraction of the maximum 60 bit timestamp
long timestamp = UuidUtil.getTimestamp(uuid);
assertEquals(maxTimestamp, timestamp);
// Test the extraction of the maximum date and time
Instant instant = UuidUtil.getInstant(uuid);
assertEquals(maxInstant, instant);
}
@Test
public void testGetTimeOrderedInParallel() throws InterruptedException {
Thread[] threads = new Thread[THREAD_TOTAL];
TestThread.clearHashSet();
// Instantiate and start many threads
for (int i = 0; i < THREAD_TOTAL; i++) {
TimeOrderedFactory factory = TimeOrderedFactory.builder().withHashNodeId().build();
threads[i] = new TestThread(factory, DEFAULT_LOOP_MAX);
threads[i].start();
}
// Wait all the threads to finish
for (Thread thread : threads) {
thread.join();
}
// Check if the quantity of unique UUIDs is correct
assertEquals(DUPLICATE_UUID_MSG, (DEFAULT_LOOP_MAX * THREAD_TOTAL), TestThread.hashSet.size());
}
@Test
public void testGetTimeOrderedWithOptionalArguments() {
Random random = new Random();
for (int i = 0; i < DEFAULT_LOOP_MAX; i++) {
// Get 46 random bits to generate a date from the year 1970 to 2193.
// (2^46 / 10000 / 60 / 60 / 24 / 365.25 + 1970 A.D. = ~2193 A.D.)
final Instant instant = Instant.ofEpochMilli(random.nextLong() >>> 24);
// Get 14 random bits random to generate the clock sequence
final int clockseq = random.nextInt() & 0x000003ff;
// Get 48 random bits for the node identifier, and set the multicast bit to ONE
final long nodeid = random.nextLong() & 0x0000ffffffffffffL | 0x0000010000000000L;
// Create a time-based UUID with those random values
UUID uuid = UuidCreator.getTimeOrdered(instant, clockseq, nodeid);
// Check if it is valid
assertTrue(UuidUtil.isRfc4122(uuid));
// Check if the embedded values are correct.
assertEquals("The timestamp is incorrect.", instant, UuidUtil.getInstant(uuid));
assertEquals("The node identifier is incorrect", nodeid, UuidUtil.getNodeIdentifier(uuid));
assertEquals("The clock sequence is incorrect", clockseq, UuidUtil.getClockSequence(uuid));
// Repeat the same tests to time-based UUIDs with hardware address, ignoring the
// node identifier
// Create a time-based UUID with those random values
uuid = UuidCreator.getTimeOrderedWithMac(instant, clockseq);
// Check if it is valid
assertTrue(UuidUtil.isRfc4122(uuid));
// Check if the embedded values are correct.
assertEquals("The timestamp is incorrect.", instant, UuidUtil.getInstant(uuid));
assertEquals("The clock sequence is incorrect", clockseq, UuidUtil.getClockSequence(uuid));
// Repeat the same tests to time-based UUIDs with system data hash, ignoring the
// node identifier
// Create a time-based UUID with those random values
uuid = UuidCreator.getTimeOrderedWithHash(instant, clockseq);
// Check if it is valid
assertTrue(UuidUtil.isRfc4122(uuid));
// Check if the embedded values are correct.
assertEquals("The timestamp is incorrect.", instant, UuidUtil.getInstant(uuid));
assertEquals("The clock sequence is incorrect", clockseq, UuidUtil.getClockSequence(uuid));
}
}
}
|
923f3ba6a55d30b4b09a0b407ff25fb032625a0e
| 1,519 |
java
|
Java
|
Exareme-Docker/src/exareme/exareme-worker/src/main/java/madgik/exareme/worker/art/managementBean/ManagementUtil.java
|
tchamabe1979/exareme
|
462983e4feec7808e1fd447d02901502588a8879
|
[
"MIT"
] | null | null | null |
Exareme-Docker/src/exareme/exareme-worker/src/main/java/madgik/exareme/worker/art/managementBean/ManagementUtil.java
|
tchamabe1979/exareme
|
462983e4feec7808e1fd447d02901502588a8879
|
[
"MIT"
] | null | null | null |
Exareme-Docker/src/exareme/exareme-worker/src/main/java/madgik/exareme/worker/art/managementBean/ManagementUtil.java
|
tchamabe1979/exareme
|
462983e4feec7808e1fd447d02901502588a8879
|
[
"MIT"
] | null | null | null | 35.325581 | 89 | 0.665569 | 1,001,081 |
/**
* Copyright MaDgIK Group 2010 - 2015.
*/
package madgik.exareme.worker.art.managementBean;
import javax.management.MBeanServer;
import javax.management.ObjectName;
import java.lang.management.ManagementFactory;
import java.rmi.RemoteException;
/**
* @author Herald Kllapi <br>
* University of Athens /
* Department of Informatics and Telecommunications.
* @since 1.0
*/
public class ManagementUtil {
public static void registerMBean(Object object, String name) throws RemoteException {
try {
MBeanServer beanServer = ManagementFactory.getPlatformMBeanServer();
ObjectName engineManagerName =
new ObjectName("madgik.exareme.db:type=art,name=" + name);
if (!beanServer.isRegistered(engineManagerName))
beanServer.registerMBean(object, engineManagerName);
} catch (Exception e) {
throw new RemoteException("Cannot register bean: " + name, e);
}
}
public static void unregisterMBean(String name) throws RemoteException {
try {
MBeanServer beanServer = ManagementFactory.getPlatformMBeanServer();
ObjectName engineManagerName =
new ObjectName("madgik.exareme.db:type=art,name=" + name);
if (beanServer.isRegistered(engineManagerName))
beanServer.unregisterMBean(engineManagerName);
} catch (Exception e) {
throw new RemoteException("Cannot unregister bean: " + name, e);
}
}
}
|
923f3baee2012fbd9adcce261bc72fb1f9185f83
| 6,612 |
java
|
Java
|
fiestas-back/src/main/java/co/edu/uniandes/csw/fiestas/ejb/ServicioLogic.java
|
Uniandes-isis2603/s2_g1_fiestas
|
2ecfac51be040c96468eb0147f07b57d7fbf8e40
|
[
"MIT"
] | null | null | null |
fiestas-back/src/main/java/co/edu/uniandes/csw/fiestas/ejb/ServicioLogic.java
|
Uniandes-isis2603/s2_g1_fiestas
|
2ecfac51be040c96468eb0147f07b57d7fbf8e40
|
[
"MIT"
] | null | null | null |
fiestas-back/src/main/java/co/edu/uniandes/csw/fiestas/ejb/ServicioLogic.java
|
Uniandes-isis2603/s2_g1_fiestas
|
2ecfac51be040c96468eb0147f07b57d7fbf8e40
|
[
"MIT"
] | null | null | null | 39.357143 | 111 | 0.676951 | 1,001,082 |
/*
* 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 co.edu.uniandes.csw.fiestas.ejb;
import co.edu.uniandes.csw.fiestas.entities.ProductoEntity;
import co.edu.uniandes.csw.fiestas.entities.ServicioEntity;
import co.edu.uniandes.csw.fiestas.exceptions.BusinessLogicException;
import co.edu.uniandes.csw.fiestas.persistence.ServicioPersistence;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ejb.Stateless;
import javax.inject.Inject;
/**
* Clase que implementa la conexion con la persistencia para la entidad de
* Servicio.
*
* @author ls.arias
*/
@Stateless
public class ServicioLogic {
private static final Logger LOGGER = Logger.getLogger(ServicioLogic.class.getName());
@Inject
private ServicioPersistence persistence;
/**
* Obtiene la lista de los registros de Servicio.
*
* @return Colección de objetos de ServicioEntity.
*/
public List<ServicioEntity> getServicios() {
LOGGER.log(Level.INFO, "Inicia proceso de consultar todos los servicios");
return persistence.findAll();
}
/**
* Obtiene los datos de una instancia de Servicio a partir de su ID.
*
* @param id Identificador de la instancia a consultar
* @return Instancia de ServicioEntity con los datos del Servicio consultado.
*/
public ServicioEntity getServicio(Long id) {
LOGGER.log(Level.INFO, "Inicia proceso de consultar el servicio con el id dado");
return persistence.find(id);
}
/**
* Se encarga de crear un Servicio en la base de datos.
*
* @param entity Objeto de ServicioEntity con los datos nuevos
* @return Objeto de ServicioEntity con los datos nuevos y su ID.
*/
public ServicioEntity createServicio(ServicioEntity entity) {
LOGGER.log(Level.INFO, "Inicia proceso de crear un servicio");
return persistence.create(entity);
}
/**
* Actualiza la información de una instancia de Servicio.
*
* @param entity Instancia de ServicioEntity con los nuevos datos.
* @return Instancia de ServicioEntity con los datos actualizados.
* @throws co.edu.uniandes.csw.fiestas.exceptions.BusinessLogicException
*/
public ServicioEntity updateServicio(ServicioEntity entity) throws BusinessLogicException {
LOGGER.log(Level.INFO, "Inicia proceso de actualizar un servicio");
if(getServicio(entity.getId()) == null)
{
throw new BusinessLogicException("No existe un servicio con dicho id para actualizar");
}
return persistence.update(entity);
}
/**
* Elimina una instancia de Servicio de la base de datos.
*
* @param id Identificador de la instancia a eliminar.
* @throws co.edu.uniandes.csw.fiestas.exceptions.BusinessLogicException
*/
public void deleteServicio(Long id) throws BusinessLogicException {
LOGGER.log(Level.INFO, "Inicia proceso de borrar un servicio.");
if(persistence.find(id)==null)
{
throw new BusinessLogicException("El servicio que se quiere borrar no existe.");
}
persistence.delete(id);
}
/**
* Obtiene una colección de instancias de ProductoEntity asociadas a una
* instancia de Servicio
*
* @param servicioId Identificador de la instancia de Servicio
* @return Colección de instancias de ProductoEntity asociadas a la instancia
* de Servicio
*
*/
public List<ProductoEntity> listProductos(Long servicioId) {
LOGGER.log(Level.INFO, "Inicia proceso de consultar la lista de productos asociada a un servicio.");
return getServicio(servicioId).getProductos();
}
/**
* Obtiene una instancia de ProductoEntity asociada a una instancia de Servicio
*
* @param servicioId Identificador de la instancia de Servicio
* @param productosId Identificador de la instancia de Producto
* @return La entidad del Producto asociada al servicio
* @throws co.edu.uniandes.csw.fiestas.exceptions.BusinessLogicException
*/
public ProductoEntity getProducto(Long servicioId, Long productosId) throws BusinessLogicException {
LOGGER.log(Level.INFO, "Inicia proceso de consultar el producto con el id dado asociado al servicio");
List<ProductoEntity> list = getServicio(servicioId).getProductos();
ProductoEntity productoEntity = new ProductoEntity();
productoEntity.setId(productosId);
int index = list.indexOf(productoEntity);
if (index >= 0) {
return list.get(index);
}
throw new BusinessLogicException("El producto no está asociado al servicio");
}
/**
* Asocia un Producto existente a un Servicio
*
* @param servicioId Identificador de la instancia de Servicio
* @param productoId Identificador de la instancia de Producto
* @return Instancia de ProductoEntity que fue asociada a Servicio
* @throws co.edu.uniandes.csw.fiestas.exceptions.BusinessLogicException
*
*/
public ProductoEntity addProducto(Long servicioId, Long productoId) throws BusinessLogicException {
LOGGER.log(Level.INFO, "Inicia proceso de agregar un producto al servicio");
ServicioEntity servicioEntity = getServicio(servicioId);
ProductoEntity productoEntity = new ProductoEntity();
productoEntity.setId(productoId);
servicioEntity.getProductos().add(productoEntity);
return getProducto(servicioId, productoId);
}
/**
* Desasocia un Producto existente de un Servicio existente
* @param servicioId Identificador de la instancia de Servicio
* @param productosId Identificador de la instancia de Producto
*
*/
public void removeProducto(Long servicioId, Long productosId) throws BusinessLogicException {
LOGGER.log(Level.INFO, "Inicia proceso de eliminar el producto asociado al servicio");
ServicioEntity entity = getServicio(servicioId);
ProductoEntity productosEntity = new ProductoEntity();
productosEntity.setId(productosId);
entity.getProductos().remove(productosEntity);
updateServicio(entity);
}
}
|
923f3c47cc85a59cee2ba7776b6e9758d6a7fec0
| 2,720 |
java
|
Java
|
phoenix-core/src/main/java/com/salesforce/phoenix/index/BaseIndexCodec.java
|
ifwe/phoenix-salesforce
|
5e49d5f940f9dbd2538fb890f0cc6697068c74ac
|
[
"BSD-3-Clause"
] | 127 |
2015-01-05T08:44:58.000Z
|
2021-03-22T20:09:57.000Z
|
phoenix-core/src/main/java/com/salesforce/phoenix/index/BaseIndexCodec.java
|
ifwe/phoenix-salesforce
|
5e49d5f940f9dbd2538fb890f0cc6697068c74ac
|
[
"BSD-3-Clause"
] | 18 |
2015-01-09T15:29:11.000Z
|
2018-01-12T09:34:10.000Z
|
phoenix-core/src/main/java/com/salesforce/phoenix/index/BaseIndexCodec.java
|
ifwe/phoenix-salesforce
|
5e49d5f940f9dbd2538fb890f0cc6697068c74ac
|
[
"BSD-3-Clause"
] | 65 |
2015-01-13T15:56:53.000Z
|
2021-09-08T12:18:15.000Z
| 39.42029 | 100 | 0.699632 | 1,001,083 |
/*******************************************************************************
* Copyright (c) 2013, Salesforce.com, Inc.
* 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 Salesforce.com 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 HOLDER 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 com.salesforce.phoenix.index;
import java.io.IOException;
import org.apache.hadoop.hbase.client.Mutation;
import org.apache.hadoop.hbase.coprocessor.RegionCoprocessorEnvironment;
import com.salesforce.hbase.index.covered.IndexCodec;
/**
*
*/
public abstract class BaseIndexCodec implements IndexCodec {
@Override
public void initialize(RegionCoprocessorEnvironment env) throws IOException {
// noop
}
/**
* {@inheritDoc}
* <p>
* By default, the codec is always enabled. Subclasses should override this method if they want do
* decide to index on a per-mutation basis.
* @throws IOException
*/
@Override
public boolean isEnabled(Mutation m) throws IOException {
return true;
}
/**
* {@inheritDoc}
* <p>
* Assumes each mutation is not in a batch. Subclasses that have different batching behavior
* should override this.
*/
@Override
public byte[] getBatchId(Mutation m) {
return null;
}
}
|
923f3c4b2c2253b160e56010ffd053821991d430
| 996 |
java
|
Java
|
aat/src/aat/java/uk/gov/hmcts/ccd/definitionstore/befta/DefinitionStoreBeftaRunner.java
|
banderous/ccd-definition-store-api
|
8668a29f47eb1647c0e890bf26bb37a528aad14c
|
[
"MIT"
] | 7 |
2020-05-19T08:09:58.000Z
|
2022-01-07T12:43:56.000Z
|
aat/src/aat/java/uk/gov/hmcts/ccd/definitionstore/befta/DefinitionStoreBeftaRunner.java
|
banderous/ccd-definition-store-api
|
8668a29f47eb1647c0e890bf26bb37a528aad14c
|
[
"MIT"
] | 950 |
2018-05-01T09:37:08.000Z
|
2022-03-31T17:41:32.000Z
|
aat/src/aat/java/uk/gov/hmcts/ccd/definitionstore/befta/DefinitionStoreBeftaRunner.java
|
duranfatih/ccd-definition-store-api
|
23d5477f0f58e676c1e55a0f7800f7605ebbc35b
|
[
"MIT"
] | 11 |
2018-06-01T10:20:46.000Z
|
2022-03-03T13:57:15.000Z
| 26.210526 | 107 | 0.696787 | 1,001,084 |
package uk.gov.hmcts.ccd.definitionstore.befta;
import io.cucumber.junit.Cucumber;
import io.cucumber.junit.CucumberOptions;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.runner.RunWith;
import uk.gov.hmcts.befta.BeftaMain;
@RunWith(Cucumber.class)
@CucumberOptions(
plugin = { "json:target/cucumber.json", "pretty" },
glue = { "uk.gov.hmcts.befta.player" },
features = { "classpath:features" },
tags = { "not @Ignore" }
)
public class DefinitionStoreBeftaRunner {
private DefinitionStoreBeftaRunner() {
// Hide Utility Class Constructor : Utility classes should not have a public or default constructor
// (squid:S1118)
}
@BeforeClass
public static void setUp() {
var taAdapter = new DefinitionStoreTestAutomationAdapter();
taAdapter.initialiseTestDataLoader();
BeftaMain.setUp(taAdapter);
}
@AfterClass
public static void tearDown() {
BeftaMain.tearDown();
}
}
|
923f3d9f91a6e965f35d04222eea48c2ed1e24ec
| 3,102 |
java
|
Java
|
wayang-plugins/wayang-iejoin/code/main/java/org/apache/wayang/iejoin/mapping/spark/IESelfJoinMapping.java
|
hboutemy/incubator-wayang
|
a91bd3615432cd8f3bf44bd2f4b99b5d8df3cdba
|
[
"Apache-2.0"
] | 67 |
2021-02-15T18:59:42.000Z
|
2022-03-28T06:27:41.000Z
|
wayang-plugins/wayang-iejoin/code/main/java/org/apache/wayang/iejoin/mapping/spark/IESelfJoinMapping.java
|
hboutemy/incubator-wayang
|
a91bd3615432cd8f3bf44bd2f4b99b5d8df3cdba
|
[
"Apache-2.0"
] | 76 |
2021-02-09T13:00:41.000Z
|
2022-03-30T22:48:50.000Z
|
wayang-plugins/wayang-iejoin/code/main/java/org/apache/wayang/iejoin/mapping/spark/IESelfJoinMapping.java
|
hboutemy/incubator-wayang
|
a91bd3615432cd8f3bf44bd2f4b99b5d8df3cdba
|
[
"Apache-2.0"
] | 23 |
2021-02-07T05:19:10.000Z
|
2022-03-04T18:05:20.000Z
| 47.723077 | 212 | 0.77176 | 1,001,085 |
/*
* 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.wayang.iejoin.mapping.spark;
import org.apache.wayang.basic.data.Record;
import org.apache.wayang.core.mapping.Mapping;
import org.apache.wayang.core.mapping.OperatorPattern;
import org.apache.wayang.core.mapping.PlanTransformation;
import org.apache.wayang.core.mapping.ReplacementSubplanFactory;
import org.apache.wayang.core.mapping.SubplanMatch;
import org.apache.wayang.core.mapping.SubplanPattern;
import org.apache.wayang.core.plan.wayangplan.Operator;
import org.apache.wayang.core.types.DataSetType;
import org.apache.wayang.iejoin.operators.IEJoinMasterOperator;
import org.apache.wayang.iejoin.operators.IESelfJoinOperator;
import org.apache.wayang.iejoin.operators.SparkIESelfJoinOperator;
import org.apache.wayang.spark.platform.SparkPlatform;
import java.util.Collection;
import java.util.Collections;
/**
* Mapping from {@link IESelfJoinOperator} to {@link SparkIESelfJoinOperator}.
*/
public class IESelfJoinMapping implements Mapping {
@Override
public Collection<PlanTransformation> getTransformations() {
return Collections.singleton(new PlanTransformation(this.createSubplanPattern(), new ReplacementFactory(),
SparkPlatform.getInstance()));
}
private SubplanPattern createSubplanPattern() {
final OperatorPattern operatorPattern = new OperatorPattern(
"ieselfjoin", new IESelfJoinOperator<>(DataSetType.none(), null, IEJoinMasterOperator.JoinCondition.GreaterThan, null, IEJoinMasterOperator.JoinCondition.GreaterThan), false);
return SubplanPattern.createSingleton(operatorPattern);
}
private static class ReplacementFactory<InputType0 extends Record, InputType1 extends Record,
Type0 extends Comparable<Type0>, Type1 extends Comparable<Type1>> extends ReplacementSubplanFactory {
@Override
protected Operator translate(SubplanMatch subplanMatch, int epoch) {
final IESelfJoinOperator<?, ?, ?> originalOperator = (IESelfJoinOperator<?, ?, ?>) subplanMatch.getMatch("ieselfjoin").getOperator();
return new SparkIESelfJoinOperator(originalOperator.getInputType(), originalOperator.getGet0Pivot(), originalOperator.getCond0(), originalOperator.getGet0Ref(), originalOperator.getCond1()).at(epoch);
}
}
}
|
923f3fbf0fa40a9e7f914b756a7c05748e00d28a
| 3,434 |
java
|
Java
|
syncer-jedis/src/main/java/syncer/jedis/ShardedJedisPool.java
|
susongyan/redissyncer-server
|
410f2b68c9388a14d91f6f2e5c0cffe0ebcc1d73
|
[
"Apache-2.0"
] | 558 |
2021-01-22T09:30:06.000Z
|
2022-03-21T07:10:06.000Z
|
syncer-jedis/src/main/java/syncer/jedis/ShardedJedisPool.java
|
susongyan/redissyncer-server
|
410f2b68c9388a14d91f6f2e5c0cffe0ebcc1d73
|
[
"Apache-2.0"
] | 16 |
2021-04-22T02:03:18.000Z
|
2022-03-29T03:08:34.000Z
|
syncer-jedis/src/main/java/syncer/jedis/ShardedJedisPool.java
|
susongyan/redissyncer-server
|
410f2b68c9388a14d91f6f2e5c0cffe0ebcc1d73
|
[
"Apache-2.0"
] | 75 |
2021-01-22T10:42:21.000Z
|
2022-03-10T07:01:38.000Z
| 28.857143 | 98 | 0.692778 | 1,001,086 |
package syncer.jedis;
import org.apache.commons.pool2.PooledObject;
import org.apache.commons.pool2.PooledObjectFactory;
import org.apache.commons.pool2.impl.DefaultPooledObject;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import syncer.jedis.util.Hashing;
import syncer.jedis.util.Pool;
import java.util.List;
import java.util.regex.Pattern;
public class ShardedJedisPool extends Pool<ShardedJedis> {
public ShardedJedisPool(final GenericObjectPoolConfig poolConfig, List<JedisShardInfo> shards) {
this(poolConfig, shards, Hashing.MURMUR_HASH);
}
public ShardedJedisPool(final GenericObjectPoolConfig poolConfig, List<JedisShardInfo> shards,
Hashing algo) {
this(poolConfig, shards, algo, null);
}
public ShardedJedisPool(final GenericObjectPoolConfig poolConfig, List<JedisShardInfo> shards,
Pattern keyTagPattern) {
this(poolConfig, shards, Hashing.MURMUR_HASH, keyTagPattern);
}
public ShardedJedisPool(final GenericObjectPoolConfig poolConfig, List<JedisShardInfo> shards,
Hashing algo, Pattern keyTagPattern) {
super(poolConfig, new ShardedJedisFactory(shards, algo, keyTagPattern));
}
@Override
public ShardedJedis getResource() {
ShardedJedis jedis = super.getResource();
jedis.setDataSource(this);
return jedis;
}
@Override
protected void returnBrokenResource(final ShardedJedis resource) {
if (resource != null) {
returnBrokenResourceObject(resource);
}
}
@Override
protected void returnResource(final ShardedJedis resource) {
if (resource != null) {
resource.resetState();
returnResourceObject(resource);
}
}
/**
* PoolableObjectFactory custom impl.
*/
private static class ShardedJedisFactory implements PooledObjectFactory<ShardedJedis> {
private List<JedisShardInfo> shards;
private Hashing algo;
private Pattern keyTagPattern;
public ShardedJedisFactory(List<JedisShardInfo> shards, Hashing algo, Pattern keyTagPattern) {
this.shards = shards;
this.algo = algo;
this.keyTagPattern = keyTagPattern;
}
@Override
public PooledObject<ShardedJedis> makeObject() throws Exception {
ShardedJedis jedis = new ShardedJedis(shards, algo, keyTagPattern);
return new DefaultPooledObject<ShardedJedis>(jedis);
}
@Override
public void destroyObject(PooledObject<ShardedJedis> pooledShardedJedis) throws Exception {
final ShardedJedis shardedJedis = pooledShardedJedis.getObject();
for (Jedis jedis : shardedJedis.getAllShards()) {
if (jedis.isConnected()) {
try {
try {
jedis.quit();
} catch (Exception e) {
}
jedis.disconnect();
} catch (Exception e) {
}
}
}
}
@Override
public boolean validateObject(PooledObject<ShardedJedis> pooledShardedJedis) {
try {
ShardedJedis jedis = pooledShardedJedis.getObject();
for (Jedis shard : jedis.getAllShards()) {
if (!"PONG".equals(shard.ping())) {
return false;
}
}
return true;
} catch (Exception ex) {
return false;
}
}
@Override
public void activateObject(PooledObject<ShardedJedis> p) throws Exception {
}
@Override
public void passivateObject(PooledObject<ShardedJedis> p) throws Exception {
}
}
}
|
923f41bc62934c957c9867ed1e04b7888b679575
| 173 |
java
|
Java
|
src/main/java/net/minecraft/world/MinecraftException.java
|
eldariamc/clien
|
c01d23eb05ed83abb4fee00f9bf603b6bc3e2e27
|
[
"MIT"
] | 10 |
2019-08-08T12:00:44.000Z
|
2021-11-25T19:43:52.000Z
|
src/main/java/net/minecraft/world/MinecraftException.java
|
eldariamc/clien
|
c01d23eb05ed83abb4fee00f9bf603b6bc3e2e27
|
[
"MIT"
] | null | null | null |
src/main/java/net/minecraft/world/MinecraftException.java
|
eldariamc/clien
|
c01d23eb05ed83abb4fee00f9bf603b6bc3e2e27
|
[
"MIT"
] | 14 |
2018-07-13T11:17:16.000Z
|
2022-01-26T15:23:47.000Z
| 15.727273 | 49 | 0.716763 | 1,001,087 |
package net.minecraft.world;
public class MinecraftException extends Exception
{
public MinecraftException(String p_i1955_1_)
{
super(p_i1955_1_);
}
}
|
923f42a09de21baacd2c2ed73a41fb60ae350e37
| 923 |
java
|
Java
|
src/main/java/eu/macphail/amqclitoolset/amq/control/JmsClient.java
|
mmacphail/amq-cli-toolset
|
09215425135829ea82cb27cb236c165f42c7d899
|
[
"MIT"
] | null | null | null |
src/main/java/eu/macphail/amqclitoolset/amq/control/JmsClient.java
|
mmacphail/amq-cli-toolset
|
09215425135829ea82cb27cb236c165f42c7d899
|
[
"MIT"
] | null | null | null |
src/main/java/eu/macphail/amqclitoolset/amq/control/JmsClient.java
|
mmacphail/amq-cli-toolset
|
09215425135829ea82cb27cb236c165f42c7d899
|
[
"MIT"
] | null | null | null | 29.774194 | 82 | 0.71506 | 1,001,088 |
package eu.macphail.amqclitoolset.amq.control;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.stereotype.Component;
import javax.jms.BytesMessage;
@Slf4j
@Component
public class JmsClient {
@Autowired
private JmsTemplate jmsTemplate;
public void sendTextMessage(String destination, String text) {
jmsTemplate.send(destination, session -> session.createTextMessage(text));
log.trace("Text message sent at " + destination);
}
public void sendBytesMessage(String destination, byte[] payload) {
jmsTemplate.send(destination, session -> {
BytesMessage message = session.createBytesMessage();
message.writeBytes(payload);
return message;
});
log.trace("Bytes message sent at " + destination);
}
}
|
923f440617a2229c2b8faf085c918d1f81776527
| 2,277 |
java
|
Java
|
apptbook/src/main/java/edu/pdx/cs410J/mberz2/TextParser.java
|
mberz2/PortlandStateJavaSummer2021
|
0d3b4ddaad3db8baf46748288bd51b775f363896
|
[
"Apache-2.0"
] | null | null | null |
apptbook/src/main/java/edu/pdx/cs410J/mberz2/TextParser.java
|
mberz2/PortlandStateJavaSummer2021
|
0d3b4ddaad3db8baf46748288bd51b775f363896
|
[
"Apache-2.0"
] | null | null | null |
apptbook/src/main/java/edu/pdx/cs410J/mberz2/TextParser.java
|
mberz2/PortlandStateJavaSummer2021
|
0d3b4ddaad3db8baf46748288bd51b775f363896
|
[
"Apache-2.0"
] | null | null | null | 26.788235 | 76 | 0.6917 | 1,001,089 |
package edu.pdx.cs410J.mberz2;
import edu.pdx.cs410J.AppointmentBookParser;
import edu.pdx.cs410J.ParserException;
import java.io.*;
/**
* This class implements read-only class {@link AppointmentBookParser}.
* This class contains methods for the parsing of a BufferedReader into an
* appointmentBook object.
*
* @author Matthew Berzinskas
* @since 2020-6-23
* @see AppointmentBook
*/
public class TextParser implements AppointmentBookParser<AppointmentBook> {
/* Buffered reader containing the input stream. */
private final BufferedReader reader;
/**
* Default constructor.
*
* @param reader Reader object containing the input stream.
*/
TextParser (Reader reader){
this.reader = new BufferedReader(reader);
}
/**
* Method for creating, parsing, and returning an AppointmentBook object
* from the parser's BufferedReader data member. The method first checks
* if the reader is ready, then reads line by line. If the method is unable
* to validate the input against the requirements of an apptBook object, it
* will exit and notify the user of a variety of errors.
*
* @return AppointmentBook object containing the contents of the reader.
* @throws ParserException Exception handling for empty files.
*/
@Override
public AppointmentBook parse () throws ParserException {
try{
if(!reader.ready()){
throw new ParserException("Error: Malformed or empty file.");
}
} catch (IOException e) {
e.printStackTrace();
System.exit(1);
}
try {
AppointmentBook tempBook = new AppointmentBook();
String line;
while((line = reader.readLine()) != null) {
// Parse line based on comma to the end of the line.
String [] newArgs = line.split("\\|");
if(newArgs[0].equals("\n") || newArgs[0].equals("")
|| newArgs.length < 8)
throw (new ParserException("Error: Malformed file."));
// Create a temporary appointment.
Appointment app = new Appointment(newArgs[1],
newArgs[2]+" "+newArgs[3]+" "+newArgs[4],
newArgs[5]+" "+newArgs[6]+" "+newArgs[7]);
tempBook.setOwnerName(newArgs[0]);
tempBook.addAppointment(app);
}
reader.close();
return tempBook;
} catch (IOException e) {
e.printStackTrace();
System.exit(1);
}
return null;
}
}
|
923f440b713ab48f54be137486038ea3cc47ca1e
| 18,265 |
java
|
Java
|
alp_interpreter/src/Parser.java
|
hashbang404/ALP
|
b9cf8c95b32163bb4bdd71681938d3b7c016d596
|
[
"MIT"
] | null | null | null |
alp_interpreter/src/Parser.java
|
hashbang404/ALP
|
b9cf8c95b32163bb4bdd71681938d3b7c016d596
|
[
"MIT"
] | null | null | null |
alp_interpreter/src/Parser.java
|
hashbang404/ALP
|
b9cf8c95b32163bb4bdd71681938d3b7c016d596
|
[
"MIT"
] | null | null | null | 45.6625 | 141 | 0.539557 | 1,001,090 |
import java.util.List;
import java.util.Arrays;
import java.util.ArrayList;
/* Parser class for ALP
* created --> ( Tue Sep 15 2020 )
* lastEdited --> ( Thu Sep 17 2020 )
* author --> cantbebothered ( Alixhan Basha )
*/
public class Parser {
// Like the lexer, but instead of taking characters, take the tokens
private static class ParseError extends RuntimeException {}
private final List<Token> tokens ;
private int current = 0 ; /* Counter intuitively points to the "next" Token */
private boolean varflag = false;
public Parser( List<Token> t ){ tokens = t; }
public List<Statement> parse(){
List<Statement> statements = new ArrayList<>();
while( !isAtFileEnd() ){
statements.add( declaration() );
}
return statements;
}
private Statement declaration(){
try{
if( match( TokenType.FUNKSIONI ) ) return funcDeclaration("funksion");
if( match( TokenType.VAR ) ) return varDeclaration();
if( match( TokenType.KLASA ) ) return classDeclaration();
return statement();
}catch( ParseError pe){ synchronize(); return null; }
}
private Statement classDeclaration(){
Token name = consume( TokenType.IDENTIFIER , "Deklarimi i klases duhet te kete nje emer !" );
Expression.Variable superclass = null;
if( match(TokenType.TRASHEGON, TokenType.LT) ){ // trashogon ose <
consume( TokenType.IDENTIFIER , "Duhet te ceket emri i klases nga i cili klasa " + name.getLexme() + " do te trashegon !" );
superclass = new Expression.Variable( previous() );
}
consume( TokenType.LEFT_BRACE , "Pritet qe te hapet kllapa gjarperore '{' pas deklarimit te klases '" + name.getLexme() + "' " );
List<Statement.Function> methods = new ArrayList<>();
while( !check(TokenType.RIGHT_BRACE) && !isAtFileEnd() ){
methods.add( funcDeclaration("metode") );
}
consume( TokenType.RIGHT_BRACE , "Pritet qe te mbyllet kllapa gjarperore '}' pas deklarimit te klases '" + name.getLexme() + "' " );
return new Statement.Class( name , superclass , methods );
}
private Statement.Function funcDeclaration( String type ){
Token name = consume( TokenType.IDENTIFIER , "Pritet qe definimi i " + type + " te ket nje emer!" );
consume( TokenType.LEFT_PAREN , "Pritet qe te hapet kllapa '(' ne funksionin '\033[0;34m" + name.getLexme() + "\033[0m'" );
List<Token> params = new ArrayList<>();
if( !check(TokenType.RIGHT_PAREN) ){
do{
if( params.size() >= 255 )
error(peek(),"Funksioni '" + name.getLexme() + "' nuk mund te ket me shume se 255 parametra !");
params.add( consume( TokenType.IDENTIFIER , "Pritet emri i parametrit !" ) );
}while( match(TokenType.COMMA) );
}
consume( TokenType.RIGHT_PAREN , "Pritet qe te mbyllet kllapa ')' ne " + type + " " + name.getLexme() );
consume( TokenType.LEFT_BRACE , "Pritet qe te haper kllapa '{' per trupin e " + type + " " + name.getLexme());
List<Statement> body = block();
return new Statement.Function( name , params , body );
}
private Statement statement(){
if( match( TokenType.NESE ) ) return ifStatement();
if( match( TokenType.PERDERISA ) ) return whileStatement();
if( match( TokenType.SHKRUAJ ) ) return printStatement( false );
if( match( TokenType.SHKRUAJR ) ) return printStatement( true );
if( match( TokenType.IMPORTO ) ) return importStatement();
if( match( TokenType.LEFT_BRACE ) ) return new Statement.Block( block() );
if( match( TokenType.PER ) ) return forStatement();
if( match( TokenType.KTHEN ) ) return returnStatement();
return expressionStatement();
}
private Statement returnStatement(){
Token name = previous();
Expression value = null;
if( !check( TokenType.SEMICOLON ) ){
value = expression();
}
consume( TokenType.SEMICOLON , "Pritet ';' ne fund te 'kthen' ! " );
return new Statement.Return( name , value );
}
private Statement forStatement(){
consume( TokenType.LEFT_PAREN , "Pritet te hapet kllapa '(' ne bllokun 'per'!" );
Statement initializer;
if( match( TokenType.SEMICOLON ) ) initializer=null;
else if( match(TokenType.VAR) ) initializer = varDeclaration();
else initializer = expressionStatement();
Expression condition = null;
if( !check( TokenType.SEMICOLON ) ) condition = expression();
consume( TokenType.SEMICOLON , "Pritet ';' pas deklarimit te kushtit ne bllokun 'per'" );
Expression increment = null;
if( !check(TokenType.RIGHT_PAREN )) increment = expression();
consume( TokenType.RIGHT_PAREN , "Pritet te mbyllet kllapa ')' ne bllokun 'per'" );
consume( TokenType.LEFT_BRACE , "Pritet qe te hapet kllapa '{' ne bllokun 'per'" );
List<Statement> body = block();
return new Statement.For( initializer , condition , increment , body );
}
private Statement ifStatement(){
List<Statement> then_ = new ArrayList<>();
List<Statement> elif_ = new ArrayList<>();
List<Object> elifobj_ = new ArrayList<>();
List<Statement> else_ = new ArrayList<>();
consume( TokenType.LEFT_PAREN , "Pritet te hapet kllapa '(' ne bllokun 'nese' !" );
Expression condition = expression();
Expression elifCondition = null;
consume( TokenType.RIGHT_PAREN , "Pritet te mbyllet kllapa ')' ne bllokun 'nese' !" );
consume( TokenType.LEFT_BRACE , "Pritet te hapet kllapa '{' ne bllokun 'nese' !" );
then_ = block();
if( check(TokenType.TJETER) ){
while( check(TokenType.TJETER) ) {
advance();
elifCondition = expression();
elifobj_.add( elifCondition );
consume( TokenType.LEFT_BRACE , "Pritet te hapet kllapa '{' ne bllokun 'perndryshe' !" );
elif_ = block();
elifobj_.add(elif_);
}
}
/*
while( !check( TokenType.RIGHT_BRACE ) && !isAtFileEnd() ){
then_.add( declaration() ); // gjej nje menyre per me leju -- declaration(); --
}
consume( TokenType.RIGHT_BRACE , "Pritet te mbyllet kllapa '}' ne bllokun 'nese' !" );
*/
if( match(TokenType.PERNDRYSHE) ){
consume( TokenType.LEFT_BRACE , "Pritet te hapet kllapa '{' ne bllokun 'perndryshe' !" );
else_ = block();
/*
while( !check( TokenType.RIGHT_BRACE ) && !isAtFileEnd() ){
else_.add( declaration() );
}
consume( TokenType.RIGHT_BRACE , "Pritet te hapet kllapa '}' ne bllokun 'perndryshe' !" );
*/
}
return new Statement.If(condition , then_ , elifobj_ , else_);
}
private Statement whileStatement(){
List<Statement> body = new ArrayList<>();
consume( TokenType.LEFT_PAREN , "Pritet te hapet kllapa '(' ne bllokun 'perderisa' !" );
Expression condition = expression();
consume( TokenType.RIGHT_PAREN , "Pritet te mbyllet kllapa ')' ne bllokun 'perderisa' !" );
consume( TokenType.LEFT_BRACE , "Pritet te hapet kllapa '{' ne bllokun 'perderisa' !" );
body = block();
return new Statement.While( condition , body );
}
private Statement importStatement(){
Expression val = expression();
consume( TokenType.SEMICOLON , "Pritet simboli ';' ne fund te komandes " );
return new Statement.Import( val );
}
private Statement varDeclaration(){
/*
* At the moment, if you multi-declare variables in the same line, all
* but the first one have global scoping !
*/
Token name = consume( TokenType.IDENTIFIER , "Deklarimi i variables duhet te ket nje emer !\n\tp.sh --> deklaro emri = \"EMRI\"; " );
Expression initializer = null;
if( match( TokenType.EQ ) ) initializer = expression();
if( varflag ) {
// if blockMode insert to the new environment ; continue;
ALP.interpreter.visitVarStatement( new Statement.Var(name,initializer) );
}
if( match( TokenType.COMMA ) ){
varflag = true;
varDeclaration();
varflag = false;
}
if( previous().getType() != TokenType.SEMICOLON ) consume( TokenType.SEMICOLON , "Pritet ';' pas deklarimit te variables !" );
return new Statement.Var( name , initializer );
}
private Statement printStatement( boolean println ){
Expression val = expression();
consume( TokenType.SEMICOLON , "Pritet simboli ';' ne fund te komandes shkruaj --> shkruaj \"\" ; " );
if( println ) return new Statement.Print( val , true ); /* Print the value and then a new line */
return new Statement.Print( val , false );
}
private Statement expressionStatement(){
Expression val = expression();
consume( TokenType.SEMICOLON , "Pritet simboli ';' ne fund te komandes" );
return new Statement.StmtExpression( val );
}
private List<Statement> block(){
List<Statement> statements = new ArrayList<>();
while( !check( TokenType.RIGHT_BRACE ) && !isAtFileEnd() ){
if( check(TokenType.RIGHT_BRACE) ) break;
statements.add( declaration() );
}
consume( TokenType.RIGHT_BRACE , "Duhet qe blloku te mbyllet me '}' ! " );
return statements;
}
/* Grammar Functions ! */
private Expression expression(){ return assignment(); }
private Expression assignment(){
Expression expr = OrExpr();
if( match( TokenType.EQ ) ){
Token equals = previous();
Expression value = assignment();
if( expr instanceof Expression.Variable ){
Token name = ( (Expression.Variable)expr ).name;
return new Expression.Assign( name , value );
}
else if( expr instanceof Expression.Get ){
Expression.Get ge = (Expression.Get) expr;
return new Expression.Set( ge.obj, ge.name , value );
}
error( equals , "Targeti i gabuar per caktim (barazim) !" );
}
return expr;
}
private Expression OrExpr(){
Expression expr = AndExpr();
while( match( TokenType.OSE ) ){
Token op = previous();
Expression right = AndExpr();
expr = new Expression.Logical( expr , op , right );
}
return expr;
}
private Expression AndExpr(){
Expression expr = equality();
while( match( TokenType.DHE ) ){
Token op = previous();
Expression right = equality();
expr = new Expression.Logical( expr , op , right );
}
return expr;
}
private Expression equality(){
/* equality → comparison ( ( "!=" | "==" ) comparison )* ; */
Expression comp = comparison();
while( match( TokenType.NOTEQ , TokenType.EQEQ ) ){
Token operator = previous();
Expression right = comparison();
comp = new Expression.Binary( comp , operator , right );
}
return comp ;
}
//-----------------------------------------------------------------------------------------------------------
private Expression comparison(){
/* comparison → addition ( ( ">" | ">=" | "<" | "<=" ) addition )* ; */
Expression add = addition();
while( match( TokenType.GT , TokenType.GTEQ , TokenType.LT , TokenType.LTEQ ) ){
Token operator = previous();
Expression right = addition();
add = new Expression.Binary( add , operator , right );
}
return add;
}
//-----------------------------------------------------------------------------------------------------------
private Expression addition(){
Expression mult = multiplication();
while( match( TokenType.PLUS , TokenType.MINUS ) ){
Token operator = previous();
Expression right = multiplication();
mult = new Expression.Binary( mult , operator , right );
}
return mult;
}
//-----------------------------------------------------------------------------------------------------------
private Expression multiplication() {
Expression expr = unary();
while (match(TokenType.SLASH, TokenType.STAR, TokenType.MODULO)) {
Token operator = previous();
Expression right = unary();
expr = new Expression.Binary(expr, operator, right);
}
return expr;
}
//-----------------------------------------------------------------------------------------------------------
private Expression unary(){
if( match( TokenType.BANG , TokenType.MINUS ) ){
Token operator = previous();
Expression right = unary();
return new Expression.Unary( operator , right );
}
return functionCall();
}
private Expression functionCall(){
Expression expr = primary();
while( true ){
if( match(TokenType.LEFT_PAREN) ) expr = finishCall(expr);
else if( match(TokenType.DOT) ){
Token name = consume( TokenType.IDENTIFIER , "Pritet te emertohet prona e instances pas '.'" );
expr = new Expression.Get( expr, name );
}
else break;
}
return expr;
}
private Expression finishCall( Expression ex ){
List<Expression> arguments = new ArrayList<>();
if( !check(TokenType.RIGHT_PAREN) ){
do{
if( arguments.size() > 255 )
error( peek() , "Funksioni nuk mund te pranoj me shume se 255 argumenteQ" );
arguments.add( expression() );
}while( match(TokenType.COMMA) );
}
Token rparen = consume( TokenType.RIGHT_PAREN , "Pritet te mbyllet kllapa ')' ne thirje te funksionit!" );
return new Expression.Call( ex , rparen , arguments );
}
//-----------------------------------------------------------------------------------------------------------
private Expression primary() {
if( match(TokenType.FALSE) ) return new Expression.Literal( false );
if( match(TokenType.VERTET) ) return new Expression.Literal( previous().getLiteral() );
if( match(TokenType.ZBRAZET) ) return new Expression.Literal( null );
if( match( TokenType.SUPER ) ){
Token keyword = previous();
consume( TokenType.DOT , "Pritet '.' pas 'super'" );
Token method = consume( TokenType.IDENTIFIER , "Duhet te ceket emri i metodes apo variables pas 'super' !" );
return new Expression.Super( keyword, method );
}
if( match( TokenType.AKTUAL ) ) return new Expression.This( previous() );
if( match(TokenType.NUMBER , TokenType.TEXT) ) { return new Expression.Literal( previous().getLiteral() ); }
if( match( TokenType.IDENTIFIER ) ){ return new Expression.Variable( previous() ); }
// To add functions and classes, also make something similar to the above code for IDENTIFIER
if( match( TokenType.LEFT_PAREN ) ){
Expression expr = expression();
consume( TokenType.RIGHT_PAREN , "Pritet qe kllapa ')' te mbyllet." );
return new Expression.Grouping( expr );
}
throw error( peek() , "Pritet qe te jete nje expression ( shpreheje ) valide ! " );
}
/* Parser Helper Functions ! */
private Token consume( TokenType t , String message ){ /* Could be named "expect" because it expects a token, or it failes */
if( check(t) ) return advance();
throw error( peek() , "[Parse Error] => "+message );
}
//-----------------------------------------------------------------------------------------------------------
private ParseError error( Token t , String message ){
ALP.error( t , message );
return new ParseError();
}
//-----------------------------------------------------------------------------------------------------------
private void synchronize(){
advance();
while( !isAtFileEnd() ){
if( previous().getType() == TokenType.SEMICOLON ) return;
switch( peek().getType() ){
case KLASA :
case FUNKSIONI:
case IMPORTO:
case PER:
case NESE:
case PERDERISA :
case SHKRUAJ :
case SHKRUAJR :
case KTHEN :
case LEXO :
case LEXOF :
case NET :
return;
}
advance();
}
}
//-----------------------------------------------------------------------------------------------------------
private boolean match( TokenType... t ){ /* Match a tokentype. */
for( TokenType tt : t ){
if( check(tt) ){
advance();
return true ;
}
}
return false ;
}
//-----------------------------------------------------------------------------------------------------------
private boolean check( TokenType type ){ /* Same as match, but only for one tokentype, used as helper */
if( isAtFileEnd() ) return false;
return peek().getType() == type;
}
//-----------------------------------------------------------------------------------------------------------
private Token advance(){ /* */
if( !isAtFileEnd() ) current++;
return previous();
}
//-----------------------------------------------------------------------------------------------------------
private boolean isAtFileEnd(){ return peek().getType() == TokenType.EOF; }
private Token peek(){ return tokens.get( current ); }
private Token previous(){ return tokens.get( current-1 ); }
}
|
923f445de92d15d1ffc0d999acc26ef69ce38fa4
| 1,928 |
java
|
Java
|
lab3/RBTree_Main.java
|
it03team6/asd2labs
|
302ae00d3059a198f919be79a4953febfec946ac
|
[
"MIT"
] | null | null | null |
lab3/RBTree_Main.java
|
it03team6/asd2labs
|
302ae00d3059a198f919be79a4953febfec946ac
|
[
"MIT"
] | null | null | null |
lab3/RBTree_Main.java
|
it03team6/asd2labs
|
302ae00d3059a198f919be79a4953febfec946ac
|
[
"MIT"
] | null | null | null | 28.352941 | 102 | 0.491701 | 1,001,091 |
package ua.kpi.fict.acts.it03.asdlabs.lab3;
public class RBTree_Main {
public static void main(String[] args) {
RedBlackTree tree = new RedBlackTree();
long start = System.currentTimeMillis();
for (int i = 0; i < 1_000_000; i++) {
tree.insert(i);
}
long end = System.currentTimeMillis();
System.out.println("RBTree Adding 1kk: " + (end - start) + " ms");
System.out.println("#####");
start = System.currentTimeMillis();
for(int i = 0; i<1_000_000 ;i++ )
{
tree.deleteNode(i);
}
end = System.currentTimeMillis();
System.out.println("RBTree Deleting 1kk: " + (end - start) +" ms");
System.out.println("#####");
for(int i = 0; i<1_000_000 ;i++ )
{
tree.insert(i);
}
start = System.currentTimeMillis();
for(int i = 0; i<1_000_000 ;i++ )
{
tree.searchTree(i);
}
end = System.currentTimeMillis();
System.out.println("RBTree Existing test: " + (end-start) + " ms");
System.out.println("#####");
start = System.currentTimeMillis();
for(int i = 1_000_000; i<2_000_000 ;i++ )
{
tree.searchTree(i);
}
end = System.currentTimeMillis();
System.out.println("RBTree Existing test(elements which not exist): " + (end-start) + " ms");
System.out.println("#####");
for(int i = 0; i<1_000_000 ;i++ )
{
tree.deleteNode(i);
}
for(int i = 0; i<1_000_000 ;i++ )
{
tree.insert(i);
}
start = System.currentTimeMillis();
tree.getSum();
end = System.currentTimeMillis();
System.out.println("RBTree Sum of tree elements(8k): " + (end-start) + " ms");
}
}
|
923f44c04885a7babef7eae742c2863c1ce4150c
| 17,030 |
java
|
Java
|
src/test/java/com/obdobion/funnel/HeaderTests.java
|
fedups/funnelsort
|
e3b0966b2fd971aa49609c864def80d86f5b9237
|
[
"MIT"
] | null | null | null |
src/test/java/com/obdobion/funnel/HeaderTests.java
|
fedups/funnelsort
|
e3b0966b2fd971aa49609c864def80d86f5b9237
|
[
"MIT"
] | null | null | null |
src/test/java/com/obdobion/funnel/HeaderTests.java
|
fedups/funnelsort
|
e3b0966b2fd971aa49609c864def80d86f5b9237
|
[
"MIT"
] | null | null | null | 31.72067 | 104 | 0.514853 | 1,001,092 |
package com.obdobion.funnel;
import java.io.File;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;
import org.junit.Assert;
import org.junit.Test;
import com.obdobion.Helper;
import com.obdobion.funnel.parameters.FunnelContext;
/**
* <p>
* HeaderTests class.
* </p>
*
* @author Chris DeGreef [email protected]
* @since 1.6.6
*/
public class HeaderTests
{
/**
* <p>
* addHeaderToFile.
* </p>
*
* @throws java.lang.Throwable if any.
*/
@Test
public void addHeaderToFile()
throws Throwable
{
final String testName = Helper.testName();
Helper.initializeFor(testName);
final List<String> logFile = new ArrayList<>();
logFile.add("TEST20160608 1");
logFile.add("TEST20160608 2");
final File file = Helper.createUnsortedFile(testName, logFile);
final FunnelContext context = Funnel.sort(Helper.config(), file.getAbsolutePath()
+ " --replace"
+ " --col(string -l4 -n TYPE)"
+ " (date -l8 -n DATE -d'yyyyMMdd')"
+ " (int -l2 -n SEQ)"
+ " --orderBy(seq desc)"
+ " --headerOut(-e'datefmt(\"20160609\", \"yyyyMMdd\")' -l 28 -d '%tF')");
Assert.assertEquals("records", 2L, context.getWriteCount());
final List<String> expectedLines = new ArrayList<>();
expectedLines.add("2016-06-09 ");
expectedLines.add("TEST20160608 2");
expectedLines.add("TEST20160608 1");
Helper.compare(file, expectedLines);
Assert.assertTrue(file.delete());
}
/**
* <p>
* consumeHeader.
* </p>
*
* @throws java.lang.Throwable if any.
*/
@Test
public void consumeHeader()
throws Throwable
{
final String testName = Helper.testName();
Helper.initializeFor(testName);
final List<String> logFile = new ArrayList<>();
logFile.add("20160608TEST");
logFile.add("TEST20160608 1");
logFile.add("TEST20160608 2");
final File file = Helper.createUnsortedFile(testName, logFile);
final FunnelContext context = Funnel.sort(Helper.config(), file.getAbsolutePath()
+ " --col(string -l4 -n TYPE)"
+ " (date -l8 -n DATE -d'yyyyMMdd')"
+ " (int -l2 -n SEQ)"
+ " --headerIn"
+ " (date -l8 -n RUNDATE -d'yyyyMMdd')"
+ " (string -l4 -n RUNTYPE)"
+ " --headerOut()");
Assert.assertEquals("records", 2L, context.getWriteCount());
Assert.assertTrue(file.delete());
}
/**
* <p>
* duplicateNameWithColumn.
* </p>
*
* @throws java.lang.Throwable if any.
*/
@Test
public void duplicateNameWithColumn()
throws Throwable
{
final String testName = Helper.testName();
Helper.initializeFor(testName);
try
{
Funnel.sort(Helper.config(), ""
+ " --col(string -l4 -n TYPE)"
+ " (date -l8 -n DATE -d'yyyyMMdd')"
+ " (int -l2 -n SEQ)"
+ " --headerIn"
+ " (date -l8 -n DATE -d'yyyyMMdd')"
+ " (string -l4 -n TYPE)");
Assert.fail("Expected exception");
} catch (final ParseException e)
{
Assert.assertEquals("columnsIn must be unique from headerIn: TYPE", e.getMessage());
}
}
/**
* <p>
* duplicateNameWithHeader.
* </p>
*
* @throws java.lang.Throwable if any.
*/
@Test
public void duplicateNameWithHeader()
throws Throwable
{
final String testName = Helper.testName();
Helper.initializeFor(testName);
try
{
Funnel.sort(Helper.config(), ""
+ " --col(string -l4 -n type)"
+ " (date -l8 -n DATE -d'yyyyMMdd')"
+ " (int -l2 -n SEQ)"
+ " --headerIn"
+ " (date -l8 -n TYPE -d'yyyyMMdd')"
+ " (string -l4 -n TYPE)");
Assert.fail("Expected exception");
} catch (final ParseException e)
{
Assert.assertEquals("headerIn must be unique: TYPE", e.getMessage());
}
}
/**
* <p>
* filler.
* </p>
*
* @throws java.lang.Throwable if any.
*/
@Test
public void filler()
throws Throwable
{
final String testName = Helper.testName();
Helper.initializeFor(testName);
final List<String> logFile = new ArrayList<>();
logFile.add("06/01/2016 16:43:56 06/01/2016 00:00:00 0230");
logFile.add("TEST20160608 1");
logFile.add("TEST20160608 2");
final File file = Helper.createUnsortedFile(testName, logFile);
final FunnelContext context = Funnel.sort(Helper.config(), file.getAbsolutePath()
+ " --replace"
+ " --headerIn "
+ " (Date -n RUNTIME -d'MM/dd/yyyy HH:mm:ss')"
+ " (filler -l 11)"
+ " (Date -n BUSDATE -d'MM/dd/yyyy HH:mm:ss')"
+ " (filler -l 1)"
+ " (Int -n LRECL -l4)"
+ " --headerOut(-eRUNTIME -l 28 -d '%tF')");
Assert.assertEquals("records", 2L, context.getWriteCount());
final List<String> expectedLines = new ArrayList<>();
expectedLines.add("2016-06-01 ");
Helper.compare(file, expectedLines);
Assert.assertTrue(file.delete());
}
/**
* <p>
* notValidForCSV.
* </p>
*
* @throws java.lang.Throwable if any.
*/
@Test
public void notValidForCSV()
throws Throwable
{
final String testName = Helper.testName();
Helper.initializeFor(testName);
try
{
Funnel.sort(Helper.config(), "--csv()"
+ " --col"
+ " (int -l2 -n SEQ)"
+ " --headerIn"
+ " (date -l8 -n DATE -d'yyyyMMdd')"
+ " (string -l4 -n TYPE)");
Assert.fail("Expected exception");
} catch (final ParseException e)
{
Assert.assertEquals("headerIn not supported for csv files", e.getMessage());
}
}
/**
* <p>
* useHeaderForStop.
* </p>
*
* @throws java.lang.Throwable if any.
*/
@Test
public void useHeaderForStop()
throws Throwable
{
final String testName = Helper.testName();
Helper.initializeFor(testName);
final List<String> logFile = new ArrayList<>();
logFile.add("20160608TEST");
logFile.add("TEST20160608 1");
logFile.add("TEST20160608 2");
final File file = Helper.createUnsortedFile(testName, logFile);
final FunnelContext context = Funnel.sort(Helper.config(), file.getAbsolutePath()
+ " --col(string -l4 -n TYPE)"
+ " (date -l8 -n DATE -d'yyyyMMdd')"
+ " (int -l2 -n SEQ)"
+ " --headerIn"
+ " (date -l8 -n RUNDATE -d'yyyyMMdd')"
+ " (string -l4 -n RUNTYPE)"
+ " --headerOut()"
+ " --stop 'runtype = type'");
Assert.assertEquals("records", 0L, context.getWriteCount());
Assert.assertTrue(file.delete());
}
/**
* <p>
* useHeaderForWhere.
* </p>
*
* @throws java.lang.Throwable if any.
*/
@Test
public void useHeaderForWhere()
throws Throwable
{
final String testName = Helper.testName();
Helper.initializeFor(testName);
final List<String> logFile = new ArrayList<>();
logFile.add("20160608TEST");
logFile.add("TEST20160608 1");
logFile.add("TEST20160608 2");
final File file = Helper.createUnsortedFile(testName, logFile);
final FunnelContext context = Funnel.sort(Helper.config(), file.getAbsolutePath()
+ " --col(string -l4 -n TYPE)"
+ " (date -l8 -n DATE -d'yyyyMMdd')"
+ " (int -l2 -n SEQ)"
+ " --headerIn"
+ " (date -l8 -n RUNDATE -d'yyyyMMdd')"
+ " (string -l4 -n RUNTYPE)"
+ " --headerOut()"
+ " --where 'runtype = type'");
Assert.assertEquals("records", 2L, context.getWriteCount());
Assert.assertTrue(file.delete());
}
/**
* <p>
* writeEntireHeaderToOutput.
* </p>
*
* @throws java.lang.Throwable if any.
*/
@Test
public void writeEntireHeaderToOutput()
throws Throwable
{
final String testName = Helper.testName();
Helper.initializeFor(testName);
final List<String> logFile = new ArrayList<>();
logFile.add("20160608TEST");
logFile.add("TEST20160608 1");
logFile.add("TEST20160608 2");
final File file = Helper.createUnsortedFile(testName, logFile);
final FunnelContext context = Funnel.sort(Helper.config(), file.getAbsolutePath()
+ " --replace"
+ " --col(string -l4 -n TYPE)"
+ " (date -l8 -n DATE -d'yyyyMMdd')"
+ " (int -l2 -n SEQ)"
+ " --orderBy(seq desc)"
+ " --headerIn"
+ " (date -l8 -n RUNDATE -d'yyyyMMdd')"
+ " (string -l4 -n RUNTYPE)");
Assert.assertEquals("records", 2L, context.getWriteCount());
final List<String> expectedLines = new ArrayList<>();
expectedLines.add("20160608TEST");
expectedLines.add("TEST20160608 2");
expectedLines.add("TEST20160608 1");
Helper.compare(file, expectedLines);
Assert.assertTrue(file.delete());
}
/**
* <p>
* writeHeaderColumnToDetailRecordAsCol.
* </p>
*
* @throws java.lang.Throwable if any.
*/
@Test
public void writeHeaderColumnToDetailRecordAsCol()
throws Throwable
{
final String testName = Helper.testName();
Helper.initializeFor(testName);
final List<String> logFile = new ArrayList<>();
logFile.add("20160608TEST");
logFile.add("TEST20160608 1");
logFile.add("TEST20160608 2");
final File file = Helper.createUnsortedFile(testName, logFile);
final FunnelContext context = Funnel.sort(Helper.config(), file.getAbsolutePath() + " --replace"
+ " --col(string -l4 -n TYPE)"
+ " (date -l8 -n DATE -d'yyyyMMdd')"
+ " (int -l2 -n SEQ)"
+ " --headerIn"
+ " (date -l8 -n RUNDATE -d'yyyyMMdd')"
+ " (string -l4 -n RUNTYPE)"
+ " --headerOut()"
+ " --formatOut(TYPE)(RUNTYPE)(DATE)(RUNDATE)(SEQ)");
Assert.assertEquals("records", 2L, context.getWriteCount());
final List<String> expectedLines = new ArrayList<>();
expectedLines.add("TESTTEST2016060820160608 1");
expectedLines.add("TESTTEST2016060820160608 2");
Helper.compare(file, expectedLines);
Assert.assertTrue(file.delete());
}
/**
* <p>
* writeHeaderColumnToDetailRecordAsEqu.
* </p>
*
* @throws java.lang.Throwable if any.
*/
@Test
public void writeHeaderColumnToDetailRecordAsEqu()
throws Throwable
{
final String testName = Helper.testName();
Helper.initializeFor(testName);
final List<String> logFile = new ArrayList<>();
logFile.add("20160608TEST");
logFile.add("TEST20160608 1");
logFile.add("TEST20160608 2");
final File file = Helper.createUnsortedFile(testName, logFile);
final FunnelContext context = Funnel.sort(Helper.config(), file.getAbsolutePath()
+ " --col(string -l4 -n TYPE)"
+ " (date -l8 -n DATE -d'yyyyMMdd')"
+ " (int -l2 -n SEQ)"
+ " --headerIn"
+ " (date -l8 -n RUNDATE -d'yyyyMMdd')"
+ " (string -l4 -n RUNTYPE)"
+ " --headerOut()"
+ " --formatOut(TYPE)(-eRUNTYPE -l4)(DATE)(-eRUNDATE -l8 -d'%tY%1$tm%1$td')(SEQ)");
Assert.assertEquals("records", 2L, context.getWriteCount());
Assert.assertTrue(file.delete());
}
/**
* <p>
* writeHeaderOutWithEqu.
* </p>
*
* @throws java.lang.Throwable if any.
*/
@Test
public void writeHeaderOutWithEqu()
throws Throwable
{
final String testName = Helper.testName();
Helper.initializeFor(testName);
final List<String> logFile = new ArrayList<>();
logFile.add("20160608TEST");
logFile.add("TEST20160608 1");
logFile.add("TEST20160608 2");
final File file = Helper.createUnsortedFile(testName, logFile);
final FunnelContext context = Funnel.sort(Helper.config(), file.getAbsolutePath()
+ " --replace"
+ " --col(string -l4 -n TYPE)"
+ " (date -l8 -n DATE -d'yyyyMMdd')"
+ " (int -l2 -n SEQ)"
+ " --orderBy(seq desc)"
+ " --headerIn"
+ " (date -l8 -n RUNDATE -d'yyyyMMdd')"
+ " (string -l4 -n RUNTYPE)"
+ " --headerOut(-eRUNDATE -l 28 -d '%tF')");
Assert.assertEquals("records", 2L, context.getWriteCount());
final List<String> expectedLines = new ArrayList<>();
expectedLines.add("2016-06-08 ");
expectedLines.add("TEST20160608 2");
expectedLines.add("TEST20160608 1");
Helper.compare(file, expectedLines);
Assert.assertTrue(file.delete());
}
/**
* <p>
* writeMinimalHeaderToOutput.
* </p>
*
* @throws java.lang.Throwable if any.
*/
@Test
public void writeMinimalHeaderToOutput()
throws Throwable
{
final String testName = Helper.testName();
Helper.initializeFor(testName);
final List<String> logFile = new ArrayList<>();
logFile.add("20160608TEST");
logFile.add("TEST20160608 1");
logFile.add("TEST20160608 2");
final File file = Helper.createUnsortedFile(testName, logFile);
final FunnelContext context = Funnel.sort(Helper.config(), file.getAbsolutePath()
+ " --replace"
+ " --col(string -l4 -n TYPE)"
+ " (date -l8 -n DATE -d'yyyyMMdd')"
+ " (int -l2 -n SEQ)"
+ " --orderBy(seq desc)"
+ " --headerIn(filler)");
Assert.assertEquals("records", 2L, context.getWriteCount());
final List<String> expectedLines = new ArrayList<>();
expectedLines.add("20160608TEST");
expectedLines.add("TEST20160608 2");
expectedLines.add("TEST20160608 1");
Helper.compare(file, expectedLines);
Assert.assertTrue(file.delete());
}
/**
* <p>
* writeSpecificColumnsToHeaderOutput.
* </p>
*
* @throws java.lang.Throwable if any.
*/
@Test
public void writeSpecificColumnsToHeaderOutput()
throws Throwable
{
final String testName = Helper.testName();
Helper.initializeFor(testName);
final List<String> logFile = new ArrayList<>();
logFile.add("20160608TEST");
logFile.add("TEST20160608 1");
logFile.add("TEST20160608 2");
final File file = Helper.createUnsortedFile(testName, logFile);
final FunnelContext context = Funnel.sort(Helper.config(), file.getAbsolutePath()
+ " --replace"
+ " --col(string -l4 -n TYPE)"
+ " (date -l8 -n DATE -d'yyyyMMdd')"
+ " (int -l2 -n SEQ)"
+ " --orderBy(seq desc)"
+ " --headerIn"
+ " (date -l8 -n RUNDATE -d'yyyyMMdd')"
+ " (string -l4 -n RUNTYPE)"
+ " --headerOut(RUNTYPE)(RUNDATE)");
Assert.assertEquals("records", 2L, context.getWriteCount());
final List<String> expectedLines = new ArrayList<>();
expectedLines.add("TEST20160608");
expectedLines.add("TEST20160608 2");
expectedLines.add("TEST20160608 1");
Helper.compare(file, expectedLines);
Assert.assertTrue(file.delete());
}
}
|
923f450974928f9ebd7f03cfa89b0893e7b1475c
| 4,131 |
java
|
Java
|
app/src/main/java/com/ikuchko/world_population/activities/CounrtyDetailActivity.java
|
ikuchko/world_statistic
|
92ca0fab77bc51db44ecab3527785b9dee88a1b7
|
[
"Unlicense",
"MIT"
] | 1 |
2016-04-17T04:59:07.000Z
|
2016-04-17T04:59:07.000Z
|
app/src/main/java/com/ikuchko/world_population/activities/CounrtyDetailActivity.java
|
ikuchko/world_statistic
|
92ca0fab77bc51db44ecab3527785b9dee88a1b7
|
[
"Unlicense",
"MIT"
] | null | null | null |
app/src/main/java/com/ikuchko/world_population/activities/CounrtyDetailActivity.java
|
ikuchko/world_statistic
|
92ca0fab77bc51db44ecab3527785b9dee88a1b7
|
[
"Unlicense",
"MIT"
] | null | null | null | 38.607477 | 135 | 0.693537 | 1,001,093 |
package com.ikuchko.world_population.activities;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.Color;
import android.support.v4.view.PagerTabStrip;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import com.firebase.client.DataSnapshot;
import com.firebase.client.Firebase;
import com.firebase.client.FirebaseError;
import com.firebase.client.ValueEventListener;
import com.ikuchko.world_population.R;
import com.ikuchko.world_population.adapters.CountryPagerAdapter;
import com.ikuchko.world_population.models.Country;
import com.ikuchko.world_population.models.User;
import com.ikuchko.world_population.util.ScaleAndFadePageTransformer;
import org.parceler.Parcels;
import java.util.ArrayList;
import butterknife.Bind;
import butterknife.ButterKnife;
public class CounrtyDetailActivity extends AppCompatActivity {
@Bind(R.id.viewPager) ViewPager viewPager;
private ArrayList<Country> countries = new ArrayList<>();
private CountryPagerAdapter adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
finish();
}
setContentView(R.layout.activity_counrty_detail);
ButterKnife.bind(this);
countries = Parcels.unwrap(getIntent().getParcelableExtra("countries"));
int startPosition = Integer.parseInt(getIntent().getStringExtra("position"));
adapter = new CountryPagerAdapter(getSupportFragmentManager(), countries);
viewPager.setAdapter(adapter);
viewPager.setCurrentItem(startPosition);
viewPager.setPageTransformer(true, new ScaleAndFadePageTransformer());
PagerTabStrip pagerTabStrip = (PagerTabStrip) findViewById(R.id.pagerHeader);
pagerTabStrip.setTabIndicatorColor(Color.GRAY);
}
//inflate the menu
@Override
public boolean onCreateOptionsMenu (Menu menu) {
getMenuInflater().inflate(R.menu.country_detail_menu, menu);
final MenuItem visited = menu.findItem(R.id.favorite);
if (User.getUser() != null) {
getVisitedCountries(visited);
} else {
visited.setVisible(false);
this.invalidateOptionsMenu();
}
return true;
}
//Determine if actionBar item was selected. If true then do corresponding actions
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.share:
Country currentCountry = countries.get(viewPager.getCurrentItem());
Intent impIntent = new Intent();
impIntent.setAction(Intent.ACTION_SEND);
impIntent.putExtra(Intent.EXTRA_TEXT, currentCountry.getShareContent());
impIntent.setType("text/plain");
if (impIntent.resolveActivity(getPackageManager()) != null) {
startActivity(impIntent.createChooser(impIntent, getResources().getString(R.string.intent_title)));
}
return true;
case R.id.favorite:
Intent favoriteIntent = new Intent(CounrtyDetailActivity.this, WishListActivity.class);
startActivity(favoriteIntent);
return true;
}
return super.onOptionsItemSelected(item);
}
public void getVisitedCountries(final MenuItem item) {
Firebase ref = new Firebase(getResources().getString(R.string.firebase_url) + "/favorite_countries/" +User.getUser().getuId());
ref.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
item.setTitle("Favorite: " + dataSnapshot.getChildrenCount());
}
@Override
public void onCancelled(FirebaseError firebaseError) {
}
});
}
}
|
923f464e0f69cad4b0018db55732f9fa0126c0ff
| 876 |
java
|
Java
|
src/test/java/pages/MainPage.java
|
rarean/BDD_Cucumber
|
2731a5a5370260a91fe16b0f667028b6b572d74b
|
[
"MIT"
] | null | null | null |
src/test/java/pages/MainPage.java
|
rarean/BDD_Cucumber
|
2731a5a5370260a91fe16b0f667028b6b572d74b
|
[
"MIT"
] | 1 |
2019-11-19T19:17:45.000Z
|
2019-11-19T19:17:45.000Z
|
src/test/java/pages/MainPage.java
|
rarean/BDD_Cucumber
|
2731a5a5370260a91fe16b0f667028b6b572d74b
|
[
"MIT"
] | null | null | null | 25.028571 | 68 | 0.727169 | 1,001,094 |
package pages;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.remote.RemoteWebDriver;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.How;
import org.openqa.selenium.support.PageFactory;
import utils.ConfigFileReader;
public class MainPage extends PageObject {
private static String url;
public MainPage(final RemoteWebDriver driver) {
super(driver);
final String maybeUrl = ConfigFileReader.getProperty("baseUrl");
if (maybeUrl != null){
url = maybeUrl;
} else {
System.err.println("unable to get url: "+maybeUrl);
}
driver.get(url);
//use pagefactory to get page webelements
PageFactory.initElements(driver, this);
}
@FindBy(how = How.CLASS_NAME, using = "main-header")
public WebElement mainHeader;
public String getTitle(){
return driver.getTitle();
}
}
|
923f46838066ff3e72b38f6689d5dcd1c3187165
| 2,114 |
java
|
Java
|
ace-modules/ace-admin/src/main/java/com/github/hollykunge/security/admin/biz/OrgBiz.java
|
yzq8023/work
|
5e40b9510cac921618743634ca2352f2c547ca7e
|
[
"Apache-2.0"
] | null | null | null |
ace-modules/ace-admin/src/main/java/com/github/hollykunge/security/admin/biz/OrgBiz.java
|
yzq8023/work
|
5e40b9510cac921618743634ca2352f2c547ca7e
|
[
"Apache-2.0"
] | null | null | null |
ace-modules/ace-admin/src/main/java/com/github/hollykunge/security/admin/biz/OrgBiz.java
|
yzq8023/work
|
5e40b9510cac921618743634ca2352f2c547ca7e
|
[
"Apache-2.0"
] | null | null | null | 31.552239 | 106 | 0.689688 | 1,001,095 |
package com.github.hollykunge.security.admin.biz;
import com.ace.cache.annotation.CacheClear;
import com.github.hollykunge.security.admin.entity.Org;
import com.github.hollykunge.security.admin.mapper.MenuMapper;
import com.github.hollykunge.security.admin.mapper.OrgMapper;
import com.github.hollykunge.security.admin.mapper.ResourceAuthorityMapper;
import com.github.hollykunge.security.admin.mapper.UserMapper;
import com.github.hollykunge.security.admin.vo.OrgUsers;
import com.github.hollykunge.security.common.biz.BaseBiz;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
@Service
@Transactional(rollbackFor = Exception.class)
public class OrgBiz extends BaseBiz<OrgMapper, Org> {
@Autowired
private UserMapper userMapper;
@Autowired
private ResourceAuthorityMapper resourceAuthorityMapper;
@Autowired
private MenuMapper menuMapper;
/**
* 变更组织所分配用户
*
* @param orgId
* @param members
* @param leaders
*/
@CacheClear(pre = "permission")
public void modifyOrgUsers(int orgId, String members, String leaders) {
mapper.deleteOrgLeadersById(orgId);
mapper.deleteOrgMembersById(orgId);
if (!StringUtils.isEmpty(members)) {
String[] mem = members.split(",");
for (String m : mem) {
mapper.insertOrgMembersById(orgId, Integer.parseInt(m));
}
}
if (!StringUtils.isEmpty(leaders)) {
String[] mem = leaders.split(",");
for (String m : mem) {
mapper.insertOrgLeadersById(orgId, Integer.parseInt(m));
}
}
}
/**
* 获取组织关联用户
*
* @param orgId
* @return
*/
public OrgUsers getOrgUsers(Integer orgId) {
return new OrgUsers(userMapper.selectMemberByOrgId(orgId), userMapper.selectLeaderByOrgId(orgId));
}
@Override
protected String getPageName() {
return null;
}
}
|
923f4710368b789e0c53c42aaf7d3f98795e3e60
| 501 |
java
|
Java
|
src/main/java/com/ping_pong/controller/Controller.java
|
st-a-novoseltcev/ping-pong
|
7be7886164ddecc82538272aac754420bfd0c532
|
[
"MIT"
] | null | null | null |
src/main/java/com/ping_pong/controller/Controller.java
|
st-a-novoseltcev/ping-pong
|
7be7886164ddecc82538272aac754420bfd0c532
|
[
"MIT"
] | null | null | null |
src/main/java/com/ping_pong/controller/Controller.java
|
st-a-novoseltcev/ping-pong
|
7be7886164ddecc82538272aac754420bfd0c532
|
[
"MIT"
] | null | null | null | 18.555556 | 42 | 0.590818 | 1,001,096 |
package com.ping_pong.controller;
import com.ping_pong.app.CustomApp;
public abstract class Controller {
protected CustomApp app;
protected boolean initialized = false;
public void setApp(CustomApp app) {
this.app = app;
run();
}
protected void run() {
if (!initialized) {
initialize();
}
}
protected void initialize() {
assert !initialized;
initialized = true;
System.out.println("INIT");
};
}
|
923f4749a5771a1905c10ee27f4932cba3acf1ec
| 1,484 |
java
|
Java
|
src/com/leetcode/tree/L_652_DuplicateSubtrees.java
|
xiaojianchen/leetcode
|
d9f44ce849198b44bf50adedc5d18558f7f73137
|
[
"Apache-2.0"
] | null | null | null |
src/com/leetcode/tree/L_652_DuplicateSubtrees.java
|
xiaojianchen/leetcode
|
d9f44ce849198b44bf50adedc5d18558f7f73137
|
[
"Apache-2.0"
] | null | null | null |
src/com/leetcode/tree/L_652_DuplicateSubtrees.java
|
xiaojianchen/leetcode
|
d9f44ce849198b44bf50adedc5d18558f7f73137
|
[
"Apache-2.0"
] | null | null | null | 24.327869 | 70 | 0.588275 | 1,001,097 |
package com.leetcode.tree;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class L_652_DuplicateSubtrees {
public static void main(String[] args) {
}
// 记录重新的树,只出现一次。
List<TreeNode> result = new ArrayList<>();
// 记录子树出现的重复次数,把所有树都存储这里
Map<String, Integer> dupCount = new HashMap<>();
public List<TreeNode> findDuplicateSubtrees(TreeNode root) {
traverse(root);
return result;
}
/**
* 还是老套路,先思考,对于某一个节点,它应该做什么。
* 你需要知道以下两点:
* 1、以我为根的这棵二叉树(子树)长啥样?--- 所以,把所有节点的子树全部序列化成字符串去比较
* 2、以其他节点为根的子树都长啥样? -- 以节点描述为key,出现次数为value。
* 最关键的是为啥用后序,因为是左、右子树都遍历完,回到根节点这个时机做逻辑,只有这个时间点做逻辑,才知道该节点的树形结构
*/
/* 辅助函数 */
String traverse(TreeNode node) {
if (node == null) {
return "#";
}
// 最关键的是为啥用后序,因为是左、右子树都遍历完,回到根节点这个时机做逻辑,只有这个时间点做逻辑,才知道该节点的树形结构
String left = traverse(node.left);
String right = traverse(node.right);
String subTree = left + "," + right + "," + node.val;
//先获取有没有存储过
int feq = dupCount.getOrDefault(subTree, 0);
// 说明之前有过一个,再来的就是重复的,然后把归回来路上的节点放进去
if (feq == 1) {
result.add(node);
}
dupCount.put(subTree, feq + 1);
return subTree;
}
public static class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) {
val = x;
}
}
}
|
923f47755dd4469a916f5861a23e694a31c39273
| 318 |
java
|
Java
|
src/main/java/com/hust/edu/cn/dp/_509.java
|
YourFantasy/LeetCode
|
89626891fca52bbe20276db9a4d2e32a8b911fa9
|
[
"Apache-2.0"
] | 24 |
2019-02-26T12:36:33.000Z
|
2022-02-07T09:35:33.000Z
|
src/main/java/com/hust/edu/cn/dp/_509.java
|
YourFantasy/LeetCode
|
89626891fca52bbe20276db9a4d2e32a8b911fa9
|
[
"Apache-2.0"
] | null | null | null |
src/main/java/com/hust/edu/cn/dp/_509.java
|
YourFantasy/LeetCode
|
89626891fca52bbe20276db9a4d2e32a8b911fa9
|
[
"Apache-2.0"
] | 10 |
2019-02-27T01:00:54.000Z
|
2021-04-16T05:49:30.000Z
| 18.705882 | 42 | 0.342767 | 1,001,098 |
package com.hust.edu.cn.dp;
class _509 {
public int fib(int N) {
if (N < 2) {
return N;
}
int[] dp = new int[N + 1];
dp[0] = 0;
dp[1] = 1;
for (int i = 2; i <= N; i++) {
dp[i] = dp[i - 1] + dp[i - 2];
}
return dp[N];
}
}
|
923f47ca29e829eead2bd4f1e0a8c879b34ee1d6
| 229 |
java
|
Java
|
api/src/test/java/com/ecom/SpringContextIntegrationTest.java
|
jmavs21/e-commerce
|
b4fe0281206642941af2a94fb34de3ee5629011e
|
[
"MIT"
] | null | null | null |
api/src/test/java/com/ecom/SpringContextIntegrationTest.java
|
jmavs21/e-commerce
|
b4fe0281206642941af2a94fb34de3ee5629011e
|
[
"MIT"
] | null | null | null |
api/src/test/java/com/ecom/SpringContextIntegrationTest.java
|
jmavs21/e-commerce
|
b4fe0281206642941af2a94fb34de3ee5629011e
|
[
"MIT"
] | null | null | null | 19.083333 | 60 | 0.812227 | 1,001,099 |
package com.ecom;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class SpringContextIntegrationTest {
@Test
void whenContextIsLoaded_thenNoExceptions() {}
}
|
923f47d048710409b66e75436873e2aa1c2556c6
| 1,279 |
java
|
Java
|
ibello-hu/src/main/java/hu/ibello/demo/steps/ChoosingProductSteps.java
|
mateelekibello/ibello-tests
|
aec7ea6c3453d94f791d7fc9650ca4cf25183918
|
[
"Apache-2.0"
] | null | null | null |
ibello-hu/src/main/java/hu/ibello/demo/steps/ChoosingProductSteps.java
|
mateelekibello/ibello-tests
|
aec7ea6c3453d94f791d7fc9650ca4cf25183918
|
[
"Apache-2.0"
] | null | null | null |
ibello-hu/src/main/java/hu/ibello/demo/steps/ChoosingProductSteps.java
|
mateelekibello/ibello-tests
|
aec7ea6c3453d94f791d7fc9650ca4cf25183918
|
[
"Apache-2.0"
] | null | null | null | 34.567568 | 86 | 0.677091 | 1,001,100 |
package hu.ibello.demo.steps;
import hu.ibello.core.Name;
import hu.ibello.demo.model.ProductToOrder;
import hu.ibello.demo.pages.OrderPage;
import hu.ibello.steps.StepLibrary;
@Name("Choosing product to order")
public class ChoosingProductSteps extends StepLibrary {
private OrderPage orderPage;
public void i_use_$_test_data_to_select_products(ProductToOrder data) {
if (data != null) {
change_number_of_product(data.getOutpost(), 1);
change_number_of_product(data.getSentinel(), 2);
change_number_of_product(data.getHunter(), 3);
change_number_of_product(data.getMasterHunter(), 4);
}
}
private void change_number_of_product(int expectedNum, int productIndex) {
productIndex--;
int currentNum = Integer.parseInt(orderPage.getNumberOfProduct(productIndex));
while (expectedNum != currentNum) {
if (expectedNum > currentNum) {
orderPage.click_increase_button_with_$_index(productIndex);
}
if (expectedNum < currentNum) {
orderPage.click_decrease_button_with_$_index(productIndex);
}
currentNum = Integer.parseInt(orderPage.getNumberOfProduct(productIndex));
}
}
}
|
923f493056483c1c247e4a7582b659ffeb489060
| 1,330 |
java
|
Java
|
src/com/programing/multithreading/util/ThreadLocalDemo.java
|
tttodorov13/programing
|
7b6ca651845fa277b563a7815f10e63d41300f41
|
[
"MIT"
] | null | null | null |
src/com/programing/multithreading/util/ThreadLocalDemo.java
|
tttodorov13/programing
|
7b6ca651845fa277b563a7815f10e63d41300f41
|
[
"MIT"
] | null | null | null |
src/com/programing/multithreading/util/ThreadLocalDemo.java
|
tttodorov13/programing
|
7b6ca651845fa277b563a7815f10e63d41300f41
|
[
"MIT"
] | null | null | null | 27.708333 | 89 | 0.596992 | 1,001,101 |
package com.programing.multithreading.util;
/**
* Thanks to: https://www.tutorialspoint.com/java_concurrency/concurrency_threadlocal.htm
*/
public class ThreadLocalDemo {
public static void main(String args[]) {
RunnableThreadLocalDemo commonInstance = new RunnableThreadLocalDemo();
Thread t1 = new Thread(commonInstance);
Thread t2 = new Thread(commonInstance);
Thread t3 = new Thread(commonInstance);
Thread t4 = new Thread(commonInstance);
t1.start();
t2.start();
t3.start();
t4.start();
// wait for threads to end
try {
t1.join();
t2.join();
t3.join();
t4.join();
} catch (Exception e) {
System.out.println("Interrupted");
}
}
}
class RunnableThreadLocalDemo implements Runnable {
int counter;
ThreadLocal<Integer> threadLocalCounter = new ThreadLocal<Integer>();
public void run() {
counter++;
if (threadLocalCounter.get() != null) {
threadLocalCounter.set(threadLocalCounter.get().intValue() + 1);
} else {
threadLocalCounter.set(0);
}
System.out.println("Counter: " + counter);
System.out.println("threadLocalCounter: " + threadLocalCounter.get());
}
}
|
923f497de1b52d622d68a2fd192f34a2f7f7771a
| 3,361 |
java
|
Java
|
spring-batch-core/src/main/java/org/springframework/batch/core/jsr/step/builder/JsrBatchletStepBuilder.java
|
rchandavaram/spring-batch
|
d3fa7d084b95938b1c91f11bd76b70c7f6a76ae7
|
[
"Apache-2.0"
] | 5 |
2018-09-04T08:33:22.000Z
|
2021-12-19T07:19:30.000Z
|
spring-batch-core/src/main/java/org/springframework/batch/core/jsr/step/builder/JsrBatchletStepBuilder.java
|
AlanBinu007/spring-batch
|
d6419f4479157ac666159403f7ba0908d817fab6
|
[
"Apache-2.0"
] | 2 |
2021-03-27T11:30:49.000Z
|
2021-03-27T11:31:08.000Z
|
spring-batch-core/src/main/java/org/springframework/batch/core/jsr/step/builder/JsrBatchletStepBuilder.java
|
AlanBinu007/spring-batch
|
d6419f4479157ac666159403f7ba0908d817fab6
|
[
"Apache-2.0"
] | 3 |
2015-09-11T06:18:03.000Z
|
2021-07-09T10:14:00.000Z
| 32.317308 | 117 | 0.769116 | 1,001,102 |
/*
* Copyright 2013-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
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.batch.core.jsr.step.builder;
import org.springframework.batch.core.ChunkListener;
import org.springframework.batch.core.Step;
import org.springframework.batch.core.jsr.configuration.support.BatchPropertyContext;
import org.springframework.batch.core.jsr.step.BatchletStep;
import org.springframework.batch.core.step.builder.StepBuilderException;
import org.springframework.batch.core.step.builder.StepBuilderHelper;
import org.springframework.batch.core.step.builder.TaskletStepBuilder;
import org.springframework.batch.core.step.tasklet.TaskletStep;
import org.springframework.batch.item.ItemStream;
import org.springframework.batch.repeat.support.RepeatTemplate;
import org.springframework.batch.repeat.support.TaskExecutorRepeatTemplate;
/**
* Extension of the {@link TaskletStepBuilder} that uses a {@link BatchletStep} instead
* of a {@link TaskletStep}.
*
* @author Michael Minella
* @author Mahmoud Ben Hassine
* @since 3.0
*/
public class JsrBatchletStepBuilder extends TaskletStepBuilder {
private BatchPropertyContext batchPropertyContext;
/**
* @param context used to resolve lazy bound properties
*/
public void setBatchPropertyContext(BatchPropertyContext context) {
this.batchPropertyContext = context;
}
public JsrBatchletStepBuilder(StepBuilderHelper<? extends StepBuilderHelper<?>> parent) {
super(parent);
}
/**
* Build the step from the components collected by the fluent setters. Delegates first to {@link #enhance(Step)} and
* then to {@link #createTasklet()} in subclasses to create the actual tasklet.
*
* @return a tasklet step fully configured and read to execute
*/
@Override
public TaskletStep build() {
registerStepListenerAsChunkListener();
BatchletStep step = new BatchletStep(getName(), batchPropertyContext);
super.enhance(step);
step.setChunkListeners(chunkListeners.toArray(new ChunkListener[0]));
if (getTransactionAttribute() != null) {
step.setTransactionAttribute(getTransactionAttribute());
}
if (getStepOperations() == null) {
stepOperations(new RepeatTemplate());
if (getTaskExecutor() != null) {
TaskExecutorRepeatTemplate repeatTemplate = new TaskExecutorRepeatTemplate();
repeatTemplate.setTaskExecutor(getTaskExecutor());
repeatTemplate.setThrottleLimit(getThrottleLimit());
stepOperations(repeatTemplate);
}
((RepeatTemplate) getStepOperations()).setExceptionHandler(getExceptionHandler());
}
step.setStepOperations(getStepOperations());
step.setTasklet(createTasklet());
step.setStreams(getStreams().toArray(new ItemStream[0]));
try {
step.afterPropertiesSet();
}
catch (Exception e) {
throw new StepBuilderException(e);
}
return step;
}
}
|
923f49e672e051ff107ce780e5b761075fe9c196
| 1,277 |
java
|
Java
|
liquibase-core/src/main/java/liquibase/statement/core/CreateViewStatement.java
|
The-Alchemist/liquibase
|
0eb61ae121964b12c0df2724cacbec01e31ddbb4
|
[
"Apache-2.0"
] | 5 |
2015-03-13T08:19:12.000Z
|
2019-06-27T07:50:55.000Z
|
liquibase-core/src/main/java/liquibase/statement/core/CreateViewStatement.java
|
The-Alchemist/liquibase
|
0eb61ae121964b12c0df2724cacbec01e31ddbb4
|
[
"Apache-2.0"
] | 42 |
2017-08-18T14:01:27.000Z
|
2022-02-16T01:16:30.000Z
|
liquibase-core/src/main/java/liquibase/statement/core/CreateViewStatement.java
|
The-Alchemist/liquibase
|
0eb61ae121964b12c0df2724cacbec01e31ddbb4
|
[
"Apache-2.0"
] | 4 |
2016-01-12T15:51:46.000Z
|
2019-07-02T15:41:26.000Z
| 25.039216 | 133 | 0.696163 | 1,001,103 |
package liquibase.statement.core;
import liquibase.statement.AbstractSqlStatement;
public class CreateViewStatement extends AbstractSqlStatement {
private String catalogName;
private String schemaName;
private String viewName;
private String selectQuery;
private boolean replaceIfExists;
private boolean fullDefinition;
public CreateViewStatement(String catalogName, String schemaName, String viewName, String selectQuery, boolean replaceIfExists) {
this.catalogName = catalogName;
this.schemaName = schemaName;
this.viewName = viewName;
this.selectQuery = selectQuery;
this.replaceIfExists = replaceIfExists;
}
public String getCatalogName() {
return catalogName;
}
public String getSchemaName() {
return schemaName;
}
public String getViewName() {
return viewName;
}
public String getSelectQuery() {
return selectQuery;
}
public boolean isReplaceIfExists() {
return replaceIfExists;
}
public boolean isFullDefinition() {
return fullDefinition;
}
public CreateViewStatement setFullDefinition(boolean fullDefinition) {
this.fullDefinition = fullDefinition;
return this;
}
}
|
923f4a11c8c2c46e904ad31dc575b3eea9530a94
| 549 |
java
|
Java
|
src/main/java/com/zipcode/justcode/clamfortress/ClamFortress/models/game/models/items/artifacts/HolyCrown.java
|
adambennett/JustCode
|
10a112461aa0b515a94b0c19e97ec319570d5baa
|
[
"MIT"
] | 1 |
2020-03-13T14:48:32.000Z
|
2020-03-13T14:48:32.000Z
|
src/main/java/com/zipcode/justcode/clamfortress/ClamFortress/models/game/models/items/artifacts/HolyCrown.java
|
adambennett/JustCode
|
10a112461aa0b515a94b0c19e97ec319570d5baa
|
[
"MIT"
] | null | null | null |
src/main/java/com/zipcode/justcode/clamfortress/ClamFortress/models/game/models/items/artifacts/HolyCrown.java
|
adambennett/JustCode
|
10a112461aa0b515a94b0c19e97ec319570d5baa
|
[
"MIT"
] | null | null | null | 24.954545 | 90 | 0.717668 | 1,001,104 |
package com.zipcode.justcode.clamfortress.ClamFortress.models.game.models.items.artifacts;
import com.zipcode.justcode.clamfortress.ClamFortress.models.game.interfaces.*;
public class HolyCrown extends AbstractArtifact implements Unique {
private static final Integer faithBonus = 15;
public HolyCrown() {
super("Holy Crown", "Improves your faith gain by 15.");
}
@Override
public Integer modifyFaithInc() { return faithBonus; }
@Override
public HolyCrown clone() {
return new HolyCrown();
}
}
|
923f4b6b05e3eccbcab573c58404ed28362f56e7
| 335 |
java
|
Java
|
apollo-client/src/main/java/com/ctrip/framework/apollo/ConfigFileChangeListener.java
|
smilesnake/apollo
|
6d911fbf58c6a35236a3a22037c9df6c47be06f4
|
[
"Apache-2.0"
] | null | null | null |
apollo-client/src/main/java/com/ctrip/framework/apollo/ConfigFileChangeListener.java
|
smilesnake/apollo
|
6d911fbf58c6a35236a3a22037c9df6c47be06f4
|
[
"Apache-2.0"
] | null | null | null |
apollo-client/src/main/java/com/ctrip/framework/apollo/ConfigFileChangeListener.java
|
smilesnake/apollo
|
6d911fbf58c6a35236a3a22037c9df6c47be06f4
|
[
"Apache-2.0"
] | null | null | null | 17.578947 | 62 | 0.730539 | 1,001,105 |
package com.ctrip.framework.apollo;
import com.ctrip.framework.apollo.model.ConfigFileChangeEvent;
/**
* 配置文件变更监听器接口
*
* @author Jason Song([email protected])
*/
public interface ConfigFileChangeListener {
/**
* 当命名空间有任何配置更改时调用
*
* @param changeEvent 更改的事件
*/
void onChange(ConfigFileChangeEvent changeEvent);
}
|
923f4bd663397a8da89e5b76ba9f3a08feda8abf
| 565 |
java
|
Java
|
flowable-biz-suite/bizcore/WEB-INF/flowable_core_src/com/doublechain/flowable/secuser/SecUserManagerException.java
|
jarryscript/flowable
|
7c2f7ab87123f016bf2b95e7bde9857e706353b0
|
[
"MIT"
] | null | null | null |
flowable-biz-suite/bizcore/WEB-INF/flowable_core_src/com/doublechain/flowable/secuser/SecUserManagerException.java
|
jarryscript/flowable
|
7c2f7ab87123f016bf2b95e7bde9857e706353b0
|
[
"MIT"
] | null | null | null |
flowable-biz-suite/bizcore/WEB-INF/flowable_core_src/com/doublechain/flowable/secuser/SecUserManagerException.java
|
jarryscript/flowable
|
7c2f7ab87123f016bf2b95e7bde9857e706353b0
|
[
"MIT"
] | null | null | null | 24.565217 | 64 | 0.80885 | 1,001,106 |
package com.doublechain.flowable.secuser;
//import com.doublechain.flowable.EntityNotFoundException;
import com.doublechain.flowable.FlowableException;
import com.doublechain.flowable.Message;
import java.util.List;
public class SecUserManagerException extends FlowableException {
private static final long serialVersionUID = 1L;
public SecUserManagerException(String string) {
super(string);
}
public SecUserManagerException(Message message) {
super(message);
}
public SecUserManagerException(List<Message> messageList) {
super(messageList);
}
}
|
923f4bffe72024f44f7a9fdba81a41e631805289
| 832 |
java
|
Java
|
src/main/java/com/manson/domain/fed76/response/PlanPriceCheckResponse.java
|
sdaskaliesku/fo76Domain
|
f084c991644f0524ea1d294ec67671a582a03c28
|
[
"Apache-2.0"
] | 3 |
2020-10-03T19:21:28.000Z
|
2021-06-03T09:28:00.000Z
|
src/main/java/com/manson/domain/fed76/response/PlanPriceCheckResponse.java
|
sdaskaliesku/fo76Domain
|
f084c991644f0524ea1d294ec67671a582a03c28
|
[
"Apache-2.0"
] | null | null | null |
src/main/java/com/manson/domain/fed76/response/PlanPriceCheckResponse.java
|
sdaskaliesku/fo76Domain
|
f084c991644f0524ea1d294ec67671a582a03c28
|
[
"Apache-2.0"
] | null | null | null | 25.212121 | 68 | 0.766827 | 1,001,107 |
package com.manson.domain.fed76.response;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.manson.domain.fed76.PriceType;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.ToString;
@Data
@EqualsAndHashCode(callSuper = false)
@AllArgsConstructor
@ToString(callSuper = true)
public class PlanPriceCheckResponse extends BasePriceCheckResponse {
private String verdict;
@JsonProperty("plan_class")
private String planClass;
@JsonProperty("plan_subclass")
private String planSubclass;
private boolean tradeable;
@JsonProperty("plan_type")
private String planType;
private String formId;
private PlanReview review;
private String message;
public PlanPriceCheckResponse() {
this.type = PriceType.PLAN;
}
}
|
923f4cb87e158dc682969dc115d293db028ea6fa
| 6,271 |
java
|
Java
|
swim-java/swim-runtime-java/swim-polyglot-java/swim.dynamic.api/src/main/java/swim/dynamic/api/plane/HostPlaneContext.java
|
swimos/swim
|
b403143d89d83e24a6bf842851bab57f1a1bc035
|
[
"Apache-2.0"
] | 458 |
2019-02-19T14:04:55.000Z
|
2022-03-27T19:52:37.000Z
|
swim-java/swim-runtime-java/swim-polyglot-java/swim.dynamic.api/src/main/java/swim/dynamic/api/plane/HostPlaneContext.java
|
swimos/swim
|
b403143d89d83e24a6bf842851bab57f1a1bc035
|
[
"Apache-2.0"
] | 57 |
2019-06-17T11:07:18.000Z
|
2021-12-21T12:47:53.000Z
|
swim-java/swim-runtime-java/swim-polyglot-java/swim.dynamic.api/src/main/java/swim/dynamic/api/plane/HostPlaneContext.java
|
swimos/swim
|
b403143d89d83e24a6bf842851bab57f1a1bc035
|
[
"Apache-2.0"
] | 34 |
2019-02-21T02:47:34.000Z
|
2022-01-17T13:51:51.000Z
| 27.504386 | 101 | 0.735927 | 1,001,108 |
// Copyright 2015-2021 Swim 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 swim.dynamic.api.plane;
import swim.api.agent.AgentRoute;
import swim.api.auth.Authenticator;
import swim.api.plane.PlaneContext;
import swim.api.policy.PlanePolicy;
import swim.dynamic.Bridge;
import swim.dynamic.HostMethod;
import swim.dynamic.HostObjectType;
import swim.dynamic.JavaHostObjectType;
import swim.dynamic.api.agent.GuestAgentRoute;
import swim.dynamic.java.lang.HostObject;
import swim.uri.Uri;
import swim.uri.UriPattern;
public final class HostPlaneContext {
private HostPlaneContext() {
// static
}
public static final HostObjectType<PlaneContext> TYPE;
static {
final JavaHostObjectType<PlaneContext> type = new JavaHostObjectType<>(PlaneContext.class);
TYPE = type;
type.inheritType(HostObject.TYPE); // FIXME: remove once any other base type is inherited
// FIXME: type.inheritType(HostWarpRef.TYPE);
// FIXME: type.inheritType(HostLog.TYPE);
type.addMember(new HostPlaneContextSchedule());
type.addMember(new HostPlaneContextStage());
type.addMember(new HostPlaneContextPolicy());
type.addMember(new HostPlaneContextSetPolicy());
type.addMember(new HostPlaneContextGetAuthenticator());
type.addMember(new HostPlaneContextAddAuthenticator());
type.addMember(new HostPlaneContextGetAgentFactory());
type.addMember(new HostPlaneContextGetAgentRoute());
type.addMember(new HostPlaneContextAddAgentRoute());
type.addMember(new HostPlaneContextRemoveAgentRoute());
}
}
final class HostPlaneContextSchedule implements HostMethod<PlaneContext> {
@Override
public String key() {
return "schedule";
}
@Override
public Object invoke(Bridge bridge, PlaneContext planeContext, Object... arguments) {
return planeContext.schedule();
}
}
final class HostPlaneContextStage implements HostMethod<PlaneContext> {
@Override
public String key() {
return "stage";
}
@Override
public Object invoke(Bridge bridge, PlaneContext planeContext, Object... arguments) {
return planeContext.stage();
}
}
final class HostPlaneContextPolicy implements HostMethod<PlaneContext> {
@Override
public String key() {
return "policy";
}
@Override
public Object invoke(Bridge bridge, PlaneContext planeContext, Object... arguments) {
return planeContext.policy();
}
}
final class HostPlaneContextSetPolicy implements HostMethod<PlaneContext> {
@Override
public String key() {
return "setPolicy";
}
@Override
public Object invoke(Bridge bridge, PlaneContext planeContext, Object... arguments) {
final Object policy = arguments[0];
// TODO: convert guest policy to host PlanePolicy.
planeContext.setPolicy((PlanePolicy) policy);
return null;
}
}
final class HostPlaneContextGetAuthenticator implements HostMethod<PlaneContext> {
@Override
public String key() {
return "getAuthenticator";
}
@Override
public Object invoke(Bridge bridge, PlaneContext planeContext, Object... arguments) {
final Object authenticatorName = arguments[0];
return planeContext.getAuthenticator((String) authenticatorName);
}
}
final class HostPlaneContextAddAuthenticator implements HostMethod<PlaneContext> {
@Override
public String key() {
return "addAuthenticator";
}
@Override
public Object invoke(Bridge bridge, PlaneContext planeContext, Object... arguments) {
final Object authenticatorName = arguments[1];
final Object authenticator = arguments[1];
// TODO: convert guest authenticator to host Authenticator.
planeContext.addAuthenticator((String) authenticatorName, (Authenticator) authenticator);
return null;
}
}
final class HostPlaneContextGetAgentFactory implements HostMethod<PlaneContext> {
@Override
public String key() {
return "getAgentFactory";
}
@Override
public Object invoke(Bridge bridge, PlaneContext planeContext, Object... arguments) {
Object nodeUri = arguments[0];
if (nodeUri instanceof String) {
nodeUri = Uri.parse((String) nodeUri);
}
return planeContext.getAgentFactory((Uri) nodeUri);
}
}
final class HostPlaneContextGetAgentRoute implements HostMethod<PlaneContext> {
@Override
public String key() {
return "getAgentRoute";
}
@Override
public Object invoke(Bridge bridge, PlaneContext planeContext, Object... arguments) {
final Object routeName = arguments[0];
return planeContext.getAgentRoute((String) routeName);
}
}
final class HostPlaneContextAddAgentRoute implements HostMethod<PlaneContext> {
@Override
public String key() {
return "addAgentRoute";
}
@Override
public Object invoke(Bridge bridge, PlaneContext planeContext, Object... arguments) {
final Object routeName = arguments[0];
Object pattern = arguments[1];
if (pattern == null) {
throw new NullPointerException();
}
if (pattern instanceof String) {
pattern = UriPattern.parse((String) pattern);
}
Object agentRoute = arguments[2];
if (agentRoute == null) {
throw new NullPointerException();
}
if (!(agentRoute instanceof AgentRoute<?>)) {
agentRoute = new GuestAgentRoute(bridge, agentRoute);
}
planeContext.addAgentRoute((String) routeName, (UriPattern) pattern, (AgentRoute<?>) agentRoute);
return null;
}
}
final class HostPlaneContextRemoveAgentRoute implements HostMethod<PlaneContext> {
@Override
public String key() {
return "removeAgentRoute";
}
@Override
public Object invoke(Bridge bridge, PlaneContext planeContext, Object... arguments) {
final Object routeName = arguments[0];
planeContext.removeAgentRoute((String) routeName);
return null;
}
}
|
923f4d048579fdf886302ffbfa68a6dd693aaa97
| 8,292 |
java
|
Java
|
src/main/java/de/esoco/coroutine/step/Condition.java
|
krmahadevan/coroutines
|
e77d3ca54081383be1384f088415cfa9e8b384d7
|
[
"Apache-2.0"
] | 279 |
2018-11-02T02:52:46.000Z
|
2022-03-30T13:38:01.000Z
|
src/main/java/de/esoco/coroutine/step/Condition.java
|
krmahadevan/coroutines
|
e77d3ca54081383be1384f088415cfa9e8b384d7
|
[
"Apache-2.0"
] | 7 |
2018-11-11T16:31:16.000Z
|
2019-08-27T20:39:56.000Z
|
src/main/java/de/esoco/coroutine/step/Condition.java
|
krmahadevan/coroutines
|
e77d3ca54081383be1384f088415cfa9e8b384d7
|
[
"Apache-2.0"
] | 36 |
2018-11-11T19:46:24.000Z
|
2021-12-16T09:09:58.000Z
| 35.741379 | 78 | 0.642909 | 1,001,109 |
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// This file is a part of the 'coroutines' project.
// Copyright 2018 Elmar Sonnenschein, esoco GmbH, Flensburg, Germany
//
// 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 de.esoco.coroutine.step;
import de.esoco.coroutine.Continuation;
import de.esoco.coroutine.Coroutine;
import de.esoco.coroutine.CoroutineStep;
import java.util.Objects;
import java.util.concurrent.CompletableFuture;
import java.util.function.BiPredicate;
import java.util.function.Predicate;
/********************************************************************
* A {@link Coroutine} step that test a logical expression in the form of a
* {@link Predicate} or {@link BiPredicate} and executes certain steps (which
* may be a subroutines) based on the boolean result.
*
* @author eso
*/
public class Condition<I, O> extends CoroutineStep<I, O>
{
//~ Instance fields --------------------------------------------------------
private final BiPredicate<? super I, Continuation<?>> pCondition;
private final CoroutineStep<I, O> rRunIfTrue;
private final CoroutineStep<I, O> rRunIfFalse;
//~ Constructors -----------------------------------------------------------
/***************************************
* Creates a new instance.
*
* @param pCondition The condition to test
* @param rRunIfTrue The step to run if the condition is TRUE
* @param rRunIfFalse The step to run if the condition is FALSE
*/
public Condition(BiPredicate<? super I, Continuation<?>> pCondition,
CoroutineStep<I, O> rRunIfTrue,
CoroutineStep<I, O> rRunIfFalse)
{
Objects.requireNonNull(pCondition);
Objects.requireNonNull(rRunIfTrue);
this.pCondition = pCondition;
this.rRunIfTrue = rRunIfTrue;
this.rRunIfFalse = rRunIfFalse;
}
//~ Static methods ---------------------------------------------------------
/***************************************
* Tests a logical condition and executes a certain step if the condition is
* TRUE. To create a condition that also runs a step if the condition is
* FALSE either a subsequent call to {@link #orElse(CoroutineStep)} or the
* alternative method {@link #doIfElse(Predicate, CoroutineStep,
* CoroutineStep)}can be used. If no 'else' step is set the coroutine will
* terminate if the condition is not met.
*
* <p>This variant expects a unary predicate that only receives the input
* value. If the {@link Continuation} needs to be tested too the method
* {@link #doIf(BiPredicate, CoroutineStep)} can be used instead.</p>
*
* @param fCondition The condition to test
* @param rRunIfTrue The step to run if the condition is TRUE
*
* @return The new conditional step
*/
public static <I, O> Condition<I, O> doIf(
Predicate<? super I> fCondition,
CoroutineStep<I, O> rRunIfTrue)
{
return new Condition<>((i, c) -> fCondition.test(i), rRunIfTrue, null);
}
/***************************************
* Tests a logical condition and executes a certain step if the condition is
* TRUE. To create a condition that also runs a step if the condition is
* FALSE either a subsequent call to {@link #orElse(CoroutineStep)} or the
* alternative method {@link #doIfElse(Predicate, CoroutineStep,
* CoroutineStep)}can be used. If no 'else' step is set the coroutine will
* terminate if the condition is not met.
*
* <p>This variant expects a binary predicate that also receives the current
* {@link Continuation}. If a test of the input value is sufficient the
* method {@link #doIf(Predicate, CoroutineStep)} can be used instead.</p>
*
* @param fCondition The condition to test
* @param rRunIfTrue The step to run if the condition is TRUE
*
* @return The new conditional step
*/
public static <I, O> Condition<I, O> doIf(
BiPredicate<? super I, Continuation<?>> fCondition,
CoroutineStep<I, O> rRunIfTrue)
{
return new Condition<>(fCondition, rRunIfTrue, null);
}
/***************************************
* Tests a logical condition and executes certain steps if the condition is
* either TRUE or FALSE. A semantic alternative is the factory method {@link
* #doIf(BiPredicate, CoroutineStep)} in conjunction with the instance
* method {@link #orElse(CoroutineStep)}.
*
* <p>This variant expects a binary predicate that also receives the current
* {@link Continuation}. If a test of the input value is sufficient the
* method {@link #doIfElse(Predicate, CoroutineStep, CoroutineStep)} can be
* used instead.</p>
*
* @param fCondition The condition to test
* @param rRunIfTrue The step to run if the condition is TRUE
* @param rRunIfFalse The step to run if the condition is FALSE
*
* @return The new conditional step
*/
public static <I, O> Condition<I, O> doIfElse(
BiPredicate<? super I, Continuation<?>> fCondition,
CoroutineStep<I, O> rRunIfTrue,
CoroutineStep<I, O> rRunIfFalse)
{
return new Condition<>(fCondition, rRunIfTrue, rRunIfFalse);
}
/***************************************
* Tests a logical condition and executes certain steps if the condition is
* either TRUE or FALSE. A semantic alternative is the factory method {@link
* #doIf(BiPredicate, CoroutineStep)} in conjunction with the instance
* method {@link #orElse(CoroutineStep)}.
*
* <p>This variant expects a unary predicate that only receives the input
* value. If the {@link Continuation} needs to be tested too the method
* {@link #doIf(BiPredicate, CoroutineStep)} can be used instead.</p>
*
* @param fCondition The condition to test
* @param rRunIfTrue The step to run if the condition is TRUE
* @param rRunIfFalse The step to run if the condition is FALSE
*
* @return The new conditional step
*/
public static <I, O> Condition<I, O> doIfElse(
Predicate<? super I> fCondition,
CoroutineStep<I, O> rRunIfTrue,
CoroutineStep<I, O> rRunIfFalse)
{
return new Condition<>(
(i, c) -> fCondition.test(i),
rRunIfTrue,
rRunIfFalse);
}
//~ Methods ----------------------------------------------------------------
/***************************************
* Returns a new instance with the condition and TRUE step of this and a
* certain step to execute if the condition is FALSE. This is just a
* semantic alternative to {@link #doIfElse(BiPredicate, CoroutineStep,
* CoroutineStep)}.
*
* @param rRunIfFalse The step to run if the condition is FALSE
*
* @return A new conditional step
*/
public Condition<I, O> orElse(CoroutineStep<I, O> rRunIfFalse)
{
return new Condition<>(pCondition, rRunIfTrue, rRunIfFalse);
}
/***************************************
* {@inheritDoc}
*/
@Override
public void runAsync(CompletableFuture<I> fPreviousExecution,
CoroutineStep<O, ?> rNextStep,
Continuation<?> rContinuation)
{
fPreviousExecution.thenAcceptAsync(
i ->
{
CoroutineStep<I, O> rStep =
pCondition.test(i, rContinuation) ? rRunIfTrue
: rRunIfFalse;
if (rStep != null)
{
// forward to rStep which handles future chaining and errors
rStep.runAsync(fPreviousExecution, rNextStep, rContinuation);
}
else
{
terminateCoroutine(rContinuation);
}
},
rContinuation);
}
/***************************************
* {@inheritDoc}
*/
@Override
protected O execute(I rInput, Continuation<?> rContinuation)
{
O rResult = null;
if (pCondition.test(rInput, rContinuation))
{
rResult = rRunIfTrue.runBlocking(rInput, rContinuation);
}
else if (rRunIfFalse != null)
{
rResult = rRunIfFalse.runBlocking(rInput, rContinuation);
}
return rResult;
}
}
|
923f4f97e83e2c89cab419215bc1291ba7ade987
| 46,406 |
java
|
Java
|
profilers/src/com/android/tools/profilers/StudioProfilers.java
|
Ret-Mode/android
|
5b427d1fc6a66ff4db09a9e2f02ae61292ccd797
|
[
"Apache-2.0"
] | 831 |
2016-06-09T06:55:34.000Z
|
2022-03-30T11:17:10.000Z
|
profilers/src/com/android/tools/profilers/StudioProfilers.java
|
Ret-Mode/android
|
5b427d1fc6a66ff4db09a9e2f02ae61292ccd797
|
[
"Apache-2.0"
] | 19 |
2017-10-27T00:36:35.000Z
|
2021-02-04T13:59:45.000Z
|
profilers/src/com/android/tools/profilers/StudioProfilers.java
|
Ret-Mode/android
|
5b427d1fc6a66ff4db09a9e2f02ae61292ccd797
|
[
"Apache-2.0"
] | 210 |
2016-07-05T12:22:36.000Z
|
2022-03-19T09:07:15.000Z
| 43.370093 | 140 | 0.709714 | 1,001,110 |
/*
* Copyright (C) 2016 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.android.tools.profilers;
import com.android.sdklib.AndroidVersion;
import com.android.tools.adtui.model.AspectModel;
import com.android.tools.adtui.model.FpsTimer;
import com.android.tools.adtui.model.Range;
import com.android.tools.adtui.model.StopwatchTimer;
import com.android.tools.adtui.model.StreamingTimeline;
import com.android.tools.adtui.model.axis.AxisComponentModel;
import com.android.tools.adtui.model.axis.ResizingAxisComponentModel;
import com.android.tools.adtui.model.formatter.TimeAxisFormatter;
import com.android.tools.adtui.model.updater.Updatable;
import com.android.tools.adtui.model.updater.Updater;
import com.android.tools.idea.transport.poller.TransportEventPoller;
import com.android.tools.profiler.proto.Commands;
import com.android.tools.profiler.proto.Common;
import com.android.tools.profiler.proto.Common.AgentData;
import com.android.tools.profiler.proto.Common.Device;
import com.android.tools.profiler.proto.Common.Event;
import com.android.tools.profiler.proto.Common.Stream;
import com.android.tools.profiler.proto.Cpu;
import com.android.tools.profiler.proto.Memory;
import com.android.tools.profiler.proto.Memory.MemoryAllocSamplingData;
import com.android.tools.profiler.proto.MemoryProfiler.SetAllocationSamplingRateRequest;
import com.android.tools.profiler.proto.MemoryProfiler.SetAllocationSamplingRateResponse;
import com.android.tools.profiler.proto.Transport;
import com.android.tools.profiler.proto.Transport.AgentStatusRequest;
import com.android.tools.profiler.proto.Transport.EventGroup;
import com.android.tools.profiler.proto.Transport.GetDevicesRequest;
import com.android.tools.profiler.proto.Transport.GetDevicesResponse;
import com.android.tools.profiler.proto.Transport.GetEventGroupsRequest;
import com.android.tools.profiler.proto.Transport.GetEventGroupsResponse;
import com.android.tools.profiler.proto.Transport.GetProcessesRequest;
import com.android.tools.profiler.proto.Transport.GetProcessesResponse;
import com.android.tools.profiler.proto.Transport.TimeRequest;
import com.android.tools.profiler.proto.Transport.TimeResponse;
import com.android.tools.profilers.cpu.CpuProfiler;
import com.android.tools.profilers.cpu.CpuProfilerStage;
import com.android.tools.profilers.customevent.CustomEventProfiler;
import com.android.tools.profilers.customevent.CustomEventProfilerStage;
import com.android.tools.profilers.energy.EnergyProfiler;
import com.android.tools.profilers.energy.EnergyProfilerStage;
import com.android.tools.profilers.event.EventProfiler;
import com.android.tools.profilers.memory.MemoryProfiler;
import com.android.tools.profilers.memory.MemoryProfilerStage;
import com.android.tools.profilers.network.NetworkProfiler;
import com.android.tools.profilers.network.NetworkProfilerStage;
import com.android.tools.profilers.sessions.SessionAspect;
import com.android.tools.profilers.sessions.SessionsManager;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.hash.Hashing;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.util.Pair;
import com.intellij.openapi.util.text.StringUtil;
import io.grpc.StatusRuntimeException;
import java.io.File;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.annotations.TestOnly;
/**
* The suite of profilers inside Android Studio. This object is responsible for maintaining the information
* global across all the profilers, device management, process management, current state of the tool etc.
*/
public class StudioProfilers extends AspectModel<ProfilerAspect> implements Updatable {
@NotNull
private static Logger getLogger() {
return Logger.getInstance(StudioProfilers.class);
}
// Device directory where the transport daemon lives.
public static final String DAEMON_DEVICE_DIR_PATH = "/data/local/tmp/perfd";
@VisibleForTesting static final int AGENT_STATUS_MAX_RETRY_COUNT = 10;
/**
* The number of updates per second our simulated object models receive.
*/
public static final int PROFILERS_UPDATE_RATE = 60;
public static final long TRANSPORT_POLLER_INTERVAL_NS = TimeUnit.MILLISECONDS.toNanos(500);
@NotNull private final ProfilerClient myClient;
private final StreamingTimeline myTimeline;
private final List<StudioProfiler> myProfilers;
@NotNull
private final IdeProfilerServices myIdeServices;
/**
* Processes from devices come from the latest update, and are filtered to include only ALIVE ones and {@code myProcess}.
*/
private Map<Common.Device, List<Common.Process>> myProcesses;
/**
* A map of device to stream ids. This is needed to map devices to their transport-database streams.
*/
private Map<Common.Device, Long> myDeviceToStreamIds;
private Map<Long, Common.Stream> myStreamIdToStreams;
@NotNull private final SessionsManager mySessionsManager;
@Nullable
private Common.Process myProcess;
@NotNull
private AgentData myAgentData;
@Nullable
private String myPreferredDeviceName;
@Nullable
private String myPreferredProcessName;
private Predicate<Common.Process> myPreferredProcessFilter;
private Common.Device myDevice;
/**
* The session that is currently selected.
*/
@NotNull private Common.Session mySelectedSession;
/**
* The session that is currently under profiling.
*/
@NotNull private Common.Session myProfilingSession;
@NotNull
private Stage myStage;
private Updater myUpdater;
private AxisComponentModel myViewAxis;
private long myRefreshDevices;
private long myEventPollingInternvalNs;
private final Map<Common.SessionMetaData.SessionType, Runnable> mySessionChangeListener;
/**
* Whether the profiler should auto-select a process to profile.
*/
private boolean myAutoProfilingEnabled;
/**
* The number of update count the profilers have waited for an agent status to become ATTACHED for a particular session id.
* If the agent status remains UNSPECIFIED after {@link StudioProfilers#AGENT_STATUS_MAX_RETRY_COUNT}, the profilers deem the process to
* be without agent.
*/
public final Map<Long, Integer> mySessionIdToAgentStatusRetryMap = new HashMap<>();
private TransportEventPoller myTransportPoller;
public StudioProfilers(@NotNull ProfilerClient client, @NotNull IdeProfilerServices ideServices) {
this(client, ideServices, new FpsTimer(PROFILERS_UPDATE_RATE));
}
@VisibleForTesting
public StudioProfilers(@NotNull ProfilerClient client, @NotNull IdeProfilerServices ideServices, @NotNull StopwatchTimer timer) {
myClient = client;
myIdeServices = ideServices;
myPreferredProcessName = null;
myPreferredProcessFilter = null;
myStage = new NullMonitorStage(this);
mySessionsManager = new SessionsManager(this);
mySessionChangeListener = new HashMap<>();
myDeviceToStreamIds = new HashMap<>();
myStreamIdToStreams = new HashMap<>();
myStage.enter();
myUpdater = new Updater(timer);
// Order in which events are added to profilersBuilder will be order they appear in monitor stage
ImmutableList.Builder<StudioProfiler> profilersBuilder = new ImmutableList.Builder<>();
profilersBuilder.add(new EventProfiler(this));
// Show the custom event monitor in the monitor stage view when enabled right under the activity bar
if (myIdeServices.getFeatureConfig().isCustomEventVisualizationEnabled()) {
profilersBuilder.add(new CustomEventProfiler(this));
}
profilersBuilder.add(new CpuProfiler(this));
profilersBuilder.add(new MemoryProfiler(this));
profilersBuilder.add(new NetworkProfiler(this));
if (myIdeServices.getFeatureConfig().isEnergyProfilerEnabled()) {
profilersBuilder.add(new EnergyProfiler(this));
}
myProfilers = profilersBuilder.build();
myTimeline = new StreamingTimeline(myUpdater);
myProcesses = Maps.newHashMap();
myDevice = null;
myProcess = null;
// TODO: StudioProfilers initalizes with a default session, which a lot of tests now relies on to avoid a NPE.
// We should clean all the tests up to either have StudioProfilers create a proper session first or handle the null cases better.
mySelectedSession = myProfilingSession = Common.Session.getDefaultInstance();
myAgentData = AgentData.getDefaultInstance();
myTimeline.getSelectionRange().addDependency(this).onChange(Range.Aspect.RANGE, () -> {
if (!myTimeline.getSelectionRange().isEmpty()) {
myTimeline.setStreaming(false);
}
});
registerSessionChangeListener(Common.SessionMetaData.SessionType.FULL, () -> {
setStage(new StudioMonitorStage(this));
if (SessionsManager.isSessionAlive(mySelectedSession)) {
// The session is live - move the timeline to the current time.
TimeResponse timeResponse = myClient.getTransportClient().getCurrentTime(
TimeRequest.newBuilder().setStreamId(mySelectedSession.getStreamId()).build());
myTimeline.reset(mySelectedSession.getStartTimestamp(), timeResponse.getTimestampNs());
if (startupCpuProfilingStarted()) {
setStage(new CpuProfilerStage(this));
}
else if (startupMemoryProfilingStarted()) {
setStage(new MemoryProfilerStage(this));
}
}
else {
// The session is finished, reset the timeline to include the entire data range.
myTimeline.reset(mySelectedSession.getStartTimestamp(), mySelectedSession.getEndTimestamp());
// Disable data range update and stream/snap features.
myTimeline.setIsPaused(true);
myTimeline.setStreaming(false);
myTimeline.getViewRange().set(mySessionsManager.getSessionPreferredViewRange(mySelectedSession));
}
});
mySessionsManager.addDependency(this)
.onChange(SessionAspect.SELECTED_SESSION, this::selectedSessionChanged)
.onChange(SessionAspect.PROFILING_SESSION, this::profilingSessionChanged);
myViewAxis = new ResizingAxisComponentModel.Builder(myTimeline.getViewRange(), TimeAxisFormatter.DEFAULT)
.setGlobalRange(myTimeline.getDataRange()).build();
// Manage our own poll interval with the poller instead of using the ScheduledExecutorService helper provided in TransportEventPoller.
// The rest of the Studio code runs on its own updater and assumes all UI-related code (e.g. Aspect) be handled via the updating
// thread. Using the ScheduleExecutorService would violate that assumption and cause concurrency issues.
myTransportPoller = new TransportEventPoller(myClient.getTransportClient(), Comparator.comparing(Common.Event::getTimestamp));
myUpdater.register(this);
}
public boolean isStopped() {
return !myUpdater.isRunning();
}
public void stop() {
if (isStopped()) {
// Profiler is already stopped. Nothing to do. Ideally, this method shouldn't be called when the profiler is already stopped.
// However, some exceptions might be thrown when listeners are notified about ProfilerAspect.STAGE aspect change and react
// accordingly. In this case, we could end up with an inconsistent model and allowing to try to call stop and notify the listeners
// again can only make it worse. Therefore, we return early to avoid making the model problem bigger.
return;
}
// The following line can't throw an exception, will stop the updater's timer and guarantees future calls to isStopped() return true.
myUpdater.stop();
// The following lines trigger aspect changes and, therefore, can make many models to update. That might cause an exception to be thrown
// and make some models inconsistent. In this case, we want future calls to this method to return early, as we can only make the
// inconsistency worse if we call these lines again.
setProcess(null, null);
changed(ProfilerAspect.STAGE);
}
@NotNull
public TransportEventPoller getTransportPoller() {
return myTransportPoller;
}
public Map<Common.Device, List<Common.Process>> getDeviceProcessMap() {
return myProcesses;
}
public List<Common.Device> getDevices() {
return Lists.newArrayList(myProcesses.keySet());
}
/**
* Tells the profiler to select and profile the device+process combo of the same name next time it is detected.
*
* @param processFilter Additional filter used for choosing the most desirable preferred process. e.g. Process of a particular pid,
* or process that starts after a certain time.
*/
public void setPreferredProcess(@Nullable String deviceName,
@Nullable String processName,
@Nullable Predicate<Common.Process> processFilter) {
myIdeServices.getFeatureTracker().trackAutoProfilingRequested();
myPreferredDeviceName = deviceName;
setPreferredProcessName(processName);
myPreferredProcessFilter = processFilter;
// Checks whether we can switch immediately if the device is already there.
setAutoProfilingEnabled(true);
changed(ProfilerAspect.PREFERRED_PROCESS);
}
public void setPreferredProcessName(@Nullable String processName) {
myPreferredProcessName = processName;
}
@Nullable
public String getPreferredProcessName() {
return myPreferredProcessName;
}
/**
* Enable/disable auto device+process selection, which looks for the preferred device + process combination and starts profiling. If no
* preference has been set (via {@link #setProcess(Device, Common.Process)}, then we profiling any online device+process combo.
*/
public void setAutoProfilingEnabled(boolean enabled) {
myAutoProfilingEnabled = enabled;
if (myIdeServices.getFeatureConfig().isUnifiedPipelineEnabled()) {
// Do nothing. Let update() take care of which process should be selected.
// If setProcess() is called now, it may be confused if the process start/end events don't arrive immediately.
// For example, if the user ends a session (which will set myProcess null), then click the Run button.
// setAutoProfilingEnabled(true) will be called when Run button is clicked. If the previous process's
// DEAD event is delayed, setProcess() may start a new session on it (which is already dead) because
// the event stream shows it is still alive, and it's "new" in the perspective of StudioProfilers.
}
else if (myAutoProfilingEnabled) {
setProcess(findPreferredDevice(), null);
}
}
@TestOnly
public boolean getAutoProfilingEnabled() {
return myAutoProfilingEnabled;
}
private List<Common.Device> getUpToDateDevices() {
return getUpToDateDevices(myIdeServices.getFeatureConfig().isUnifiedPipelineEnabled(), myClient, myDeviceToStreamIds,
myStreamIdToStreams);
}
/**
* Returns a up-to-date list of devices including disconnected ones.
* This method works under either new or old data pipeline.
*
* @param isUnifiedPipelineEnabled The flag to control whether unified pipeline is enabled.
* @param client The ProfilerClient that can call into ProfilerService.
* @param deviceToStreamIds An updatable cache that maps a device to its stream ID.
* @param streamIdToStreams An updatable cache that maps a stream ID to the stream.
*/
@NotNull
public static List<Common.Device> getUpToDateDevices(boolean isUnifiedPipelineEnabled,
@NotNull ProfilerClient client,
@Nullable Map<Common.Device, Long> deviceToStreamIds,
@Nullable Map<Long, Common.Stream> streamIdToStreams) {
List<Common.Device> devices = new LinkedList<>();
if (isUnifiedPipelineEnabled) {
// Get all streams of all types.
GetEventGroupsRequest request = GetEventGroupsRequest.newBuilder()
.setStreamId(-1) // DataStoreService.DATASTORE_RESERVED_STREAM_ID
.setKind(Event.Kind.STREAM)
.build();
GetEventGroupsResponse response = client.getTransportClient().getEventGroups(request);
for (EventGroup group : response.getGroupsList()) {
boolean isStreamDead = group.getEvents(group.getEventsCount() - 1).getIsEnded();
Common.Event connectedEvent = getLastMatchingEvent(group, e -> (e.hasStream() && e.getStream().hasStreamConnected()));
if (connectedEvent == null) {
// Ignore stream event groups that do not have the connected event.
continue;
}
Common.Stream stream = connectedEvent.getStream().getStreamConnected().getStream();
// We only want streams of type device to get process information.
if (stream.getType() == Stream.Type.DEVICE) {
if (isStreamDead) {
// TODO state changes are represented differently in the unified pipeline (with two separate events)
// remove this once we move complete away from the legacy pipeline.
stream = stream.toBuilder().setDevice(stream.getDevice().toBuilder().setState(Device.State.DISCONNECTED)).build();
}
if (deviceToStreamIds != null) {
deviceToStreamIds.putIfAbsent(stream.getDevice(), stream.getStreamId());
}
if (streamIdToStreams != null) {
streamIdToStreams.putIfAbsent(stream.getStreamId(), stream);
}
devices.add(stream.getDevice());
}
}
}
else {
GetDevicesResponse response = client.getTransportClient().getDevices(GetDevicesRequest.getDefaultInstance());
devices = response.getDeviceList();
}
return devices;
}
@NotNull
public Common.Stream getStream(long streamId) {
return myStreamIdToStreams.getOrDefault(streamId, Common.Stream.getDefaultInstance());
}
@Override
public void update(long elapsedNs) {
myEventPollingInternvalNs += elapsedNs;
if (myEventPollingInternvalNs >= TRANSPORT_POLLER_INTERVAL_NS) {
myTransportPoller.poll();
myEventPollingInternvalNs = 0;
}
myRefreshDevices += elapsedNs;
if (myRefreshDevices < TimeUnit.SECONDS.toNanos(1)) {
return;
}
myRefreshDevices = 0;
try {
Map<Common.Device, List<Common.Process>> newProcesses = new HashMap<>();
List<Common.Device> devices = getUpToDateDevices();
if (myIdeServices.getFeatureConfig().isUnifiedPipelineEnabled()) {
for (Common.Device device : devices) {
GetEventGroupsRequest processRequest = GetEventGroupsRequest.newBuilder()
.setStreamId(myDeviceToStreamIds.get(device))
.setKind(Event.Kind.PROCESS)
.build();
GetEventGroupsResponse processResponse = myClient.getTransportClient().getEventGroups(processRequest);
List<Common.Process> processList = new ArrayList<>();
int lastProcessId = myProcess == null ? 0 : myProcess.getPid();
// A group is a collection of events that happened to a single process.
for (EventGroup groupProcess : processResponse.getGroupsList()) {
boolean isProcessAlive = !groupProcess.getEvents(groupProcess.getEventsCount() - 1).getIsEnded();
Common.Event aliveEvent = getLastMatchingEvent(groupProcess, e -> (e.hasProcess() && e.getProcess().hasProcessStarted()));
if (aliveEvent == null) {
// Ignore process event groups that do not have the started event.
continue;
}
Common.Process process = aliveEvent.getProcess().getProcessStarted().getProcess();
if (isProcessAlive || process.getPid() == lastProcessId) {
if (!isProcessAlive) {
// TODO state changes are represented differently in the unified pipeline (with two separate events)
// remove this once we move complete away from the legacy pipeline.
process = process.toBuilder().setState(Common.Process.State.DEAD).build();
}
processList.add(process);
}
}
newProcesses.put(device, processList);
}
}
else {
for (Common.Device device : devices) {
GetProcessesRequest request = GetProcessesRequest.newBuilder().setDeviceId(device.getDeviceId()).build();
GetProcessesResponse processes = myClient.getTransportClient().getProcesses(request);
int lastProcessId = myProcess == null ? 0 : myProcess.getPid();
List<Common.Process> processList = processes.getProcessList()
.stream()
.filter(process -> process.getState() == Common.Process.State.ALIVE ||
process.getPid() == lastProcessId)
.collect(Collectors.toList());
newProcesses.put(device, processList);
}
}
if (!newProcesses.equals(myProcesses)) {
myProcesses = newProcesses;
setProcess(findPreferredDevice(), null);
// These need to be fired every time the process list changes so that the device/process dropdown always reflects the latest.
changed(ProfilerAspect.PROCESSES);
}
mySessionsManager.update();
// A heartbeat event may not have been sent by perfa when we first profile an app, here we keep pinging the status and
// fire the corresponding change and tracking events.
if (SessionsManager.isSessionAlive(mySelectedSession)) {
AgentData agentData = getAgentData(mySelectedSession);
// Consider the agent to be unattachable if it remains unspecified for long enough.
int agentStatusRetryCount = mySessionIdToAgentStatusRetryMap.getOrDefault(mySelectedSession.getSessionId(), 0) + 1;
if (agentData.getStatus() == AgentData.Status.UNSPECIFIED && agentStatusRetryCount >= AGENT_STATUS_MAX_RETRY_COUNT) {
agentData = AgentData.newBuilder().setStatus(AgentData.Status.UNATTACHABLE).build();
}
mySessionIdToAgentStatusRetryMap.put(mySelectedSession.getSessionId(), agentStatusRetryCount);
if (!myAgentData.equals(agentData)) {
if (myAgentData.getStatus() != AgentData.Status.ATTACHED &&
agentData.getStatus() == AgentData.Status.ATTACHED) {
getIdeServices().getFeatureTracker().trackAdvancedProfilingStarted();
}
myAgentData = agentData;
changed(ProfilerAspect.AGENT);
}
}
}
catch (StatusRuntimeException e) {
// TODO: Clean up this exception, this has the potential to capture some subtle bugs
// As an example the MemoryProfilerStateTest:testAgentStatusUpdatesObjectSeries depends on this exception being thrown
// the exception gets thrown due to startMonitor being called on a service the test didn't setup, this seems like an
// unintentional side effect of the state of the test that sets this class up properly, if we handle the exception elsewhere
// the test will fail as a different service will run and an UNIMPLEMENTED exception will be thrown.
System.err.println("Cannot find profiler service, retrying...");
}
}
/**
* Finds and returns the preferred device if there is an online device with a matching name.
* Otherwise, we attempt to maintain the currently selected device.
*/
@Nullable
private Common.Device findPreferredDevice() {
Set<Common.Device> devices = myProcesses.keySet();
Set<Common.Device> onlineDevices =
devices.stream().filter(device -> device.getState().equals(Common.Device.State.ONLINE)).collect(Collectors.toSet());
// We have a preferred device, try not to select anything else.
if (myAutoProfilingEnabled && myPreferredDeviceName != null) {
for (Common.Device device : onlineDevices) {
if (myPreferredDeviceName.equals(buildDeviceName(device))) {
return device;
}
}
}
// Next, prefer the device currently used.
if (myDevice != null) {
for (Common.Device device : devices) {
if (myDevice.getDeviceId() == device.getDeviceId()) {
return device;
}
}
}
return null;
}
public void setMonitoringStage() {
setStage(new StudioMonitorStage(this));
}
/**
* Chooses a device+process combination, and starts profiling it if not already (and stops profiling the previous one).
*
* @param device the device that will be selected. If it is null, no device and process will be selected for profiling.
* @param process the process that will be selected. Note that the process is expected to be spawned from the specified device.
* If it is null, a process will be determined automatically by heuristics.
*/
public void setProcess(@Nullable Common.Device device, @Nullable Common.Process process) {
if (device != null) {
// Device can be not null in the following scenarios:
// 1. User explicitly sets a device from the dropdown.
// 2. The update loop has found the preferred device, in which case it will stay selected until the user selects something else.
// All of these cases mean that we can unset the preferred device.
myPreferredDeviceName = null;
// If the device is unsupported (e.g. pre-Lolipop), switch to the null stage with the unsupported reason.
if (!device.getUnsupportedReason().isEmpty()) {
setStage(new NullMonitorStage(this, device.getUnsupportedReason()));
}
}
if (!Objects.equals(device, myDevice)) {
// The device has changed and we need to reset the process.
// First, end the current session on the previous device.
mySessionsManager.endCurrentSession();
myDevice = device;
myIdeServices.getFeatureTracker().trackChangeDevice(myDevice);
}
List<Common.Process> processes = myProcesses.get(myDevice);
if (process == null || processes == null || !processes.contains(process)) {
process = getPreferredProcess(processes);
}
else {
// The user wants to select a different process explicitly.
// If the user intentionally selects something else, the profiler should not switch
// back to the preferred process in any cases.
setAutoProfilingEnabled(false);
}
if (!Objects.equals(process, myProcess)) {
// First make sure to end the previous session.
mySessionsManager.endCurrentSession();
myProcess = process;
changed(ProfilerAspect.PROCESSES);
myIdeServices.getFeatureTracker().trackChangeProcess(myProcess);
// Only start a new session if the process is valid.
if (myProcess != null && myProcess.getState() == Common.Process.State.ALIVE) {
if (myIdeServices.getFeatureConfig().isUnifiedPipelineEnabled()) {
mySessionsManager.beginSession(myDeviceToStreamIds.get(myDevice), myDevice, myProcess);
}
else {
mySessionsManager.beginSession(myDevice, myProcess);
}
}
}
}
/**
* Register the listener to set proper stage when a new session is selected.
*
* @param sessionType type of the new session.
* @param listener listener to register.
*/
public void registerSessionChangeListener(Common.SessionMetaData.SessionType sessionType, Runnable listener) {
mySessionChangeListener.put(sessionType, listener);
}
private void selectedSessionChanged() {
Common.Session newSession = mySessionsManager.getSelectedSession();
// The current selected session has not changed but it has gone from live to finished, simply pause the timeline.
if (mySelectedSession.getSessionId() == newSession.getSessionId() &&
SessionsManager.isSessionAlive(mySelectedSession) && !SessionsManager.isSessionAlive(newSession)) {
mySelectedSession = newSession;
myTimeline.setIsPaused(true);
return;
}
mySelectedSession = newSession;
myAgentData = getAgentData(mySelectedSession);
if (Common.Session.getDefaultInstance().equals(newSession)) {
// No selected session - go to the null stage.
myTimeline.setIsPaused(true);
setStage(new NullMonitorStage(this));
return;
}
// Set the stage base on session type
Common.SessionMetaData.SessionType sessionType = mySessionsManager.getSelectedSessionMetaData().getType();
assert mySessionChangeListener.containsKey(sessionType);
mySessionChangeListener.get(sessionType).run();
// Profilers can query data depending on whether the agent is set. Even though we set the status above, delay until after the
// session is properly assigned before firing this aspect change.
changed(ProfilerAspect.AGENT);
}
private void profilingSessionChanged() {
Common.Session newSession = mySessionsManager.getProfilingSession();
// Stops the previous profiling session if it is active
if (!Common.Session.getDefaultInstance().equals(myProfilingSession)) {
assert SessionsManager.isSessionAlive(myProfilingSession);
// TODO: If there are multiple instances of StudioProfiers class, we should call stopProfiling() only once.
myProfilers.forEach(profiler -> profiler.stopProfiling(myProfilingSession));
}
myProfilingSession = newSession;
if (!Common.Session.getDefaultInstance().equals(myProfilingSession)
// When multiple instances of Studio are open, there may be multiple instances of StudioProfiers class. Each of them
// registers to PROFILING_SESSION aspect and this method will be called on each of the instance. We should not call
// startProfiling() if the device isn't the one where the new session is from. Ideally, we should call startProfiling()
// only once.
&& myDevice != null && myDevice.getDeviceId() == myProfilingSession.getStreamId()) {
assert SessionsManager.isSessionAlive(myProfilingSession);
myProfilers.forEach(profiler -> profiler.startProfiling(myProfilingSession));
myIdeServices.getFeatureTracker().trackProfilingStarted();
if (getAgentData(myProfilingSession).getStatus() == AgentData.Status.ATTACHED) {
getIdeServices().getFeatureTracker().trackAdvancedProfilingStarted();
}
}
}
private boolean startupMemoryProfilingStarted() {
List<Memory.MemoryNativeTrackingData> samples =
MemoryProfiler.getNativeHeapStatusForSession(myClient, mySelectedSession, new Range(Long.MIN_VALUE, Long.MAX_VALUE));
if (samples.isEmpty()) {
return false;
}
Memory.MemoryNativeTrackingData last = samples.get(samples.size() - 1);
// If we are ongoing, and we started before the process then we have a startup session.
return last.getStatus() == Memory.MemoryNativeTrackingData.Status.SUCCESS &&
last.getStartTime() <= mySelectedSession.getStartTimestamp();
}
/**
* Checks whether startup CPU Profiling started for the selected session by making RPC call to perfd.
*/
private boolean startupCpuProfilingStarted() {
if (!getIdeServices().getFeatureConfig().isStartupCpuProfilingEnabled()) {
return false;
}
List<Cpu.CpuTraceInfo> traceInfoList =
CpuProfiler.getTraceInfoFromSession(myClient, mySelectedSession, myIdeServices.getFeatureConfig().isUnifiedPipelineEnabled());
if (!traceInfoList.isEmpty()) {
Cpu.CpuTraceInfo lastTraceInfo = traceInfoList.get(traceInfoList.size() - 1);
if (lastTraceInfo.getConfiguration().getInitiationType() == Cpu.TraceInitiationType.INITIATED_BY_STARTUP) {
return true;
}
}
return false;
}
/**
* Chooses a process among all potential candidates starting from the project's app process, and then the one previously used. If no
* candidate is available and no preferred process has been configured, select the first available process.
*/
@Nullable
private Common.Process getPreferredProcess(List<Common.Process> processes) {
if (processes == null || processes.isEmpty()) {
return null;
}
// Prefer the project's app if available.
if (myAutoProfilingEnabled && myPreferredProcessName != null) {
for (Common.Process process : processes) {
if (process.getName().equals(myPreferredProcessName) && process.getState() == Common.Process.State.ALIVE &&
(myPreferredProcessFilter == null || myPreferredProcessFilter.test(process))) {
myIdeServices.getFeatureTracker().trackAutoProfilingSucceeded();
myAutoProfilingEnabled = false;
return process;
}
}
}
// Next, prefer the one previously used, either selected by user or automatically (even if the process has switched states)
if (myProcess != null) {
for (Common.Process process : processes) {
if (isSameProcess(myProcess, process) &&
// The profilers only keep the same process under the following scenarios:
// 1. The process's states have not changed
// 2. The process went from alive to dead. (e.g. the process is killed, the device is disconnected)
// If a identical process goes from dead to alive, it is most likely due to a device being reconnected, or an emulator snapshot
// being booted with a previously running process. We don't want to select and profiler that process in those cases.
(myProcess.getState() == process.getState() ||
(myProcess.getState() == Common.Process.State.ALIVE && process.getState() == Common.Process.State.DEAD))) {
return process;
}
}
}
return null;
}
@NotNull
private AgentData getAgentData(@NotNull Common.Session session) {
AgentData agentData = AgentData.getDefaultInstance();
if (Common.Session.getDefaultInstance().equals(session)) {
return agentData;
}
if (!myIdeServices.getFeatureConfig().isUnifiedPipelineEnabled()) {
// In legacy pipeline we don't have streams so we set device ID to session's stream ID.
AgentStatusRequest statusRequest =
AgentStatusRequest.newBuilder().setPid(session.getPid()).setDeviceId(session.getStreamId()).build();
return myClient.getTransportClient().getAgentStatus(statusRequest);
}
// Get agent data for requested session.
GetEventGroupsRequest request = GetEventGroupsRequest.newBuilder()
.setKind(Event.Kind.AGENT)
.setStreamId(session.getStreamId())
.setPid(session.getPid())
.build();
GetEventGroupsResponse response = myClient.getTransportClient().getEventGroups(request);
for (EventGroup group : response.getGroupsList()) {
agentData = group.getEvents(group.getEventsCount() - 1).getAgentData();
}
return agentData;
}
/**
* @return true if the processes are the same, false otherwise. The reason Objects.equals is not used here is because the states could
* have changed between process1 and process2, but they should be considered the same as long as we have matching pids and names, so we
* don't reset the stage.
*/
private static boolean isSameProcess(@Nullable Common.Process process1, @Nullable Common.Process process2) {
return process1 != null &&
process2 != null &&
process1.getPid() == process2.getPid() && process1.getName().equals(process2.getName()) &&
// pid and name are not enough, because emulator snapshot could try to restore previous pid of the app.
process1.getStartTimestampNs() == process2.getStartTimestampNs();
}
public List<Common.Process> getProcesses() {
List<Common.Process> processes = myProcesses.get(myDevice);
return processes == null ? ImmutableList.of() : processes;
}
@NotNull
public Stage getStage() {
return myStage;
}
@NotNull
public ProfilerClient getClient() {
return myClient;
}
@NotNull
public SessionsManager getSessionsManager() {
return mySessionsManager;
}
/**
* @return the active session, otherwise {@link Common.Session#getDefaultInstance()} if no session is currently being profiled.
*/
@NotNull
public Common.Session getSession() {
return mySelectedSession;
}
/**
* Return the selected app's package name if present, otherwise returns empty string.
* <p>
* <p>TODO (78597376): Clean up the method to make it reusable.</p>
*/
@NotNull
public String getSelectedAppName() {
String name = "";
if (!getSession().equals(Common.Session.getDefaultInstance())) {
name = mySessionsManager.getSelectedSessionMetaData().getSessionName();
}
else if (myProcess != null) {
name = myProcess.getName();
}
// The selected profiling name could be android.com.test (Google Pixel), remove the phone name.
String[] nameSplit = name.split(" \\(", 2);
return nameSplit.length > 0 ? nameSplit[0] : "";
}
public void setStage(@NotNull Stage stage) {
myStage.exit();
getTimeline().getSelectionRange().clear();
myStage = stage;
myStage.getStudioProfilers().getUpdater().reset();
myStage.enter();
this.changed(ProfilerAspect.STAGE);
}
@NotNull
public StreamingTimeline getTimeline() {
return myTimeline;
}
@Nullable
public Common.Device getDevice() {
return myDevice;
}
@Nullable
public Common.Process getProcess() {
return myProcess;
}
public boolean isAgentAttached() {
return myAgentData.getStatus() == AgentData.Status.ATTACHED;
}
@NotNull
public AgentData getAgentData() {
return myAgentData;
}
public List<StudioProfiler> getProfilers() {
return myProfilers;
}
public ProfilerMode getMode() {
return myStage.getProfilerMode();
}
public void modeChanged() {
changed(ProfilerAspect.MODE);
}
@NotNull
public IdeProfilerServices getIdeServices() {
return myIdeServices;
}
public Updater getUpdater() {
return myUpdater;
}
public AxisComponentModel getViewAxis() {
return myViewAxis;
}
/**
* Return the list of stages that target a specific profiler, which a user might want to jump
* between. This should exclude things like the top-level profiler stage, null stage, etc.
*/
public List<Class<? extends Stage>> getDirectStages() {
ImmutableList.Builder<Class<? extends Stage>> listBuilder = ImmutableList.builder();
listBuilder.add(CpuProfilerStage.class);
listBuilder.add(MemoryProfilerStage.class);
listBuilder.add(NetworkProfilerStage.class);
// Show the energy stage in the list only when the session has JVMTI enabled or the device is above O.
boolean hasSession = mySelectedSession.getSessionId() != 0;
boolean isEnergyStageEnabled = hasSession ? mySessionsManager.getSelectedSessionMetaData().getJvmtiEnabled()
: myDevice != null && myDevice.getFeatureLevel() >= AndroidVersion.VersionCodes.O;
if (getIdeServices().getFeatureConfig().isEnergyProfilerEnabled() && isEnergyStageEnabled) {
listBuilder.add(EnergyProfilerStage.class);
}
// Show the custom event stage in the dropdown list of profiling options when enabled
if (getIdeServices().getFeatureConfig().isCustomEventVisualizationEnabled()) {
listBuilder.add(CustomEventProfilerStage.class);
}
return listBuilder.build();
}
@NotNull
public Class<? extends Stage> getStageClass() {
return myStage.getClass();
}
// TODO: Unify with how monitors expand.
public void setNewStage(Class<? extends Stage> clazz) {
try {
Constructor<? extends Stage> constructor = clazz.getConstructor(StudioProfilers.class);
Stage stage = constructor.newInstance(this);
setStage(stage);
}
catch (NoSuchMethodException | IllegalAccessException | InstantiationException | InvocationTargetException e) {
// will not happen
}
}
@NotNull
public static String buildSessionName(@NotNull Common.Device device, @NotNull Common.Process process) {
return String.format("%s (%s)", process.getName(), buildDeviceName(device));
}
/**
* Enable or disable Memory Profiler live allocation tracking to improve app performance.
*
* @param enabled True to enable live allocation, false to disable.
*/
public void setMemoryLiveAllocationEnabled(boolean enabled) {
if (getIdeServices().getFeatureConfig().isLiveAllocationsSamplingEnabled() &&
getDevice() != null && getDevice().getFeatureLevel() >= AndroidVersion.VersionCodes.O &&
isAgentAttached()) {
int savedSamplingRate = getIdeServices().getPersistentProfilerPreferences().getInt(
MemoryProfilerStage.LIVE_ALLOCATION_SAMPLING_PREF, MemoryProfilerStage.DEFAULT_LIVE_ALLOCATION_SAMPLING_MODE.getValue());
int samplingRateOff = MemoryProfilerStage.LiveAllocationSamplingMode.NONE.getValue();
// If live allocation is already disabled, don't send any request.
if (savedSamplingRate != samplingRateOff) {
MemoryAllocSamplingData samplingRate = MemoryAllocSamplingData.newBuilder()
.setSamplingNumInterval(enabled ? savedSamplingRate : samplingRateOff)
.build();
if (getIdeServices().getFeatureConfig().isUnifiedPipelineEnabled()) {
// TODO(b/150503095)
Transport.ExecuteResponse response = getClient().getTransportClient().execute(
Transport.ExecuteRequest.newBuilder().setCommand(Commands.Command.newBuilder()
.setStreamId(getSession().getStreamId())
.setPid(getSession().getPid())
.setType(Commands.Command.CommandType.MEMORY_ALLOC_SAMPLING)
.setMemoryAllocSampling(samplingRate))
.build());
}
else {
// TODO(b/150503095)
SetAllocationSamplingRateResponse response =
getClient().getMemoryClient().setAllocationSamplingRate(SetAllocationSamplingRateRequest.newBuilder()
.setSession(getSession())
.setSamplingRate(samplingRate)
.build());
}
}
}
}
/**
* Mirrors AndroidProfilerToolWindow#getDeviceDisplayName but works with a {@link Common.Device}.
*/
@NotNull
public static String buildDeviceName(@NotNull Common.Device device) {
StringBuilder deviceNameBuilder = new StringBuilder();
String manufacturer = device.getManufacturer();
String model = device.getModel();
String serial = device.getSerial();
String suffix = String.format("-%s", serial);
if (model.endsWith(suffix)) {
model = model.substring(0, model.length() - suffix.length());
}
if (!StringUtil.isEmpty(manufacturer)) {
deviceNameBuilder.append(manufacturer);
deviceNameBuilder.append(" ");
}
deviceNameBuilder.append(model);
return deviceNameBuilder.toString();
}
/**
* Helper method to return the last even in an EventGroup that matches the input condition.
*/
@Nullable
private static Common.Event getLastMatchingEvent(@NotNull EventGroup group, @NotNull Predicate<Event> predicate) {
Common.Event matched = null;
for (Event event : group.getEventsList()) {
if (predicate.test(event)) {
matched = event;
}
}
return matched;
}
/**
* Return the start and end timestamps for the artificial session created for the given imported file.
*
* For each imported file, an artificial session is created. The start timestamp will be used as the
* session's ID. Therefore, this function returns a nearly unique hash as the start timestamp for each file.
*
* The range constructed by the two timestamps (after casting to microseconds) should still include the start
* timestamp in nanoseconds because our code base shares much of live session's logic to handle imported
* files. The two timestamps will construct a Range object. As the Range class uses microseconds, the
* range may become a point when nanoseconds are casted into microseconds if it's too short, and the
* nanosecond-timestamp may fall out of it. Therefore, this method makes the range one microsecond long
* to avoid a point-range after casting.
*
* This method avoid negative timestamps which may be counter-intuitive.
*/
public static Pair<Long, Long> computeImportedFileStartEndTimestampsNs(File file) {
long hash = Hashing.sha256().hashString(file.getAbsolutePath(), StandardCharsets.UTF_8).asLong();
// Avoid Long.MAX_VALUE which as the end timestamp means ongoing in transport pipeline.
if (hash == Long.MAX_VALUE || hash == Long.MIN_VALUE || hash == Long.MIN_VALUE + 1) {
hash /= 2;
}
// Avoid negative values.
if (hash < 0) {
hash = -hash;
}
long rangeNs = TimeUnit.MICROSECONDS.toNanos(1);
// Make sure (hash + rangeNs) as the end timestamp doesn't overflow.
if (hash >= Long.MAX_VALUE - rangeNs) {
hash -= rangeNs;
}
return new Pair<>(hash, hash + rangeNs);
}
}
|
923f51364f199257da77b49a8bb6a18c84655b3b
| 3,156 |
java
|
Java
|
src/test/java/guitests/guihandles/PersonCardHandle.java
|
ivyyangyq/main
|
853e943557e682ea6a8d2f849a666166c632fd48
|
[
"MIT"
] | 4 |
2019-02-13T04:08:32.000Z
|
2019-02-19T15:56:14.000Z
|
src/test/java/guitests/guihandles/PersonCardHandle.java
|
ivyyangyq/main
|
853e943557e682ea6a8d2f849a666166c632fd48
|
[
"MIT"
] | 106 |
2019-02-19T21:49:35.000Z
|
2019-04-14T10:41:54.000Z
|
src/test/java/guitests/guihandles/PersonCardHandle.java
|
ivyyangyq/main
|
853e943557e682ea6a8d2f849a666166c632fd48
|
[
"MIT"
] | 9 |
2019-02-07T14:59:16.000Z
|
2019-04-02T13:14:55.000Z
| 32.536082 | 112 | 0.635615 | 1,001,111 |
package guitests.guihandles;
import java.util.List;
import java.util.stream.Collectors;
import com.google.common.collect.ImmutableMultiset;
import javafx.scene.Node;
import javafx.scene.control.Label;
import javafx.scene.layout.Region;
import seedu.address.model.person.Person;
/**
* Provides a handle to a person card in the person list panel.
*/
public class PersonCardHandle extends NodeHandle<Node> {
private static final String ID_FIELD_ID = "#id";
private static final String NAME_FIELD_ID = "#name";
private static final String MATRICNUMBER_FIELD_ID = "#matricNumber";
private static final String YEAROFSTUDY_FIELD_ID = "#yearOfStudy";
private static final String MAJOR_FIELD_ID = "#major";
private static final String TAGS_FIELD_ID = "#tags";
private final Label idLabel;
private final Label nameLabel;
private final Label matricNumberLabel;
private final Label yearOfStudyLabel;
private final Label majorLabel;
private final List<Label> tagLabels;
public PersonCardHandle(Node cardNode) {
super(cardNode);
idLabel = getChildNode(ID_FIELD_ID);
nameLabel = getChildNode(NAME_FIELD_ID);
matricNumberLabel = getChildNode(MATRICNUMBER_FIELD_ID);
yearOfStudyLabel = getChildNode(YEAROFSTUDY_FIELD_ID);
majorLabel = getChildNode(MAJOR_FIELD_ID);
Region tagsContainer = getChildNode(TAGS_FIELD_ID);
tagLabels = tagsContainer
.getChildrenUnmodifiable()
.stream()
.map(Label.class::cast)
.collect(Collectors.toList());
}
public String getId() {
return idLabel.getText();
}
public String getName() {
return nameLabel.getText();
}
public String getMatricNumber() {
return matricNumberLabel.getText();
}
public String getYearOfStudy() {
return "Year " + yearOfStudyLabel.getText();
}
public String getMajor() {
return majorLabel.getText();
}
public List<String> getTags() {
return tagLabels
.stream()
.map(Label::getText)
.collect(Collectors.toList());
}
public List<String> getTagStyleClasses(String tag) {
return tagLabels
.stream()
.filter(label -> label.getText().equals(tag))
.map(Label::getStyleClass)
.findFirst()
.orElseThrow(() -> new IllegalArgumentException("No such tag."));
}
/**
* Returns true if this handle contains {@code person}.
*/
public boolean equals(Person person) {
return getName().equals(person.getName().fullName)
&& getMatricNumber().equals(person.getMatricNumber().value)
//&& getYearOfStudy().equals("Year " + person.getYearOfStudy().value)
&& getMajor().equals(person.getMajor().value)
&& ImmutableMultiset.copyOf(getTags()).equals(ImmutableMultiset.copyOf(person.getTags().stream()
.map(tag -> tag.tagName)
.collect(Collectors.toList())));
}
}
|
923f513bf1c0b0fbce680b870fca30f40155dee4
| 703 |
java
|
Java
|
statistics-service/src/main/java/com/piggymetrics/statistics/service/StatisticsService.java
|
Mintelgen/piggymetrics
|
5ad2580990c5e5074f9f38eca662a59926a1a0f0
|
[
"MIT"
] | 7,377 |
2019-01-21T02:41:59.000Z
|
2022-03-31T06:46:11.000Z
|
statistics-service/src/main/java/com/piggymetrics/statistics/service/StatisticsService.java
|
Mintelgen/piggymetrics
|
5ad2580990c5e5074f9f38eca662a59926a1a0f0
|
[
"MIT"
] | 40 |
2016-02-14T00:44:32.000Z
|
2018-09-24T09:18:55.000Z
|
statistics-service/src/main/java/com/piggymetrics/statistics/service/StatisticsService.java
|
Mintelgen/piggymetrics
|
5ad2580990c5e5074f9f38eca662a59926a1a0f0
|
[
"MIT"
] | 3,127 |
2019-01-21T06:53:36.000Z
|
2022-03-31T14:34:14.000Z
| 22.677419 | 67 | 0.736842 | 1,001,112 |
package com.piggymetrics.statistics.service;
import com.piggymetrics.statistics.domain.Account;
import com.piggymetrics.statistics.domain.timeseries.DataPoint;
import java.util.List;
public interface StatisticsService {
/**
* Finds account by given name
*
* @param accountName
* @return found account
*/
List<DataPoint> findByAccountName(String accountName);
/**
* Converts given {@link Account} object to {@link DataPoint} with
* a set of significant statistic metrics.
*
* Compound {@link DataPoint#id} forces to rewrite the object
* for each account within a day.
*
* @param accountName
* @param account
*/
DataPoint save(String accountName, Account account);
}
|
923f51eef6f3508b22325af45a1d51894e133c2d
| 607 |
java
|
Java
|
extensions/opentelemetry/opentelemetry/runtime/src/main/java/io/quarkus/opentelemetry/runtime/graal/RandomSupplier.java
|
tiago-marques/quarkus
|
7442da1ea202ffe51103ad52b2fb522d99623ee1
|
[
"Apache-2.0"
] | 1 |
2022-02-23T03:51:32.000Z
|
2022-02-23T03:51:32.000Z
|
extensions/opentelemetry/opentelemetry/runtime/src/main/java/io/quarkus/opentelemetry/runtime/graal/RandomSupplier.java
|
tiago-marques/quarkus
|
7442da1ea202ffe51103ad52b2fb522d99623ee1
|
[
"Apache-2.0"
] | 19 |
2021-09-24T00:36:50.000Z
|
2022-03-30T19:22:33.000Z
|
extensions/opentelemetry/opentelemetry/runtime/src/main/java/io/quarkus/opentelemetry/runtime/graal/RandomSupplier.java
|
tiago-marques/quarkus
|
7442da1ea202ffe51103ad52b2fb522d99623ee1
|
[
"Apache-2.0"
] | 1 |
2022-01-02T20:56:26.000Z
|
2022-01-02T20:56:26.000Z
| 31.947368 | 125 | 0.785832 | 1,001,113 |
package io.quarkus.opentelemetry.runtime.graal;
import java.util.Random;
import java.util.concurrent.ThreadLocalRandom;
import java.util.function.Supplier;
import com.oracle.svm.core.annotate.Substitute;
import com.oracle.svm.core.annotate.TargetClass;
@TargetClass(className = "io.opentelemetry.sdk.internal.RandomSupplier")
final class RandomSupplier {
@Substitute
public static Supplier<Random> platformDefault() {
// removed delegation to AndroidFriendlyRandomHolder (which has a Random constant), making it effectively unreachable
return ThreadLocalRandom::current;
}
}
|
923f53cca9fcd2c166be7d3a06556ee170be286d
| 2,927 |
java
|
Java
|
cursospringrestapi/src/main/java/curso/api/rest/ControleExcecoes.java
|
ramirovictor/API-Spring-Boot-REST-RESTful-JPA-Microservi-os
|
de27750fc354d5068accf9aae7d2f252b1a5339d
|
[
"MIT"
] | null | null | null |
cursospringrestapi/src/main/java/curso/api/rest/ControleExcecoes.java
|
ramirovictor/API-Spring-Boot-REST-RESTful-JPA-Microservi-os
|
de27750fc354d5068accf9aae7d2f252b1a5339d
|
[
"MIT"
] | 1 |
2021-05-12T11:49:09.000Z
|
2021-05-12T11:49:09.000Z
|
cursospringrestapi/src/main/java/curso/api/rest/ControleExcecoes.java
|
ramirovictor/API-Spring-Boot-REST-RESTful-JPA-Microservi-os
|
de27750fc354d5068accf9aae7d2f252b1a5339d
|
[
"MIT"
] | null | null | null | 35.695122 | 118 | 0.755039 | 1,001,114 |
package curso.api.rest;
import java.sql.SQLException;
import java.util.List;
import org.hibernate.exception.ConstraintViolationException;
import org.postgresql.util.PSQLException;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;
@RestControllerAdvice
@ControllerAdvice
public class ControleExcecoes extends ResponseEntityExceptionHandler {
@ExceptionHandler({Exception.class, RuntimeException.class, Throwable.class})
@Override
protected ResponseEntity<Object> handleExceptionInternal(Exception ex, Object body, HttpHeaders headers,
HttpStatus status, WebRequest request) {
String msg = "";
if(ex instanceof MethodArgumentNotValidException) {
List<ObjectError> list = ((MethodArgumentNotValidException) ex).getBindingResult().getAllErrors();
for (ObjectError objectError : list) {
msg += objectError.getDefaultMessage() + "\n";
}
}else {
msg = ex.getMessage();
}
ObjetoErro objetoErro = new ObjetoErro();
objetoErro.setError(msg);
objetoErro.setCode(status.value() + "==> "+ status.getReasonPhrase());
return new ResponseEntity<>(objetoErro, headers, status);
}
//erros a nivel de banco
@ExceptionHandler({DataIntegrityViolationException.class, ConstraintViolationException.class,
PSQLException.class, SQLException.class})
protected ResponseEntity<Object> handleExceptionDataIntegry(Exception ex){
String msg = "";
if(ex instanceof DataIntegrityViolationException) {
msg = ((DataIntegrityViolationException) ex).getCause().getCause().getMessage();
}
else if(ex instanceof ConstraintViolationException) {
msg = ((ConstraintViolationException) ex).getCause().getCause().getMessage();
}
else if(ex instanceof PSQLException) {
msg = ((PSQLException) ex).getCause().getCause().getMessage();
}
else if(ex instanceof SQLException) {
msg = ((SQLException) ex).getCause().getCause().getMessage();
}
else {
msg = ex.getMessage();
}
ObjetoErro objetoErro = new ObjetoErro();
objetoErro.setError(msg);
objetoErro.setCode(HttpStatus.INTERNAL_SERVER_ERROR + " ==> "+ HttpStatus.INTERNAL_SERVER_ERROR.getReasonPhrase());
return new ResponseEntity<>(objetoErro, HttpStatus.INTERNAL_SERVER_ERROR);
}
}
|
923f53dbf9b9a11964c389008490abe52eb293be
| 350 |
java
|
Java
|
test-cloud-common/src/main/java/test/cloud/service/stream/OutputChannel.java
|
ZhongCW/test-cloud
|
12c7119e3d4d2502001377382bec218d477626b4
|
[
"Apache-2.0"
] | null | null | null |
test-cloud-common/src/main/java/test/cloud/service/stream/OutputChannel.java
|
ZhongCW/test-cloud
|
12c7119e3d4d2502001377382bec218d477626b4
|
[
"Apache-2.0"
] | null | null | null |
test-cloud-common/src/main/java/test/cloud/service/stream/OutputChannel.java
|
ZhongCW/test-cloud
|
12c7119e3d4d2502001377382bec218d477626b4
|
[
"Apache-2.0"
] | null | null | null | 20.588235 | 58 | 0.771429 | 1,001,115 |
package test.cloud.service.stream;
import org.springframework.cloud.stream.annotation.Output;
import org.springframework.messaging.MessageChannel;
/**
* @author ZCW
* @createTime 2018/7/12
* @lastUpdateTime 2018/7/12 ZCW
*/
public interface OutputChannel extends Channel{
@Output(USER_REGISTER)
MessageChannel userRegisterOutput();
}
|
923f53fabbf99ee55e71af5abb5ca5b71d19fce7
| 1,108 |
java
|
Java
|
appinventor/components/src/com/google/appinventor/components/annotations/UsesQueries.java
|
daki7711/appinventor-sources
|
85ff32316820aedc0ad21ac0c9de4799e5039fd2
|
[
"Apache-2.0"
] | 2 |
2017-09-06T13:04:10.000Z
|
2018-08-01T13:17:03.000Z
|
appinventor/components/src/com/google/appinventor/components/annotations/UsesQueries.java
|
Tomislav-Tomsic/appinventor-sources
|
c73ff916a1b3c763f71c9f944f8d77845a11f9a6
|
[
"Apache-2.0"
] | 3 |
2015-07-25T23:04:22.000Z
|
2016-03-26T22:11:02.000Z
|
appinventor/components/src/com/google/appinventor/components/annotations/UsesQueries.java
|
Tomislav-Tomsic/appinventor-sources
|
c73ff916a1b3c763f71c9f944f8d77845a11f9a6
|
[
"Apache-2.0"
] | 3 |
2015-08-25T14:08:36.000Z
|
2017-09-15T17:21:41.000Z
| 30.777778 | 89 | 0.716606 | 1,001,116 |
// -*- mode: java; c-basic-offset: 2; -*-
// Copyright 2021 MIT, All rights reserved
// Released under the Apache License, Version 2.0
// http://www.apache.org/licenses/LICENSE-2.0
package com.google.appinventor.components.annotations;
import com.google.appinventor.components.annotations.androidmanifest.IntentFilterElement;
import com.google.appinventor.components.annotations.androidmanifest.ProviderElement;
/**
* Annotation to describe a <queries> entry required by Android SDK 30.
*/
public @interface UsesQueries {
/**
* An array of intents that will be included in the <queries> element.
*
* @return the array of intents of interest
*/
IntentFilterElement[] intents() default {};
/**
* A package name that will be included in the <queries> element.
*
* @return the array containing package names of interest
*/
String[] packageNames() default {};
/**
* A provider element that will be included in the <queries>
*
* @return the array containing provider elements of interest
*/
ProviderElement[] providers() default {};
}
|
923f54bd3546437b75c66463c05982dfb0493503
| 143,622 |
java
|
Java
|
server/src/test/java/io/crate/analyze/SelectStatementAnalyzerTest.java
|
Wiewiogr/crate
|
5651d8d4f6d149c496e329751af3e1fd28f8a5a8
|
[
"Apache-2.0"
] | 3,066 |
2015-01-01T05:44:20.000Z
|
2022-03-31T19:33:32.000Z
|
server/src/test/java/io/crate/analyze/SelectStatementAnalyzerTest.java
|
Wiewiogr/crate
|
5651d8d4f6d149c496e329751af3e1fd28f8a5a8
|
[
"Apache-2.0"
] | 7,255 |
2015-01-02T08:25:25.000Z
|
2022-03-31T21:05:43.000Z
|
server/src/test/java/io/crate/analyze/SelectStatementAnalyzerTest.java
|
Wiewiogr/crate
|
5651d8d4f6d149c496e329751af3e1fd28f8a5a8
|
[
"Apache-2.0"
] | 563 |
2015-01-06T19:07:27.000Z
|
2022-03-25T03:03:36.000Z
| 46.874021 | 150 | 0.653939 | 1,001,117 |
/*
* Licensed to Crate.io GmbH ("Crate") under one or more contributor
* license agreements. See the NOTICE file distributed with this work for
* additional information regarding copyright ownership. Crate licenses
* this file to you under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. You may
* obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*
* However, if you have executed another commercial license agreement
* with Crate these terms will supersede the license and you may use the
* software solely pursuant to the terms of the relevant commercial agreement.
*/
package io.crate.analyze;
import io.crate.analyze.relations.AnalyzedRelation;
import io.crate.analyze.relations.DocTableRelation;
import io.crate.analyze.relations.TableFunctionRelation;
import io.crate.analyze.relations.TableRelation;
import io.crate.common.collections.Lists2;
import io.crate.exceptions.AmbiguousColumnException;
import io.crate.exceptions.ColumnUnknownException;
import io.crate.exceptions.ConversionException;
import io.crate.exceptions.RelationUnknown;
import io.crate.exceptions.UnsupportedFeatureException;
import io.crate.execution.engine.aggregation.impl.average.AverageAggregation;
import io.crate.expression.eval.EvaluatingNormalizer;
import io.crate.expression.operator.EqOperator;
import io.crate.expression.operator.LikeOperators;
import io.crate.expression.operator.LteOperator;
import io.crate.expression.operator.OrOperator;
import io.crate.expression.operator.RegexpMatchOperator;
import io.crate.expression.operator.any.AnyEqOperator;
import io.crate.expression.predicate.IsNullPredicate;
import io.crate.expression.predicate.NotPredicate;
import io.crate.expression.scalar.SubscriptFunction;
import io.crate.expression.scalar.arithmetic.ArithmeticFunctions;
import io.crate.expression.scalar.cast.ExplicitCastFunction;
import io.crate.expression.scalar.cast.TryCastFunction;
import io.crate.expression.scalar.geo.DistanceFunction;
import io.crate.expression.symbol.AliasSymbol;
import io.crate.expression.symbol.Function;
import io.crate.expression.symbol.Literal;
import io.crate.expression.symbol.MatchPredicate;
import io.crate.expression.symbol.ParameterSymbol;
import io.crate.expression.symbol.SelectSymbol;
import io.crate.expression.symbol.Symbol;
import io.crate.expression.symbol.SymbolType;
import io.crate.expression.symbol.Symbols;
import io.crate.metadata.CoordinatorTxnCtx;
import io.crate.metadata.FunctionType;
import io.crate.metadata.PartitionName;
import io.crate.metadata.RelationName;
import io.crate.metadata.RowGranularity;
import io.crate.metadata.doc.DocTableInfo;
import io.crate.metadata.sys.SysNodesTableInfo;
import io.crate.sql.parser.ParsingException;
import io.crate.sql.tree.BitString;
import io.crate.test.integration.CrateDummyClusterServiceUnitTest;
import io.crate.testing.Asserts;
import io.crate.testing.SQLExecutor;
import io.crate.testing.SymbolMatchers;
import io.crate.testing.T3;
import io.crate.testing.TestingHelpers;
import io.crate.types.ArrayType;
import io.crate.types.DataType;
import io.crate.types.DataTypes;
import io.crate.types.TimeTZ;
import org.elasticsearch.Version;
import org.elasticsearch.common.io.stream.BytesStreamOutput;
import org.elasticsearch.common.io.stream.StreamInput;
import org.hamcrest.Matchers;
import org.hamcrest.core.IsInstanceOf;
import org.junit.Test;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import static io.crate.testing.Asserts.assertThrowsMatches;
import static io.crate.testing.RelationMatchers.isDocTable;
import static io.crate.testing.SymbolMatchers.isAlias;
import static io.crate.testing.SymbolMatchers.isField;
import static io.crate.testing.SymbolMatchers.isFunction;
import static io.crate.testing.SymbolMatchers.isLiteral;
import static io.crate.testing.SymbolMatchers.isReference;
import static io.crate.testing.SymbolMatchers.isVoidReference;
import static io.crate.testing.TestingHelpers.isSQL;
import static org.hamcrest.Matchers.allOf;
import static org.hamcrest.Matchers.anyOf;
import static org.hamcrest.Matchers.contains;
import static org.hamcrest.Matchers.containsInAnyOrder;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasEntry;
import static org.hamcrest.Matchers.hasItem;
import static org.hamcrest.Matchers.instanceOf;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.not;
import static org.hamcrest.Matchers.notNullValue;
import static org.hamcrest.Matchers.nullValue;
@SuppressWarnings("ConstantConditions")
public class SelectStatementAnalyzerTest extends CrateDummyClusterServiceUnitTest {
@Test
public void testIsNullQuery() {
var executor = SQLExecutor.builder(clusterService).build();
QueriedSelectRelation relation = executor.analyze("select * from sys.nodes where id is not null");
Function query = (Function) relation.where();
assertThat(query.name(), is(NotPredicate.NAME));
assertThat(query.arguments().get(0), instanceOf(Function.class));
Function isNull = (Function) query.arguments().get(0);
assertThat(isNull.name(), is(IsNullPredicate.NAME));
}
@Test
public void testQueryUsesSearchPath() throws IOException {
SQLExecutor executor = SQLExecutor.builder(clusterService)
.setSearchPath("first", "second", "third")
.addTable("create table \"first\".t (id int)")
.addTable("create table third.t1 (id int)")
.build();
QueriedSelectRelation queriedTable = executor.analyze("select * from t");
assertThat(queriedTable.from(), contains(isDocTable(new RelationName("first", "t"))));
queriedTable = executor.analyze("select * from t1");
assertThat(queriedTable.from(), contains(isDocTable(new RelationName("third", "t1"))));
}
@Test
public void testOrderedSelect() throws Exception {
var executor = SQLExecutor.builder(clusterService).build();
QueriedSelectRelation table = executor.analyze("select load['1'] from sys.nodes order by load['5'] desc");
assertThat(table.limit(), nullValue());
assertThat(table.groupBy().isEmpty(), is(true));
assertThat(table.orderBy(), notNullValue());
assertThat(table.outputs().size(), is(1));
assertThat(table.orderBy().orderBySymbols().size(), is(1));
assertThat(table.orderBy().reverseFlags().length, is(1));
assertThat(table.orderBy().orderBySymbols().get(0), isReference("load['5']"));
}
@Test
public void testNegativeLiteral() throws Exception {
var executor = SQLExecutor.builder(clusterService).build();
QueriedSelectRelation relation = executor.analyze("select * from sys.nodes where port['http'] = -400");
Function whereClause = (Function) relation.where();
Symbol symbol = whereClause.arguments().get(1);
assertThat(((Literal<?>) symbol).value(), is(-400));
}
@Test
public void testSimpleSelect() throws Exception {
var executor = SQLExecutor.builder(clusterService).build();
QueriedSelectRelation relation = executor.analyze("select load['5'] from sys.nodes limit 2");
assertThat(relation.limit(), is(Literal.of(2L)));
assertThat(relation.groupBy().isEmpty(), is(true));
assertThat(relation.outputs().size(), is(1));
assertThat(relation.outputs().get(0), isReference("load['5']"));
}
@Test
public void testAggregationSelect() throws Exception {
var executor = SQLExecutor.builder(clusterService).build();
QueriedSelectRelation relation = executor.analyze("select avg(load['5']) from sys.nodes");
assertThat(relation.groupBy().isEmpty(), is(true));
assertThat(relation.outputs().size(), is(1));
Function col1 = (Function) relation.outputs().get(0);
assertThat(col1.signature().getKind(), is(FunctionType.AGGREGATE));
assertThat(col1.name(), is(AverageAggregation.NAME));
}
private List<String> outputNames(AnalyzedRelation relation) {
return Lists2.map(relation.outputs(), x -> Symbols.pathFromSymbol(x).sqlFqn());
}
@Test
public void testAllColumnCluster() throws Exception {
var executor = SQLExecutor.builder(clusterService).build();
AnalyzedRelation relation = executor.analyze("select * from sys.cluster");
assertThat(relation.outputs().size(), is(5));
assertThat(outputNames(relation), containsInAnyOrder("id", "license", "master_node", "name", "settings"));
assertThat(relation.outputs().size(), is(5));
}
@Test
public void testAllColumnNodes() throws Exception {
var executor = SQLExecutor.builder(clusterService).build();
AnalyzedRelation relation = executor.analyze("select id, * from sys.nodes");
List<String> outputNames = outputNames(relation);
assertThat(outputNames, contains(
"id",
"cluster_state_version",
"connections",
"fs",
"heap",
"hostname",
"id",
"load",
"mem",
"name",
"network",
"os",
"os_info",
"port",
"process",
"rest_url",
"thread_pools",
"version"
));
assertThat(relation.outputs().size(), is(outputNames.size()));
}
@Test
public void testWhereSelect() throws Exception {
var executor = SQLExecutor.builder(clusterService).build();
QueriedSelectRelation relation = executor.analyze(
"select load from sys.nodes where load['1'] = 1.2 or 1 >= load['5']");
assertThat(relation.groupBy().isEmpty(), is(true));
Function whereClause = (Function) relation.where();
assertThat(whereClause.name(), is(OrOperator.NAME));
assertThat(whereClause.signature().getKind() == FunctionType.AGGREGATE, is(false));
Function left = (Function) whereClause.arguments().get(0);
assertThat(left.name(), is(EqOperator.NAME));
assertThat(left.arguments().get(0), isReference("load['1']"));
assertThat(left.arguments().get(1), IsInstanceOf.instanceOf(Literal.class));
assertThat(left.arguments().get(1).valueType(), is(DataTypes.DOUBLE));
Function right = (Function) whereClause.arguments().get(1);
assertThat(right.name(), is(LteOperator.NAME));
assertThat(right.arguments().get(0), isReference("load['5']"));
assertThat(right.arguments().get(1), IsInstanceOf.instanceOf(Literal.class));
assertThat(left.arguments().get(1).valueType(), is(DataTypes.DOUBLE));
}
@Test
public void testSelectWithParameters() throws Exception {
var executor = SQLExecutor.builder(clusterService).build();
QueriedSelectRelation relation = executor.analyze(
"select load from sys.nodes " +
"where load['1'] = ? or load['5'] <= ? or load['15'] >= ? or load['1'] = ? " +
"or load['1'] = ? or name = ?");
Function whereClause = (Function) relation.where();
assertThat(whereClause.name(), is(OrOperator.NAME));
assertThat(whereClause.signature().getKind() == FunctionType.AGGREGATE, is(false));
Function function = (Function) whereClause.arguments().get(0);
assertThat(function.name(), is(OrOperator.NAME));
function = (Function) function.arguments().get(1);
assertThat(function.name(), is(EqOperator.NAME));
assertThat(function.arguments().get(1), IsInstanceOf.instanceOf(ParameterSymbol.class));
assertThat(function.arguments().get(1).valueType(), is(DataTypes.DOUBLE));
function = (Function) whereClause.arguments().get(1);
assertThat(function.name(), is(EqOperator.NAME));
assertThat(function.arguments().get(1), IsInstanceOf.instanceOf(ParameterSymbol.class));
assertThat(function.arguments().get(1).valueType(), is(DataTypes.STRING));
}
@Test
public void testOutputNames() throws Exception {
var executor = SQLExecutor.builder(clusterService).build();
AnalyzedRelation relation = executor.analyze("select load as l, id, load['1'] from sys.nodes");
List<String> outputNames = outputNames(relation);
assertThat(outputNames.size(), is(3));
assertThat(outputNames.get(0), is("l"));
assertThat(outputNames.get(1), is("id"));
assertThat(outputNames.get(2), is("load['1']"));
}
@Test
public void testDuplicateOutputNames() throws Exception {
var executor = SQLExecutor.builder(clusterService).build();
AnalyzedRelation relation = executor.analyze("select load as l, load['1'] as l from sys.nodes");
List<String> outputNames = outputNames(relation);
assertThat(outputNames.size(), is(2));
assertThat(outputNames.get(0), is("l"));
assertThat(outputNames.get(1), is("l"));
}
@Test
public void testOrderByOnAlias() throws Exception {
var executor = SQLExecutor.builder(clusterService).build();
QueriedSelectRelation relation = executor.analyze(
"select name as cluster_name from sys.cluster order by cluster_name");
List<String> outputNames = outputNames(relation);
assertThat(outputNames.size(), is(1));
assertThat(outputNames.get(0), is("cluster_name"));
assertThat(relation.orderBy(), notNullValue());
assertThat(relation.orderBy().orderBySymbols().size(), is(1));
assertThat(relation.orderBy().orderBySymbols().get(0), is(relation.outputs().get(0)));
}
@Test
public void testSelectGlobalAggregationOrderByWithColumnMissingFromSelect() throws Exception {
var executor = SQLExecutor.builder(clusterService)
.addTable(TableDefinitions.USER_TABLE_DEFINITION)
.build();
expectedException.expect(UnsupportedOperationException.class);
expectedException.expectMessage("ORDER BY expression 'id' must appear in the select clause " +
"when grouping or global aggregation is used");
executor.analyze("select count(id) from users order by id");
}
@Test
public void testValidCombinationsOrderByWithAggregation() throws Exception {
var executor = SQLExecutor.builder(clusterService)
.addTable(TableDefinitions.USER_TABLE_DEFINITION)
.build();
executor.analyze("select name, count(id) from users group by name order by 1");
executor.analyze("select name, count(id) from users group by name order by 2");
executor.analyze("select name, count(id) from users group by name order by name");
executor.analyze("select name, count(id) from users group by name order by count(id)");
executor.analyze("select name, count(id) from users group by name order by lower(name)");
executor.analyze("select name, count(id) from users group by name order by lower(upper(name))");
executor.analyze("select name, count(id) from users group by name order by sin(count(id))");
executor.analyze("select name, count(id) from users group by name order by sin(sqrt(count(id)))");
}
@Test
public void testOffsetSupportInAnalyzer() throws Exception {
var executor = SQLExecutor.builder(clusterService).build();
QueriedSelectRelation relation = executor.analyze("select * from sys.nodes limit 1 offset 3");
assertThat(relation.offset(), is(Literal.of(3L)));
}
@Test
public void testNoMatchStatement() throws Exception {
var executor = SQLExecutor.builder(clusterService).build();
for (String stmt : List.of(
"select id from sys.nodes where false",
"select id from sys.nodes where 1=0"
)) {
QueriedSelectRelation relation = executor.analyze(stmt);
assertThat(stmt, relation.where(), isLiteral(false));
}
}
@Test
public void testEvaluatingMatchAllStatement() throws Exception {
var executor = SQLExecutor.builder(clusterService).build();
QueriedSelectRelation relation = executor.analyze("select id from sys.nodes where 1 = 1");
assertThat(relation.where(), isLiteral(true));
}
@Test
public void testAllMatchStatement() throws Exception {
var executor = SQLExecutor.builder(clusterService).build();
for (String stmt : List.of(
"select id from sys.nodes where true",
"select id from sys.nodes where 1=1",
"select id from sys.nodes"
)) {
QueriedSelectRelation relation = executor.analyze(stmt);
assertThat(stmt, relation.where(), isLiteral(true));
}
}
@Test
public void testRewriteNotEquals() {
var executor = SQLExecutor.builder(clusterService).build();
// should rewrite to:
// not(eq(sys.noes.name, 'something'))
List<String> statements = List.of(
"select * from sys.nodes where sys.nodes.name <> 'something'",
"select * from sys.nodes where sys.nodes.name != 'something'"
);
for (String statement : statements) {
QueriedSelectRelation relation = executor.analyze(statement);
Function notFunction = (Function) relation.where();
assertThat(notFunction.name(), is(NotPredicate.NAME));
assertThat(notFunction.arguments().size(), is(1));
Function eqFunction = (Function) notFunction.arguments().get(0);
assertThat(eqFunction.name(), is(EqOperator.NAME));
assertThat(eqFunction.arguments().size(), is(2));
List<Symbol> eqArguments = eqFunction.arguments();
assertThat(eqArguments.get(1), isLiteral("something"));
}
}
@Test
public void testRewriteRegexpNoMatch() throws Exception {
var executor = SQLExecutor.builder(clusterService).build();
String statement = "select * from sys.nodes where sys.nodes.name !~ '[sS]omething'";
QueriedSelectRelation relation = executor.analyze(statement);
Function notFunction = (Function) relation.where();
assertThat(notFunction.name(), is(NotPredicate.NAME));
assertThat(notFunction.arguments().size(), is(1));
Function eqFunction = (Function) notFunction.arguments().get(0);
assertThat(eqFunction.name(), is(RegexpMatchOperator.NAME));
assertThat(eqFunction.arguments().size(), is(2));
List<Symbol> eqArguments = eqFunction.arguments();
assertThat(eqArguments.get(0), isReference("name"));
assertThat(eqArguments.get(1), isLiteral("[sS]omething"));
}
@Test
public void testGranularityWithSingleAggregation() throws Exception {
var executor = SQLExecutor.builder(clusterService).build();
QueriedSelectRelation table = executor.analyze("select count(*) from sys.nodes");
assertEquals(((TableRelation) table.from().get(0)).tableInfo().ident(), SysNodesTableInfo.IDENT);
}
@Test
public void testRewriteCountStringLiteral() {
var executor = SQLExecutor.builder(clusterService).build();
AnalyzedRelation relation = executor.analyze("select count('id') from sys.nodes");
List<Symbol> outputSymbols = relation.outputs();
assertThat(outputSymbols.size(), is(1));
assertThat(outputSymbols.get(0), instanceOf(Function.class));
assertThat(((Function) outputSymbols.get(0)).arguments().size(), is(0));
}
@Test
public void testRewriteCountNull() {
var executor = SQLExecutor.builder(clusterService).build();
AnalyzedRelation relation = executor.analyze("select count(null) from sys.nodes");
List<Symbol> outputSymbols = relation.outputs();
assertThat(outputSymbols.size(), is(1));
assertThat(outputSymbols.get(0), instanceOf(Literal.class));
assertThat(((Literal) outputSymbols.get(0)).value(), is(0L));
}
@Test
public void testWhereInSelect() throws Exception {
var executor = SQLExecutor.builder(clusterService).build();
QueriedSelectRelation relation = executor.analyze(
"select load from sys.nodes where load['1'] in (1.0, 2.0, 4.0, 8.0, 16.0)");
Function whereClause = (Function) relation.where();
assertThat(whereClause.name(), is(AnyEqOperator.NAME));
}
@Test
public void testWhereInSelectListWithNull() throws Exception {
var executor = SQLExecutor.builder(clusterService)
.addTable(TableDefinitions.USER_TABLE_DEFINITION)
.build();
QueriedSelectRelation relation = executor.analyze("select 'found' from users where 1 in (3, 2, null)");
assertThat(relation.where(), isLiteral(null));
}
@Test
public void testWhereInSelectValueIsNull() throws Exception {
var executor = SQLExecutor.builder(clusterService)
.addTable(TableDefinitions.USER_TABLE_DEFINITION)
.build();
QueriedSelectRelation relation = executor.analyze("select 'found' from users where null in (1, 2)");
assertThat(relation.where(), isLiteral(null));
}
@Test
public void testWhereInSelectDifferentDataTypeValue() throws Exception {
var executor = SQLExecutor.builder(clusterService)
.addTable(TableDefinitions.USER_TABLE_DEFINITION)
.build();
QueriedSelectRelation relation;
relation = executor.analyze("select 'found' from users where 1.2 in (1, 2)");
assertThat(relation.where(), isLiteral(false)); // already normalized to 1.2 in (1.0, 2.0) --> false
relation = executor.analyze("select 'found' from users where 1 in (1.2, 2)");
assertThat(relation.where(), isLiteral(false));
}
@Test
public void testWhereInSelectDifferentDataTypeValueIncompatibleDataTypes() throws Exception {
var executor = SQLExecutor.builder(clusterService)
.addTable(TableDefinitions.USER_TABLE_DEFINITION)
.build();
expectedException.expect(ConversionException.class);
expectedException.expectMessage("Cannot cast `'foo'` of type `text` to type `integer`");
executor.analyze("select 'found' from users where 1 in (1, 'foo', 2)");
}
@Test
public void testAggregationDistinct() {
var executor = SQLExecutor.builder(clusterService)
.build();
AnalyzedRelation relation = executor.analyze("select count(distinct load['1']) from sys.nodes");
Symbol output = relation.outputs().get(0);
assertThat(output, isFunction("collection_count"));
Function collectionCount = (Function) output;
assertThat(collectionCount.arguments().size(), is(1));
Symbol symbol = collectionCount.arguments().get(0);
assertThat(symbol, isFunction("collect_set"));
Function collectSet = (Function) symbol;
assertThat(collectSet.signature().getKind(), equalTo(FunctionType.AGGREGATE));
assertThat(collectSet.arguments().size(), is(1));
assertThat(collectSet.arguments().get(0), isReference("load['1']"));
}
@Test
public void test_count_distinct_on_length_limited_varchar_preserves_varchar_type() throws Exception {
var executor = SQLExecutor.builder(clusterService)
.addTable("create table tbl (name varchar(10))")
.build();
Symbol symbol = executor.asSymbol("count(distinct name)");
assertThat(symbol, SymbolMatchers.isFunction("collection_count", List.of(new ArrayType<>(DataTypes.STRING))));
}
@Test
public void testSelectDistinctWithFunction() throws Exception {
var executor = SQLExecutor.builder(clusterService)
.addTable(TableDefinitions.USER_TABLE_DEFINITION)
.build();
QueriedSelectRelation relation = executor.analyze("select distinct id + 1 from users");
assertThat(relation.isDistinct(), is(true));
assertThat(relation.outputs(), isSQL("(doc.users.id + 1::bigint)"));
}
@Test
public void testSelectDistinctWithGroupBySameFieldsSameOrder() throws Exception {
var executor = SQLExecutor.builder(clusterService)
.addTable(TableDefinitions.USER_TABLE_DEFINITION)
.build();
QueriedSelectRelation distinctRelation = executor.analyze("select distinct id, name from users group by id, name");
QueriedSelectRelation groupByRelation = executor.analyze("select id, name from users group by id, name");
assertThat(distinctRelation.groupBy(), equalTo(groupByRelation.groupBy()));
assertThat(distinctRelation.outputs(), equalTo(groupByRelation.outputs()));
}
@Test
public void testSelectDistinctWithGroupBySameFieldsDifferentOrder() throws Exception {
var executor = SQLExecutor.builder(clusterService)
.addTable(TableDefinitions.USER_TABLE_DEFINITION)
.build();
AnalyzedRelation relation = executor.analyze("select distinct name, id from users group by id, name");
assertThat(
relation,
isSQL("SELECT doc.users.name, doc.users.id GROUP BY doc.users.id, doc.users.name"));
}
@Test
public void testDistinctOnLiteral() throws Exception {
var executor = SQLExecutor.builder(clusterService)
.addTable(TableDefinitions.USER_TABLE_DEFINITION)
.build();
QueriedSelectRelation relation = executor.analyze("select distinct [1,2,3] from users");
assertThat(relation.isDistinct(), is(true));
assertThat(relation.outputs(), isSQL("[1, 2, 3]"));
}
@Test
public void testDistinctOnNullLiteral() throws Exception {
var executor = SQLExecutor.builder(clusterService)
.addTable(TableDefinitions.USER_TABLE_DEFINITION)
.build();
QueriedSelectRelation relation = executor.analyze("select distinct null from users");
assertThat(relation.isDistinct(), is(true));
assertThat(relation.outputs(), isSQL("NULL"));
}
@Test
public void testSelectGlobalDistinctAggregate() throws Exception {
var executor = SQLExecutor.builder(clusterService)
.addTable(TableDefinitions.USER_TABLE_DEFINITION)
.build();
QueriedSelectRelation relation = executor.analyze("select distinct count(*) from users");
assertThat(relation.groupBy().isEmpty(), is(true));
}
@Test
public void testSelectGlobalDistinctRewriteAggregationGroupBy() throws Exception {
var executor = SQLExecutor.builder(clusterService)
.addTable(TableDefinitions.USER_TABLE_DEFINITION)
.build();
QueriedSelectRelation distinctRelation = executor.analyze("select distinct name, count(id) from users group by name");
QueriedSelectRelation groupByRelation = executor.analyze("select name, count(id) from users group by name");
assertEquals(groupByRelation.groupBy(), distinctRelation.groupBy());
}
@Test
public void testSelectWithObjectLiteral() throws Exception {
var executor = SQLExecutor.builder(clusterService)
.build();
QueriedSelectRelation relation = executor.analyze("select id from sys.nodes where load={\"1\"=1.0}");
Function whereClause = (Function) relation.where();
assertThat(whereClause.arguments(), hasItem(isLiteral(Map.of("1", 1.0))));
}
@Test
public void testLikeInWhereQuery() {
var executor = SQLExecutor.builder(clusterService)
.build();
QueriedSelectRelation relation = executor.analyze("select * from sys.nodes where name like 'foo'");
assertNotNull(relation.where());
Function whereClause = (Function) relation.where();
assertThat(whereClause.name(), is(LikeOperators.OP_LIKE));
List<DataType> argumentTypes = List.of(DataTypes.STRING, DataTypes.STRING);
assertEquals(argumentTypes, Symbols.typeView(whereClause.arguments()));
assertThat(whereClause.arguments().get(0), isReference("name"));
assertThat(whereClause.arguments().get(1), isLiteral("foo"));
}
@Test
public void testILikeInWhereQuery() {
var executor = SQLExecutor.builder(clusterService)
.build();
QueriedSelectRelation relation = executor.analyze("select * from sys.nodes where name ilike 'foo%'");
assertNotNull(relation.where());
Function whereClause = (Function) relation.where();
assertThat(whereClause.name(), is(LikeOperators.OP_ILIKE));
List<DataType> argumentTypes = List.of(DataTypes.STRING, DataTypes.STRING);
assertEquals(argumentTypes, Symbols.typeView(whereClause.arguments()));
assertThat(whereClause.arguments().get(0), isReference("name"));
assertThat(whereClause.arguments().get(1), isLiteral("foo%"));
}
@Test
public void testLikeEscapeInWhereQuery() {
var executor = SQLExecutor.builder(clusterService)
.build();
// ESCAPE is not supported yet
expectedException.expect(UnsupportedOperationException.class);
expectedException.expectMessage("ESCAPE is not supported.");
executor.analyze("select * from sys.nodes where name like 'foo' escape 'o'");
}
@Test
public void testILikeEscapeInWhereQuery() {
var executor = SQLExecutor.builder(clusterService)
.build();
// ESCAPE is not supported yet
expectedException.expect(UnsupportedOperationException.class);
expectedException.expectMessage("ESCAPE is not supported.");
executor.analyze("select * from sys.nodes where name ilike 'foo%' escape 'o'");
}
@Test
public void testLikeNoStringDataTypeInWhereQuery() {
var executor = SQLExecutor.builder(clusterService)
.build();
QueriedSelectRelation relation = executor.analyze("select * from sys.nodes where name like 1");
// check if the implicit cast of the pattern worked
List<DataType> argumentTypes = List.of(DataTypes.STRING, DataTypes.STRING);
Function whereClause = (Function) relation.where();
assertEquals(argumentTypes, Symbols.typeView(whereClause.arguments()));
assertThat(whereClause.arguments().get(1), IsInstanceOf.instanceOf(Literal.class));
Literal stringLiteral = (Literal) whereClause.arguments().get(1);
assertThat(stringLiteral.value(), is("1"));
}
@Test
public void testLikeLongDataTypeInWhereQuery() {
var executor = SQLExecutor.builder(clusterService)
.build();
QueriedSelectRelation relation = executor.analyze("select * from sys.nodes where 1 like 2");
assertThat(relation.where(), isLiteral(false));
}
@Test
public void testILikeLongDataTypeInWhereQuery() {
var executor = SQLExecutor.builder(clusterService)
.build();
QueriedSelectRelation relation = executor.analyze("select * from sys.nodes where 1 ilike 2");
assertThat(relation.where(), isLiteral(false));
}
@Test
public void testIsNullInWhereQuery() {
var executor = SQLExecutor.builder(clusterService)
.build();
QueriedSelectRelation relation = executor.analyze("select * from sys.nodes where name is null");
Function isNullFunction = (Function) relation.where();
assertThat(isNullFunction.name(), is(IsNullPredicate.NAME));
assertThat(isNullFunction.arguments().size(), is(1));
assertThat(isNullFunction.arguments().get(0), isReference("name"));
assertNotNull(relation.where());
}
@Test
public void testNullIsNullInWhereQuery() {
var executor = SQLExecutor.builder(clusterService)
.build();
QueriedSelectRelation relation = executor.analyze("select * from sys.nodes where null is null");
assertThat(relation.where(), is(Literal.BOOLEAN_TRUE));
}
@Test
public void testLongIsNullInWhereQuery() {
var executor = SQLExecutor.builder(clusterService)
.build();
QueriedSelectRelation relation = executor.analyze("select * from sys.nodes where 1 is null");
assertThat(relation.where(), isSQL("false"));
}
@Test
public void testNotPredicate() throws Exception {
var executor = SQLExecutor.builder(clusterService)
.addTable(TableDefinitions.USER_TABLE_DEFINITION)
.build();
QueriedSelectRelation relation = executor.analyze("select * from users where name not like 'foo%'");
assertThat(((Function) relation.where()).name(), is(NotPredicate.NAME));
}
@Test
public void testFilterByLiteralBoolean() throws Exception {
var executor = SQLExecutor.builder(clusterService)
.addTable(TableDefinitions.USER_TABLE_DEFINITION)
.build();
QueriedSelectRelation relation = executor.analyze("select * from users where awesome=TRUE");
assertThat(((Function) relation.where()).arguments().get(1).symbolType(),
is(SymbolType.LITERAL));
}
@Test
public void testSelectColumnWitoutFromResultsInColumnUnknownException() throws Exception {
var executor = SQLExecutor.builder(clusterService)
.build();
expectedException.expect(ColumnUnknownException.class);
expectedException.expectMessage("Column name unknown");
executor.analyze("select 'bar', name");
}
@Test
public void test2From() throws Exception {
var executor = SQLExecutor.builder(clusterService)
.addTable(TableDefinitions.USER_TABLE_DEFINITION)
.build();
AnalyzedRelation relation = executor.analyze("select a.name from users a, users b");
assertThat(relation, instanceOf(QueriedSelectRelation.class));
}
@Test
public void testOrderByQualifiedName() throws Exception {
var executor = SQLExecutor.builder(clusterService)
.addTable(TableDefinitions.USER_TABLE_DEFINITION)
.build();
expectedException.expect(RelationUnknown.class);
expectedException.expectMessage("Relation 'doc.friends' unknown");
executor.analyze("select * from users order by friends.id");
}
@Test
public void testNotTimestamp() throws Exception {
var executor = SQLExecutor.builder(clusterService)
.addPartitionedTable(TableDefinitions.TEST_PARTITIONED_TABLE_DEFINITION)
.build();
expectedException.expect(UnsupportedOperationException.class);
expectedException.expectMessage("Unknown function: (NOT doc.parted.date)," +
" no overload found for matching argument types: (timestamp with time zone).");
executor.analyze("select id, name from parted where not date");
}
@Test
public void testJoin() throws Exception {
var executor = SQLExecutor.builder(clusterService)
.addTable(TableDefinitions.USER_TABLE_DEFINITION)
.addTable(TableDefinitions.USER_TABLE_MULTI_PK_DEFINITION)
.build();
AnalyzedRelation relation = executor.analyze("select * from users, users_multi_pk where users.id = users_multi_pk.id");
assertThat(relation, instanceOf(QueriedSelectRelation.class));
}
@Test
public void testInnerJoinSyntaxDoesNotExtendsWhereClause() throws Exception {
var executor = SQLExecutor.builder(clusterService)
.addTable(TableDefinitions.USER_TABLE_DEFINITION)
.addTable(TableDefinitions.USER_TABLE_MULTI_PK_DEFINITION)
.build();
QueriedSelectRelation mss = executor.analyze(
"select * from users inner join users_multi_pk on users.id = users_multi_pk.id");
assertThat(mss.where(), isLiteral(true));
assertThat(mss.joinPairs().get(0).condition(),
isSQL("(doc.users.id = doc.users_multi_pk.id)"));
}
@Test
public void testJoinSyntaxWithMoreThan2Tables() throws Exception {
var executor = SQLExecutor.builder(clusterService)
.addTable(TableDefinitions.USER_TABLE_DEFINITION)
.addTable(TableDefinitions.USER_TABLE_MULTI_PK_DEFINITION)
.addTable(TableDefinitions.USER_TABLE_CLUSTERED_BY_ONLY_DEFINITION)
.build();
QueriedSelectRelation relation = executor.analyze("select * from users u1 " +
"join users_multi_pk u2 on u1.id = u2.id " +
"join users_clustered_by_only u3 on u2.id = u3.id ");
assertThat(relation.where(), isLiteral(true));
assertThat(relation.joinPairs().get(0).condition(),
isSQL("(u1.id = u2.id)"));
assertThat(relation.joinPairs().get(1).condition(),
isSQL("(u2.id = u3.id)"));
}
@Test
public void testCrossJoinWithJoinCondition() throws Exception {
var executor = SQLExecutor.builder(clusterService)
.addTable(TableDefinitions.USER_TABLE_DEFINITION)
.addTable(TableDefinitions.USER_TABLE_MULTI_PK_DEFINITION)
.build();
expectedException.expect(ParsingException.class);
executor.analyze("select * from users cross join users_multi_pk on users.id = users_multi_pk.id");
}
@Test
public void testJoinUsingSyntax() throws Exception {
var executor = SQLExecutor.builder(clusterService)
.addTable(TableDefinitions.USER_TABLE_DEFINITION)
.addTable(TableDefinitions.USER_TABLE_MULTI_PK_DEFINITION)
.build();
QueriedSelectRelation relation = executor.analyze("select * from users join users_multi_pk using (id, name)");
assertThat(relation.where(), isLiteral(true));
assertEquals(relation.joinPairs().size(), 1);
assertThat(relation.joinPairs().get(0).condition(),
isSQL("((doc.users.id = doc.users_multi_pk.id) AND (doc.users.name = doc.users_multi_pk.name))"));
}
@Test
public void testNaturalJoinSyntax() throws Exception {
var executor = SQLExecutor.builder(clusterService)
.addTable(TableDefinitions.USER_TABLE_DEFINITION)
.addTable(TableDefinitions.USER_TABLE_MULTI_PK_DEFINITION)
.build();
expectedException.expect(UnsupportedOperationException.class);
executor.analyze("select * from users natural join users_multi_pk");
}
@Test
public void testInnerJoinSyntaxWithWhereClause() throws Exception {
var executor = SQLExecutor.builder(clusterService)
.addTable(TableDefinitions.USER_TABLE_DEFINITION)
.addTable(TableDefinitions.USER_TABLE_MULTI_PK_DEFINITION)
.build();
QueriedSelectRelation relation = executor.analyze(
"select * from users join users_multi_pk on users.id = users_multi_pk.id " +
"where users.name = 'Arthur'");
assertThat(relation.joinPairs().get(0).condition(),
isSQL("(doc.users.id = doc.users_multi_pk.id)"));
assertThat(relation.where(), isSQL("(doc.users.name = 'Arthur')"));
AnalyzedRelation users = relation.from().get(0);
}
public void testSelfJoinSyntaxWithWhereClause() throws Exception {
var executor = SQLExecutor.builder(clusterService)
.addTable(TableDefinitions.USER_TABLE_DEFINITION)
.build();
QueriedSelectRelation relation = executor.analyze("select t2.id from users as t1 join users as t2 on t1.id = t2.id " +
"where t1.name = 'foo' and t2.name = 'bar'");
assertThat(relation.where(), isSQL("((t1.name = 'foo') AND (t2.name = 'bar'))"));
assertThat(relation, instanceOf(QueriedSelectRelation.class));
}
@Test
public void testJoinWithOrderBy() throws Exception {
var executor = SQLExecutor.builder(clusterService)
.addTable(TableDefinitions.USER_TABLE_DEFINITION)
.addTable(TableDefinitions.USER_TABLE_MULTI_PK_DEFINITION)
.build();
AnalyzedRelation relation = executor.analyze("select users.id from users, users_multi_pk order by users.id");
assertThat(relation, instanceOf(QueriedSelectRelation.class));
QueriedSelectRelation mss = (QueriedSelectRelation) relation;
assertThat(mss.orderBy(), isSQL("doc.users.id"));
}
@Test
public void testJoinWithOrderByOnCount() throws Exception {
var executor = SQLExecutor.builder(clusterService)
.addTable(TableDefinitions.USER_TABLE_DEFINITION)
.addTable(TableDefinitions.USER_TABLE_MULTI_PK_DEFINITION)
.build();
AnalyzedRelation relation = executor.analyze("select count(*) from users u1, users_multi_pk u2 " +
"order by 1");
QueriedSelectRelation mss = (QueriedSelectRelation) relation;
assertThat(mss.orderBy(), isSQL("count(*)"));
}
@Test
public void testJoinWithMultiRelationOrderBy() throws Exception {
var executor = SQLExecutor.builder(clusterService)
.addTable(TableDefinitions.USER_TABLE_DEFINITION)
.addTable(TableDefinitions.USER_TABLE_MULTI_PK_DEFINITION)
.build();
AnalyzedRelation relation = executor.analyze(
"select u1.id from users u1, users_multi_pk u2 order by u2.id, u1.name || u2.name");
assertThat(relation, instanceOf(QueriedSelectRelation.class));
QueriedSelectRelation mss = (QueriedSelectRelation) relation;
AnalyzedRelation u1 = mss.from().iterator().next();
assertThat(u1.outputs(), allOf(
hasItem(isField("name")),
hasItem(isField("id")))
);
}
@Test
public void testJoinConditionIsNotPartOfOutputs() throws Exception {
var executor = SQLExecutor.builder(clusterService)
.addTable(TableDefinitions.USER_TABLE_DEFINITION)
.build();
AnalyzedRelation rel = executor.analyze(
"select u1.name from users u1 inner join users u2 on u1.id = u2.id order by u2.date");
assertThat(rel.outputs(), contains(isField("name")));
}
@Test
public void testUnionDistinct() throws Exception {
var executor = SQLExecutor.builder(clusterService)
.addTable(TableDefinitions.USER_TABLE_DEFINITION)
.addTable(TableDefinitions.USER_TABLE_MULTI_PK_DEFINITION)
.build();
expectedException.expect(UnsupportedFeatureException.class);
expectedException.expectMessage("UNION [DISTINCT] is not supported");
executor.analyze("select * from users union select * from users_multi_pk");
}
@Test
public void testIntersect() throws Exception {
var executor = SQLExecutor.builder(clusterService)
.addTable(TableDefinitions.USER_TABLE_DEFINITION)
.build();
expectedException.expect(UnsupportedFeatureException.class);
expectedException.expectMessage("INTERSECT is not supported");
executor.analyze("select * from users intersect select * from users_multi_pk");
}
@Test
public void testExcept() throws Exception {
var executor = SQLExecutor.builder(clusterService)
.addTable(TableDefinitions.USER_TABLE_DEFINITION)
.build();
expectedException.expect(UnsupportedFeatureException.class);
expectedException.expectMessage("EXCEPT is not supported");
executor.analyze("select * from users except select * from users_multi_pk");
}
@Test
public void testArrayCompareInvalidArray() throws Exception {
var executor = SQLExecutor.builder(clusterService)
.addTable(TableDefinitions.USER_TABLE_DEFINITION)
.build();
expectedException.expect(UnsupportedOperationException.class);
expectedException.expectMessage("Unknown function: ('George' = ANY(doc.users.name))," +
" no overload found for matching argument types: (text, text).");
executor.analyze("select * from users where 'George' = ANY (name)");
}
@Test
public void testArrayCompareObjectArray() throws Exception {
var executor = SQLExecutor.builder(clusterService)
.addTable(TableDefinitions.USER_TABLE_DEFINITION)
.build();
QueriedSelectRelation relation = executor.analyze("select * from users where {id=1} = ANY (friends)");
assertThat(relation.where(), is(isFunction("any_=")));
}
@Test
public void testArrayCompareAny() throws Exception {
var executor = SQLExecutor.builder(clusterService)
.addTable(TableDefinitions.USER_TABLE_DEFINITION)
.build();
QueriedSelectRelation relation = executor.analyze("select * from users where 0 = ANY (counters)");
var func = (Function) relation.where();
assertThat(func.name(), is("any_="));
relation = executor.analyze("select * from users where 0 = ANY (counters)");
func = (Function) relation.where();
assertThat(func.name(), is("any_="));
}
@Test
public void testArrayCompareAnyNeq() throws Exception {
var executor = SQLExecutor.builder(clusterService)
.addTable(TableDefinitions.USER_TABLE_DEFINITION)
.build();
QueriedSelectRelation relation = executor.analyze("select * from users where 4.3 != ANY (counters)");
var func = (Function) relation.where();
assertThat(func.name(), is("any_<>"));
}
@Test
public void testArrayCompareAll() throws Exception {
var executor = SQLExecutor.builder(clusterService)
.addTable(TableDefinitions.USER_TABLE_DEFINITION)
.build();
QueriedSelectRelation relation = executor.analyze("select * from users where 0 = ALL (counters)");
assertThat(relation.where(), isFunction("_all_="));
}
@Test
public void testImplicitContainmentOnObjectArrayFields() throws Exception {
var executor = SQLExecutor.builder(clusterService)
.addTable(TableDefinitions.USER_TABLE_DEFINITION)
.build();
// users.friends is an object array,
// so its fields are selected as arrays,
// ergo simple comparison does not work here
expectedException.expect(UnsupportedOperationException.class);
expectedException.expectMessage("Unknown function: (doc.users.friends['id'] = 5)," +
" no overload found for matching argument types: (bigint_array, integer).");
executor.analyze("select * from users where 5 = friends['id']");
}
@Test
public void testAnyOnObjectArrayField() throws Exception {
var executor = SQLExecutor.builder(clusterService)
.addTable(TableDefinitions.USER_TABLE_DEFINITION)
.build();
QueriedSelectRelation relation = executor.analyze(
"select * from users where 5 = ANY (friends['id'])");
Function anyFunction = (Function) relation.where();
assertThat(anyFunction.name(), is(AnyEqOperator.NAME));
assertThat(anyFunction.arguments().get(1), isReference("friends['id']", new ArrayType<>(DataTypes.LONG)));
assertThat(anyFunction.arguments().get(0), isLiteral(5L));
}
@Test
public void testAnyOnArrayInObjectArray() throws Exception {
var executor = SQLExecutor.builder(clusterService)
.addTable(TableDefinitions.USER_TABLE_DEFINITION)
.build();
QueriedSelectRelation relation = executor.analyze(
"select * from users where ['vogon lyric lovers'] = ANY (friends['groups'])");
assertThat(
relation.where(),
isFunction(
"any_=",
isLiteral(
List.of("vogon lyric lovers"),
new ArrayType<>(DataTypes.STRING)),
isReference("friends['groups']", new ArrayType<>(new ArrayType<>(DataTypes.STRING)))
)
);
}
@Test
public void testTableAliasWrongUse() throws Exception {
var executor = SQLExecutor.builder(clusterService)
.addTable(TableDefinitions.USER_TABLE_DEFINITION)
.build();
expectedException.expect(RelationUnknown.class);
// caused by where users.awesome, would have to use where u.awesome = true instead
expectedException.expectMessage("Relation 'doc.users' unknown");
executor.analyze("select * from users as u where users.awesome = true");
}
@Test
public void testTableAliasFullQualifiedName() throws Exception {
var executor = SQLExecutor.builder(clusterService)
.addTable(TableDefinitions.USER_TABLE_DEFINITION)
.build();
expectedException.expect(RelationUnknown.class);
// caused by where users.awesome, would have to use where u.awesome = true instead
expectedException.expectMessage("Relation 'doc.users' unknown");
executor.analyze("select * from users as u where doc.users.awesome = true");
}
@Test
public void testAliasSubscript() throws Exception {
var executor = SQLExecutor.builder(clusterService)
.addTable(TableDefinitions.USER_TABLE_DEFINITION)
.build();
AnalyzedRelation relation = executor.analyze(
"select u.friends['id'] from users as u");
assertThat(relation.outputs().size(), is(1));
Symbol s = relation.outputs().get(0);
assertThat(s, notNullValue());
assertThat(s, isField("friends['id']"));
}
@Test
public void testOrderByWithOrdinal() throws Exception {
var executor = SQLExecutor.builder(clusterService)
.addTable(TableDefinitions.USER_TABLE_DEFINITION)
.build();
QueriedSelectRelation relation = executor.analyze("select name from users u order by 1");
assertThat(
relation.outputs(),
equalTo(relation.orderBy().orderBySymbols())
);
}
@Test
public void testOrderByOnArray() throws Exception {
var executor = SQLExecutor.builder(clusterService)
.addTable(TableDefinitions.USER_TABLE_DEFINITION)
.build();
expectedException.expect(UnsupportedOperationException.class);
expectedException.expectMessage("Cannot ORDER BY 'friends': invalid data type 'object_array'.");
executor.analyze("select * from users order by friends");
}
@Test
public void testOrderByOnObject() throws Exception {
var executor = SQLExecutor.builder(clusterService)
.build();
expectedException.expect(UnsupportedOperationException.class);
expectedException.expectMessage("Cannot ORDER BY 'load': invalid data type 'object'.");
executor.analyze("select * from sys.nodes order by load");
}
@Test
public void testArithmeticPlus() throws Exception {
var executor = SQLExecutor.builder(clusterService)
.build();
AnalyzedRelation relation = executor.analyze("select load['1'] + load['5'] from sys.nodes");
assertThat(((Function) relation.outputs().get(0)).name(), is(ArithmeticFunctions.Names.ADD));
}
@Test
public void testPrefixedNumericLiterals() throws Exception {
var executor = SQLExecutor.builder(clusterService)
.build();
AnalyzedRelation relation = executor.analyze("select - - - 10");
List<Symbol> outputs = relation.outputs();
assertThat(outputs.get(0), is(Literal.of(-10)));
relation = executor.analyze("select - + - 10");
outputs = relation.outputs();
assertThat(outputs.get(0), is(Literal.of(10)));
relation = executor.analyze("select - (- 10 - + 10) * - (+ 10 + - 10)");
outputs = relation.outputs();
assertThat(outputs.get(0), is(Literal.of(0)));
}
@Test
public void testAnyLike() throws Exception {
var executor = SQLExecutor.builder(clusterService)
.addTable(TableDefinitions.USER_TABLE_DEFINITION)
.build();
QueriedSelectRelation relation = executor.analyze("select * from users where 'awesome' LIKE ANY (tags)");
Function query = (Function) relation.where();
assertThat(query.name(), is("any_like"));
assertThat(query.arguments().size(), is(2));
assertThat(query.arguments().get(0), instanceOf(Literal.class));
assertThat(query.arguments().get(0), isLiteral("awesome", DataTypes.STRING));
assertThat(query.arguments().get(1), isReference("tags"));
}
@Test
public void testAnyLikeLiteralMatchAll() throws Exception {
var executor = SQLExecutor.builder(clusterService)
.addTable(TableDefinitions.USER_TABLE_DEFINITION)
.build();
QueriedSelectRelation relation = executor.analyze("select * from users where 'awesome' LIKE ANY (['a', 'b', 'awesome'])");
assertThat(relation.where(), isLiteral(true));
}
@Test
public void testAnyLikeLiteralNoMatch() throws Exception {
var executor = SQLExecutor.builder(clusterService)
.addTable(TableDefinitions.USER_TABLE_DEFINITION)
.build();
QueriedSelectRelation relation = executor.analyze("select * from users where 'awesome' LIKE ANY (['a', 'b'])");
assertThat(relation.where(), isLiteral(false));
}
@Test
public void testAnyNotLike() throws Exception {
var executor = SQLExecutor.builder(clusterService)
.addTable(TableDefinitions.USER_TABLE_DEFINITION)
.build();
QueriedSelectRelation relation = executor.analyze("select * from users where 'awesome' NOT LIKE ANY (tags)");
Function query = (Function) relation.where();
assertThat(query.name(), is("any_not_like"));
assertThat(query.arguments().size(), is(2));
assertThat(query.arguments().get(0), instanceOf(Literal.class));
assertThat(query.arguments().get(0), isLiteral("awesome", DataTypes.STRING));
assertThat(query.arguments().get(1), isReference("tags"));
}
@Test
public void testAnyLikeInvalidArray() throws Exception {
var executor = SQLExecutor.builder(clusterService)
.addTable(TableDefinitions.USER_TABLE_DEFINITION)
.build();
expectedException.expect(UnsupportedOperationException.class);
expectedException.expectMessage("Unknown function: ('awesome' LIKE ANY(doc.users.name))," +
" no overload found for matching argument types: (text, text).");
executor.analyze("select * from users where 'awesome' LIKE ANY (name)");
}
@Test
public void testPositionalArgumentOrderByArrayType() throws Exception {
var executor = SQLExecutor.builder(clusterService)
.addTable(TableDefinitions.USER_TABLE_DEFINITION)
.build();
expectedException.expect(UnsupportedOperationException.class);
expectedException.expectMessage("Cannot ORDER BY 'friends': invalid data type 'object_array'.");
executor.analyze("SELECT id, friends FROM users ORDER BY 2");
}
@Test
public void testOrderByDistanceAlias() throws Exception {
var executor = SQLExecutor.builder(clusterService)
.addTable(TableDefinitions.TEST_DOC_LOCATIONS_TABLE_DEFINITION)
.build();
String stmt = "SELECT distance(loc, 'POINT(-0.1275 51.507222)') AS distance_to_london " +
"FROM locations " +
"ORDER BY distance_to_london";
testDistanceOrderBy(executor, stmt);
}
@Test
public void testOrderByDistancePositionalArgument() throws Exception {
var executor = SQLExecutor.builder(clusterService)
.addTable(TableDefinitions.TEST_DOC_LOCATIONS_TABLE_DEFINITION)
.build();
String stmt = "SELECT distance(loc, 'POINT(-0.1275 51.507222)') " +
"FROM locations " +
"ORDER BY 1";
testDistanceOrderBy(executor, stmt);
}
@Test
public void testOrderByDistanceExplicitly() throws Exception {
var executor = SQLExecutor.builder(clusterService)
.addTable(TableDefinitions.TEST_DOC_LOCATIONS_TABLE_DEFINITION)
.build();
String stmt = "SELECT distance(loc, 'POINT(-0.1275 51.507222)') " +
"FROM locations " +
"ORDER BY distance(loc, 'POINT(-0.1275 51.507222)')";
testDistanceOrderBy(executor, stmt);
}
@Test
public void testOrderByDistancePermutatedExplicitly() throws Exception {
var executor = SQLExecutor.builder(clusterService)
.addTable(TableDefinitions.TEST_DOC_LOCATIONS_TABLE_DEFINITION)
.build();
String stmt = "SELECT distance('POINT(-0.1275 51.507222)', loc) " +
"FROM locations " +
"ORDER BY distance('POINT(-0.1275 51.507222)', loc)";
testDistanceOrderBy(executor, stmt);
}
private void testDistanceOrderBy(SQLExecutor executor, String stmt) throws Exception {
QueriedSelectRelation relation = executor.analyze(stmt);
assertThat(relation.orderBy(), notNullValue());
assertThat(
relation.orderBy().orderBySymbols(),
contains(
anyOf(
isAlias("distance_to_london", isFunction(DistanceFunction.NAME)),
isFunction(DistanceFunction.NAME)
)
)
);
}
@Test
public void testWhereMatchOnColumn() throws Exception {
var executor = SQLExecutor.builder(clusterService)
.addTable(TableDefinitions.USER_TABLE_DEFINITION)
.build();
QueriedSelectRelation relation = executor.analyze("select * from users where match(name, 'Arthur Dent')");
assertThat(relation.where(), Matchers.instanceOf(MatchPredicate.class));
MatchPredicate matchPredicate = (MatchPredicate) relation.where();
assertThat(matchPredicate.queryTerm(), isLiteral("Arthur Dent"));
assertThat(matchPredicate.identBoostMap(), hasEntry(isReference("name"), isLiteral(null)));
assertThat(matchPredicate.matchType(), is("best_fields"));
assertThat(matchPredicate.options(), isLiteral(Map.of()));
}
@Test
public void testMatchOnIndex() throws Exception {
var executor = SQLExecutor.builder(clusterService)
.addTable(TableDefinitions.USER_TABLE_DEFINITION)
.build();
QueriedSelectRelation relation = executor.analyze("select * from users where match(name_text_ft, 'Arthur Dent')");
assertThat(relation.where(), instanceOf(MatchPredicate.class));
MatchPredicate match = (MatchPredicate) relation.where();
assertThat(match.identBoostMap(), hasEntry(isReference("name_text_ft"), isLiteral(null)));
assertThat(match.queryTerm(), isLiteral("Arthur Dent"));
assertThat(match.matchType(), is("best_fields"));
assertThat(match.options(), isLiteral(Map.of()));
}
@Test
public void testMatchOnDynamicColumn() throws Exception {
var executor = SQLExecutor.builder(clusterService)
.addTable(TableDefinitions.USER_TABLE_DEFINITION)
.build();
expectedException.expect(ColumnUnknownException.class);
expectedException.expectMessage("Column details['me_not_exizzt'] unknown");
executor.analyze("select * from users where match(details['me_not_exizzt'], 'Arthur Dent')");
}
@Test
public void testMatchPredicateInResultColumnList() throws Exception {
var executor = SQLExecutor.builder(clusterService)
.addTable(TableDefinitions.USER_TABLE_DEFINITION)
.build();
expectedException.expect(UnsupportedOperationException.class);
expectedException.expectMessage("match predicate cannot be selected");
executor.analyze("select match(name, 'bar') from users");
}
@Test
public void testMatchPredicateInGroupByClause() throws Exception {
var executor = SQLExecutor.builder(clusterService)
.addTable(TableDefinitions.USER_TABLE_DEFINITION)
.build();
expectedException.expect(UnsupportedOperationException.class);
expectedException.expectMessage("match predicate cannot be used in a GROUP BY clause");
executor.analyze("select count(*) from users group by MATCH(name, 'bar')");
}
@Test
public void testMatchPredicateInOrderByClause() throws Exception {
var executor = SQLExecutor.builder(clusterService)
.addTable(TableDefinitions.USER_TABLE_DEFINITION)
.build();
expectedException.expect(UnsupportedOperationException.class);
expectedException.expectMessage("match predicate cannot be used in an ORDER BY clause");
executor.analyze("select name from users order by match(name, 'bar')");
}
@Test
public void testMatchPredicateWithWrongQueryTerm() throws Exception {
var executor = SQLExecutor.builder(clusterService)
.addTable(TableDefinitions.USER_TABLE_DEFINITION)
.build();
expectedException.expect(IllegalArgumentException.class);
expectedException.expectMessage("Cannot cast expressions from type `integer_array` to type `text`");
executor.analyze("select name from users order by match(name, [10, 20])");
}
@Test
public void testSelectWhereSimpleMatchPredicate() throws Exception {
var executor = SQLExecutor.builder(clusterService)
.addTable(TableDefinitions.USER_TABLE_DEFINITION)
.build();
QueriedSelectRelation relation = executor.analyze("select * from users where match (text, 'awesome')");
assertThat(relation.where(), instanceOf(MatchPredicate.class));
MatchPredicate query = (MatchPredicate) relation.where();
assertThat(query.identBoostMap(), hasEntry(isReference("text"), isLiteral(null)));
assertThat(query.options(), isLiteral(Map.of()));
assertThat(query.queryTerm(), isLiteral("awesome"));
assertThat(query.matchType(), is("best_fields"));
}
@Test
public void testSelectWhereFullMatchPredicate() throws Exception {
var executor = SQLExecutor.builder(clusterService)
.addTable(TableDefinitions.USER_TABLE_DEFINITION)
.build();
QueriedSelectRelation relation = executor.analyze(
"select * from users " +
"where match ((name 1.2, text), 'awesome') using best_fields with (analyzer='german')");
Symbol query = relation.where();
assertThat(query, instanceOf(MatchPredicate.class));
MatchPredicate match = (MatchPredicate) query;
assertThat(match.identBoostMap(), hasEntry(isReference("name"), isLiteral(1.2)));
assertThat(match.identBoostMap(), hasEntry(isReference("text"), isLiteral(null)));
assertThat(match.queryTerm(), isLiteral("awesome"));
assertThat(match.matchType(), is("best_fields"));
assertThat(match.options(), isLiteral(Map.of("analyzer", "german")));
}
@Test
public void testWhereMatchUnknownType() throws Exception {
var executor = SQLExecutor.builder(clusterService)
.addTable(TableDefinitions.USER_TABLE_DEFINITION)
.build();
expectedException.expect(IllegalArgumentException.class);
expectedException.expectMessage("invalid MATCH type 'some_fields'");
executor.analyze("select * from users " +
"where match ((name 1.2, text), 'awesome') using some_fields");
}
@Test
public void testUnknownSubscriptInSelectList() throws Exception {
var executor = SQLExecutor.builder(clusterService)
.addTable(TableDefinitions.USER_TABLE_DEFINITION)
.build();
expectedException.expect(ColumnUnknownException.class);
expectedException.expectMessage("Column o['no_such_column'] unknown");
executor.analyze("select o['no_such_column'] from users");
}
@Test
public void testUnknownSubscriptInQuery() throws Exception {
var executor = SQLExecutor.builder(clusterService)
.addTable(TableDefinitions.USER_TABLE_DEFINITION)
.build();
expectedException.expect(ColumnUnknownException.class);
expectedException.expectMessage("Column o['no_such_column'] unknown");
executor.analyze("select * from users where o['no_such_column'] is not null");
}
@Test
public void testWhereMatchAllowedTypes() throws Exception {
var executor = SQLExecutor.builder(clusterService)
.addTable(TableDefinitions.USER_TABLE_DEFINITION)
.build();
QueriedSelectRelation best_fields_relation = executor.analyze("select * from users " +
"where match ((name 1.2, text), 'awesome') using best_fields");
QueriedSelectRelation most_fields_relation = executor.analyze("select * from users " +
"where match ((name 1.2, text), 'awesome') using most_fields");
QueriedSelectRelation cross_fields_relation = executor.analyze("select * from users " +
"where match ((name 1.2, text), 'awesome') using cross_fields");
QueriedSelectRelation phrase_relation = executor.analyze("select * from users " +
"where match ((name 1.2, text), 'awesome') using phrase");
QueriedSelectRelation phrase_prefix_relation = executor.analyze("select * from users " +
"where match ((name 1.2, text), 'awesome') using phrase_prefix");
assertThat(((MatchPredicate) best_fields_relation.where()).matchType(), is("best_fields"));
assertThat(((MatchPredicate) most_fields_relation.where()).matchType(), is("most_fields"));
assertThat(((MatchPredicate) cross_fields_relation.where()).matchType(), is("cross_fields"));
assertThat(((MatchPredicate) phrase_relation.where()).matchType(), is("phrase"));
assertThat(((MatchPredicate) phrase_prefix_relation.where()).matchType(), is("phrase_prefix"));
}
@Test
public void testWhereMatchAllOptions() throws Exception {
var executor = SQLExecutor.builder(clusterService)
.addTable(TableDefinitions.USER_TABLE_DEFINITION)
.build();
QueriedSelectRelation relation = executor.analyze("select * from users " +
"where match ((name 1.2, text), 'awesome') using best_fields with " +
"(" +
" analyzer='german'," +
" boost=4.6," +
" tie_breaker=0.75," +
" operator='or'," +
" minimum_should_match=4," +
" fuzziness=12," +
" max_expansions=3," +
" prefix_length=4," +
" rewrite='constant_score_boolean'," +
" fuzzy_rewrite='top_terms_20'," +
" zero_terms_query='all'," +
" cutoff_frequency=5," +
" slop=3" +
")");
MatchPredicate match = (MatchPredicate) relation.where();
assertThat(match.options(), isLiteral(Map.ofEntries(
Map.entry("analyzer", "german"),
Map.entry("boost", 4.6),
Map.entry("cutoff_frequency", 5),
Map.entry("fuzziness", 12),
Map.entry("fuzzy_rewrite", "top_terms_20"),
Map.entry("max_expansions", 3),
Map.entry("minimum_should_match", 4),
Map.entry("operator", "or"),
Map.entry("prefix_length", 4),
Map.entry("rewrite", "constant_score_boolean"),
Map.entry("slop", 3),
Map.entry("tie_breaker", 0.75),
Map.entry("zero_terms_query", "all")
)));
}
@Test
public void testHavingWithoutGroupBy() throws Exception {
var executor = SQLExecutor.builder(clusterService)
.addTable(TableDefinitions.USER_TABLE_DEFINITION)
.build();
expectedException.expect(IllegalArgumentException.class);
expectedException.expectMessage("HAVING clause can only be used in GROUP BY or global aggregate queries");
executor.analyze("select * from users having max(bytes) > 100");
}
@Test
public void testGlobalAggregateHaving() throws Exception {
var executor = SQLExecutor.builder(clusterService)
.addTable(TableDefinitions.USER_TABLE_DEFINITION)
.build();
QueriedSelectRelation relation = executor.analyze("select sum(floats) from users having sum(bytes) in (42, 43, 44)");
Function havingFunction = (Function) relation.having();
// assert that the in was converted to or
assertThat(havingFunction.name(), is(AnyEqOperator.NAME));
}
@Test
public void testGlobalAggregateReference() throws Exception {
var executor = SQLExecutor.builder(clusterService)
.addTable(TableDefinitions.USER_TABLE_DEFINITION)
.build();
expectedException.expect(IllegalArgumentException.class);
expectedException.expectMessage("Cannot use column bytes outside of an Aggregation in HAVING clause. Only GROUP BY keys allowed here.");
executor.analyze("select sum(floats) from users having bytes in (42, 43, 44)");
}
@Test
public void testScoreReferenceInvalidComparison() throws Exception {
var executor = SQLExecutor.builder(clusterService)
.addTable(TableDefinitions.USER_TABLE_DEFINITION)
.build();
expectedException.expect(UnsupportedOperationException.class);
expectedException.expectMessage("System column '_score' can only be used within a '>=' comparison without any surrounded predicate");
executor.analyze("select * from users where \"_score\" = 0.9");
}
@Test
public void testScoreReferenceComparisonWithColumn() throws Exception {
var executor = SQLExecutor.builder(clusterService)
.addTable(TableDefinitions.USER_TABLE_DEFINITION)
.build();
expectedException.expect(UnsupportedOperationException.class);
expectedException.expectMessage("System column '_score' can only be used within a '>=' comparison without any surrounded predicate");
executor.analyze("select * from users where \"_score\" >= id::float");
}
@Test
public void testScoreReferenceInvalidNotPredicate() throws Exception {
var executor = SQLExecutor.builder(clusterService)
.addTable(TableDefinitions.USER_TABLE_DEFINITION)
.build();
expectedException.expect(UnsupportedOperationException.class);
expectedException.expectMessage("System column '_score' can only be used within a '>=' comparison without any surrounded predicate");
executor.analyze("select * from users where not \"_score\" >= 0.9");
}
@Test
public void testScoreReferenceInvalidLikePredicate() throws Exception {
var executor = SQLExecutor.builder(clusterService)
.addTable(TableDefinitions.USER_TABLE_DEFINITION)
.build();
expectedException.expect(UnsupportedOperationException.class);
expectedException.expectMessage("System column '_score' can only be used within a '>=' comparison without any surrounded predicate");
executor.analyze("select * from users where \"_score\" in (0.9)");
}
@Test
public void testScoreReferenceInvalidNullPredicate() throws Exception {
var executor = SQLExecutor.builder(clusterService)
.addTable(TableDefinitions.USER_TABLE_DEFINITION)
.build();
expectedException.expect(UnsupportedOperationException.class);
expectedException.expectMessage("System column '_score' can only be used within a '>=' comparison without any surrounded predicate");
executor.analyze("select * from users where \"_score\" is null");
}
@Test
public void testScoreReferenceInvalidNotNullPredicate() throws Exception {
var executor = SQLExecutor.builder(clusterService)
.addTable(TableDefinitions.USER_TABLE_DEFINITION)
.build();
expectedException.expect(UnsupportedOperationException.class);
expectedException.expectMessage("System column '_score' can only be used within a '>=' comparison without any surrounded predicate");
executor.analyze("select * from users where \"_score\" is not null");
}
@Test
public void test_regex_match_on_non_string_columns_use_casts() throws Exception {
var executor = SQLExecutor.builder(clusterService)
.addTable(TableDefinitions.USER_TABLE_DEFINITION)
.build();
QueriedSelectRelation stmt = executor.analyze("select * from users where floats ~ 'foo'");
assertThat(stmt.where(), isSQL("(_cast(doc.users.floats, 'text') ~ 'foo')"));
}
@Test
public void test_case_insensitive_regex_match_uses_cast_on_non_string_col() throws Exception {
var executor = SQLExecutor.builder(clusterService)
.addTable(TableDefinitions.USER_TABLE_DEFINITION)
.build();
QueriedSelectRelation stmt = executor.analyze("select * from users where floats ~* 'foo'");
assertThat(stmt.where(), isSQL("(_cast(doc.users.floats, 'text') ~* 'foo')"));
}
@Test
public void testRegexpMatchNull() throws Exception {
var executor = SQLExecutor.builder(clusterService)
.addTable(TableDefinitions.USER_TABLE_DEFINITION)
.build();
QueriedSelectRelation relation = executor.analyze("select * from users where name ~ null");
assertThat(relation.where(), isLiteral(null));
}
@Test
public void testRegexpMatch() throws Exception {
var executor = SQLExecutor.builder(clusterService)
.addTable(TableDefinitions.USER_TABLE_DEFINITION)
.build();
QueriedSelectRelation relation = executor.analyze("select * from users where name ~ '.*foo(bar)?'");
assertThat(((Function) relation.where()).name(), is("op_~"));
}
@Test
public void testSubscriptArray() throws Exception {
var executor = SQLExecutor.builder(clusterService)
.addTable(TableDefinitions.USER_TABLE_DEFINITION)
.build();
AnalyzedRelation relation = executor.analyze("select tags[1] from users");
assertThat(relation.outputs().get(0), isFunction(SubscriptFunction.NAME));
List<Symbol> arguments = ((Function) relation.outputs().get(0)).arguments();
assertThat(arguments.size(), is(2));
assertThat(arguments.get(0), isReference("tags"));
assertThat(arguments.get(1), isLiteral(1));
}
@Test
public void testSubscriptArrayInvalidIndexMin() throws Exception {
var executor = SQLExecutor.builder(clusterService)
.addTable(TableDefinitions.USER_TABLE_DEFINITION)
.build();
expectedException.expect(UnsupportedOperationException.class);
expectedException.expectMessage("Array index must be in range 1 to 2147483648");
executor.analyze("select tags[0] from users");
}
@Test
public void testSubscriptArrayInvalidIndexMax() throws Exception {
var executor = SQLExecutor.builder(clusterService)
.addTable(TableDefinitions.USER_TABLE_DEFINITION)
.build();
expectedException.expect(UnsupportedOperationException.class);
expectedException.expectMessage("Array index must be in range 1 to 2147483648");
executor.analyze("select tags[2147483649] from users");
}
@Test
public void testSubscriptArrayNested() throws Exception {
var executor = SQLExecutor.builder(clusterService)
.addTable(TableDefinitions.DEEPLY_NESTED_TABLE_DEFINITION)
.build();
AnalyzedRelation relation = executor.analyze("select tags[1]['name'] from deeply_nested");
assertThat(relation.outputs().get(0), isFunction(SubscriptFunction.NAME));
List<Symbol> arguments = ((Function) relation.outputs().get(0)).arguments();
assertThat(arguments.size(), is(2));
assertThat(arguments.get(0), isReference("tags['name']"));
assertThat(arguments.get(1), isLiteral(1));
}
@Test
public void testSubscriptArrayInvalidNesting() throws Exception {
var executor = SQLExecutor.builder(clusterService)
.addTable(TableDefinitions.DEEPLY_NESTED_TABLE_DEFINITION)
.build();
expectedException.expect(UnsupportedOperationException.class);
expectedException.expectMessage("Nested array access is not supported");
executor.analyze("select tags[1]['metadata'][2] from deeply_nested");
}
@Test
public void testSubscriptArrayAsAlias() throws Exception {
var executor = SQLExecutor.builder(clusterService)
.addTable(TableDefinitions.USER_TABLE_DEFINITION)
.build();
AnalyzedRelation relation = executor.analyze("select tags[1] as t_alias from users");
assertThat(
relation.outputs().get(0),
isAlias(
"t_alias",
isFunction(SubscriptFunction.NAME, isReference("tags"), isLiteral(1))));
}
@Test
public void testSubscriptArrayOnScalarResult() throws Exception {
var executor = SQLExecutor.builder(clusterService)
.addTable(TableDefinitions.USER_TABLE_DEFINITION)
.build();
QueriedSelectRelation relation = executor.analyze("select regexp_matches(name, '.*')[1] as t_alias from users order by t_alias");
assertThat(
relation.outputs(),
contains(
isAlias(
"t_alias",
isFunction(
SubscriptFunction.NAME,
isFunction("regexp_matches", isReference("name"), isLiteral(".*")),
isLiteral(1)
)
)
)
);
assertThat(
relation.orderBy().orderBySymbols(),
contains(
isAlias("t_alias", isFunction(SubscriptFunction.NAME))
)
);
}
@Test
public void testParameterSubcriptColumn() throws Exception {
var executor = SQLExecutor.builder(clusterService)
.addTable(TableDefinitions.USER_TABLE_DEFINITION)
.build();
expectedException.expect(UnsupportedOperationException.class);
expectedException.expectMessage("Parameter substitution is not supported in subscript");
executor.analyze("select friends[?] from users");
}
@Test
public void testParameterSubscriptLiteral() throws Exception {
var executor = SQLExecutor.builder(clusterService)
.addTable(TableDefinitions.USER_TABLE_DEFINITION)
.build();
expectedException.expect(UnsupportedOperationException.class);
expectedException.expectMessage("Parameter substitution is not supported in subscript");
executor.analyze("select ['a','b','c'][?] from users");
}
@Test
public void testArraySubqueryExpression() throws Exception {
var executor = SQLExecutor.builder(clusterService)
.build();
AnalyzedRelation relation = executor.analyze("select array(select id from sys.shards) as shards_id_array from sys.shards");
SelectSymbol arrayProjection = (SelectSymbol) ((AliasSymbol) relation.outputs().get(0)).symbol();
assertThat(arrayProjection.getResultType(), is(SelectSymbol.ResultType.SINGLE_COLUMN_MULTIPLE_VALUES));
assertThat(arrayProjection.valueType().id(), is(ArrayType.ID));
}
@Test
public void testArraySubqueryWithMultipleColsThrowsUnsupportedSubExpression() throws Exception {
var executor = SQLExecutor.builder(clusterService)
.build();
expectedException.expect(UnsupportedOperationException.class);
expectedException.expectMessage("Subqueries with more than 1 column are not supported");
executor.analyze("select array(select id, num_docs from sys.shards) as tmp from sys.shards");
}
@Test
public void testCastExpression() throws Exception {
var executor = SQLExecutor.builder(clusterService)
.addTable(TableDefinitions.USER_TABLE_DEFINITION)
.build();
AnalyzedRelation relation = executor.analyze("select cast(other_id as text) from users");
assertThat(
relation.outputs().get(0),
isFunction(
ExplicitCastFunction.NAME,
List.of(DataTypes.LONG, DataTypes.STRING)
)
);
relation = executor.analyze("select cast(1+1 as string) from users");
assertThat(relation.outputs().get(0), isLiteral("2", DataTypes.STRING));
relation = executor.analyze("select cast(friends['id'] as array(text)) from users");
assertThat(
relation.outputs().get(0),
isFunction(
ExplicitCastFunction.NAME,
List.of(DataTypes.BIGINT_ARRAY, DataTypes.STRING_ARRAY)
)
);
}
@Test
public void testTryCastExpression() throws Exception {
var executor = SQLExecutor.builder(clusterService)
.addTable(TableDefinitions.USER_TABLE_DEFINITION)
.build();
AnalyzedRelation relation = executor.analyze("select try_cast(other_id as text) from users");
assertThat(
relation.outputs().get(0),
isFunction(
TryCastFunction.NAME,
List.of(DataTypes.LONG, DataTypes.STRING)
)
);
relation = executor.analyze("select try_cast(1+1 as string) from users");
assertThat(relation.outputs().get(0), isLiteral("2", DataTypes.STRING));
relation = executor.analyze("select try_cast(null as string) from users");
assertThat(relation.outputs().get(0), isLiteral(null, DataTypes.STRING));
relation = executor.analyze("select try_cast(counters as array(boolean)) from users");
assertThat(
relation.outputs().get(0),
isFunction(
TryCastFunction.NAME,
List.of(DataTypes.BIGINT_ARRAY, DataTypes.BOOLEAN_ARRAY)
)
);
}
@Test
public void testTryCastReturnNullWhenCastFailsOnLiterals() throws Exception {
var executor = SQLExecutor.builder(clusterService)
.addTable(TableDefinitions.USER_TABLE_DEFINITION)
.build();
AnalyzedRelation relation = executor.analyze("select try_cast('124123asdf' as integer) from users");
assertThat(relation.outputs().get(0), isLiteral(null));
relation = executor.analyze("select try_cast(['fd', '3', '5'] as array(integer)) from users");
assertThat(relation.outputs().get(0), isLiteral(Arrays.asList(null, 3, 5)));
relation = executor.analyze("select try_cast('1' as boolean) from users");
assertThat(relation.outputs().get(0), isLiteral(null));
}
@Test
public void testSelectWithAliasRenaming() throws Exception {
var executor = SQLExecutor.builder(clusterService)
.addTable(TableDefinitions.USER_TABLE_DEFINITION)
.build();
AnalyzedRelation relation = executor.analyze("select text as name, name as n from users");
assertThat(
relation.outputs(),
contains(
isAlias("name", isReference("text")),
isAlias("n", isReference("name"))
));
}
@Test
public void testFunctionArgumentsCantBeAliases() throws Exception {
var executor = SQLExecutor.builder(clusterService)
.addTable(TableDefinitions.USER_TABLE_DEFINITION)
.build();
expectedException.expect(ColumnUnknownException.class);
expectedException.expectMessage("Column n unknown");
executor.analyze("select name as n, substr(n, 1, 1) from users");
}
@Test
public void testSubscriptOnAliasShouldNotWork() throws Exception {
var executor = SQLExecutor.builder(clusterService)
.addTable(TableDefinitions.USER_TABLE_DEFINITION)
.build();
expectedException.expect(ColumnUnknownException.class);
expectedException.expectMessage("Column n unknown");
executor.analyze("select name as n, n[1] from users");
}
@Test
public void testCanSelectColumnWithAndWithoutSubscript() throws Exception {
var executor = SQLExecutor.builder(clusterService)
.addTable(TableDefinitions.USER_TABLE_DEFINITION)
.build();
AnalyzedRelation relation = executor.analyze("select counters, counters[1] from users");
Symbol counters = relation.outputs().get(0);
Symbol countersSubscript = relation.outputs().get(1);
assertThat(counters, isReference("counters"));
assertThat(countersSubscript, isFunction("subscript"));
}
@Test
public void testOrderByOnAliasWithSameColumnNameInSchema() throws Exception {
var executor = SQLExecutor.builder(clusterService)
.addTable(TableDefinitions.USER_TABLE_DEFINITION)
.build();
// name exists in the table but isn't selected so not ambiguous
QueriedSelectRelation relation = executor.analyze("select other_id as name from users order by name");
assertThat(relation.outputs(), contains(isAlias("name", isReference("other_id"))));
assertThat(relation.orderBy().orderBySymbols(), contains(isAlias("name", isReference("other_id"))));
}
@Test
public void testSelectPartitionedTableOrderBy() throws Exception {
RelationName multiPartName = new RelationName("doc", "multi_parted");
var executor = SQLExecutor.builder(clusterService)
.addPartitionedTable(
"create table doc.multi_parted (" +
" id int," +
" date timestamp with time zone," +
" num long," +
" obj object as (name string)" +
") partitioned by (date, obj['name'])",
new PartitionName(multiPartName, Arrays.asList("1395874800000", "0")).toString(),
new PartitionName(multiPartName, Arrays.asList("1395961200000", "-100")).toString(),
new PartitionName(multiPartName, Arrays.asList(null, "-100")).toString()
)
.build();
QueriedSelectRelation relation = executor.analyze(
"select id from multi_parted order by id, abs(num)");
List<Symbol> symbols = relation.orderBy().orderBySymbols();
assert symbols != null;
assertThat(symbols.size(), is(2));
assertThat(symbols.get(0), isReference("id"));
assertThat(symbols.get(1), isFunction("abs"));
}
@Test
public void testExtractFunctionWithLiteral() throws Exception {
var executor = SQLExecutor.builder(clusterService)
.addTable(TableDefinitions.USER_TABLE_DEFINITION)
.build();
AnalyzedRelation relation = executor.analyze("select extract('day' from '2012-03-24') from users");
Symbol symbol = relation.outputs().get(0);
assertThat(symbol, isLiteral(24));
}
@Test
public void testExtractFunctionWithWrongType() throws Exception {
var executor = SQLExecutor.builder(clusterService)
.addTable(TableDefinitions.USER_TABLE_DEFINITION)
.build();
AnalyzedRelation relation = executor.analyze(
"select extract(day from name::timestamp with time zone) from users");
Symbol symbol = relation.outputs().get(0);
assertThat(symbol, isFunction("extract_DAY_OF_MONTH"));
Symbol argument = ((Function) symbol).arguments().get(0);
assertThat(
argument,
isFunction(
ExplicitCastFunction.NAME,
List.of(DataTypes.STRING, DataTypes.TIMESTAMPZ)
)
);
}
@Test
public void testExtractFunctionWithCorrectType() throws Exception {
var executor = SQLExecutor.builder(clusterService)
.addTable(TableDefinitions.TEST_DOC_TRANSACTIONS_TABLE_DEFINITION)
.build();
AnalyzedRelation relation = executor.analyze("select extract(day from timestamp) from transactions");
Symbol symbol = relation.outputs().get(0);
assertThat(symbol, isFunction("extract_DAY_OF_MONTH"));
Symbol argument = ((Function) symbol).arguments().get(0);
assertThat(argument, isReference("timestamp"));
}
@Test
public void selectCurrentTimestamp() throws Exception {
var executor = SQLExecutor.builder(clusterService)
.build();
AnalyzedRelation relation = executor.analyze("select CURRENT_TIMESTAMP from sys.cluster");
assertThat(
relation.outputs(),
contains(
isFunction("current_timestamp")
)
);
}
@Test
public void testAnyRightLiteral() throws Exception {
var executor = SQLExecutor.builder(clusterService)
.build();
QueriedSelectRelation relation = executor.analyze("select id from sys.shards where id = any ([1,2])");
assertThat(relation.where(),
isFunction("any_=", List.of(DataTypes.INTEGER, new ArrayType<>(DataTypes.INTEGER))));
}
@Test
public void testNonDeterministicFunctionsAreNotAllocated() throws Exception {
var executor = SQLExecutor.builder(clusterService)
.addTable(TableDefinitions.TEST_DOC_TRANSACTIONS_TABLE_DEFINITION)
.build();
QueriedSelectRelation relation = executor.analyze(
"select random(), random(), random() " +
"from transactions " +
"where random() = 13.2 " +
"order by 1, random(), random()");
List<Symbol> outputs = relation.outputs();
List<Symbol> orderBySymbols = relation.orderBy().orderBySymbols();
// non deterministic, all equal
assertThat(outputs.get(0),
allOf(
equalTo(outputs.get(2)),
equalTo(orderBySymbols.get(1))
)
);
// different instances
assertThat(outputs.get(0), allOf(
not(Matchers.sameInstance(outputs.get(2))),
not(Matchers.sameInstance(orderBySymbols.get(1))
)));
assertThat(outputs.get(1),
equalTo(orderBySymbols.get(2)));
// "order by 1" references output 1, its the same
assertThat(outputs.get(0), is(equalTo(orderBySymbols.get(0))));
assertThat(outputs.get(0), is(Matchers.sameInstance(orderBySymbols.get(0))));
assertThat(orderBySymbols.get(0), is(equalTo(orderBySymbols.get(1))));
// check where clause
Function eqFunction = (Function) relation.where();
Symbol whereClauseSleepFn = eqFunction.arguments().get(0);
assertThat(outputs.get(0), is(equalTo(whereClauseSleepFn)));
}
@Test
public void testSelectSameTableTwice() throws Exception {
var executor = SQLExecutor.builder(clusterService)
.addTable(TableDefinitions.USER_TABLE_DEFINITION)
.build();
expectedException.expect(IllegalArgumentException.class);
expectedException.expectMessage("\"doc.users\" specified more than once in the FROM clause");
executor.analyze("select * from users, users");
}
@Test
public void testSelectSameTableTwiceWithAndWithoutSchemaName() throws Exception {
var executor = SQLExecutor.builder(clusterService)
.addTable(TableDefinitions.USER_TABLE_DEFINITION)
.build();
expectedException.expect(IllegalArgumentException.class);
expectedException.expectMessage("\"doc.users\" specified more than once in the FROM clause");
executor.analyze("select * from doc.users, users");
}
@Test
public void testSelectSameTableTwiceWithSchemaName() throws Exception {
var executor = SQLExecutor.builder(clusterService)
.build();
expectedException.expect(IllegalArgumentException.class);
expectedException.expectMessage("\"sys.nodes\" specified more than once in the FROM clause");
executor.analyze("select * from sys.nodes, sys.nodes");
}
@Test
public void testStarToFieldsInMultiSelect() throws Exception {
var executor = SQLExecutor.builder(clusterService)
.build();
AnalyzedRelation relation = executor.analyze(
"select jobs.stmt, operations.* from sys.jobs, sys.operations where jobs.id = operations.job_id");
List<Symbol> joinOutputs = relation.outputs();
AnalyzedRelation operations = executor.analyze("select * from sys.operations");
List<Symbol> operationOutputs = operations.outputs();
assertThat(joinOutputs.size(), is(operationOutputs.size() + 1));
}
@Test
public void testSelectStarWithInvalidPrefix() throws Exception {
var executor = SQLExecutor.builder(clusterService)
.build();
expectedException.expect(IllegalArgumentException.class);
expectedException.expectMessage("The relation \"foo\" is not in the FROM clause.");
executor.analyze("select foo.* from sys.operations");
}
@Test
public void testFullQualifiedStarPrefix() throws Exception {
var executor = SQLExecutor.builder(clusterService)
.build();
AnalyzedRelation relation = executor.analyze("select sys.jobs.* from sys.jobs");
List<Symbol> outputs = relation.outputs();
assertThat(outputs.size(), is(5));
assertThat(outputs, Matchers.contains(isReference("id"),
isReference("node"),
isReference("started"),
isReference("stmt"),
isReference("username"))
);
}
@Test
public void testFullQualifiedStarPrefixWithAliasForTable() throws Exception {
var executor = SQLExecutor.builder(clusterService)
.build();
expectedException.expect(IllegalArgumentException.class);
expectedException.expectMessage("The relation \"sys.operations\" is not in the FROM clause.");
executor.analyze("select sys.operations.* from sys.operations t1");
}
@Test
public void testSelectStarWithTableAliasAsPrefix() throws Exception {
var executor = SQLExecutor.builder(clusterService)
.build();
AnalyzedRelation relation = executor.analyze("select t1.* from sys.jobs t1");
List<Symbol> outputs = relation.outputs();
assertThat(outputs.size(), is(5));
assertThat(outputs, Matchers.contains(
isField("id"),
isField("node"),
isField("started"),
isField("stmt"),
isField("username"))
);
}
@Test
public void testAmbiguousStarPrefix() throws Exception {
var executor = SQLExecutor.builder(clusterService)
.addTable("create table foo.users (id bigint primary key, name text)")
.addTable(TableDefinitions.USER_TABLE_DEFINITION)
.build();
expectedException.expect(IllegalArgumentException.class);
expectedException.expectMessage("The referenced relation \"users\" is ambiguous.");
executor.analyze("select users.* from doc.users, foo.users");
}
@Test
public void testSelectMatchOnGeoShape() throws Exception {
var executor = SQLExecutor.builder(clusterService)
.addTable(TableDefinitions.USER_TABLE_DEFINITION)
.build();
QueriedSelectRelation relation = executor.analyze(
"select * from users where match(shape, 'POLYGON ((30 10, 40 40, 20 40, 10 20, 30 10))')");
assertThat(relation.where(), Matchers.instanceOf(MatchPredicate.class));
}
@Test
public void testSelectMatchOnGeoShapeObjectLiteral() throws Exception {
var executor = SQLExecutor.builder(clusterService)
.addTable(TableDefinitions.USER_TABLE_DEFINITION)
.build();
QueriedSelectRelation relation = executor.analyze(
"select * from users where match(shape, {type='Polygon', coordinates=[[[30, 10], [40, 40], [20, 40], [10, 20], [30, 10]]]})");
assertThat(relation.where(), Matchers.instanceOf(MatchPredicate.class));
}
@Test
public void testOrderByGeoShape() throws Exception {
var executor = SQLExecutor.builder(clusterService)
.addTable(TableDefinitions.USER_TABLE_DEFINITION)
.build();
expectedException.expect(UnsupportedOperationException.class);
expectedException.expectMessage("Cannot ORDER BY 'shape': invalid data type 'geo_shape'.");
executor.analyze("select * from users ORDER BY shape");
}
@Test
public void testSelectStarFromUnnest() throws Exception {
var executor = SQLExecutor.builder(clusterService)
.build();
AnalyzedRelation relation = executor.analyze("select * from unnest([1, 2], ['Marvin', 'Trillian'])");
//noinspection generics
assertThat(relation.outputs(), contains(isReference("col1"), isReference("col2")));
}
@Test
public void testSelectStarFromUnnestWithInvalidArguments() throws Exception {
var executor = SQLExecutor.builder(clusterService)
.build();
expectedException.expect(UnsupportedOperationException.class);
expectedException.expectMessage("Unknown function: unnest(1, 'foo')," +
" no overload found for matching argument types: (integer, text).");
executor.analyze("select * from unnest(1, 'foo')");
}
@Test
public void testSelectCol1FromUnnest() throws Exception {
var executor = SQLExecutor.builder(clusterService)
.build();
AnalyzedRelation relation = executor.analyze("select col1 from unnest([1, 2], ['Marvin', 'Trillian'])");
assertThat(relation.outputs(), contains(isReference("col1")));
}
@Test
public void testCollectSetCanBeUsedInHaving() throws Exception {
var executor = SQLExecutor.builder(clusterService)
.build();
QueriedSelectRelation relation = executor.analyze(
"select collect_set(recovery['size']['percent']), schema_name, table_name " +
"from sys.shards " +
"group by 2, 3 " +
"having collect_set(recovery['size']['percent']) != [100.0] " +
"order by 2, 3");
assertThat(relation.having(), notNullValue());
assertThat(relation.having(),
isSQL("(NOT (_cast(collect_set(sys.shards.recovery['size']['percent']), 'array(double precision)') = [100.0]))"));
}
@Test
public void testNegationOfNonNumericLiteralsShouldFail() throws Exception {
var executor = SQLExecutor.builder(clusterService)
.build();
expectedException.expectMessage("Cannot negate 'foo'. You may need to add explicit type casts");
executor.analyze("select - 'foo'");
}
@Test
public void testMatchInExplicitJoinConditionIsProhibited() throws Exception {
var executor = SQLExecutor.builder(clusterService)
.addTable(TableDefinitions.USER_TABLE_DEFINITION)
.build();
expectedException.expect(IllegalArgumentException.class);
expectedException.expectMessage("Cannot use MATCH predicates on columns of 2 different relations");
executor.analyze("select * from users u1 inner join users u2 on match((u1.name, u2.name), 'foo')");
}
@Test
public void testUnnestWithMoreThat10Columns() {
var executor = SQLExecutor.builder(clusterService)
.build();
AnalyzedRelation relation =
executor.analyze("select * from unnest(['a'], ['b'], [0], [0], [0], [0], [0], [0], [0], [0], [0])");
assertThat(relation.outputs(), contains(
isReference("col1"),
isReference("col2"),
isReference("col3"),
isReference("col4"),
isReference("col5"),
isReference("col6"),
isReference("col7"),
isReference("col8"),
isReference("col9"),
isReference("col10"),
isReference("col11")
));
}
@Test
public void testUnnestWithObjectColumn() {
var executor = SQLExecutor.builder(clusterService)
.build();
QueriedSelectRelation rel = executor.analyze("select col1['x'] from unnest([{x=1}])");
assertThat(rel.outputs(), contains(isFunction("subscript_obj", isReference("col1"), isLiteral("x"))));
}
@Test
public void testScalarCanBeUsedInFromClause() {
var executor = SQLExecutor.builder(clusterService)
.build();
QueriedSelectRelation relation = executor.analyze("select * from abs(1)");
assertThat(relation.outputs(), contains(isReference("abs")));
assertThat(relation.from().get(0), instanceOf(TableFunctionRelation.class));
}
@Test
public void testCannotUseSameTableNameMoreThanOnce() {
var executor = SQLExecutor.builder(clusterService)
.build();
expectedException.expect(IllegalArgumentException.class);
expectedException.expectMessage("\"abs\" specified more than once in the FROM clause");
executor.analyze("select * from abs(1), abs(5)");
}
@Test
public void testWindowFunctionCannotBeUsedInFromClause() {
var executor = SQLExecutor.builder(clusterService)
.build();
expectedException.expect(UnsupportedOperationException.class);
expectedException.expectMessage("Window or Aggregate function: 'row_number' is not allowed in function in FROM clause");
executor.analyze("select * from row_number()");
}
@Test
public void testAggregateCannotBeUsedInFromClause() {
var executor = SQLExecutor.builder(clusterService)
.build();
expectedException.expect(UnsupportedOperationException.class);
expectedException.expectMessage("Window or Aggregate function: 'count' is not allowed in function in FROM clause");
executor.analyze("select * from count()");
}
@Test
public void testSubSelectWithAccessToParentRelationThrowsUnsupportedFeature() throws Exception {
var executor = SQLExecutor.builder(clusterService)
.addTable(T3.T1_DEFINITION)
.build();
expectedException.expect(UnsupportedOperationException.class);
expectedException.expectMessage("Cannot use relation \"doc.t1\" in this context. It is only accessible in the parent context");
executor.analyze("select (select 1 from t1 as ti where ti.x = t1.x) from t1");
}
@Test
public void testSubSelectWithAccessToParentRelationAliasThrowsUnsupportedFeature() throws Exception {
var executor = SQLExecutor.builder(clusterService)
.addTable(T3.T1_DEFINITION)
.build();
expectedException.expect(UnsupportedOperationException.class);
expectedException.expectMessage("Cannot use relation \"tparent\" in this context. It is only accessible in the parent context");
executor.analyze("select (select 1 from t1 where t1.x = tparent.x) from t1 as tparent");
}
@Test
public void testSubSelectWithAccessToGrandParentRelation() throws Exception {
var executor = SQLExecutor.builder(clusterService)
.addTable(T3.T1_DEFINITION)
.build();
expectedException.expect(UnsupportedOperationException.class);
expectedException.expectMessage("Cannot use relation \"grandparent\" in this context. It is only accessible in the parent context");
executor.analyze("select (select (select 1 from t1 where grandparent.x = t1.x) from t1 as parent) from t1 as grandparent");
}
@Test
public void testCustomSchemaSubSelectWithAccessToParentRelation() throws Exception {
var executor = SQLExecutor.builder(clusterService)
.addTable(T3.T1_DEFINITION)
.build();
SQLExecutor sqlExecutor2 = SQLExecutor.builder(clusterService)
.setSearchPath("foo")
.addTable("create table foo.t1 (id bigint primary key, name text)")
.build();
expectedException.expect(UnsupportedOperationException.class);
expectedException.expectMessage("Cannot use relation \"foo.t1\" in this context. It is only accessible in the parent context");
sqlExecutor2.analyze("select * from t1 where id = (select 1 from t1 as x where x.id = t1.id)");
}
@Test
public void testContextForExplicitJoinsPrecedesImplicitJoins() throws Exception {
var executor = SQLExecutor.builder(clusterService)
.addTable(T3.T1_DEFINITION)
.addTable(T3.T2_DEFINITION)
.build();
expectedException.expect(UnsupportedOperationException.class);
expectedException.expectMessage("Cannot use relation \"doc.t1\" in this context. It is only accessible in the parent context");
// Inner join has to be processed before implicit cross join.
// Inner join does not know about t1's fields (!)
executor.analyze("select * from t1, t2 inner join t1 b on b.x = t1.x");
}
@Test
public void testColumnOutputWithSingleRowSubselect() {
var executor = SQLExecutor.builder(clusterService)
.build();
AnalyzedRelation relation = executor.analyze("select 1 = \n (select \n 2\n)\n");
assertThat(relation.outputs(), contains(
isFunction("op_=", isLiteral(1), instanceOf(SelectSymbol.class)))
);
}
@Test
public void testTableAliasIsNotAddressableByColumnNameWithSchema() throws Exception {
var executor = SQLExecutor.builder(clusterService)
.addTable(T3.T1_DEFINITION)
.build();
expectedException.expectMessage("Relation 'doc.a' unknown");
executor.analyze("select doc.a.x from t1 as a");
}
@Test
public void testUsingTableFunctionInGroupByIsProhibited() throws Exception {
var executor = SQLExecutor.builder(clusterService)
.addTable(T3.T1_DEFINITION)
.build();
expectedException.expectMessage("Table functions are not allowed in GROUP BY");
executor.analyze("select count(*) from t1 group by unnest([1])");
}
@Test
public void test_aliased_table_function_in_group_by_is_prohibited() throws Exception {
var executor = SQLExecutor.builder(clusterService).build();
assertThrowsMatches(
() -> executor.analyze("select unnest([1]) as a from sys.cluster group by 1"),
IllegalArgumentException.class,
"Table functions are not allowed in GROUP BY"
);
}
@Test
public void testUsingTableFunctionInHavingIsProhibited() throws Exception {
var executor = SQLExecutor.builder(clusterService)
.addTable(T3.T1_DEFINITION)
.build();
expectedException.expectMessage("Table functions are not allowed in HAVING");
executor.analyze("select count(*) from t1 having unnest([1]) > 1");
}
@Test
public void testUsingTableFunctionInWhereClauseIsNotAllowed() {
var executor = SQLExecutor.builder(clusterService)
.build();
expectedException.expectMessage("Table functions are not allowed in WHERE");
executor.analyze("select * from sys.nodes where unnest([1]) = 1");
}
public void testUsingWindowFunctionInGroupByIsProhibited() throws Exception {
var executor = SQLExecutor.builder(clusterService)
.addTable(T3.T1_DEFINITION)
.build();
expectedException.expectMessage("Window functions are not allowed in GROUP BY");
executor.analyze("select count(*) from t1 group by sum(1) OVER()");
}
@Test
public void testUsingWindowFunctionInHavingIsProhibited() throws Exception {
var executor = SQLExecutor.builder(clusterService)
.addTable(T3.T1_DEFINITION)
.build();
expectedException.expectMessage("Window functions are not allowed in HAVING");
executor.analyze("select count(*) from t1 having sum(1) OVER() > 1");
}
@Test
public void testUsingWindowFunctionInWhereClauseIsNotAllowed() throws Exception {
var executor = SQLExecutor.builder(clusterService)
.addTable(T3.T1_DEFINITION)
.build();
expectedException.expectMessage("Window functions are not allowed in WHERE");
executor.analyze("select count(*) from t1 where sum(1) OVER() = 1");
}
@Test
public void testCastToNestedArrayCanBeUsed() {
var executor = SQLExecutor.builder(clusterService)
.build();
AnalyzedRelation relation = executor.analyze("select [[1, 2, 3]]::array(array(int))");
assertThat(relation.outputs().get(0).valueType(), is(new ArrayType<>(DataTypes.INTEGER_ARRAY)));
}
@Test
public void testCastTimestampFromStringLiteral() {
var executor = SQLExecutor.builder(clusterService)
.build();
AnalyzedRelation relation = executor.analyze("select timestamp '2018-12-12T00:00:00'");
assertThat(relation.outputs().get(0).valueType(), is(DataTypes.TIMESTAMPZ));
}
@Test
public void testCastTimestampWithoutTimeZoneFromStringLiteralUsingSQLStandardFormat() {
var executor = SQLExecutor.builder(clusterService)
.build();
AnalyzedRelation relation = executor.analyze("select timestamp without time zone '2018-12-12 00:00:00'");
assertThat(relation.outputs().get(0).valueType(), is(DataTypes.TIMESTAMP));
}
@Test
public void test_cast_time_from_string_literal() {
var executor = SQLExecutor.builder(clusterService)
.build();
AnalyzedRelation relation = executor.analyze("select time with time zone '23:59:59.999+02'");
assertThat(relation.outputs().get(0).valueType(), is(DataTypes.TIMETZ));
assertThat(relation.outputs().get(0).toString(), is("23:59:59.999+02:00"));
relation = executor.analyze("select '23:59:59.999+02'::timetz");
assertThat(relation.outputs().get(0).valueType(), is(DataTypes.TIMETZ));
assertThat(relation.outputs().get(0).toString(), is(new TimeTZ(86399999000L, 7200).toString()));
}
@Test
public void test_element_within_object_array_of_derived_table_can_be_accessed_using_subscript() throws Exception {
var executor = SQLExecutor.builder(clusterService)
.addTable(TableDefinitions.USER_TABLE_DEFINITION)
.build();
QueriedSelectRelation relation = executor.analyze("select s.friends['id'] from (select friends from doc.users) s");
assertThat(
relation.outputs(),
contains(isField("friends['id']"))
);
}
@Test
public void test_can_access_element_within_object_array_of_derived_table_containing_a_join() throws Exception {
var executor = SQLExecutor.builder(clusterService)
.addTable(TableDefinitions.USER_TABLE_DEFINITION)
.build();
AnalyzedRelation relation = executor.analyze("select joined.f1['id'], joined.f2['id'] from " +
"(select u1.friends as f1, u2.friends as f2 from doc.users u1, doc.users u2) joined");
assertThat(relation.outputs(), contains(
isFunction(SubscriptFunction.NAME, isField("f1"), isLiteral("id")),
isFunction(SubscriptFunction.NAME, isField("f2"), isLiteral("id"))
));
}
@Test
public void test_can_access_element_within_object_array_of_derived_table_containing_a_join_with_ambiguous_column_name() throws Exception {
var executor = SQLExecutor.builder(clusterService)
.addTable(TableDefinitions.USER_TABLE_DEFINITION)
.build();
expectedException.expect(AmbiguousColumnException.class);
expectedException.expectMessage("Column \"friends['id']\" is ambiguous");
executor.analyze("select joined.friends['id'] from " +
"(select u1.friends, u2.friends from doc.users u1, doc.users u2) joined");
}
@Test
public void test_can_access_element_within_object_array_of_derived_table_containing_a_union() throws Exception {
var executor = SQLExecutor.builder(clusterService)
.addTable(TableDefinitions.USER_TABLE_DEFINITION)
.build();
AnalyzedRelation relation = executor.analyze("select joined.f1['id'] from" +
" (select friends as f1 from doc.users u1 " +
" union all" +
" select friends from doc.users u2) as joined");
assertThat(relation.outputs(), contains(
isFunction(
SubscriptFunction.NAME,
isField("f1"),
isLiteral("id")
)
));
}
@Test
public void test_select_from_unknown_schema_has_suggestion_for_correct_schema() throws Exception {
var executor = SQLExecutor.builder(clusterService)
.addTable(TableDefinitions.USER_TABLE_DEFINITION)
.build();
expectedException.expectMessage("Schema 'Doc' unknown. Maybe you meant 'doc'");
executor.analyze("select * from \"Doc\".users");
}
@Test
public void test_select_from_unkown_table_has_suggestion_for_correct_table() throws Exception {
var executor = SQLExecutor.builder(clusterService)
.addTable(TableDefinitions.USER_TABLE_DEFINITION)
.build();
expectedException.expectMessage("Relation 'uusers' unknown. Maybe you meant 'users'");
executor.analyze("select * from uusers");
}
@Test
public void test_select_from_unkown_table_has_suggestion_for_similar_tables() throws Exception {
var executor = SQLExecutor.builder(clusterService)
.addTable("create table fooobar (id bigint primary key, name text)")
.addTable("create table \"Foobaarr\" (id bigint primary key, name text)")
.build();
expectedException.expectMessage("Relation 'foobar' unknown. Maybe you meant one of: fooobar, \"Foobaarr\"");
executor.analyze("select * from foobar");
}
@Test
public void test_nested_column_of_object_can_be_selected_using_composite_type_access_syntax() throws Exception {
var executor = SQLExecutor.builder(clusterService)
.addTable(TableDefinitions.USER_TABLE_DEFINITION)
.build();
AnalyzedRelation relation = executor.analyze("select (address).postcode from users");
assertThat(relation.outputs(), contains(isReference("address['postcode']")));
}
@Test
public void test_deep_nested_column_of_object_can_be_selected_using_composite_type_access_syntax() throws Exception {
var executor = SQLExecutor.builder(clusterService)
.addTable(TableDefinitions.DEEPLY_NESTED_TABLE_DEFINITION)
.build();
AnalyzedRelation relation = executor.analyze("select ((details).stuff).name from deeply_nested");
assertThat(relation.outputs(), contains(isReference("details['stuff']['name']")));
}
@Test
public void test_record_subscript_syntax_can_be_used_on_object_literals() {
var executor = SQLExecutor.builder(clusterService)
.build();
AnalyzedRelation rel = executor.analyze("select ({x=10}).x");
assertThat(
rel.outputs(),
contains(isLiteral(10))
);
}
@Test
public void test_table_function_with_multiple_columns_in_select_list_has_row_type() {
var executor = SQLExecutor.builder(clusterService)
.build();
AnalyzedRelation rel = executor.analyze("select unnest([1, 2], [3, 4])");
assertThat(rel.outputs().get(0).valueType().getName(), is("record"));
}
@Test
public void test_select_sys_columns_on_aliased_table() throws Exception {
var executor = SQLExecutor.builder(clusterService)
.addTable(T3.T1_DEFINITION)
.build();
AnalyzedRelation rel = executor.analyze("SELECT t._score, t._id, t._version, t._score, t._uid, t._doc, t._raw, t._primary_term FROM t1 as t");
assertThat(rel.outputs().size(), is(8));
}
@Test
public void test_match_with_geo_shape_is_streamed_as_text_type_to_4_1_8_nodes() throws Exception {
var executor = SQLExecutor.builder(clusterService)
.addTable("create table test (shape GEO_SHAPE)")
.build();
String stmt = "SELECT * FROM test WHERE MATCH (shape, 'POINT(1.2 1.3)')";
QueriedSelectRelation rel = executor.analyze(stmt);
Symbol where = rel.where();
assertThat(where, instanceOf(MatchPredicate.class));
DocTableInfo table = executor.resolveTableInfo("test");
EvaluatingNormalizer normalizer = new EvaluatingNormalizer(
executor.nodeCtx,
RowGranularity.DOC,
null,
new DocTableRelation(table)
);
Symbol normalized = normalizer.normalize(where, CoordinatorTxnCtx.systemTransactionContext());
assertThat(normalized, isFunction("match"));
Function match = (Function) normalized;
assertThat(match.arguments().get(1).valueType(), is(DataTypes.GEO_SHAPE));
assertThat(match.info().ident().argumentTypes().get(1), is(DataTypes.GEO_SHAPE));
BytesStreamOutput out = new BytesStreamOutput();
out.setVersion(Version.V_4_1_8);
match.writeTo(out);
StreamInput in = out.bytes().streamInput();
in.setVersion(Version.V_4_1_8);
Function serializedTo41 = new Function(in);
assertThat(serializedTo41.info().ident().argumentTypes().get(1), is(DataTypes.STRING));
}
@Test
public void test_table_function_wrapped_inside_scalar_can_be_used_inside_group_by() {
var executor = SQLExecutor.builder(clusterService)
.build();
AnalyzedRelation rel = executor.analyze("select regexp_matches('foo', '.*')[1] from sys.cluster group by 1");
assertThat(rel.outputs().get(0).valueType().getName(), is("text"));
}
@Test
public void test_cast_expression_with_parameterized_bit() {
var executor = SQLExecutor.builder(clusterService).build();
Symbol symbol = executor.asSymbol("B'0010'::bit(3)");
assertThat(symbol, isLiteral(BitString.ofRawBits("001")));
}
@Test
public void test_cast_expression_with_parameterized_varchar() {
var executor = SQLExecutor.builder(clusterService).build();
Symbol symbol = executor.asSymbol("'foo'::varchar(2)");
assertThat(symbol, isLiteral("fo"));
}
@Test
public void test_can_resolve_index_through_aliased_relation() throws Exception {
var executor = SQLExecutor.builder(clusterService)
.addTable("create table tbl (body text, INDEX body_ft using fulltext (body))")
.build();
String statement = "select * from tbl t where match (t.body_ft, 'foo')";
QueriedSelectRelation rel = executor.analyze(statement);
assertThat(rel.outputs(), Matchers.contains(
SymbolMatchers.isField("body")
));
assertThat(
rel.where(),
TestingHelpers.isSQL("MATCH((t.body_ft NULL), 'foo') USING best_fields WITH ({})")
);
}
@Test
public void testSubscriptExpressionWithUnknownRootWithSessionSetting() throws Exception {
/*
* create table tbl (a int);
* select unknown['u'] from tbl; --> ColumnUnknownException
* set errorOnUnknownObjectKey = false;
* select unknown['u'] from tbl; --> ColumnUnknownException
*/
var executor = SQLExecutor.builder(clusterService)
.addTable("CREATE TABLE tbl (a int)")
.build();
executor.getSessionContext().setErrorOnUnknownObjectKey(true);
Asserts.assertThrowsMatches(
() -> executor.analyze("select unknown['u'] from tbl"),
ColumnUnknownException.class,
"Column unknown['u'] unknown"
);
executor.getSessionContext().setErrorOnUnknownObjectKey(false);
Asserts.assertThrowsMatches(
() -> executor.analyze("select unknown['u'] from tbl"),
ColumnUnknownException.class,
"Column unknown['u'] unknown"
);
}
@Test
public void testSubscriptExpressionWithUnknownObjectKeyWithSessionSetting() throws Exception{
/*
* CREATE TABLE tbl (obj object, obj_n object as (obj_n2 object));
* select obj['u'] from tbl; --> ColumnUnknownException
* select obj_n['obj_n2']['u'] from tbl; --> ColumnUnknownException
* set errorOnUnknownObjectKey = false;
* select obj['u'] from tbl; --> works
* select obj_n['obj_n2']['u'] from tbl; --> works
*/
var executor = SQLExecutor.builder(clusterService)
.addTable("CREATE TABLE tbl (obj object, obj_n object as (obj_n2 object))")
.build();
executor.getSessionContext().setErrorOnUnknownObjectKey(true);
Asserts.assertThrowsMatches(
() -> executor.analyze("select obj['u'] from tbl"),
ColumnUnknownException.class,
"Column obj['u'] unknown"
);
Asserts.assertThrowsMatches(
() -> executor.analyze("select obj_n['obj_n2']['u'] from tbl"),
ColumnUnknownException.class,
"Column obj_n['obj_n2']['u'] unknown"
);
executor.getSessionContext().setErrorOnUnknownObjectKey(false);
var analyzed = executor.analyze("select obj['u'] from tbl");
assertThat(analyzed.outputs().size(), is(1));
assertThat(analyzed.outputs().get(0), isVoidReference("obj['u']"));
analyzed = executor.analyze("select obj_n['obj_n2']['u'] from tbl");
assertThat(analyzed.outputs().size(), is(1));
assertThat(analyzed.outputs().get(0), isVoidReference("obj_n['obj_n2']['u']"));
}
@Test
public void testSubscriptExpressionFromSelectLiteralWithSessionSetting() throws Exception {
/*
* SELECT ''::OBJECT['x']; --> ColumnUnknownException
* set errorOnUnknownObjectKey = false;
* SELECT ''::OBJECT['x']; --> works
*/
var executor = SQLExecutor.builder(clusterService).build();
executor.getSessionContext().setErrorOnUnknownObjectKey(true);
Asserts.assertThrowsMatches(
() -> executor.analyze("SELECT ''::OBJECT['x']"),
ColumnUnknownException.class,
"The object `{}` does not contain the key `x`"
);
executor.getSessionContext().setErrorOnUnknownObjectKey(false);
var analyzed = executor.analyze("SELECT ''::OBJECT['x']");
assertThat(analyzed.outputs().size(), is(1));
assertThat(analyzed.outputs().get(0), isLiteral(null));
/*
* This is documenting a bug. If this fails, it is a breaking change.
* select (['{"x":1,"y":2}','{"y":2,"z":3}']::ARRAY(OBJECT))['x']; --> works --> bug?
* set errorOnUnknownObjectKey = false;
* select (['{"x":1,"y":2}','{"y":2,"z":3}']::ARRAY(OBJECT))['x']; --> works
*/
executor.getSessionContext().setErrorOnUnknownObjectKey(true);
analyzed = executor.analyze("select (['{\"x\":1,\"y\":2}','{\"y\":2,\"z\":3}']::ARRAY(OBJECT))['x']");
assertThat(analyzed.outputs().size(), is(1));
assertThat(analyzed.outputs().get(0).toString(), is("[1, NULL]"));
executor.getSessionContext().setErrorOnUnknownObjectKey(false);
analyzed = executor.analyze("select (['{\"x\":1,\"y\":2}','{\"y\":2,\"z\":3}']::ARRAY(OBJECT))['x']");
assertThat(analyzed.outputs().size(), is(1));
assertThat(analyzed.outputs().get(0).toString(), is("[1, NULL]"));
}
@Test
public void testRecordSubscriptWithUnknownObjectKeyWithSessionSetting() throws Exception {
/*
* This is documenting a bug. If this fails, it is a breaking change.
* CREATE TABLE tbl (obj object(dynamic));
* select (obj).y from tbl; --> works --> bug
* set errorOnUnknownObjectKey = false;
* select (obj).y from tbl; --> works
*/
var executor = SQLExecutor.builder(clusterService)
.addTable("CREATE TABLE tbl (obj object(dynamic))")
.build();
executor.getSessionContext().setErrorOnUnknownObjectKey(true);
var analyzed = executor.analyze("select (obj).y from tbl");
assertThat(analyzed.outputs().size(), is(1));
assertThat(analyzed.outputs().get(0), isFunction("subscript_obj", isReference("obj"), isLiteral("y")));
executor.getSessionContext().setErrorOnUnknownObjectKey(false);
analyzed = executor.analyze("select (obj).y from tbl");
assertThat(analyzed.outputs().size(), is(1));
assertThat(analyzed.outputs().get(0), isVoidReference("obj['y']"));
/*
* select ('{}'::object).x; --> ColumnUnknownException
* set errorOnUnknownObjectKey = false;
* select ('{}'::object).x; --> works
*/
executor.getSessionContext().setErrorOnUnknownObjectKey(true);
Asserts.assertThrowsMatches(
() -> executor.analyze("select ('{}'::object).x"),
ColumnUnknownException.class,
"The object `{}` does not contain the key `x`"
);
executor.getSessionContext().setErrorOnUnknownObjectKey(false);
analyzed = executor.analyze("select ('{}'::object).x");
assertThat(analyzed.outputs().size(), is(1));
assertThat(analyzed.outputs().get(0), isLiteral(null));
}
@Test
public void testAmbiguousSubscriptExpressionWithUnknownObjectKeyToDynamicObjectsWithSessionSetting() throws Exception {
/*
* CREATE TABLE c1 (obj_dynamic object (dynamic) as (x int))
* CREATE TABLE c2 (obj_dynamic object (dynamic) as (y int))
*
* select obj_dynamic from c1, c2 --> AmbiguousColumnException
* select obj_dynamic['x'] from c1, c2 --> works
* select obj_dynamic['y'] from c1, c2 --> works
* select obj_dynamic['z'] from c1, c2 --> AmbiguousColumnException
* set errorOnUnknownObjectKey = false;
* select obj_dynamic from c1, c2 --> AmbiguousColumnException
* select obj_dynamic['x'] from c1, c2 --> works
* select obj_dynamic['y'] from c1, c2 --> works
* select obj_dynamic['z'] from c1, c2 --> AmbiguousColumnException
*/
var executor = SQLExecutor.builder(clusterService)
.addTable("CREATE TABLE c1 (obj_dynamic object (dynamic) as (x int))")
.addTable("CREATE TABLE c2 (obj_dynamic object (dynamic) as (y int))")
.build();
executor.getSessionContext().setErrorOnUnknownObjectKey(true);
Asserts.assertThrowsMatches(
() -> executor.analyze("select obj_dynamic from c1, c2"),
AmbiguousColumnException.class,
"Column \"obj_dynamic\" is ambiguous"
);
var analyzed = executor.analyze("select obj_dynamic['x'] from c1, c2");
assertThat(analyzed.outputs().size(), is(1));
assertThat(analyzed.outputs().get(0), isReference("obj_dynamic['x']"));
analyzed = executor.analyze("select obj_dynamic['y'] from c1, c2");
assertThat(analyzed.outputs().size(), is(1));
assertThat(analyzed.outputs().get(0), isReference("obj_dynamic['y']"));
Asserts.assertThrowsMatches(
() -> executor.analyze("select obj_dynamic['z'] from c1, c2"),
AmbiguousColumnException.class,
"Column \"obj_dynamic\" is ambiguous"
);
executor.getSessionContext().setErrorOnUnknownObjectKey(false);
Asserts.assertThrowsMatches(
() -> executor.analyze("select obj_dynamic from c1, c2"),
AmbiguousColumnException.class,
"Column \"obj_dynamic\" is ambiguous"
);
analyzed = executor.analyze("select obj_dynamic['x'] from c1, c2");
assertThat(analyzed.outputs().size(), is(1));
assertThat(analyzed.outputs().get(0), isReference("obj_dynamic['x']"));
analyzed = executor.analyze("select obj_dynamic['y'] from c1, c2");
assertThat(analyzed.outputs().size(), is(1));
assertThat(analyzed.outputs().get(0), isReference("obj_dynamic['y']"));
Asserts.assertThrowsMatches(
() -> executor.analyze("select obj_dynamic['z'] from c1, c2"),
AmbiguousColumnException.class,
"Column \"obj_dynamic\" is ambiguous"
);
}
@Test
public void testAmbiguousSubscriptExpressionWithUnknownObjectKeyToStrictObjectsWithSessionSetting() throws Exception {
/*
* CREATE TABLE c1 (obj_strict object (strict) as (x int))
* CREATE TABLE c2 (obj_strict object (strict) as (y int))
*
* select obj_strict from c1, c2 --> AmbiguousColumnException
* select obj_strict['x'] from c1, c2 --> works
* select obj_strict['y'] from c1, c2 --> works
* select obj_strict['z'] from c1, c2 --> AmbiguousColumnException
* set errorOnUnknownObjectKey = false;
* select obj_strict from c1, c2 --> AmbiguousColumnException
* select obj_strict['x'] from c1, c2 --> works
* select obj_strict['y'] from c1, c2 --> works
* select obj_strict['z'] from c1, c2 --> AmbiguousColumnException
*/
var executor = SQLExecutor.builder(clusterService)
.addTable("CREATE TABLE c1 (obj_strict object (strict) as (x int))")
.addTable("CREATE TABLE c2 (obj_strict object (strict) as (y int))")
.build();
executor.getSessionContext().setErrorOnUnknownObjectKey(true);
Asserts.assertThrowsMatches(
() -> executor.analyze("select obj_strict from c1, c2"),
AmbiguousColumnException.class,
"Column \"obj_strict\" is ambiguous"
);
var analyzed = executor.analyze("select obj_strict['x'] from c1, c2");
assertThat(analyzed.outputs().size(), is(1));
assertThat(analyzed.outputs().get(0), isReference("obj_strict['x']"));
analyzed = executor.analyze("select obj_strict['y'] from c1, c2");
assertThat(analyzed.outputs().size(), is(1));
assertThat(analyzed.outputs().get(0), isReference("obj_strict['y']"));
Asserts.assertThrowsMatches(
() -> executor.analyze("select obj_strict['z'] from c1, c2"),
AmbiguousColumnException.class,
"Column \"obj_strict\" is ambiguous"
);
executor.getSessionContext().setErrorOnUnknownObjectKey(false);
Asserts.assertThrowsMatches(
() -> executor.analyze("select obj_strict from c1, c2"),
AmbiguousColumnException.class,
"Column \"obj_strict\" is ambiguous"
);
analyzed = executor.analyze("select obj_strict['x'] from c1, c2");
assertThat(analyzed.outputs().size(), is(1));
assertThat(analyzed.outputs().get(0), isReference("obj_strict['x']"));
analyzed = executor.analyze("select obj_strict['y'] from c1, c2");
assertThat(analyzed.outputs().size(), is(1));
assertThat(analyzed.outputs().get(0), isReference("obj_strict['y']"));
Asserts.assertThrowsMatches(
() -> executor.analyze("select obj_strict['z'] from c1, c2"),
AmbiguousColumnException.class,
"Column \"obj_strict\" is ambiguous"
);
}
@Test
public void testAmbiguousSubscriptExpressionWithUnknownObjectKeyToIgnoredObjectsWithSessionSetting() throws Exception {
/*
* CREATE TABLE c3 (obj_ignored object (ignored) as (x int))
* CREATE TABLE c4 (obj_ignored object (ignored) as (y int))
*
* select obj_ignored from c3, c4 --> AmbiguousColumnException
* select obj_ignored['x'] from c3, c4 --> AmbiguousColumnException
* select obj_ignored['y'] from c3, c4 --> AmbiguousColumnException
* set errorOnUnknownObjectKey = false
* select obj_ignored from c3, c4 --> AmbiguousColumnException
* select obj_ignored['x'] from c3, c4 --> AmbiguousColumnException
* select obj_ignored['y'] from c3, c4 --> AmbiguousColumnException
*/
var executor = SQLExecutor.builder(clusterService)
.addTable("CREATE TABLE c3 (obj_ignored object (ignored) as (x int))")
.addTable("CREATE TABLE c4 (obj_ignored object (ignored) as (y int))")
.build();
executor.getSessionContext().setErrorOnUnknownObjectKey(true);
Asserts.assertThrowsMatches(
() -> executor.analyze("select obj_ignored from c3, c4"),
AmbiguousColumnException.class,
"Column \"obj_ignored\" is ambiguous"
);
Asserts.assertThrowsMatches(
() -> executor.analyze("select obj_ignored['x'] from c3, c4"),
AmbiguousColumnException.class,
"Column \"obj_ignored['x']\" is ambiguous"
);
Asserts.assertThrowsMatches(
() -> executor.analyze("select obj_ignored['y'] from c3, c4"),
AmbiguousColumnException.class,
"Column \"obj_ignored['y']\" is ambiguous"
);
executor.getSessionContext().setErrorOnUnknownObjectKey(false);
Asserts.assertThrowsMatches(
() -> executor.analyze("select obj_ignored from c3, c4"),
AmbiguousColumnException.class,
"Column \"obj_ignored\" is ambiguous"
);
Asserts.assertThrowsMatches(
() -> executor.analyze("select obj_ignored['x'] from c3, c4"),
AmbiguousColumnException.class,
"Column \"obj_ignored['x']\" is ambiguous"
);
Asserts.assertThrowsMatches(
() -> executor.analyze("select obj_ignored['y'] from c3, c4"),
AmbiguousColumnException.class,
"Column \"obj_ignored['y']\" is ambiguous"
);
}
@Test
public void testSubscriptExpressionWithUnknownObjectKeyFromAliasedRelationWithSessionSetting() throws Exception {
/*
* This is documenting a bug. If this fails, it is a breaking change.
* CREATE TABLE e1 (obj_dy object, obj_st object(strict))
*
* select obj_dy['missing_key'] from (select obj_dy from e1) alias; --> works ------> bug
* select obj_st['missing_key'] from (select obj_st from e1) alias; --> works ------> bug (1)
* set errorOnUnknownObjectKey = false
* select obj_dy['missing_key'] from (select obj_dy from e1) alias; --> works ------> expected
* select obj_st['missing_key'] from (select obj_st from e1) alias; --> works ------> bug (depends on (1))
*/
var executor = SQLExecutor.builder(clusterService)
.addTable("CREATE TABLE e1 (obj_dy object, obj_st object(strict))")
.build();
executor.getSessionContext().setErrorOnUnknownObjectKey(true);
var analyzed = executor.analyze("select obj_dy['missing_key'] from (select obj_dy from e1) alias");
assertThat(analyzed.outputs().size(), is(1));
assertThat(analyzed.outputs().get(0), isFunction("subscript", isField("obj_dy"), isLiteral("missing_key")));
analyzed = executor.analyze("select obj_st['missing_key'] from (select obj_st from e1) alias");
assertThat(analyzed.outputs().size(), is(1));
assertThat(analyzed.outputs().get(0), isFunction("subscript", isField("obj_st"), isLiteral("missing_key")));
executor.getSessionContext().setErrorOnUnknownObjectKey(false);
analyzed = executor.analyze("select obj_dy['missing_key'] from (select obj_dy from e1) alias");
assertThat(analyzed.outputs().size(), is(1));
assertThat(analyzed.outputs().get(0), isVoidReference("obj_dy['missing_key']"));
analyzed = executor.analyze("select obj_st['missing_key'] from (select obj_st from e1) alias");
assertThat(analyzed.outputs().size(), is(1));
assertThat(analyzed.outputs().get(0), isFunction("subscript", isField("obj_st"), isLiteral("missing_key")));
}
@Test
public void testSubscriptExpressionFromUnionAll() throws Exception {
/*
* This is documenting a bug. If this fails, it is a breaking change.
* CREATE TABLE c1 (obj object (strict) as (a int, c int))
* CREATE TABLE c2 (obj object (dynamic) as ( b int, c int))
*
* select obj['unknown'] from (select obj from c1 union all select obj from c1) alias; --> works
* select obj['unknown'] from (select obj from c2 union all select obj from c2) alias; --> works
* select obj['a'] from (select obj from c1 union all select obj from c2) alias; --> works
* select obj['b'] from (select obj from c1 union all select obj from c2) alias; --> works
* select obj['c'] from (select obj from c1 union all select obj from c2) alias; --> works
* select obj['unknown'] from (select obj from c1 union all select obj from c2) alias; --> works
* set errorOnUnknownObjectKey = false
* select obj['unknown'] from (select obj from c1 union all select obj from c1) alias; --> works
* select obj['unknown'] from (select obj from c2 union all select obj from c2) alias; --> works
* select obj['a'] from (select obj from c1 union all select obj from c2) alias; --> works
* select obj['b'] from (select obj from c1 union all select obj from c2) alias; --> works
* select obj['c'] from (select obj from c1 union all select obj from c2) alias; --> works
* select obj['unknown'] from (select obj from c1 union all select obj from c2) alias; --> works
*/
var executor = SQLExecutor.builder(clusterService)
.addTable("CREATE TABLE c1 (obj object (strict) as (a int, c int))")
.addTable("CREATE TABLE c2 (obj object (dynamic) as ( b int, c int))")
.build();
executor.getSessionContext().setErrorOnUnknownObjectKey(true);
var analyzed = executor.analyze("select obj['unknown'] from (select obj from c1 union all select obj from c1) alias");
assertThat(analyzed.outputs().size(), is(1));
assertThat(analyzed.outputs().get(0), isFunction("subscript", isField("obj"), isLiteral("unknown")));
analyzed = executor.analyze("select obj['unknown'] from (select obj from c2 union all select obj from c2) alias");
assertThat(analyzed.outputs().size(), is(1));
assertThat(analyzed.outputs().get(0), isFunction("subscript", isField("obj"), isLiteral("unknown")));
analyzed = executor.analyze("select obj['a'] from (select obj from c1 union all select obj from c2) alias");
assertThat(analyzed.outputs().size(), is(1));
assertThat(analyzed.outputs().get(0), isFunction("subscript", isField("obj"), isLiteral("a")));
analyzed = executor.analyze("select obj['b'] from (select obj from c1 union all select obj from c2) alias");
assertThat(analyzed.outputs().size(), is(1));
assertThat(analyzed.outputs().get(0), isFunction("subscript", isField("obj"), isLiteral("b")));
analyzed = executor.analyze("select obj['c'] from (select obj from c1 union all select obj from c2) alias");
assertThat(analyzed.outputs().size(), is(1));
assertThat(analyzed.outputs().get(0), isFunction("subscript", isField("obj"), isLiteral("c")));
analyzed = executor.analyze("select obj['unknown'] from (select obj from c1 union all select obj from c2) alias");
assertThat(analyzed.outputs().size(), is(1));
assertThat(analyzed.outputs().get(0), isFunction("subscript", isField("obj"), isLiteral("unknown")));
executor.getSessionContext().setErrorOnUnknownObjectKey(false);
analyzed = executor.analyze("select obj['unknown'] from (select obj from c1 union all select obj from c1) alias");
assertThat(analyzed.outputs().size(), is(1));
assertThat(analyzed.outputs().get(0), isFunction("subscript", isField("obj"), isLiteral("unknown")));
analyzed = executor.analyze("select obj['unknown'] from (select obj from c2 union all select obj from c2) alias");
assertThat(analyzed.outputs().size(), is(1));
assertThat(analyzed.outputs().get(0), isFunction("subscript", isField("obj"), isLiteral("unknown")));
analyzed = executor.analyze("select obj['a'] from (select obj from c1 union all select obj from c2) alias");
assertThat(analyzed.outputs().size(), is(1));
assertThat(analyzed.outputs().get(0), isFunction("subscript", isField("obj"), isLiteral("a")));
analyzed = executor.analyze("select obj['b'] from (select obj from c1 union all select obj from c2) alias");
assertThat(analyzed.outputs().size(), is(1));
assertThat(analyzed.outputs().get(0), isFunction("subscript", isField("obj"), isLiteral("b")));
analyzed = executor.analyze("select obj['c'] from (select obj from c1 union all select obj from c2) alias");
assertThat(analyzed.outputs().size(), is(1));
assertThat(analyzed.outputs().get(0), isFunction("subscript", isField("obj"), isLiteral("c")));
analyzed = executor.analyze("select obj['unknown'] from (select obj from c1 union all select obj from c2) alias");
assertThat(analyzed.outputs().size(), is(1));
assertThat(analyzed.outputs().get(0), isFunction("subscript", isField("obj"), isLiteral("unknown")));
}
}
|
923f54e3bd32f99d5108abbdc553dc7a9aa5a357
| 1,631 |
java
|
Java
|
MyDay10/src/com/ecnu/web/controller/ClearCartServlet.java
|
harmansecurity/JavaWebLearning
|
f91eddc7e2d16a3d88890388ed4b2c9eb4037168
|
[
"Apache-2.0"
] | 5 |
2017-05-17T03:41:21.000Z
|
2019-03-18T07:24:31.000Z
|
MyDay10/src/com/ecnu/web/controller/ClearCartServlet.java
|
harmansecurity/JavaWebLearning
|
f91eddc7e2d16a3d88890388ed4b2c9eb4037168
|
[
"Apache-2.0"
] | null | null | null |
MyDay10/src/com/ecnu/web/controller/ClearCartServlet.java
|
harmansecurity/JavaWebLearning
|
f91eddc7e2d16a3d88890388ed4b2c9eb4037168
|
[
"Apache-2.0"
] | null | null | null | 31.365385 | 87 | 0.759044 | 1,001,118 |
package com.ecnu.web.controller;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.ecnu.domain.Cart;
import com.ecnu.service.BussinessService;
public class ClearCartServlet extends HttpServlet {
/**
* The doGet method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to get.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
Cart cart = (Cart) request.getSession().getAttribute("cart");
BussinessService service = new BussinessService();
service.clearCart(cart);
request.getRequestDispatcher("/WEB-INF/jsp/listcart.jsp").forward(request, response);
}
/**
* The doPost method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to post.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
|
923f567cb45aa2d8648d802efb1e93508ac879b1
| 7,266 |
java
|
Java
|
ihmc-interfaces/src/main/generated-java/controller_msgs/msg/dds/KinematicsToolboxCenterOfMassMessage.java
|
ihmcrobotics/ihmc-open-robotics-software
|
129b261de850e85e1dc78a12e9c075f53c6019a0
|
[
"Apache-2.0"
] | 170 |
2016-02-01T18:58:50.000Z
|
2022-03-17T05:28:01.000Z
|
ihmc-interfaces/src/main/generated-java/controller_msgs/msg/dds/KinematicsToolboxCenterOfMassMessage.java
|
ihmcrobotics/ihmc-open-robotics-software
|
129b261de850e85e1dc78a12e9c075f53c6019a0
|
[
"Apache-2.0"
] | 162 |
2016-01-29T17:04:29.000Z
|
2022-02-10T16:25:37.000Z
|
ihmc-interfaces/src/main/generated-java/controller_msgs/msg/dds/KinematicsToolboxCenterOfMassMessage.java
|
ihmcrobotics/ihmc-open-robotics-software
|
129b261de850e85e1dc78a12e9c075f53c6019a0
|
[
"Apache-2.0"
] | 83 |
2016-01-28T22:49:01.000Z
|
2022-03-28T03:11:24.000Z
| 40.592179 | 217 | 0.706303 | 1,001,119 |
package controller_msgs.msg.dds;
import us.ihmc.communication.packets.Packet;
import us.ihmc.euclid.interfaces.Settable;
import us.ihmc.euclid.interfaces.EpsilonComparable;
import java.util.function.Supplier;
import us.ihmc.pubsub.TopicDataType;
/**
* This message is part of the IHMC whole-body inverse kinematics module.
* It holds all the information needed for detailing the type of constraint to apply to the center of mass.
*/
public class KinematicsToolboxCenterOfMassMessage extends Packet<KinematicsToolboxCenterOfMassMessage> implements Settable<KinematicsToolboxCenterOfMassMessage>, EpsilonComparable<KinematicsToolboxCenterOfMassMessage>
{
/**
* Unique ID used to identify this message, should preferably be consecutively increasing.
*/
public long sequence_id_;
/**
* Specifies the desired center of mass position.
* The data is assumed to be expressed in world frame.
*/
public us.ihmc.euclid.tuple3D.Point3D desired_position_in_world_;
/**
* The selection matrix is used to determinate which degree of freedom of the center of mass
* should be controlled.
* The selection frame coming along with the given selection matrix is used to determine to what
* reference frame the selected axes are referring to. For instance, if only the hand height in
* world should be controlled on the linear z component of the selection matrix should be
* selected and the reference frame should world frame. When no reference frame is provided with
* the selection matrix, it will be used as it is in the control frame, i.e. the body-fixed frame
* if not defined otherwise.
*/
public controller_msgs.msg.dds.SelectionMatrix3DMessage selection_matrix_;
/**
* Specifies the priority of controller the position along each axis independently.
* If no frame is provided, the weight matrix will be applied in the center of mass frame which is
* aligned with the world axes.
*/
public controller_msgs.msg.dds.WeightMatrix3DMessage weights_;
public KinematicsToolboxCenterOfMassMessage()
{
desired_position_in_world_ = new us.ihmc.euclid.tuple3D.Point3D();
selection_matrix_ = new controller_msgs.msg.dds.SelectionMatrix3DMessage();
weights_ = new controller_msgs.msg.dds.WeightMatrix3DMessage();
}
public KinematicsToolboxCenterOfMassMessage(KinematicsToolboxCenterOfMassMessage other)
{
this();
set(other);
}
public void set(KinematicsToolboxCenterOfMassMessage other)
{
sequence_id_ = other.sequence_id_;
geometry_msgs.msg.dds.PointPubSubType.staticCopy(other.desired_position_in_world_, desired_position_in_world_);
controller_msgs.msg.dds.SelectionMatrix3DMessagePubSubType.staticCopy(other.selection_matrix_, selection_matrix_);
controller_msgs.msg.dds.WeightMatrix3DMessagePubSubType.staticCopy(other.weights_, weights_);
}
/**
* Unique ID used to identify this message, should preferably be consecutively increasing.
*/
public void setSequenceId(long sequence_id)
{
sequence_id_ = sequence_id;
}
/**
* Unique ID used to identify this message, should preferably be consecutively increasing.
*/
public long getSequenceId()
{
return sequence_id_;
}
/**
* Specifies the desired center of mass position.
* The data is assumed to be expressed in world frame.
*/
public us.ihmc.euclid.tuple3D.Point3D getDesiredPositionInWorld()
{
return desired_position_in_world_;
}
/**
* The selection matrix is used to determinate which degree of freedom of the center of mass
* should be controlled.
* The selection frame coming along with the given selection matrix is used to determine to what
* reference frame the selected axes are referring to. For instance, if only the hand height in
* world should be controlled on the linear z component of the selection matrix should be
* selected and the reference frame should world frame. When no reference frame is provided with
* the selection matrix, it will be used as it is in the control frame, i.e. the body-fixed frame
* if not defined otherwise.
*/
public controller_msgs.msg.dds.SelectionMatrix3DMessage getSelectionMatrix()
{
return selection_matrix_;
}
/**
* Specifies the priority of controller the position along each axis independently.
* If no frame is provided, the weight matrix will be applied in the center of mass frame which is
* aligned with the world axes.
*/
public controller_msgs.msg.dds.WeightMatrix3DMessage getWeights()
{
return weights_;
}
public static Supplier<KinematicsToolboxCenterOfMassMessagePubSubType> getPubSubType()
{
return KinematicsToolboxCenterOfMassMessagePubSubType::new;
}
@Override
public Supplier<TopicDataType> getPubSubTypePacket()
{
return KinematicsToolboxCenterOfMassMessagePubSubType::new;
}
@Override
public boolean epsilonEquals(KinematicsToolboxCenterOfMassMessage other, double epsilon)
{
if(other == null) return false;
if(other == this) return true;
if (!us.ihmc.idl.IDLTools.epsilonEqualsPrimitive(this.sequence_id_, other.sequence_id_, epsilon)) return false;
if (!this.desired_position_in_world_.epsilonEquals(other.desired_position_in_world_, epsilon)) return false;
if (!this.selection_matrix_.epsilonEquals(other.selection_matrix_, epsilon)) return false;
if (!this.weights_.epsilonEquals(other.weights_, epsilon)) return false;
return true;
}
@Override
public boolean equals(Object other)
{
if(other == null) return false;
if(other == this) return true;
if(!(other instanceof KinematicsToolboxCenterOfMassMessage)) return false;
KinematicsToolboxCenterOfMassMessage otherMyClass = (KinematicsToolboxCenterOfMassMessage) other;
if(this.sequence_id_ != otherMyClass.sequence_id_) return false;
if (!this.desired_position_in_world_.equals(otherMyClass.desired_position_in_world_)) return false;
if (!this.selection_matrix_.equals(otherMyClass.selection_matrix_)) return false;
if (!this.weights_.equals(otherMyClass.weights_)) return false;
return true;
}
@Override
public java.lang.String toString()
{
StringBuilder builder = new StringBuilder();
builder.append("KinematicsToolboxCenterOfMassMessage {");
builder.append("sequence_id=");
builder.append(this.sequence_id_); builder.append(", ");
builder.append("desired_position_in_world=");
builder.append(this.desired_position_in_world_); builder.append(", ");
builder.append("selection_matrix=");
builder.append(this.selection_matrix_); builder.append(", ");
builder.append("weights=");
builder.append(this.weights_);
builder.append("}");
return builder.toString();
}
}
|
923f567eaf6821ec45bf44702a119b01f467bf80
| 994 |
java
|
Java
|
src/main/java/cc/mrbird/common/util/qiniu/Recorder.java
|
chenshuiyong/admin7
|
7ea1b4a5e237182268ccca46a21f6cfe3c29e7c7
|
[
"MIT"
] | null | null | null |
src/main/java/cc/mrbird/common/util/qiniu/Recorder.java
|
chenshuiyong/admin7
|
7ea1b4a5e237182268ccca46a21f6cfe3c29e7c7
|
[
"MIT"
] | 1 |
2022-02-09T22:14:36.000Z
|
2022-02-09T22:14:36.000Z
|
src/main/java/cc/mrbird/common/util/qiniu/Recorder.java
|
chenshuiyong/admin7
|
7ea1b4a5e237182268ccca46a21f6cfe3c29e7c7
|
[
"MIT"
] | null | null | null | 18.754717 | 103 | 0.589537 | 1,001,120 |
package cc.mrbird.common.util.qiniu;
import java.io.File;
/**
* 定义分片上传时纪录上传进度的接口
*/
public interface Recorder {
/**
* 新建或更新文件分片上传的进度
*
* @param key 持久化的键
* @param data 持久化的内容
*/
void set(String key, byte[] data);
/**
* 获取文件分片上传的进度信息
*
* @param key 持久化的键
* @return 对应的信息
*/
byte[] get(String key);
/**
* 删除文件分片上传的进度文件
*
* @param key 持久化的键
*/
void del(String key);
/**
* 根据服务器的key和本地文件名生成持久化纪录的key
*
* @param key 服务器的key
* @param file 本地文件名
* @return 持久化上传纪录的key
*/
String recorderKeyGenerate(String key, File file);
/**
* 根据目标bucket, key和本地文件名生成持久化纪录的key
*
* @param bucket 空间名或其变换的值
* @param key 文件名或其变换的值
* @param contentDataSUID 上传内容的标识字符串
* @param uploaderSUID 上传方式的标识字符串
* @return 持久化上传纪录的key
*/
String recorderKeyGenerate(String bucket, String key, String contentDataSUID, String uploaderSUID);
}
|
923f56d6949e263fe7c4a8056c3bb0aeef4e428b
| 2,717 |
java
|
Java
|
src/main/java/cn/enilu/tool/database/doc/generator/doc/WordGenerator.java
|
enilu/database-doc-generator
|
22cb6436d57b11d6a0fd4d14ff1eabc859a3ceff
|
[
"MIT"
] | 203 |
2018-10-08T03:19:17.000Z
|
2022-03-10T06:09:49.000Z
|
src/main/java/cn/enilu/tool/database/doc/generator/doc/WordGenerator.java
|
enilu/database-doc-generator
|
22cb6436d57b11d6a0fd4d14ff1eabc859a3ceff
|
[
"MIT"
] | 8 |
2018-10-15T02:04:10.000Z
|
2020-01-06T03:19:46.000Z
|
src/main/java/cn/enilu/tool/database/doc/generator/doc/WordGenerator.java
|
enilu/database-doc-generator
|
22cb6436d57b11d6a0fd4d14ff1eabc859a3ceff
|
[
"MIT"
] | 62 |
2018-10-08T05:11:37.000Z
|
2022-03-17T07:06:41.000Z
| 30.875 | 126 | 0.578947 | 1,001,121 |
package cn.enilu.tool.database.doc.generator.doc;
import cn.enilu.tool.database.doc.generator.bean.ColumnVo;
import cn.enilu.tool.database.doc.generator.bean.Constants;
import cn.enilu.tool.database.doc.generator.bean.TableVo;
import freemarker.template.Configuration;
import freemarker.template.Template;
import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* WordGenerator
*
* @author zt
* @version 2019/1/12 0012
*/
public class WordGenerator {
private static Configuration configuration = null;
static {
configuration = new Configuration();
configuration.setDefaultEncoding("utf-8");
try {
configuration.setClassForTemplateLoading(WordGenerator.class,"/");
} catch (Exception e) {
e.printStackTrace();
}
}
private WordGenerator() {
throw new AssertionError();
}
public static void createDoc(int dbType,String dbName, List<TableVo> list) {
Map map = new HashMap();
map.put("dbName", dbName);
map.put("tables", list);
try {
Template template = configuration.getTemplate(Constants.DB_MONGO == dbType?"database-mongo.html":"database.html");
String name = dbName + "-doc" + File.separator + dbName + ".html";
File f = new File(name);
Writer w = new OutputStreamWriter(new FileOutputStream(f), "utf-8");
template.process(map, w);
w.close();
new Html2DocConverter(dbName + "-doc" + File.separator + dbName + ".html", dbName + "-doc" + File
.separator + dbName + ".doc")
.writeWordFile();
} catch (Exception ex) {
ex.printStackTrace();
}
}
public static void main(String[] args) throws Exception {
Map<String, Object> map = new HashMap<String, Object>();
List<TableVo> list = new ArrayList<>();
for (int i = 0; i < 5; i++) {
TableVo tableVo = new TableVo();
tableVo.setTable("表" + i);
tableVo.setComment("注释" + i);
List<ColumnVo> columns = new ArrayList<>();
for (int j = 0; j < 5; j++) {
ColumnVo columnVo = new ColumnVo();
columnVo.setName("name" + j);
columnVo.setComment("注释" + j);
columnVo.setKey("PRI");
columnVo.setIsNullable("是");
columnVo.setType("varchar(2");
columns.add(columnVo);
}
tableVo.setColumns(columns);
list.add(tableVo);
}
createDoc(Constants.DB_MYSQL,"test", list);
}
}
|
923f56fd45c028099170b879ff585e37631b3d39
| 2,509 |
java
|
Java
|
guava-testlib/src/com/google/common/collect/testing/ReserializingTestCollectionGenerator.java
|
hastingshuang/guava
|
7d0f06f72e9a65ee15ad93e7a2e5013704036880
|
[
"Apache-2.0"
] | 47,880 |
2015-01-01T07:04:45.000Z
|
2022-03-31T22:54:44.000Z
|
guava-testlib/src/com/google/common/collect/testing/ReserializingTestCollectionGenerator.java
|
hastingshuang/guava
|
7d0f06f72e9a65ee15ad93e7a2e5013704036880
|
[
"Apache-2.0"
] | 3,584 |
2015-01-04T05:35:27.000Z
|
2022-03-31T13:41:48.000Z
|
guava-testlib/src/com/google/common/collect/testing/ReserializingTestCollectionGenerator.java
|
Buddy119/guava
|
7581939985e53d0048d3a93cd7ca4652a99e8b08
|
[
"Apache-2.0"
] | 12,693 |
2015-01-01T01:56:07.000Z
|
2022-03-31T19:47:59.000Z
| 30.597561 | 98 | 0.746513 | 1,001,122 |
/*
* Copyright (C) 2008 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect.testing;
import com.google.common.annotations.GwtIncompatible;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.Collection;
import java.util.List;
/**
* Reserializes the sets created by another test set generator.
*
* <p>TODO: make CollectionTestSuiteBuilder test reserialized collections
*
* @author Jesse Wilson
*/
@GwtIncompatible
public class ReserializingTestCollectionGenerator<E> implements TestCollectionGenerator<E> {
private final TestCollectionGenerator<E> delegate;
ReserializingTestCollectionGenerator(TestCollectionGenerator<E> delegate) {
this.delegate = delegate;
}
public static <E> ReserializingTestCollectionGenerator<E> newInstance(
TestCollectionGenerator<E> delegate) {
return new ReserializingTestCollectionGenerator<>(delegate);
}
@Override
public Collection<E> create(Object... elements) {
return reserialize(delegate.create(elements));
}
@SuppressWarnings("unchecked")
static <T> T reserialize(T object) {
try {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
ObjectOutputStream out = new ObjectOutputStream(bytes);
out.writeObject(object);
ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(bytes.toByteArray()));
return (T) in.readObject();
} catch (IOException | ClassNotFoundException e) {
Helpers.fail(e, e.getMessage());
}
throw new AssertionError("not reachable");
}
@Override
public SampleElements<E> samples() {
return delegate.samples();
}
@Override
public E[] createArray(int length) {
return delegate.createArray(length);
}
@Override
public Iterable<E> order(List<E> insertionOrder) {
return delegate.order(insertionOrder);
}
}
|
923f5726b42044455037413c24cd650bc07c2487
| 9,054 |
java
|
Java
|
dlink-gateway/src/main/java/com/dlink/gateway/kubernetes/KubernetesGateway.java
|
chengyuan1029/dlink
|
e78f6ad01d1d426d2155de0e8cc46fcefc9e0c35
|
[
"Apache-2.0"
] | 1 |
2021-12-06T01:07:27.000Z
|
2021-12-06T01:07:27.000Z
|
dlink-gateway/src/main/java/com/dlink/gateway/kubernetes/KubernetesGateway.java
|
chengyuan1029/dlink
|
e78f6ad01d1d426d2155de0e8cc46fcefc9e0c35
|
[
"Apache-2.0"
] | null | null | null |
dlink-gateway/src/main/java/com/dlink/gateway/kubernetes/KubernetesGateway.java
|
chengyuan1029/dlink
|
e78f6ad01d1d426d2155de0e8cc46fcefc9e0c35
|
[
"Apache-2.0"
] | null | null | null | 45.727273 | 160 | 0.674509 | 1,001,123 |
package com.dlink.gateway.kubernetes;
import com.dlink.assertion.Asserts;
import com.dlink.gateway.AbstractGateway;
import com.dlink.gateway.config.ActionType;
import com.dlink.gateway.config.GatewayConfig;
import com.dlink.gateway.exception.GatewayException;
import com.dlink.gateway.model.JobInfo;
import com.dlink.gateway.result.SavePointResult;
import com.dlink.gateway.result.TestResult;
import com.dlink.utils.LogUtil;
import org.apache.flink.api.common.JobID;
import org.apache.flink.client.program.ClusterClient;
import org.apache.flink.configuration.CheckpointingOptions;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.configuration.DeploymentOptions;
import org.apache.flink.configuration.GlobalConfiguration;
import org.apache.flink.kubernetes.KubernetesClusterClientFactory;
import org.apache.flink.kubernetes.KubernetesClusterDescriptor;
import org.apache.flink.kubernetes.configuration.KubernetesConfigOptions;
import org.apache.flink.kubernetes.kubeclient.FlinkKubeClient;
import org.apache.flink.kubernetes.kubeclient.FlinkKubeClientFactory;
import org.apache.flink.runtime.client.JobStatusMessage;
import org.apache.flink.runtime.jobgraph.SavepointConfigOptions;
import java.util.*;
import java.util.concurrent.CompletableFuture;
/**
* KubernetesGateway
*
* @author wenmo
* @since 2021/12/26 14:09
*/
public abstract class KubernetesGateway extends AbstractGateway {
protected FlinkKubeClient client;
public KubernetesGateway() {
}
public KubernetesGateway(GatewayConfig config) {
super(config);
}
public void init() {
initConfig();
initKubeClient();
}
private void initConfig() {
configuration = GlobalConfiguration.loadConfiguration(config.getClusterConfig().getFlinkConfigPath());
if (Asserts.isNotNull(config.getFlinkConfig().getConfiguration())) {
addConfigParas(config.getFlinkConfig().getConfiguration());
}
configuration.set(DeploymentOptions.TARGET, getType().getLongValue());
if (Asserts.isNotNullString(config.getFlinkConfig().getSavePoint())) {
configuration.setString(SavepointConfigOptions.SAVEPOINT_PATH, config.getFlinkConfig().getSavePoint());
}
if (Asserts.isNotNullString(config.getFlinkConfig().getJobName())) {
configuration.set(KubernetesConfigOptions.CLUSTER_ID, config.getFlinkConfig().getJobName());
}
if (getType().isApplicationMode()) {
String uuid = UUID.randomUUID().toString().replace("-", "");
if (configuration.contains(CheckpointingOptions.CHECKPOINTS_DIRECTORY)) {
configuration.set(CheckpointingOptions.CHECKPOINTS_DIRECTORY, configuration.getString(CheckpointingOptions.CHECKPOINTS_DIRECTORY) + "/" + uuid);
}
if (configuration.contains(CheckpointingOptions.SAVEPOINT_DIRECTORY)) {
configuration.set(CheckpointingOptions.SAVEPOINT_DIRECTORY, configuration.getString(CheckpointingOptions.SAVEPOINT_DIRECTORY) + "/" + uuid);
}
}
}
private void initKubeClient() {
client = FlinkKubeClientFactory.getInstance().fromConfiguration(configuration, "client");
}
private void addConfigParas(Map<String, String> configMap) {
if (Asserts.isNotNull(configMap)) {
for (Map.Entry<String, String> entry : configMap.entrySet()) {
this.configuration.setString(entry.getKey(), entry.getValue());
}
}
}
public SavePointResult savepointCluster() {
return savepointCluster(null);
}
public SavePointResult savepointCluster(String savePoint) {
if (Asserts.isNull(client)) {
init();
}
SavePointResult result = SavePointResult.build(getType());
configuration.set(KubernetesConfigOptions.CLUSTER_ID, config.getClusterConfig().getAppId());
KubernetesClusterClientFactory clusterClientFactory = new KubernetesClusterClientFactory();
String clusterId = clusterClientFactory.getClusterId(configuration);
if (Asserts.isNull(clusterId)) {
throw new GatewayException("No cluster id was specified. Please specify a cluster to which you would like to connect.");
}
KubernetesClusterDescriptor clusterDescriptor = clusterClientFactory.createClusterDescriptor(configuration);
try (ClusterClient<String> clusterClient = clusterDescriptor.retrieve(
clusterId).getClusterClient()) {
List<JobInfo> jobInfos = new ArrayList<>();
CompletableFuture<Collection<JobStatusMessage>> listJobsFuture = clusterClient.listJobs();
for (JobStatusMessage jobStatusMessage : listJobsFuture.get()) {
JobInfo jobInfo = new JobInfo(jobStatusMessage.getJobId().toHexString());
jobInfo.setStatus(JobInfo.JobStatus.RUN);
jobInfos.add(jobInfo);
}
runSavePointJob(jobInfos, clusterClient, savePoint);
result.setJobInfos(jobInfos);
} catch (Exception e) {
result.fail(LogUtil.getError(e));
}
return null;
}
public SavePointResult savepointJob() {
return savepointJob(null);
}
public SavePointResult savepointJob(String savePoint) {
if (Asserts.isNull(client)) {
init();
}
if (Asserts.isNull(config.getFlinkConfig().getJobId())) {
throw new GatewayException("No job id was specified. Please specify a job to which you would like to savepont.");
}
if (Asserts.isNotNullString(config.getClusterConfig().getYarnConfigPath())) {
configuration = GlobalConfiguration.loadConfiguration(config.getClusterConfig().getYarnConfigPath());
} else {
configuration = new Configuration();
}
SavePointResult result = SavePointResult.build(getType());
configuration.set(KubernetesConfigOptions.CLUSTER_ID, config.getClusterConfig().getAppId());
KubernetesClusterClientFactory clusterClientFactory = new KubernetesClusterClientFactory();
String clusterId = clusterClientFactory.getClusterId(configuration);
if (Asserts.isNull(clusterId)) {
throw new GatewayException("No cluster id was specified. Please specify a cluster to which you would like to connect.");
}
KubernetesClusterDescriptor clusterDescriptor = clusterClientFactory.createClusterDescriptor(configuration);
try (ClusterClient<String> clusterClient = clusterDescriptor.retrieve(clusterId).getClusterClient()) {
List<JobInfo> jobInfos = new ArrayList<>();
jobInfos.add(new JobInfo(config.getFlinkConfig().getJobId(), JobInfo.JobStatus.FAIL));
runSavePointJob(jobInfos, clusterClient, savePoint);
result.setJobInfos(jobInfos);
} catch (Exception e) {
result.fail(LogUtil.getError(e));
}
return result;
}
private void runSavePointJob(List<JobInfo> jobInfos, ClusterClient<String> clusterClient, String savePoint) throws Exception {
for (JobInfo jobInfo : jobInfos) {
if (ActionType.CANCEL == config.getFlinkConfig().getAction()) {
clusterClient.cancel(JobID.fromHexString(jobInfo.getJobId()));
jobInfo.setStatus(JobInfo.JobStatus.CANCEL);
continue;
}
switch (config.getFlinkConfig().getSavePointType()) {
case TRIGGER:
CompletableFuture<String> triggerFuture = clusterClient.triggerSavepoint(JobID.fromHexString(jobInfo.getJobId()), savePoint);
jobInfo.setSavePoint(triggerFuture.get());
break;
case STOP:
CompletableFuture<String> stopFuture = clusterClient.stopWithSavepoint(JobID.fromHexString(jobInfo.getJobId()), true, savePoint);
jobInfo.setStatus(JobInfo.JobStatus.STOP);
jobInfo.setSavePoint(stopFuture.get());
break;
case CANCEL:
CompletableFuture<String> cancelFuture = clusterClient.cancelWithSavepoint(JobID.fromHexString(jobInfo.getJobId()), savePoint);
jobInfo.setStatus(JobInfo.JobStatus.CANCEL);
jobInfo.setSavePoint(cancelFuture.get());
break;
default:
}
}
}
public TestResult test() {
try {
initConfig();
} catch (Exception e) {
logger.error("测试 Flink 配置失败:" + e.getMessage());
return TestResult.fail("测试 Flink 配置失败:" + e.getMessage());
}
try {
initKubeClient();
logger.info("配置连接测试成功");
return TestResult.success();
} catch (Exception e) {
logger.error("测试 Kubernetes 配置失败:" + e.getMessage());
return TestResult.fail("测试 Kubernetes 配置失败:" + e.getMessage());
}
}
}
|
923f578e9e829a83e4d355e3bfe41d0c8bd56b6a
| 1,825 |
java
|
Java
|
BlingClockRegistration/src/com/d3bug/net/PageRepository.java
|
bitsetd4d/blingclock
|
b1ab937386dcb7726b6edade5df4c8f2d39539dd
|
[
"Apache-2.0"
] | 2 |
2020-09-14T11:26:51.000Z
|
2020-12-03T14:32:18.000Z
|
BlingClockRegistration/src/com/d3bug/net/PageRepository.java
|
schorschii/blingclock
|
b1ab937386dcb7726b6edade5df4c8f2d39539dd
|
[
"Apache-2.0"
] | 2 |
2015-10-20T10:44:31.000Z
|
2015-10-20T10:45:14.000Z
|
BlingClockRegistration/src/com/d3bug/net/PageRepository.java
|
schorschii/blingclock
|
b1ab937386dcb7726b6edade5df4c8f2d39539dd
|
[
"Apache-2.0"
] | 2 |
2020-09-14T11:26:55.000Z
|
2021-11-14T07:47:56.000Z
| 28.515625 | 105 | 0.696986 | 1,001,124 |
package com.d3bug.net;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
public class PageRepository {
private Timer timer = new Timer("PageReaderTimer",true);
private Executor executor = Executors.newSingleThreadExecutor();
private Map<String,String> urls = new HashMap<String,String>();
private Map<String,String> pageCache = new HashMap<String,String>();
private Object updateLock = new Object();
private static PageRepository INSTANCE = new PageRepository();
public static PageRepository getInstance() { return INSTANCE; }
public PageRepository() {
timer.schedule(new TimerTask() { public void run() {
refreshAllPagesInCache();
}},60 * 60 * 1000,60 * 60 * 1000);
}
protected void refreshAllPagesInCache() {
synchronized (updateLock) {
for (Map.Entry<String,String> entry : urls.entrySet()) {
readPageAndStoreInCache(entry.getKey(),entry.getValue());
}
}
}
public void registerPage(String site,String page,String url) {
String key = site + "." + page;
urls.put(key,url);
readPageAndStoreInCache(key,url);
}
private void readPageAndStoreInCache(final String key, final String url) {
Runnable r = new Runnable() {
public void run() {
try {
//System.out.println("PageRepository: Reading "+key+" --> "+url);
String page = PageReader.readPage(url);
pageCache.put(key,page);
System.out.println(new Date() + " PageRepository: Read "+key+", page was "+page.length()+" chars.");
} catch (Exception e) {
e.printStackTrace();
}
}
};
executor.execute(r);
}
public String getPage(String site,String page) {
String key = site + "." + page;
return pageCache.get(key);
}
}
|
923f57eed871304d5c92e5b3aad3b5065b0b9b0e
| 309 |
java
|
Java
|
src/L04GenericsExercises/Ex03GenericSwapMethodStrings/Box.java
|
VasAtanasov/SoftUni-Java-OOP-Advanced-July-2018
|
b66fd73aff130ccbfa2c24c4ad3bd9955186ff4b
|
[
"MIT"
] | null | null | null |
src/L04GenericsExercises/Ex03GenericSwapMethodStrings/Box.java
|
VasAtanasov/SoftUni-Java-OOP-Advanced-July-2018
|
b66fd73aff130ccbfa2c24c4ad3bd9955186ff4b
|
[
"MIT"
] | null | null | null |
src/L04GenericsExercises/Ex03GenericSwapMethodStrings/Box.java
|
VasAtanasov/SoftUni-Java-OOP-Advanced-July-2018
|
b66fd73aff130ccbfa2c24c4ad3bd9955186ff4b
|
[
"MIT"
] | null | null | null | 20.6 | 82 | 0.650485 | 1,001,125 |
package L04GenericsExercises.Ex03GenericSwapMethodStrings;
public class Box<T> {
private T element;
public Box(T element) {
this.element = element;
}
@Override
public String toString() {
return String.format("%s: %s", element.getClass().getTypeName(), element);
}
}
|
923f59381e4ba99654d9c2cbd071101551d0172f
| 16,864 |
java
|
Java
|
examples/group-data-mongo/data-mongo-supported-types/src/main/java/io/rxmicro/examples/data/mongo/supported/types/GetDataRepository.java
|
rxmicro/rxmicro-usage
|
0a34f063cb3f63171f69555ce595405160262848
|
[
"Apache-2.0"
] | 5 |
2020-03-20T12:27:25.000Z
|
2022-03-30T08:36:59.000Z
|
examples/group-data-mongo/data-mongo-supported-types/src/main/java/io/rxmicro/examples/data/mongo/supported/types/GetDataRepository.java
|
rxmicro/rxmicro-usage
|
0a34f063cb3f63171f69555ce595405160262848
|
[
"Apache-2.0"
] | 2 |
2021-11-06T10:52:06.000Z
|
2021-11-06T10:52:06.000Z
|
examples/group-data-mongo/data-mongo-supported-types/src/main/java/io/rxmicro/examples/data/mongo/supported/types/GetDataRepository.java
|
rxmicro/rxmicro-usage
|
0a34f063cb3f63171f69555ce595405160262848
|
[
"Apache-2.0"
] | null | null | null | 41.333333 | 120 | 0.346537 | 1,001,126 |
/*
* Copyright (c) 2020. https://rxmicro.io
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.rxmicro.examples.data.mongo.supported.types;
import io.rxmicro.data.Pageable;
import io.rxmicro.data.SortOrder;
import io.rxmicro.data.mongo.IndexUsage;
import io.rxmicro.data.mongo.MongoRepository;
import io.rxmicro.data.mongo.ProjectionType;
import io.rxmicro.data.mongo.operation.Aggregate;
import io.rxmicro.data.mongo.operation.CountDocuments;
import io.rxmicro.data.mongo.operation.Distinct;
import io.rxmicro.data.mongo.operation.EstimatedDocumentCount;
import io.rxmicro.data.mongo.operation.Find;
import io.rxmicro.examples.data.mongo.supported.types.model.Status;
import io.rxmicro.examples.data.mongo.supported.types.model.SupportedTypesEntity;
import org.bson.types.ObjectId;
import reactor.core.publisher.Mono;
import java.math.BigDecimal;
import java.time.Instant;
import java.util.UUID;
@MongoRepository(collection = SupportedTypesEntity.COLLECTION_NAME)
public interface GetDataRepository {
@Aggregate(
pipeline = {
"{ $match: { " +
"_id: ObjectId('507f1f77bcf86cd799439011'), " +
"status: 'created', " +
"aBoolean : true, " +
"aByte : NumberInt(127), " +
"aShort : NumberInt(500), " +
"aInteger : NumberInt(1000), " +
"aLong : NumberLong(999999999999), " +
"bigDecimal : NumberDecimal('3.14'), " +
"character : 'y', " +
"string : 'string', " +
"instant : ISODate('2020-02-02T02:20:00.000Z'), " +
"uuid : BinData(03, 'Ej5FZ+ibEtOkVlVmQkQAAA==')" +
"} }",
"{ $sort: { status: 1, _id: -1 } }",
"{ $limit: 10 }",
"{ $skip: 0 }"
},
hint = "{ _id: 1 }"
)
Mono<SupportedTypesEntity> aggregate1();
@Aggregate(
pipeline = {
"{ $match: { " +
"_id: ?, " +
"status: ?, " +
"aBoolean : ?, " +
"aByte : ?, " +
"aShort : ?, " +
"aInteger : ?, " +
"aLong : ?, " +
"bigDecimal : ?, " +
"character : ?, " +
"string : ?, " +
"instant : ?, " +
"uuid : ?" +
"} }",
"{ $sort: { status: ?, _id: ? } }",
"{ $limit: ? }",
"{ $skip: ? }"
},
hint = "{ _id: ? }"
)
Mono<SupportedTypesEntity> aggregate2(ObjectId objectId,
Status status,
boolean aBoolean,
byte aByte,
short aShort,
int aInteger,
long aLong,
BigDecimal bigDecimal,
Character character,
String string,
Instant instant,
UUID uuid,
SortOrder statusSortOrder,
SortOrder idSortOrder,
int limit,
int skip,
IndexUsage indexUsage);
@Aggregate(
pipeline = {
"{ $match: { " +
"_id: ObjectId('507f1f77bcf86cd799439011'), " +
"status: 'created', " +
"aBoolean : true, " +
"aByte : NumberInt(127), " +
"aShort : NumberInt(500), " +
"aInteger : NumberInt(1000), " +
"aLong : NumberLong(999999999999), " +
"bigDecimal : NumberDecimal('3.14'), " +
"character : 'y', " +
"string : 'string', " +
"instant : ISODate('2020-02-02T02:20:00.000Z'), " +
"uuid : BinData(03, 'Ej5FZ+ibEtOkVlVmQkQAAA==')" +
"} }",
"{ $sort: { status: 1, _id: -1 } }",
"{ $limit: ? }",
"{ $skip: ? }"
}
)
Mono<SupportedTypesEntity> aggregate3(Pageable pageable);
// -----------------------------------------------------------------------------------------------------------------
@Find(
query = "{ " +
"_id: ObjectId('507f1f77bcf86cd799439011'), " +
"status: 'created', " +
"aBoolean : true, " +
"aByte : NumberInt(127), " +
"aShort : NumberInt(500), " +
"aInteger : NumberInt(1000), " +
"aLong : NumberLong(999999999999), " +
"bigDecimal : NumberDecimal('3.14'), " +
"character : 'y', " +
"string : 'string', " +
"instant : ISODate('2020-02-02T02:20:00.000Z'), " +
"uuid : BinData(03, 'Ej5FZ+ibEtOkVlVmQkQAAA==')" +
"}",
sort = "{ status: 1, _id: -1 }",
hint = "{ _id: 1 }",
limit = 10,
skip = 0
)
Mono<SupportedTypesEntity> find1();
@Find(
query = "{ " +
"_id: ?, " +
"status: ?, " +
"aBoolean : ?, " +
"aByte : ?, " +
"aShort : ?, " +
"aInteger : ?, " +
"aLong : ?, " +
"bigDecimal : ?, " +
"character : ?, " +
"string : ?, " +
"instant : ?, " +
"uuid : ?" +
"}",
hint = "{ _id: ? }",
sort = "{ status: ?, _id: ? }"
)
Mono<SupportedTypesEntity> find2(ObjectId objectId,
Status status,
boolean aBoolean,
byte aByte,
short aShort,
int aInteger,
long aLong,
BigDecimal bigDecimal,
Character character,
String string,
Instant instant,
UUID uuid,
IndexUsage indexUsage,
SortOrder statusSortOrder,
SortOrder idSortOrder,
int limit,
int skip);
@Find(
query = "{ " +
"_id: ObjectId('507f1f77bcf86cd799439011'), " +
"status: 'created', " +
"aBoolean : true, " +
"aByte : NumberInt(127), " +
"aShort : NumberInt(500), " +
"aInteger : NumberInt(1000), " +
"aLong : NumberLong(999999999999), " +
"bigDecimal : NumberDecimal('3.14'), " +
"character : 'y', " +
"string : 'string', " +
"instant : ISODate('2020-02-02T02:20:00.000Z'), " +
"uuid : BinData(03, 'Ej5FZ+ibEtOkVlVmQkQAAA==')" +
"}",
sort = "{ status: 1, _id: -1 }"
)
Mono<SupportedTypesEntity> find3(int skip, int limit);
@Find(
query = "{ " +
"_id: ObjectId('507f1f77bcf86cd799439011'), " +
"status: 'created', " +
"aBoolean : true, " +
"aByte : NumberInt(127), " +
"aShort : NumberInt(500), " +
"aInteger : NumberInt(1000), " +
"aLong : NumberLong(999999999999), " +
"bigDecimal : NumberDecimal('3.14'), " +
"character : 'y', " +
"string : 'string', " +
"instant : ISODate('2020-02-02T02:20:00.000Z'), " +
"uuid : BinData(03, 'Ej5FZ+ibEtOkVlVmQkQAAA==')" +
"}",
sort = "{ status: 1, _id: -1 }"
)
Mono<SupportedTypesEntity> find4(Pageable pageable);
@Find(
query = "{ " +
"_id: ?, " +
"status: ?, " +
"aBoolean : ?, " +
"aByte : ?, " +
"aShort : ?, " +
"aInteger : ?, " +
"aLong : ?, " +
"bigDecimal : ?, " +
"character : ?, " +
"string : ?, " +
"instant : ?, " +
"uuid : ?" +
"}",
projection = "{ bigDecimal: ? }",
hint = "{ _id: ? }",
sort = "{ status: ?, _id: ? }"
)
Mono<SupportedTypesEntity> find5(ObjectId objectId,
Status status,
boolean aBoolean,
byte aByte,
short aShort,
int aInteger,
long aLong,
BigDecimal bigDecimal,
Character character,
String string,
Instant instant,
UUID uuid,
ProjectionType bigDecimalProjectionType,
IndexUsage indexUsage,
SortOrder statusSortOrder,
SortOrder idSortOrder,
int limit,
int skip);
// -----------------------------------------------------------------------------------------------------------------
@CountDocuments
Mono<Long> countDocuments1();
@CountDocuments(
query = "{ " +
"_id: ObjectId('507f1f77bcf86cd799439011'), " +
"status: 'created', " +
"aBoolean : true, " +
"aByte : NumberInt(127), " +
"aShort : NumberInt(500), " +
"aInteger : NumberInt(1000), " +
"aLong : NumberLong(999999999999), " +
"bigDecimal : NumberDecimal('3.14'), " +
"character : 'y', " +
"string : 'string', " +
"instant : ISODate('2020-02-02T02:20:00.000Z'), " +
"uuid : BinData(03, 'Ej5FZ+ibEtOkVlVmQkQAAA==')" +
"}",
hint = "{ _id: 1 }",
limit = 10,
skip = 0
)
Mono<Long> countDocuments2();
@CountDocuments(
hint = "{ _id: 1 }"
)
Mono<Long> countDocuments3(int skip, int limit);
@CountDocuments(
query = "{ " +
"_id: ObjectId('507f1f77bcf86cd799439011'), " +
"status: 'created', " +
"aBoolean : true, " +
"aByte : NumberInt(127), " +
"aShort : NumberInt(500), " +
"aInteger : NumberInt(1000), " +
"aLong : NumberLong(999999999999), " +
"bigDecimal : NumberDecimal('3.14'), " +
"character : 'y', " +
"string : 'string', " +
"instant : ISODate('2020-02-02T02:20:00.000Z'), " +
"uuid : BinData(03, 'Ej5FZ+ibEtOkVlVmQkQAAA==')" +
"}",
hint = "{ _id: 1 }"
)
Mono<Long> countDocuments4(Pageable pageable);
@CountDocuments(
query = "{ " +
"_id: ?, " +
"status: ?, " +
"aBoolean : ?, " +
"aByte : ?, " +
"aShort : ?, " +
"aInteger : ?, " +
"aLong : ?, " +
"bigDecimal : ?, " +
"character : ?, " +
"string : ?, " +
"instant : ?, " +
"uuid : ?" +
"}",
hint = "{ _id: ? }"
)
Mono<Long> countDocuments5(ObjectId objectId,
Status status,
boolean aBoolean,
byte aByte,
short aShort,
int aInteger,
long aLong,
BigDecimal bigDecimal,
Character character,
String string,
Instant instant,
UUID uuid,
IndexUsage indexUsage,
int limit,
int skip);
// -----------------------------------------------------------------------------------------------------------------
@EstimatedDocumentCount
Mono<Long> estimatedDocumentCount();
// -----------------------------------------------------------------------------------------------------------------
@Distinct(
field = "bigDecimal"
)
Mono<BigDecimal> distinct1();
@Distinct(
field = "bigDecimal",
query = "{ " +
"_id: ObjectId('507f1f77bcf86cd799439011'), " +
"status: 'created', " +
"aBoolean : true, " +
"aByte : NumberInt(127), " +
"aShort : NumberInt(500), " +
"aInteger : NumberInt(1000), " +
"aLong : NumberLong(999999999999), " +
"bigDecimal : NumberDecimal('3.14'), " +
"character : 'y', " +
"string : 'string', " +
"instant : ISODate('2020-02-02T02:20:00.000Z'), " +
"uuid : BinData(03, 'Ej5FZ+ibEtOkVlVmQkQAAA==')" +
"}"
)
Mono<BigDecimal> distinct2();
@Distinct(
field = "bigDecimal",
query = "{ " +
"_id: ?, " +
"status: ?, " +
"aBoolean : ?, " +
"aByte : ?, " +
"aShort : ?, " +
"aInteger : ?, " +
"aLong : ?, " +
"bigDecimal : ?, " +
"character : ?, " +
"string : ?, " +
"instant : ?, " +
"uuid : ?" +
"}"
)
Mono<BigDecimal> distinct3(ObjectId objectId,
Status status,
boolean aBoolean,
byte aByte,
short aShort,
int aInteger,
long aLong,
BigDecimal bigDecimal,
Character character,
String string,
Instant instant,
UUID uuid);
}
|
923f595b1fd832f63fbbee132d8c116ef0744ef1
| 2,133 |
java
|
Java
|
src/main/java/com/synopsys/integration/blackduck/dockerinspector/help/HelpTopicParser.java
|
yashbhutwala/blackduck-docker-inspector
|
a5b5284a3c92f996b10324a1e28e2b48ed753af2
|
[
"Apache-2.0"
] | null | null | null |
src/main/java/com/synopsys/integration/blackduck/dockerinspector/help/HelpTopicParser.java
|
yashbhutwala/blackduck-docker-inspector
|
a5b5284a3c92f996b10324a1e28e2b48ed753af2
|
[
"Apache-2.0"
] | null | null | null |
src/main/java/com/synopsys/integration/blackduck/dockerinspector/help/HelpTopicParser.java
|
yashbhutwala/blackduck-docker-inspector
|
a5b5284a3c92f996b10324a1e28e2b48ed753af2
|
[
"Apache-2.0"
] | null | null | null | 37.421053 | 159 | 0.740272 | 1,001,127 |
/**
* blackduck-docker-inspector
*
* Copyright (c) 2020 Synopsys, Inc.
*
* 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.synopsys.integration.blackduck.dockerinspector.help;
import java.util.Arrays;
import java.util.List;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
@Component
public class HelpTopicParser {
public static final String HELP_TOPIC_NAME_OVERVIEW = "overview";
public static final String HELP_TOPIC_NAME_PROPERTIES = "properties";
private static final String HELP_TOPIC_NAME_ALL = "all";
private static final String ALL_HELP_TOPICS = String.format("index,%s,architecture,quickstart,running,%s,advanced,deployment,troubleshooting,releasenotes",
HELP_TOPIC_NAME_OVERVIEW, HELP_TOPIC_NAME_PROPERTIES);
public String translateGivenTopicNames(final String givenHelpTopics) {
if (StringUtils.isBlank(givenHelpTopics)) {
return HELP_TOPIC_NAME_OVERVIEW;
}
if (HELP_TOPIC_NAME_ALL.equalsIgnoreCase(givenHelpTopics)) {
return ALL_HELP_TOPICS;
}
return givenHelpTopics;
}
public List<String> deriveHelpTopicList(final String helpTopicNames) {
if (StringUtils.isBlank(helpTopicNames)) {
return Arrays.asList("");
}
return Arrays.asList(helpTopicNames.split(","));
}
}
|
923f5a9d599953950c09cd578cd41cf340cec6d3
| 10,748 |
java
|
Java
|
proxl_web_app/src/main/java/org/yeastrc/xlink/www/webservices/QC_PeptideLength_Vs_RetentionTime_Service.java
|
yeastrc/proxl-web-app
|
79b0a75a1b449c728c33a50bce185e4ee27a8df3
|
[
"Apache-2.0"
] | 9 |
2016-04-04T21:24:57.000Z
|
2021-12-11T16:06:50.000Z
|
proxl_web_app/src/main/java/org/yeastrc/xlink/www/webservices/QC_PeptideLength_Vs_RetentionTime_Service.java
|
yeastrc/proxl-web-app
|
79b0a75a1b449c728c33a50bce185e4ee27a8df3
|
[
"Apache-2.0"
] | 16 |
2017-02-21T10:52:12.000Z
|
2021-12-13T21:46:57.000Z
|
proxl_web_app/src/main/java/org/yeastrc/xlink/www/webservices/QC_PeptideLength_Vs_RetentionTime_Service.java
|
yeastrc/proxl-web-app
|
79b0a75a1b449c728c33a50bce185e4ee27a8df3
|
[
"Apache-2.0"
] | 4 |
2017-04-17T15:30:27.000Z
|
2021-01-31T18:49:19.000Z
| 44.59751 | 189 | 0.758653 | 1,001,128 |
package org.yeastrc.xlink.www.webservices;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.LoggerFactory; import org.slf4j.Logger;
import org.yeastrc.xlink.www.access_control.result_objects.WebSessionAuthAccessLevel;
import org.yeastrc.xlink.www.qc_data.a_enums.ForDownload_Enum;
import org.yeastrc.xlink.www.qc_data.a_request_json_root.QCPageRequestJSONRoot;
import org.yeastrc.xlink.www.qc_data.psm_level_data.main.PeptideLength_Vs_RT_ScatterPlot_For_PSMPeptideCutoffs;
import org.yeastrc.xlink.www.qc_data.psm_level_data.main.PeptideLength_Vs_RT_ScatterPlot_For_PSMPeptideCutoffs.PeptideLength_Vs_RT_ScatterPlot_For_PSMPeptideCutoffs_Method_Response;
import org.yeastrc.xlink.www.qc_data.psm_level_data.objects.PeptideLength_Vs_RT_ScatterPlot_For_PSMPeptideCutoffsResults;
import org.yeastrc.xlink.www.qc_data.utils.QC_DeserializeRequestJSON_To_QCPageRequestJSONRoot;
import org.yeastrc.xlink.www.searcher.ProjectIdsForProjectSearchIdsSearcher;
import org.yeastrc.xlink.www.constants.WebServiceErrorMessageConstants;
import org.yeastrc.xlink.www.dao.SearchDAO;
import org.yeastrc.xlink.www.dto.SearchDTO;
import org.yeastrc.xlink.www.exceptions.ProxlWebappDataException;
import org.yeastrc.xlink.www.form_query_json_objects.QCPageQueryJSONRoot;
import org.yeastrc.xlink.www.access_control.access_control_main.GetWebSessionAuthAccessLevelForProjectIds_And_NO_ProjectId.GetWebSessionAuthAccessLevelForProjectIds_And_NO_ProjectId_Result;
import org.yeastrc.xlink.www.access_control.access_control_main.GetWebSessionAuthAccessLevelForProjectIds_And_NO_ProjectId;
@Path("/qc/dataPage")
public class QC_PeptideLength_Vs_RetentionTime_Service {
private static final Logger log = LoggerFactory.getLogger( QC_PeptideLength_Vs_RetentionTime_Service.class);
/**
*
* Only 1 projectSearchId is allowed
*
* @param projectSearchIdList
* @param filterCriteria_JSONString
* @param request
* @return
* @throws Exception
*/
@POST
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@Path("/peptideLengthVsRetentionTime")
public WebserviceResult
getPPM_Error_Histogram_For_PSMPeptideCutoffs(
byte[] requestJSONBytes,
@Context HttpServletRequest request )
throws Exception {
if ( requestJSONBytes == null || requestJSONBytes.length == 0 ) {
String msg = "requestJSONBytes is null or requestJSONBytes is empty";
log.error( msg );
throw new WebApplicationException(
Response.status(javax.ws.rs.core.Response.Status.BAD_REQUEST) // return 400 error
// .entity( )
.build()
);
}
QCPageRequestJSONRoot qcPageRequestJSONRoot = null;
try {
qcPageRequestJSONRoot =
QC_DeserializeRequestJSON_To_QCPageRequestJSONRoot.getInstance().deserializeRequestJSON_To_QCPageRequestJSONRoot( requestJSONBytes );
} catch ( Exception e ) {
String msg = "parse request failed";
log.warn( msg );
throw new WebApplicationException(
Response.status(javax.ws.rs.core.Response.Status.BAD_REQUEST) // return 400 error
// .entity( )
.build()
);
}
List<Integer> projectSearchIdList = qcPageRequestJSONRoot.getProjectSearchIds();
QCPageQueryJSONRoot qcPageQueryJSONRoot = qcPageRequestJSONRoot.getQcPageQueryJSONRoot();
if ( projectSearchIdList == null || projectSearchIdList.isEmpty() ) {
String msg = "Provided project_search_id is null or project_search_id is missing";
log.error( msg );
throw new WebApplicationException(
Response.status(javax.ws.rs.core.Response.Status.BAD_REQUEST) // return 400 error
.entity( msg )
.build()
);
}
if ( qcPageQueryJSONRoot == null ) {
String msg = "qcPageQueryJSONRoot is null or qcPageQueryJSONRoot is missing";
log.error( msg );
throw new WebApplicationException(
Response.status(javax.ws.rs.core.Response.Status.BAD_REQUEST) // return 400 error
.entity( msg )
.build()
);
}
if ( projectSearchIdList.size() > 1 ) {
String msg = "Only 1 project_search_id is allowed";
log.error( msg );
throw new WebApplicationException(
Response.status(javax.ws.rs.core.Response.Status.BAD_REQUEST) // return 400 error
.entity( msg )
.build()
);
}
int projectSearchId = projectSearchIdList.get( 0 ); // Only 1
try {
// Get the project id for this search
// Get the project id for these searches
Set<Integer> projectSearchIdsSet = new HashSet<Integer>( );
projectSearchIdsSet.add( projectSearchId );
List<Integer> projectSearchIdsListDeduppedSorted = new ArrayList<>( projectSearchIdsSet );
Collections.sort( projectSearchIdsListDeduppedSorted );
List<Integer> projectIdsFromProjectSearchIds =
ProjectIdsForProjectSearchIdsSearcher.getInstance().getProjectIdsForProjectSearchIds( projectSearchIdsSet );
if ( projectIdsFromProjectSearchIds.isEmpty() ) {
// should never happen
@SuppressWarnings("unchecked")
String msg = "No project ids for project search ids: " + StringUtils.join( projectSearchIdList );
log.error( msg );
throw new WebApplicationException(
Response.status( WebServiceErrorMessageConstants.INVALID_SEARCH_LIST_NOT_IN_DB_STATUS_CODE ) // Send HTTP code
.entity( WebServiceErrorMessageConstants.INVALID_SEARCH_LIST_NOT_IN_DB_TEXT ) // This string will be passed to the client
.build()
);
}
if ( projectIdsFromProjectSearchIds.size() > 1 ) {
// Invalid request, searches across projects
throw new WebApplicationException(
Response.status( WebServiceErrorMessageConstants.INVALID_SEARCH_LIST_ACROSS_PROJECTS_STATUS_CODE ) // Send HTTP code
.entity( WebServiceErrorMessageConstants.INVALID_SEARCH_LIST_ACROSS_PROJECTS_TEXT ) // This string will be passed to the client
.build()
);
}
int projectId = projectIdsFromProjectSearchIds.get( 0 );
GetWebSessionAuthAccessLevelForProjectIds_And_NO_ProjectId_Result accessAndSetupWebSessionResult =
GetWebSessionAuthAccessLevelForProjectIds_And_NO_ProjectId.getSinglesonInstance().getAccessAndSetupWebSessionWithProjectId( projectId, request );
// UserSession userSession = accessAndSetupWebSessionResult.getUserSession();
// Test access to the project id
WebSessionAuthAccessLevel authAccessLevel = accessAndSetupWebSessionResult.getWebSessionAuthAccessLevel();
if ( ! authAccessLevel.isPublicAccessCodeReadAllowed() ) {
if ( accessAndSetupWebSessionResult.isNoSession() ) {
// No User session
throw new WebApplicationException(
Response.status( WebServiceErrorMessageConstants.NO_SESSION_STATUS_CODE ) // Send HTTP code
.entity( WebServiceErrorMessageConstants.NO_SESSION_TEXT ) // This string will be passed to the client
.build()
);
}
// No Access Allowed for this project id
throw new WebApplicationException(
Response.status( WebServiceErrorMessageConstants.NOT_AUTHORIZED_STATUS_CODE ) // Send HTTP code
.entity( WebServiceErrorMessageConstants.NOT_AUTHORIZED_TEXT ) // This string will be passed to the client
.build()
);
}
//////// Auth complete
//////////////////////////////////////////
SearchDTO search = SearchDAO.getInstance().getSearchFromProjectSearchId( projectSearchId );
if ( search == null ) {
String msg = "projectSearchId '" + projectSearchId + "' not found in the database. User taken to home page.";
log.warn( msg );
// Search not found, the data on the page they are requesting does not exist.
throw new WebApplicationException(
Response.status(javax.ws.rs.core.Response.Status.BAD_REQUEST) // return 400 error
.entity( msg )
.build()
);
}
PeptideLength_Vs_RT_ScatterPlot_For_PSMPeptideCutoffs_Method_Response peptideLength_Vs_RT_ScatterPlot_For_PSMPeptideCutoffs_Method_Response =
PeptideLength_Vs_RT_ScatterPlot_For_PSMPeptideCutoffs.getInstance()
.getPeptideLength_Vs_RT_ScatterPlot_For_PSMPeptideCutoffs(
ForDownload_Enum.NO,
qcPageQueryJSONRoot, search );
PeptideLength_Vs_RT_ScatterPlot_For_PSMPeptideCutoffsResults peptideLength_Vs_RT_ScatterPlot_For_PSMPeptideCutoffsResults =
peptideLength_Vs_RT_ScatterPlot_For_PSMPeptideCutoffs_Method_Response.getPeptideLength_Vs_RT_ScatterPlot_For_PSMPeptideCutoffsResults();
// Get for cutoffs and other data
WebserviceResult serviceResult = new WebserviceResult();
serviceResult.peptideLength_Vs_RT_ScatterPlot_For_PSMPeptideCutoffsResults = peptideLength_Vs_RT_ScatterPlot_For_PSMPeptideCutoffsResults;
return serviceResult;
} catch ( WebApplicationException e ) {
throw e;
} catch ( ProxlWebappDataException e ) {
String msg = "Exception processing request data, msg: " + e.toString();
log.error( msg, e );
throw new WebApplicationException(
Response.status(javax.ws.rs.core.Response.Status.BAD_REQUEST) // return 400 error
.entity( msg )
.build()
);
} catch ( Exception e ) {
String msg = "Exception caught: " + e.toString();
log.error( msg, e );
throw new WebApplicationException(
Response.status( WebServiceErrorMessageConstants.INTERNAL_SERVER_ERROR_STATUS_CODE ) // Send HTTP code
.entity( WebServiceErrorMessageConstants.INTERNAL_SERVER_ERROR_TEXT ) // This string will be passed to the client
.build()
);
}
}
/**
*
*
*/
public static class WebserviceResult {
PeptideLength_Vs_RT_ScatterPlot_For_PSMPeptideCutoffsResults peptideLength_Vs_RT_ScatterPlot_For_PSMPeptideCutoffsResults;
public PeptideLength_Vs_RT_ScatterPlot_For_PSMPeptideCutoffsResults getPeptideLength_Vs_RT_ScatterPlot_For_PSMPeptideCutoffsResults() {
return peptideLength_Vs_RT_ScatterPlot_For_PSMPeptideCutoffsResults;
}
public void setPeptideLength_Vs_RT_ScatterPlot_For_PSMPeptideCutoffsResults(
PeptideLength_Vs_RT_ScatterPlot_For_PSMPeptideCutoffsResults peptideLength_Vs_RT_ScatterPlot_For_PSMPeptideCutoffsResults) {
this.peptideLength_Vs_RT_ScatterPlot_For_PSMPeptideCutoffsResults = peptideLength_Vs_RT_ScatterPlot_For_PSMPeptideCutoffsResults;
}
}
}
|
923f5b2c9adf348823f4acecc7a620c634f66b60
| 1,442 |
java
|
Java
|
analysis/reverse-engineering/decompile-fitts-with-gradle-20191031-2200/src/main/java/jp/wasabeef/glide/transformations/R$styleable.java
|
skkuse-adv/2019Fall_team2
|
3ea84c6be39855f54634a7f9b1093e80893886eb
|
[
"Apache-2.0"
] | 4 |
2019-10-07T05:17:21.000Z
|
2020-11-02T08:29:13.000Z
|
analysis/reverse-engineering/decompile-fitts-with-gradle-20191031-2200/src/main/java/jp/wasabeef/glide/transformations/R$styleable.java
|
skkuse-adv/2019Fall_team2
|
3ea84c6be39855f54634a7f9b1093e80893886eb
|
[
"Apache-2.0"
] | 38 |
2019-10-07T02:40:35.000Z
|
2019-12-12T09:15:24.000Z
|
analysis/reverse-engineering/decompile-fitts-20191031-2200/sources/jp/wasabeef/glide/transformations/R$styleable.java
|
skkuse-adv/2019Fall_team2
|
3ea84c6be39855f54634a7f9b1093e80893886eb
|
[
"Apache-2.0"
] | 5 |
2019-10-07T02:41:15.000Z
|
2020-10-30T01:36:08.000Z
| 55.461538 | 159 | 0.771845 | 1,001,129 |
package jp.wasabeef.glide.transformations;
public final class R$styleable {
public static final int[] FontFamily = {2130968886, 2130968887, 2130968888, 2130968889, 2130968890, 2130968891};
public static final int[] FontFamilyFont = {16844082, 16844083, 16844095, 16844143, 16844144, 2130968884, 2130968892, 2130968893, 2130968894, 2130969262};
public static final int FontFamilyFont_android_font = 0;
public static final int FontFamilyFont_android_fontStyle = 2;
public static final int FontFamilyFont_android_fontVariationSettings = 4;
public static final int FontFamilyFont_android_fontWeight = 1;
public static final int FontFamilyFont_android_ttcIndex = 3;
public static final int FontFamilyFont_font = 5;
public static final int FontFamilyFont_fontStyle = 6;
public static final int FontFamilyFont_fontVariationSettings = 7;
public static final int FontFamilyFont_fontWeight = 8;
public static final int FontFamilyFont_ttcIndex = 9;
public static final int FontFamily_fontProviderAuthority = 0;
public static final int FontFamily_fontProviderCerts = 1;
public static final int FontFamily_fontProviderFetchStrategy = 2;
public static final int FontFamily_fontProviderFetchTimeout = 3;
public static final int FontFamily_fontProviderPackage = 4;
public static final int FontFamily_fontProviderQuery = 5;
private R$styleable() {
}
}
|
923f5d510970247d55329da2dc5ff5dea2102588
| 260 |
java
|
Java
|
src/test/java/org/sif/beans/ApplicationContextTestConfigurer.java
|
carloseugenio/sif.beans
|
cee98ba90d1d4a20b3281e943a6ed03b7dd313f0
|
[
"Apache-2.0"
] | 1 |
2019-09-10T22:27:40.000Z
|
2019-09-10T22:27:40.000Z
|
src/test/java/org/sif/beans/ApplicationContextTestConfigurer.java
|
carloseugenio/sif.beans
|
cee98ba90d1d4a20b3281e943a6ed03b7dd313f0
|
[
"Apache-2.0"
] | null | null | null |
src/test/java/org/sif/beans/ApplicationContextTestConfigurer.java
|
carloseugenio/sif.beans
|
cee98ba90d1d4a20b3281e943a6ed03b7dd313f0
|
[
"Apache-2.0"
] | null | null | null | 23.636364 | 60 | 0.838462 | 1,001,130 |
package org.sif.beans;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
@Configuration
@ComponentScan(basePackages = "org.sif.beans")
public class ApplicationContextTestConfigurer {
}
|
923f5daf4ed5ee45f91dbc9e8641e742679af6f9
| 2,288 |
java
|
Java
|
src/org/eclipse/recommenders/jayes/util/Graph.java
|
DataSciBurgoon/bisct
|
d644864d72a02bff4b82df6f7bb027c76739a789
|
[
"Apache-2.0"
] | null | null | null |
src/org/eclipse/recommenders/jayes/util/Graph.java
|
DataSciBurgoon/bisct
|
d644864d72a02bff4b82df6f7bb027c76739a789
|
[
"Apache-2.0"
] | 4 |
2017-07-13T15:32:49.000Z
|
2019-07-24T13:03:42.000Z
|
src/org/eclipse/recommenders/jayes/util/Graph.java
|
DataSciBurgoon/bisct
|
d644864d72a02bff4b82df6f7bb027c76739a789
|
[
"Apache-2.0"
] | null | null | null | 26.604651 | 79 | 0.593531 | 1,001,131 |
/**
* Copyright (c) 2011 Michael Kutschke.
* 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:
* Michael Kutschke - initial API and implementation.
*/
package org.eclipse.recommenders.jayes.util;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* undirected graph
*/
public class Graph implements Cloneable {
private final ArrayList<Integer>[] adjacency;
public int numberOfVertices() {
return adjacency.length;
}
@SuppressWarnings("unchecked")
public Graph(final int nodes) {
adjacency = new ArrayList[nodes];
for (int i = 0; i < nodes; i++) {
adjacency[i] = new ArrayList<Integer>();
}
}
public void addEdge(final int v1, final int v2) {
addOrdered(adjacency[v1], v2);
addOrdered(adjacency[v2], v1);
}
private void addOrdered(List<Integer> list, int v2) {
int i = Collections.binarySearch(list, v2);
if (i < 0) {
list.add(-i - 1, v2);
}
}
public void removeEdge(final int v1, final int v2) {
removeOrdered(adjacency[v1], v2);
removeOrdered(adjacency[v2], v1);
}
private void removeOrdered(List<Integer> list, int v2) {
int i = Collections.binarySearch(list, v2);
if (i >= 0) {
list.remove(i);
}
}
public void removeIncidentEdges(int v) {
for (int n : adjacency[v]) {
removeOrdered(adjacency[n], v);
}
adjacency[v].clear();
}
public List<Integer> getNeighbors(int var) {
return adjacency[var];
}
@SuppressWarnings("unchecked")
@Override
public Graph clone() {
try {
Graph clone = (Graph) super.clone();
for (int i = 0; i < adjacency.length; i++) {
clone.adjacency[i] = (ArrayList<Integer>) adjacency[i].clone();
}
return clone;
} catch (CloneNotSupportedException e) {
// should not happen
throw new AssertionError(e);
}
}
}
|
923f5f756e8f04a7c54bc641a0b96db6affa8454
| 1,157 |
java
|
Java
|
src/com/shop/mapper/OrdersMapper.java
|
2995090067/SSMShop
|
e40c3e77462a01c1d30c5645b2b995b521106db7
|
[
"MIT"
] | null | null | null |
src/com/shop/mapper/OrdersMapper.java
|
2995090067/SSMShop
|
e40c3e77462a01c1d30c5645b2b995b521106db7
|
[
"MIT"
] | null | null | null |
src/com/shop/mapper/OrdersMapper.java
|
2995090067/SSMShop
|
e40c3e77462a01c1d30c5645b2b995b521106db7
|
[
"MIT"
] | null | null | null | 26.295455 | 106 | 0.769231 | 1,001,132 |
package com.shop.mapper;
import java.util.List;
import org.apache.ibatis.annotations.Param;
import com.shop.po.Orders;
import com.shop.po.OrdersExample;
public interface OrdersMapper {
int countByExample(OrdersExample example);
int deleteByExample(OrdersExample example);
int deleteByPrimaryKey(Integer oid);
int insert(Orders record);
int insertSelective(Orders record);
List<Orders> selectByExample(OrdersExample example);
Orders selectByPrimaryKey(Integer oid);
int updateByExampleSelective(@Param("record") Orders record, @Param("example") OrdersExample example);
int updateByExample(@Param("record") Orders record, @Param("example") OrdersExample example);
int updateByPrimaryKeySelective(Orders record);
int updateByPrimaryKey(Orders record);
int countOrdersByUid(Integer uid);
//根据订单状态,查询符合条件的记录条数
int countOrdersByState(Integer state);
//全部订单记录数
int countAllOrders();
List<Orders> findOrderByUidAndPage(Integer uid, int page, int limitPage);
List<Orders> findAllOrderByPage(int page, int limitPage);
List<Orders> findAllOrderByStateAndPage(int state,int page, int limitPage);
}
|
923f5fa75d440cacd88389942f1f9c43d3472c8a
| 357 |
java
|
Java
|
src/testFixtures/java/uk/co/mruoc/demo/domain/entity/AccountMother.java
|
michaelruocco/camunda-spring-boot-demo
|
e903b47a844f1087fc3e734b2009b6d349611afe
|
[
"MIT"
] | null | null | null |
src/testFixtures/java/uk/co/mruoc/demo/domain/entity/AccountMother.java
|
michaelruocco/camunda-spring-boot-demo
|
e903b47a844f1087fc3e734b2009b6d349611afe
|
[
"MIT"
] | 1 |
2021-12-02T07:14:34.000Z
|
2021-12-02T07:54:24.000Z
|
src/testFixtures/java/uk/co/mruoc/demo/domain/entity/AccountMother.java
|
michaelruocco/camunda-spring-boot-demo
|
e903b47a844f1087fc3e734b2009b6d349611afe
|
[
"MIT"
] | null | null | null | 21 | 48 | 0.62465 | 1,001,133 |
package uk.co.mruoc.demo.domain.entity;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class AccountMother {
public static Account build() {
return Account.builder()
.id("aaa-bbb-ccc")
.owner("Joe Bloggs")
.build();
}
}
|
923f6087af807e4fe5b5783fcec34381d71325ff
| 6,137 |
java
|
Java
|
App/user-administration/src/main/java/com/project/user/administration/services/UserService.java
|
WebToLearn/trading-app
|
ff5583cf515a9e9cf4e3cd83838869b1adc777fe
|
[
"MIT"
] | 24 |
2018-09-25T20:29:17.000Z
|
2021-04-17T19:45:41.000Z
|
App/user-administration/src/main/java/com/project/user/administration/services/UserService.java
|
WebToLearn/trading-app
|
ff5583cf515a9e9cf4e3cd83838869b1adc777fe
|
[
"MIT"
] | 92 |
2019-10-08T08:25:52.000Z
|
2022-02-20T08:10:47.000Z
|
App/user-administration/src/main/java/com/project/user/administration/services/UserService.java
|
WebToLearn/trading-app
|
ff5583cf515a9e9cf4e3cd83838869b1adc777fe
|
[
"MIT"
] | 14 |
2019-03-09T09:43:51.000Z
|
2021-12-14T06:09:08.000Z
| 39.089172 | 105 | 0.672641 | 1,001,134 |
package com.project.user.administration.services;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.project.user.administration.model.User;
import com.project.user.administration.model.UserLogin;
import com.project.user.administration.repository.UserLoginRepository;
import com.project.user.administration.repository.UserRepository;
import com.project.user.administration.vo.UserAuthorizeResponseVo;
import com.project.user.administration.vo.UserTokenResponseVo;
import com.project.user.administration.vo.UserRequestVo;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
@Service
public class UserService {
@Autowired
private UserRepository userRepository;
@Autowired
private UserLoginRepository userLoginRepository;
@Autowired
private PasswordEncoder bCryptPasswordEncoder;
@Bean
public PasswordEncoder encoder() {
return new BCryptPasswordEncoder();
}
public UserRequestVo findByUserId(Long userId) {
User user = userRepository.findByUserId(userId);
return UserRequestVo.builder()
.username(user.getUserName())
.email(user.getEmail())
.build();
}
public void registerNewUser(UserRequestVo userRequestVo) {
User user = User.builder()
.userName(userRequestVo.getUsername())
.password(bCryptPasswordEncoder.encode(userRequestVo.getPassword()))
.email(userRequestVo.getEmail())
.build();
userRepository.save(user);
}
public UserTokenResponseVo validateUserCredentialsAndGenerateToken(UserRequestVo userRequestVo) {
User user = userRepository.findUserByStatusAndName(userRequestVo.getUsername());
if (user != null &&
bCryptPasswordEncoder.matches(userRequestVo.getPassword(),
user.getPassword())) {
//String token= RandomStringUtils.random(25, true, true);
String token = createJsonWebToken(userRequestVo.getUsername());
UserLogin userLogin = UserLogin.builder()
.user(user)
.token(token)
.tokenExpireTime(getCurrentTimeStamp())
.build();
userLoginRepository.save(userLogin);
UserTokenResponseVo userTokenResponseVo = new UserTokenResponseVo();
userTokenResponseVo.setToken(token);
userTokenResponseVo.setUsername(userRequestVo.getUsername());
return userTokenResponseVo;
} else {
throw new RuntimeException("User not found");
}
}
public UserAuthorizeResponseVo authorizeV1(UserRequestVo userRequestVo) throws ParseException {
UserLogin userLogin = userLoginRepository.findByUserAndToken(userRequestVo.getUsername(),
userRequestVo.getToken());
if (userLogin != null) {
DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = format.parse(userLogin.getTokenExpireTime());
if (new Date().compareTo(date) < 1) {
return new UserAuthorizeResponseVo(userRequestVo.getUsername(), true);
} else {
return new UserAuthorizeResponseVo(userRequestVo.getUsername(), false);
}
}
return new UserAuthorizeResponseVo(userRequestVo.getUsername(), false);
}
public UserAuthorizeResponseVo authorizeV2(UserRequestVo userRequestVo) throws ParseException {
String userName = extractUserNameFromToken(userRequestVo.getToken());
UserLogin userLogin = userLoginRepository.findByUserAndToken(userName, userRequestVo.getToken());
if (userLogin != null) {
return new UserAuthorizeResponseVo(userRequestVo.getUsername(),
verifyToken(userRequestVo.getUsername(), userRequestVo.getToken()));
}
return new UserAuthorizeResponseVo(userRequestVo.getUsername(), false);
}
public String getCurrentTimeStamp() {
Date newDate = DateUtils.addHours(new Date(), 3);
return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(newDate);
}
public static String createJsonWebToken(String username) {
return JWT.create()
.withSubject(username)
.withIssuer("auth0")
.withExpiresAt(DateUtils.addHours(new Date(), 3))
.sign(Algorithm.HMAC256(System.getProperty("aplication-secret")));
}
public static String extractUserNameFromToken(String token) throws JWTVerificationException {
Algorithm algorithm = Algorithm.HMAC256(System.getProperty("aplication-secret"));
JWTVerifier verifier = JWT.require(algorithm)
.withIssuer("auth0")
.build();
DecodedJWT jwt = verifier.verify(token);
return jwt.getSubject();
}
public static boolean verifyToken(String user, String token) {
try {
Algorithm algorithm = Algorithm.HMAC256(System.getProperty("aplication-secret"));
JWTVerifier verifier = JWT.require(algorithm)
.withIssuer("auth0")
.build();
DecodedJWT jwt = verifier.verify(token);
Date dateTheTokenWillExpire = jwt.getExpiresAt();
if (new Date().compareTo(dateTheTokenWillExpire) < 1) {
return true;
} else {
return false;
}
} catch (JWTVerificationException exception) {
return false;
}
}
}
|
923f61fba156dc22d1b4156e4e527c0dd4f0311c
| 4,098 |
java
|
Java
|
sdk/core/azure-core-serializer-json-jackson/src/main/java/com/azure/core/serializer/json/jackson/JacksonJsonSerializer.java
|
odidev/azure-sdk-for-java
|
46f02c1407a92fed7f11bcdb223f998bd9f3e4ce
|
[
"MIT"
] | null | null | null |
sdk/core/azure-core-serializer-json-jackson/src/main/java/com/azure/core/serializer/json/jackson/JacksonJsonSerializer.java
|
odidev/azure-sdk-for-java
|
46f02c1407a92fed7f11bcdb223f998bd9f3e4ce
|
[
"MIT"
] | null | null | null |
sdk/core/azure-core-serializer-json-jackson/src/main/java/com/azure/core/serializer/json/jackson/JacksonJsonSerializer.java
|
odidev/azure-sdk-for-java
|
46f02c1407a92fed7f11bcdb223f998bd9f3e4ce
|
[
"MIT"
] | 1 |
2020-08-12T02:32:01.000Z
|
2020-08-12T02:32:01.000Z
| 34.728814 | 105 | 0.678868 | 1,001,135 |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
package com.azure.core.serializer.json.jackson;
import com.azure.core.util.CoreUtils;
import com.azure.core.util.logging.ClientLogger;
import com.azure.core.util.serializer.JsonSerializer;
import com.azure.core.util.serializer.MemberNameConverter;
import com.azure.core.util.serializer.TypeReference;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.introspect.AnnotatedMethod;
import com.fasterxml.jackson.databind.type.TypeFactory;
import com.fasterxml.jackson.databind.util.BeanUtil;
import reactor.core.publisher.Mono;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UncheckedIOException;
import java.lang.reflect.Field;
import java.lang.reflect.Member;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
/**
* Jackson based implementation of the {@link JsonSerializer} interface.
*/
public final class JacksonJsonSerializer implements MemberNameConverter, JsonSerializer {
private final ClientLogger logger = new ClientLogger(JacksonJsonSerializer.class);
private final ObjectMapper mapper;
private final TypeFactory typeFactory;
/**
* Constructs a {@link JsonSerializer} using the passed Jackson serializer.
*
* @param mapper Configured Jackson serializer.
*/
JacksonJsonSerializer(ObjectMapper mapper) {
this.mapper = mapper;
this.typeFactory = mapper.getTypeFactory();
}
@Override
public <T> T deserialize(InputStream stream, TypeReference<T> typeReference) {
if (stream == null) {
return null;
}
try {
return mapper.readValue(stream, typeFactory.constructType(typeReference.getJavaType()));
} catch (IOException ex) {
throw logger.logExceptionAsError(new UncheckedIOException(ex));
}
}
@Override
public <T> Mono<T> deserializeAsync(InputStream stream, TypeReference<T> typeReference) {
return Mono.fromCallable(() -> deserialize(stream, typeReference));
}
@Override
public void serialize(OutputStream stream, Object value) {
try {
mapper.writeValue(stream, value);
} catch (IOException ex) {
throw logger.logExceptionAsError(new UncheckedIOException(ex));
}
}
@Override
public Mono<Void> serializeAsync(OutputStream stream, Object value) {
return Mono.fromRunnable(() -> serialize(stream, value));
}
@Override
public String convertMemberName(Member member) {
if (Modifier.isTransient(member.getModifiers())) {
return null;
}
if (member instanceof Field) {
Field f = (Field) member;
if (f.isAnnotationPresent(JsonIgnore.class)) {
return null;
}
if (f.isAnnotationPresent(JsonProperty.class)) {
String propertyName = f.getDeclaredAnnotation(JsonProperty.class).value();
return CoreUtils.isNullOrEmpty(propertyName) ? f.getName() : propertyName;
}
return f.getName();
}
if (member instanceof Method) {
Method m = (Method) member;
String methodNameWithoutJavaBeans = removePrefix(m);
if (m.isAnnotationPresent(JsonIgnore.class)) {
return null;
}
if (m.isAnnotationPresent(JsonProperty.class)) {
String propertyName = m.getDeclaredAnnotation(JsonProperty.class).value();
return CoreUtils.isNullOrEmpty(propertyName) ? methodNameWithoutJavaBeans : propertyName;
}
return methodNameWithoutJavaBeans;
}
return null;
}
private String removePrefix(Method method) {
return BeanUtil.okNameForGetter(
new AnnotatedMethod(null, method, null, null), false);
}
}
|
923f631fafdd1f36c64379fb2eeebb5b775a3be6
| 100 |
java
|
Java
|
internacao/src/main/java/br/com/basis/madre/web/rest/vm/package-info.java
|
BasisTI/madre
|
b856d26ecbb25b5ab3a3bffe97da0bd09b6985de
|
[
"CECILL-B"
] | 9 |
2019-10-09T15:48:37.000Z
|
2022-01-11T18:14:15.000Z
|
internacao/src/main/java/br/com/basis/madre/web/rest/vm/package-info.java
|
BasisTI/madre
|
b856d26ecbb25b5ab3a3bffe97da0bd09b6985de
|
[
"CECILL-B"
] | 30 |
2020-03-11T12:05:35.000Z
|
2022-03-02T05:42:56.000Z
|
gateway/src/main/java/br/com/basis/madre/web/rest/vm/package-info.java
|
BasisTI/madre
|
b856d26ecbb25b5ab3a3bffe97da0bd09b6985de
|
[
"CECILL-B"
] | 11 |
2020-08-15T15:44:48.000Z
|
2022-02-06T15:33:38.000Z
| 20 | 51 | 0.71 | 1,001,136 |
/**
* View Models used by Spring MVC REST controllers.
*/
package br.com.basis.madre.web.rest.vm;
|
923f636e1662af3a8aa7a55fb094c6d8fde41353
| 2,362 |
java
|
Java
|
src/test/java/com/willshex/sandpiles/shared/SandHelperTests.java
|
billy1380/sandpiles
|
0f6cc3dc730a22c3cc43c5b7831be51f32656d03
|
[
"Apache-2.0"
] | null | null | null |
src/test/java/com/willshex/sandpiles/shared/SandHelperTests.java
|
billy1380/sandpiles
|
0f6cc3dc730a22c3cc43c5b7831be51f32656d03
|
[
"Apache-2.0"
] | null | null | null |
src/test/java/com/willshex/sandpiles/shared/SandHelperTests.java
|
billy1380/sandpiles
|
0f6cc3dc730a22c3cc43c5b7831be51f32656d03
|
[
"Apache-2.0"
] | null | null | null | 21.472727 | 95 | 0.601609 | 1,001,137 |
//
// SandHelperTests.java
// sandpiles
//
// Created by William Shakour (billy1380) on 19 Apr 2017.
// Copyright © 2017 WillShex Limited. All rights reserved.
//
package com.willshex.sandpiles.shared;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
/**
* @author William Shakour (billy1380)
*
*/
public class SandHelperTests {
/**
* Test method for {@link com.willshex.sandpiles.PileHelper#neighbourHexagon(int, int, int)}.
*/
@Test
public void testNeighbourHexagon () {
test(new int[] { 3, 0, 1, 5, 7, 6 }, H, 4, 3);
test(new int[] { 6, 4, 5, 8, 11, 10 }, H, 7, 3);
}
/**
* Test method for {@link com.willshex.sandpiles.PileHelper#neighbourSquare(int, int, int)}.
*/
@Test
public void testNeighbourSquare () {
test(new int[] { 3, 1, 5, 7 }, S, 4, 3);
test(new int[] { 4, 2, -1, 8 }, S, 5, 3);
test(new int[] { 5, 2, 7, 10 }, S, 6, 4);
test(new int[] { 8, 5, 10, 13 }, S, 9, 4);
}
/**
* Test method for {@link com.willshex.sandpiles.PileHelper#neighbourTriangle(int, int, int)}.
*/
@Test
public void testNeighbourTriangle () {
test(new int[] { 0, -1, 2 }, T, 1, 3);
test(new int[] { 3, 5, 7 }, T, 4, 3);
test(new int[] { 0, -1, 2 }, T, 1, 4);
test(new int[] { 4, 6, 9 }, T, 5, 4);
test(new int[] { 5, 2, 7 }, T, 6, 4);
}
private interface Finder {
int find (int i, int at, int width);
int n ();
}
private static final Finder T = new Finder() {
@Override
public int find (int i, int at, int width) {
return PileHelper.neighbourTriangle(i, at, width).intValue();
}
@Override
public int n () {
return 3;
}
};
private static final Finder S = new Finder() {
@Override
public int find (int i, int at, int width) {
return PileHelper.neighbourSquare(i, at, width).intValue();
}
@Override
public int n () {
return 4;
}
};
private static final Finder H = new Finder() {
@Override
public int find (int i, int at, int width) {
return PileHelper.neighbourHexagon(i, at, width).intValue();
}
@Override
public int n () {
return 6;
}
};
/**
* @param neightbors
* @param i
* @param j
*/
private void test (int[] expected, Finder finder, int at, int width) {
assertEquals(expected.length, finder.n());
for (int i = 0; i < finder.n(); i++) {
assertEquals(expected[i], finder.find(i, at, width));
}
}
}
|
923f654e785bef7497eef5296700ee0917af529b
| 9,372 |
java
|
Java
|
src/com/puzzletimer/puzzles/VCube6.java
|
Moony22/prisma
|
41de70c9802b07840f8b172e880ceabde8edd955
|
[
"MIT"
] | 17 |
2015-01-03T00:36:40.000Z
|
2017-11-14T23:55:38.000Z
|
src/main/java/com/puzzletimer/puzzles/VCube6.java
|
defhacks/prisma
|
0b8cb4e5b23b9a421d9ee1592b206ee9bc6e332f
|
[
"MIT"
] | 15 |
2015-01-25T23:35:20.000Z
|
2017-01-17T03:33:36.000Z
|
src/com/puzzletimer/puzzles/VCube6.java
|
Moony22/prisma
|
41de70c9802b07840f8b172e880ceabde8edd955
|
[
"MIT"
] | 13 |
2015-03-04T00:25:11.000Z
|
2018-04-02T18:59:36.000Z
| 49.851064 | 86 | 0.547695 | 1,001,138 |
package com.puzzletimer.puzzles;
import java.awt.Color;
import java.util.HashMap;
import com.puzzletimer.graphics.Matrix44;
import com.puzzletimer.graphics.Mesh;
import com.puzzletimer.graphics.Plane;
import com.puzzletimer.graphics.Vector3;
import com.puzzletimer.models.ColorScheme;
import com.puzzletimer.models.PuzzleInfo;
public class VCube6 implements Puzzle {
@Override
public PuzzleInfo getPuzzleInfo() {
return new PuzzleInfo("6x6x6-CUBE");
}
@Override
public String toString() {
return getPuzzleInfo().getDescription();
}
private class Twist {
public Plane plane;
public double angle;
public Twist(Plane plane, double angle) {
this.plane = plane;
this.angle = angle;
}
}
@Override
public Mesh getScrambledPuzzleMesh(ColorScheme colorScheme, String[] sequence) {
Color[] colorArray = {
colorScheme.getFaceColor("FACE-L").getColor(),
colorScheme.getFaceColor("FACE-B").getColor(),
colorScheme.getFaceColor("FACE-D").getColor(),
colorScheme.getFaceColor("FACE-R").getColor(),
colorScheme.getFaceColor("FACE-F").getColor(),
colorScheme.getFaceColor("FACE-U").getColor(),
};
Mesh mesh = Mesh.cube(colorArray);
Plane planeL = new Plane(new Vector3(-0.3333, 0, 0), new Vector3(-1, 0, 0));
Plane planeL2 = new Plane(new Vector3(-0.1666, 0, 0), new Vector3(-1, 0, 0));
Plane planeL3 = new Plane(new Vector3(-0.0000, 0, 0), new Vector3(-1, 0, 0));
Plane planeR3 = new Plane(new Vector3( 0.0000, 0, 0), new Vector3( 1, 0, 0));
Plane planeR2 = new Plane(new Vector3( 0.1666, 0, 0), new Vector3( 1, 0, 0));
Plane planeR = new Plane(new Vector3( 0.3333, 0, 0), new Vector3( 1, 0, 0));
Plane planeD = new Plane(new Vector3(0, -0.3333, 0), new Vector3(0, -1, 0));
Plane planeD2 = new Plane(new Vector3(0, -0.1666, 0), new Vector3(0, -1, 0));
Plane planeD3 = new Plane(new Vector3(0, -0.0000, 0), new Vector3(0, -1, 0));
Plane planeU3 = new Plane(new Vector3(0, 0.0000, 0), new Vector3(0, 1, 0));
Plane planeU2 = new Plane(new Vector3(0, 0.1666, 0), new Vector3(0, 1, 0));
Plane planeU = new Plane(new Vector3(0, 0.3333, 0), new Vector3(0, 1, 0));
Plane planeF = new Plane(new Vector3(0, 0, -0.3333), new Vector3(0, 0, -1));
Plane planeF2 = new Plane(new Vector3(0, 0, -0.1666), new Vector3(0, 0, -1));
Plane planeF3 = new Plane(new Vector3(0, 0, -0.0000), new Vector3(0, 0, -1));
Plane planeB3 = new Plane(new Vector3(0, 0, 0.0000), new Vector3(0, 0, 1));
Plane planeB2 = new Plane(new Vector3(0, 0, 0.1666), new Vector3(0, 0, 1));
Plane planeB = new Plane(new Vector3(0, 0, 0.3333), new Vector3(0, 0, 1));
mesh = mesh
.cut(planeL, 0)
.cut(planeL2, 0)
.cut(planeL3, 0)
.cut(planeR2, 0)
.cut(planeR, 0)
.cut(planeD, 0)
.cut(planeD2, 0)
.cut(planeD3, 0)
.cut(planeU2, 0)
.cut(planeU, 0)
.cut(planeF, 0)
.cut(planeF2, 0)
.cut(planeF3, 0)
.cut(planeB2, 0)
.cut(planeB, 0)
.shortenFaces(0.0175)
.softenFaces(0.01)
.softenFaces(0.005);
HashMap<String, Twist> twists = new HashMap<String, Twist>();
twists.put("L", new Twist(planeL, Math.PI / 2));
twists.put("2L", new Twist(planeL2, Math.PI / 2));
twists.put("Lw", new Twist(planeL2, Math.PI / 2));
twists.put("3L", new Twist(planeL3, Math.PI / 2));
twists.put("3Lw", new Twist(planeL3, Math.PI / 2));
twists.put("L2", new Twist(planeL, Math.PI));
twists.put("2L2", new Twist(planeL2, Math.PI));
twists.put("Lw2", new Twist(planeL2, Math.PI));
twists.put("3L2", new Twist(planeL3, Math.PI));
twists.put("3Lw2", new Twist(planeL3, Math.PI));
twists.put("L'", new Twist(planeL, -Math.PI / 2));
twists.put("2L'", new Twist(planeL2, -Math.PI / 2));
twists.put("Lw'", new Twist(planeL2, -Math.PI / 2));
twists.put("3L'", new Twist(planeL3, -Math.PI / 2));
twists.put("3Lw'", new Twist(planeL3, -Math.PI / 2));
twists.put("R", new Twist(planeR, Math.PI / 2));
twists.put("2R", new Twist(planeR2, Math.PI / 2));
twists.put("Rw", new Twist(planeR2, Math.PI / 2));
twists.put("3R", new Twist(planeR3, Math.PI / 2));
twists.put("3Rw", new Twist(planeR3, Math.PI / 2));
twists.put("R2", new Twist(planeR, Math.PI));
twists.put("2R2", new Twist(planeR2, Math.PI));
twists.put("Rw2", new Twist(planeR2, Math.PI));
twists.put("3R2", new Twist(planeR3, Math.PI));
twists.put("3Rw2", new Twist(planeR3, Math.PI));
twists.put("R'", new Twist(planeR, -Math.PI / 2));
twists.put("2R'", new Twist(planeR2, -Math.PI / 2));
twists.put("Rw'", new Twist(planeR2, -Math.PI / 2));
twists.put("3R'", new Twist(planeR3, -Math.PI / 2));
twists.put("3Rw'", new Twist(planeR3, -Math.PI / 2));
twists.put("D", new Twist(planeD, Math.PI / 2));
twists.put("2D", new Twist(planeD2, Math.PI / 2));
twists.put("Dw", new Twist(planeD2, Math.PI / 2));
twists.put("3D", new Twist(planeD3, Math.PI / 2));
twists.put("3Dw", new Twist(planeD3, Math.PI / 2));
twists.put("D2", new Twist(planeD, Math.PI));
twists.put("2D2", new Twist(planeD2, Math.PI));
twists.put("Dw2", new Twist(planeD2, Math.PI));
twists.put("3D2", new Twist(planeD3, Math.PI));
twists.put("3Dw2", new Twist(planeD3, Math.PI));
twists.put("D'", new Twist(planeD, -Math.PI / 2));
twists.put("2D'", new Twist(planeD2, -Math.PI / 2));
twists.put("Dw'", new Twist(planeD2, -Math.PI / 2));
twists.put("3D'", new Twist(planeD3, -Math.PI / 2));
twists.put("3Dw'", new Twist(planeD3, -Math.PI / 2));
twists.put("U", new Twist(planeU, Math.PI / 2));
twists.put("2U", new Twist(planeU2, Math.PI / 2));
twists.put("Uw", new Twist(planeU2, Math.PI / 2));
twists.put("3U", new Twist(planeU3, Math.PI / 2));
twists.put("3Uw", new Twist(planeU3, Math.PI / 2));
twists.put("U2", new Twist(planeU, Math.PI));
twists.put("2U2", new Twist(planeU2, Math.PI));
twists.put("Uw2", new Twist(planeU2, Math.PI));
twists.put("3U2", new Twist(planeU3, Math.PI));
twists.put("3Uw2", new Twist(planeU3, Math.PI));
twists.put("U'", new Twist(planeU, -Math.PI / 2));
twists.put("2U'", new Twist(planeU2, -Math.PI / 2));
twists.put("Uw'", new Twist(planeU2, -Math.PI / 2));
twists.put("3U'", new Twist(planeU3, -Math.PI / 2));
twists.put("3Uw'", new Twist(planeU3, -Math.PI / 2));
twists.put("F", new Twist(planeF, Math.PI / 2));
twists.put("2F", new Twist(planeF2, Math.PI / 2));
twists.put("Fw", new Twist(planeF2, Math.PI / 2));
twists.put("3F", new Twist(planeF3, Math.PI / 2));
twists.put("3Fw", new Twist(planeF3, Math.PI / 2));
twists.put("F2", new Twist(planeF, Math.PI));
twists.put("2F2", new Twist(planeF2, Math.PI));
twists.put("Fw2", new Twist(planeF2, Math.PI));
twists.put("3F2", new Twist(planeF3, Math.PI));
twists.put("3Fw2", new Twist(planeF3, Math.PI));
twists.put("F'", new Twist(planeF, -Math.PI / 2));
twists.put("2F'", new Twist(planeF2, -Math.PI / 2));
twists.put("Fw'", new Twist(planeF2, -Math.PI / 2));
twists.put("3F'", new Twist(planeF3, -Math.PI / 2));
twists.put("3Fw'", new Twist(planeF3, -Math.PI / 2));
twists.put("B", new Twist(planeB, Math.PI / 2));
twists.put("2B", new Twist(planeB2, Math.PI / 2));
twists.put("Bw", new Twist(planeB2, Math.PI / 2));
twists.put("3B", new Twist(planeB3, Math.PI / 2));
twists.put("3Bw", new Twist(planeB3, Math.PI / 2));
twists.put("B2", new Twist(planeB, Math.PI));
twists.put("2B2", new Twist(planeB2, Math.PI));
twists.put("Bw2", new Twist(planeB2, Math.PI));
twists.put("3B2", new Twist(planeB3, Math.PI));
twists.put("3Bw2", new Twist(planeB3, Math.PI));
twists.put("B'", new Twist(planeB, -Math.PI / 2));
twists.put("2B'", new Twist(planeB2, -Math.PI / 2));
twists.put("Bw'", new Twist(planeB2, -Math.PI / 2));
twists.put("3B'", new Twist(planeB3, -Math.PI / 2));
twists.put("3Bw'", new Twist(planeB3, -Math.PI / 2));
for (String move : sequence) {
Twist t = twists.get(move);
mesh = mesh.rotateHalfspace(t.plane, t.angle);
}
return mesh
.transform(Matrix44.rotationY(-Math.PI / 6))
.transform(Matrix44.rotationX(Math.PI / 7));
}
}
|
923f65af3a0d53c39c77331b4544f8d6d8a6d28d
| 4,039 |
java
|
Java
|
src/test/java/seedu/address/storage/admin/JsonAdminStorageTest.java
|
garysyndromes/main
|
b4f7a4c5c7fcf97f5c969df1691fc4d3675b6c37
|
[
"MIT"
] | 1 |
2020-05-20T10:29:49.000Z
|
2020-05-20T10:29:49.000Z
|
src/test/java/seedu/address/storage/admin/JsonAdminStorageTest.java
|
garysyndromes/main
|
b4f7a4c5c7fcf97f5c969df1691fc4d3675b6c37
|
[
"MIT"
] | 157 |
2020-02-13T09:29:50.000Z
|
2020-04-14T18:12:38.000Z
|
src/test/java/seedu/address/storage/admin/JsonAdminStorageTest.java
|
garysyndromes/main
|
b4f7a4c5c7fcf97f5c969df1691fc4d3675b6c37
|
[
"MIT"
] | 7 |
2020-02-11T07:10:25.000Z
|
2021-09-21T09:40:54.000Z
| 37.398148 | 106 | 0.718 | 1,001,139 |
package seedu.address.storage.admin;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static seedu.address.testutil.Assert.assertThrows;
import static seedu.address.testutil.admin.TypicalDates.JAN_26_2020;
import static seedu.address.testutil.admin.TypicalDates.getTypicalAdmin;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import seedu.address.commons.exceptions.DataConversionException;
import seedu.address.model.admin.Admin;
import seedu.address.model.admin.ReadOnlyAdmin;
public class JsonAdminStorageTest {
private static final Path TEST_DATA_FOLDER = Paths.get("src", "test", "data", "JsonAdminStorageTest");
@TempDir
public Path testFolder;
@Test
public void readAdmin_nullFilePath_throwsNullPointerException() {
assertThrows(NullPointerException.class, () -> readAdmin(null));
}
private java.util.Optional<ReadOnlyAdmin> readAdmin(String filePath) throws Exception {
return new JsonAdminStorage(Paths.get(filePath)).readAdmin(addToTestDataPathIfNotNull(filePath));
}
private Path addToTestDataPathIfNotNull(String prefsFileInTestDataFolder) {
return prefsFileInTestDataFolder != null
? TEST_DATA_FOLDER.resolve(prefsFileInTestDataFolder)
: null;
}
@Test
public void read_missingFile_emptyResult() throws Exception {
assertFalse(readAdmin("NonExistentFile.json").isPresent());
}
@Test
public void read_notJsonFormat_exceptionThrown() {
assertThrows(DataConversionException.class, () -> readAdmin("notJsonFormatAdmin.json"));
}
@Test
public void readAdmin_invalidDateAdmin_throwDataConversionException() {
assertThrows(DataConversionException.class, () -> readAdmin("invalidDateAdmin.json"));
}
@Test
public void readTeaPet_invalidAndValidDateAdmin_throwDataConversionException() {
assertThrows(DataConversionException.class, () -> readAdmin("invalidAndValidDateAdmin.json"));
}
@Test
public void readAndSaveAdmin_allInOrder_success() throws Exception {
Path filePath = testFolder.resolve("TempAdmin.json");
Admin original = getTypicalAdmin();
JsonAdminStorage jsonAdminStorage = new JsonAdminStorage(filePath);
// Save in new file and read back
jsonAdminStorage.saveAdmin(original, filePath);
ReadOnlyAdmin readBack = jsonAdminStorage.readAdmin(filePath).get();
assertEquals(original, new Admin(readBack));
// Modify data, overwrite exiting file, and read back
original.removeDate(JAN_26_2020);
jsonAdminStorage.saveAdmin(original, filePath);
readBack = jsonAdminStorage.readAdmin(filePath).get();
assertEquals(original, new Admin(readBack));
// Save and read without specifying file path
original.addDate(JAN_26_2020);
jsonAdminStorage.saveAdmin(original); // file path not specified
readBack = jsonAdminStorage.readAdmin().get(); // file path not specified
assertEquals(original, new Admin(readBack));
}
@Test
public void saveTeaPet_nullAdmin_throwsNullPointerException() {
assertThrows(NullPointerException.class, () -> saveAdmin(null, "SomeFile.json"));
}
/**
* Saves {@code teaPet} at the specified {@code filePath}.
*/
private void saveAdmin(ReadOnlyAdmin admin, String filePath) {
try {
new JsonAdminStorage(Paths.get(filePath))
.saveAdmin(admin, addToTestDataPathIfNotNull(filePath));
} catch (IOException ioe) {
throw new AssertionError("There should not be an error writing to the file.", ioe);
}
}
@Test
public void saveAdmin_nullFilePath_throwsNullPointerException() {
assertThrows(NullPointerException.class, () -> saveAdmin(new Admin(), null));
}
}
|
923f662b1a2ddd21df9bb087dc06fafc0cbbdeb8
| 1,713 |
java
|
Java
|
src/main/java/com/asiainfo/fileservice/parser/Percent2DoubleParseServiceImpl.java
|
jaesonchen/java-study
|
093d6cb2a8513e3d402bf59026b4da1c33e3510f
|
[
"Apache-2.0"
] | null | null | null |
src/main/java/com/asiainfo/fileservice/parser/Percent2DoubleParseServiceImpl.java
|
jaesonchen/java-study
|
093d6cb2a8513e3d402bf59026b4da1c33e3510f
|
[
"Apache-2.0"
] | 7 |
2020-11-16T20:25:05.000Z
|
2022-02-01T00:56:22.000Z
|
src/main/java/com/asiainfo/fileservice/parser/Percent2DoubleParseServiceImpl.java
|
jaesonchen/java-study
|
093d6cb2a8513e3d402bf59026b4da1c33e3510f
|
[
"Apache-2.0"
] | 1 |
2021-01-09T16:21:24.000Z
|
2021-01-09T16:21:24.000Z
| 28.55 | 116 | 0.690601 | 1,001,140 |
package com.asiainfo.fileservice.parser;
import java.text.NumberFormat;
import org.springframework.util.Assert;
/**
* @Description: TODO
*
* @author zq
* @date 2017年6月4日 下午2:29:18
* Copyright: 北京亚信智慧数据科技有限公司
*/
public class Percent2DoubleParseServiceImpl implements ParseService<Double> {
private ParseService<?> delegate = null;
private int fraction = 2;
public Percent2DoubleParseServiceImpl() {}
public Percent2DoubleParseServiceImpl(int fraction) {
Assert.isTrue(fraction >= 0, "小数点位数不能小于0");
this.fraction = fraction;
}
/*
* @Description: TODO
* @param str
* @return
* @see com.asiainfo.fileservice.parse.IopParseService#parse(java.lang.String)
*/
@Override
public Double parse(String str) {
Object result = (null == this.delegate) ? str : this.delegate.parse(str);
try {
double percentValue;
String dealStr = String.valueOf(result);
if (dealStr.indexOf("%") != -1) {
percentValue = Double.parseDouble(dealStr.substring(0, dealStr.indexOf("%"))) / 100;
} else {
percentValue = Double.parseDouble(dealStr);
}
NumberFormat format = NumberFormat.getNumberInstance();
format.setMaximumFractionDigits(this.fraction);
return Double.parseDouble(format.format(percentValue));
} catch (Exception ex) {
throw new ParseException(ErrorCodes.RECORD_RESULTCODE_ERROR_TYPE, "除了(%)不能包含非数字字符");
}
}
/*
* @Description: TODO
* @param delegate
* @see com.asiainfo.fileservice.parse.IopParseService#setDelegate(com.asiainfo.fileservice.parse.IopParseService)
*/
@Override
public void setDelegate(ParseService<?> delegate) {
this.delegate = delegate;
}
}
|
923f668e3171299fbdc65eb7a4d6d6dd133ef4c4
| 4,690 |
java
|
Java
|
hsweb-system/hsweb-system-organizational/hsweb-system-organizational-controller/src/main/java/org/hswebframework/web/controller/organizational/PersonController.java
|
longfeizheng/hsweb-framework
|
83f9da757a936840e5b805bc9c7330a25de3cc2e
|
[
"Apache-2.0"
] | null | null | null |
hsweb-system/hsweb-system-organizational/hsweb-system-organizational-controller/src/main/java/org/hswebframework/web/controller/organizational/PersonController.java
|
longfeizheng/hsweb-framework
|
83f9da757a936840e5b805bc9c7330a25de3cc2e
|
[
"Apache-2.0"
] | null | null | null |
hsweb-system/hsweb-system-organizational/hsweb-system-organizational-controller/src/main/java/org/hswebframework/web/controller/organizational/PersonController.java
|
longfeizheng/hsweb-framework
|
83f9da757a936840e5b805bc9c7330a25de3cc2e
|
[
"Apache-2.0"
] | 1 |
2020-10-26T11:23:28.000Z
|
2020-10-26T11:23:28.000Z
| 38.760331 | 117 | 0.758849 | 1,001,141 |
/*
* Copyright 2016 http://www.hswebframework.org
*
* 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.hswebframework.web.controller.organizational;
import org.hswebframework.web.NotFoundException;
import org.hswebframework.web.authorization.Permission;
import org.hswebframework.web.authorization.annotation.Authorize;
import org.hswebframework.web.authorization.annotation.RequiresDataAccess;
import org.hswebframework.web.commons.entity.PagerResult;
import org.hswebframework.web.commons.entity.param.QueryParamEntity;
import org.hswebframework.web.controller.GenericEntityController;
import org.hswebframework.web.controller.SimpleGenericEntityController;
import org.hswebframework.web.controller.message.ResponseMessage;
import org.hswebframework.web.entity.organizational.DepartmentEntity;
import org.hswebframework.web.entity.organizational.PersonAuthBindEntity;
import org.hswebframework.web.entity.organizational.PersonEntity;
import org.hswebframework.web.entity.organizational.PositionEntity;
import org.hswebframework.web.logging.AccessLogger;
import org.hswebframework.web.organizational.authorization.PersonnelAuthorization;
import org.hswebframework.web.service.organizational.PersonService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;
import java.util.List;
/**
* 人员
*
* @author hsweb-generator-online
*/
@RestController
@RequestMapping("${hsweb.web.mappings.person:person}")
@Authorize(permission = "person")
@AccessLogger("人员")
public class PersonController implements SimpleGenericEntityController<PersonEntity, String, QueryParamEntity> {
private PersonService personService;
@Autowired
public void setPersonService(PersonService personService) {
this.personService = personService;
}
@Override
public PersonService getService() {
return personService;
}
@Override
public ResponseMessage<PagerResult<PersonEntity>> list(QueryParamEntity param) {
return SimpleGenericEntityController.super.list(param);
}
@GetMapping("/me")
@AccessLogger("查看当前登录用户的人员信息")
@Authorize(merge = false)
public ResponseMessage<PersonAuthBindEntity> getLoginUserPerson() {
PersonnelAuthorization authorization = PersonnelAuthorization
.current()
.orElseThrow(NotFoundException::new);
return getDetail(authorization.getPersonnel().getId());
}
@GetMapping("/me/authorization")
@AccessLogger("查看当前登录用户的人员权限信息")
@Authorize(merge = false)
public ResponseMessage<PersonnelAuthorization> getLoginUserPersonDetail() {
PersonnelAuthorization authorization = PersonnelAuthorization
.current()
.orElseThrow(NotFoundException::new);
return ResponseMessage.ok(authorization);
}
@GetMapping("/{id}/detail")
@AccessLogger("查看人员详情")
@Authorize(action = Permission.ACTION_GET)
public ResponseMessage<PersonAuthBindEntity> getDetail(@PathVariable String id) {
return ResponseMessage.ok(personService.selectAuthBindByPk(id));
}
@PostMapping("/detail")
@AccessLogger("新增人员信息,并关联用户信息")
@Authorize(action = Permission.ACTION_ADD)
@ResponseStatus(HttpStatus.CREATED)
public ResponseMessage<String> getDetail(@RequestBody PersonAuthBindEntity bindEntity) {
return ResponseMessage.ok(personService.insert(bindEntity));
}
@PutMapping("/{id}/detail")
@AccessLogger("修改人员信息,并关联用户信息")
@Authorize(action = Permission.ACTION_UPDATE)
public ResponseMessage<String> getDetail(@PathVariable String id, @RequestBody PersonAuthBindEntity bindEntity) {
bindEntity.setId(id);
personService.updateByPk(bindEntity);
return ResponseMessage.ok();
}
@GetMapping("/in-position/{positionId}")
@AccessLogger("获取指定岗位的人员")
@Authorize(action = Permission.ACTION_GET)
public ResponseMessage<List<PersonEntity>> getByPositionId(@PathVariable String positionId) {
return ResponseMessage.ok(personService.selectByPositionId(positionId));
}
}
|
923f6730f90a0558ea8e08e3384c5beb007f2ad1
| 131 |
java
|
Java
|
app/build/generated/source/dataBinding/trigger/release/com/uni/julio/superplus/DataBindingInfo.java
|
universegalaxy1112/android-supertvplus
|
b563769746222bd0cd7c927e7b09540918b75798
|
[
"MIT"
] | null | null | null |
app/build/generated/source/dataBinding/trigger/release/com/uni/julio/superplus/DataBindingInfo.java
|
universegalaxy1112/android-supertvplus
|
b563769746222bd0cd7c927e7b09540918b75798
|
[
"MIT"
] | null | null | null |
app/build/generated/source/dataBinding/trigger/release/com/uni/julio/superplus/DataBindingInfo.java
|
universegalaxy1112/android-supertvplus
|
b563769746222bd0cd7c927e7b09540918b75798
|
[
"MIT"
] | null | null | null | 18.714286 | 45 | 0.839695 | 1,001,142 |
package com.uni.julio.superplus;
import androidx.databinding.BindingBuildInfo;
@BindingBuildInfo
public class DataBindingInfo {}
|
923f67df135842345c76c0bd7c1b406e5292e93e
| 6,080 |
java
|
Java
|
src/test/java/org/testmonkeys/jentitytest/test/unit/model/AnnotationToComparatorDictionaryTest.java
|
TestMonkeys/jEntityTest
|
5610144bd97aae8075867b740e89caa2b521b2a5
|
[
"Apache-2.0"
] | 2 |
2019-04-08T10:33:33.000Z
|
2021-04-11T07:22:52.000Z
|
src/test/java/org/testmonkeys/jentitytest/test/unit/model/AnnotationToComparatorDictionaryTest.java
|
TestMonkeys/jEntityTest
|
5610144bd97aae8075867b740e89caa2b521b2a5
|
[
"Apache-2.0"
] | 101 |
2016-06-11T19:55:23.000Z
|
2022-03-30T09:17:49.000Z
|
src/test/java/org/testmonkeys/jentitytest/test/unit/model/AnnotationToComparatorDictionaryTest.java
|
TestMonkeys/jEntityTest
|
5610144bd97aae8075867b740e89caa2b521b2a5
|
[
"Apache-2.0"
] | 1 |
2016-07-26T12:37:20.000Z
|
2016-07-26T12:37:20.000Z
| 43.741007 | 123 | 0.783388 | 1,001,143 |
package org.testmonkeys.jentitytest.test.unit.model;
import org.hamcrest.junit.ExpectedException;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.testmonkeys.jentitytest.exceptions.ComparatorInstantiationByAnnotationException;
import org.testmonkeys.jentitytest.exceptions.JEntityModelException;
import org.testmonkeys.jentitytest.model.AnnotationToComparatorDictionary;
import org.testmonkeys.jentitytest.test.unit.model.util.*;
import java.beans.IntrospectionException;
import java.lang.annotation.*;
/**
* Created by cpascal on 6/21/2017.
*/
public class AnnotationToComparatorDictionaryTest {
@Rule
public ExpectedException expectedException = ExpectedException.none();
private AnnotationToComparatorDictionary comparisonMap;
/**
* initialization of EntityInspector,
* generation of comparison model for ModelMultiAnnotated.class,
* retrieval of comparable properties
*
* @throws IntrospectionException
*/
@Before
public void background() throws IntrospectionException {
comparisonMap = AnnotationToComparatorDictionary.getInstance();
comparisonMap.setComparatorForAnnotation(BadComparator.class, BadComparisonCustom.class);
}
/**
* Check comparisonMap will throw exception if it has no comparator for annotation
*/
@Test
public void unit_modelToComparison_noMappingForAnnotation() throws Throwable {
expectedException.expect(JEntityModelException.class);
expectedException.expectMessage("There is no comparator defined for annotation " +
"org.testmonkeys.jentitytest.test.unit.model.util.SimpleAnnotation");
Annotation an = () -> SimpleAnnotation.class;
comparisonMap.getComparatorForAnnotation(an);
}
/**
* Check comparisonMap will throw exception if annotation provided is null
*/
@Test
public void unit_modelToComparison_nullAnnotation() throws Throwable {
expectedException.expect(IllegalArgumentException.class);
expectedException.expectMessage("Annotation can not be null");
comparisonMap.getComparatorForAnnotation(null);
}
/**
* Invalid registration of null Comparator
*/
@Test
public void unit_modelToComparison_registrationNullComparator() throws Throwable {
expectedException.expect(IllegalArgumentException.class);
expectedException.expectMessage("Comparator can not be null");
comparisonMap.setComparatorForAnnotation(null, SimpleAnnotation.class);
}
/**
* Invalid registration of null Annotation
*/
@Test
public void unit_modelToComparison_registrationNullAnnotation() throws Throwable {
expectedException.expect(IllegalArgumentException.class);
expectedException.expectMessage("Annotation can not be null");
comparisonMap.setComparatorForAnnotation(IgnoreComparatorCustom.class, null);
}
@Test
public void annotationToComparatoryDictionary_bad_initCtrAnn_privateConstructor() {
expectedException.expect(ComparatorInstantiationByAnnotationException.class);
AnnotationToComparatorDictionary dictionary = AnnotationToComparatorDictionary.getInstance();
dictionary.setComparatorForAnnotation(BadComparatorPrivateConstructor.class, BadComparatorAnnotation.class);
dictionary.getComparatorForAnnotation(new BadComparatorAnnotationImp());
}
@Test
public void annotationToComparatoryDictionary_bad_initCtrAnn_abstractComparator() {
expectedException.expect(ComparatorInstantiationByAnnotationException.class);
AnnotationToComparatorDictionary dictionary = AnnotationToComparatorDictionary.getInstance();
dictionary.setComparatorForAnnotation(BadComparatorAbstract.class, BadComparatorAnnotation.class);
dictionary.getComparatorForAnnotation(new BadComparatorAnnotationImp());
}
@Test
public void annotationToComparatoryDictionary_bad_initCtrAnn_exceptionTrhown() {
expectedException.expect(ComparatorInstantiationByAnnotationException.class);
AnnotationToComparatorDictionary dictionary = AnnotationToComparatorDictionary.getInstance();
dictionary.setComparatorForAnnotation(BadComparatorErrInConstructor.class, BadComparatorAnnotation.class);
dictionary.getComparatorForAnnotation(new BadComparatorAnnotationImp());
}
@Test
public void annotationToComparatoryDictionary_bad_initCtrDefault_privateConstructor() {
expectedException.expect(ComparatorInstantiationByAnnotationException.class);
AnnotationToComparatorDictionary dictionary = AnnotationToComparatorDictionary.getInstance();
dictionary.setComparatorForAnnotation(BadComparatorPrivateDefaultConstructor.class, BadComparatorAnnotation.class);
dictionary.getComparatorForAnnotation(new BadComparatorAnnotationImp());
}
@Test
public void annotationToComparatoryDictionary_bad_initCtrDefault_abstractComparator() {
expectedException.expect(ComparatorInstantiationByAnnotationException.class);
AnnotationToComparatorDictionary dictionary = AnnotationToComparatorDictionary.getInstance();
dictionary.setComparatorForAnnotation(BadComparatorAbstractDefaultCtr.class, BadComparatorAnnotation.class);
dictionary.getComparatorForAnnotation(new BadComparatorAnnotationImp());
}
@Test
public void annotationToComparatoryDictionary_bad_initCtrDefault_exceptionTrhown() {
expectedException.expect(ComparatorInstantiationByAnnotationException.class);
AnnotationToComparatorDictionary dictionary = AnnotationToComparatorDictionary.getInstance();
dictionary.setComparatorForAnnotation(BadComparatorErrInDefaultConstructor.class, BadComparatorAnnotation.class);
dictionary.getComparatorForAnnotation(new BadComparatorAnnotationImp());
}
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD, ElementType.FIELD})
public @interface BadComparatorAnnotation {
int value();
}
}
|
923f68718c14c107d85ac56a15e4631ab8dcfb43
| 756 |
java
|
Java
|
source/com.microsoft.tfs.client.clc/src/com/microsoft/tfs/client/clc/vc/options/OptionForgetBuild.java
|
benzman81/team-explorer-everywhere
|
eb3985c7cb629af9b0ff1c3678403f5c910b7d06
|
[
"MIT"
] | 86 |
2019-05-13T02:21:26.000Z
|
2022-02-06T17:43:29.000Z
|
source/com.microsoft.tfs.client.clc/src/com/microsoft/tfs/client/clc/vc/options/OptionForgetBuild.java
|
benzman81/team-explorer-everywhere
|
eb3985c7cb629af9b0ff1c3678403f5c910b7d06
|
[
"MIT"
] | 82 |
2019-05-14T06:34:16.000Z
|
2022-03-23T20:20:19.000Z
|
source/com.microsoft.tfs.client.clc/src/com/microsoft/tfs/client/clc/vc/options/OptionForgetBuild.java
|
benzman81/team-explorer-everywhere
|
eb3985c7cb629af9b0ff1c3678403f5c910b7d06
|
[
"MIT"
] | 61 |
2019-05-10T19:34:33.000Z
|
2022-03-18T06:29:06.000Z
| 28 | 104 | 0.686508 | 1,001,144 |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See License.txt in the repository root.
package com.microsoft.tfs.client.clc.vc.options;
import com.microsoft.tfs.client.clc.OptionsMap;
import com.microsoft.tfs.client.clc.options.SingleValueOption;
public final class OptionForgetBuild extends SingleValueOption {
public OptionForgetBuild() {
super();
}
@Override
public String getSyntaxString() {
return OptionsMap.getPreferredOptionPrefix() + getMatchedAlias() + ":<buildName>"; //$NON-NLS-1$
}
@Override
protected String[] getValidOptionValues() {
/*
* null means that all values are permitted for this option.
*/
return null;
}
}
|
923f69025fa3ec710ea59e561e88d7f575a58c06
| 1,284 |
java
|
Java
|
src/test/java/com/gargoylesoftware/htmlunit/XMLSerializerTest.java
|
andre-becker/XLT
|
174f9f467ab3094bcdbf80bcea818134a9d1180a
|
[
"Apache-2.0"
] | null | null | null |
src/test/java/com/gargoylesoftware/htmlunit/XMLSerializerTest.java
|
andre-becker/XLT
|
174f9f467ab3094bcdbf80bcea818134a9d1180a
|
[
"Apache-2.0"
] | null | null | null |
src/test/java/com/gargoylesoftware/htmlunit/XMLSerializerTest.java
|
andre-becker/XLT
|
174f9f467ab3094bcdbf80bcea818134a9d1180a
|
[
"Apache-2.0"
] | null | null | null | 35.666667 | 126 | 0.630062 | 1,001,145 |
package com.gargoylesoftware.htmlunit;
import org.junit.Assert;
import org.junit.Test;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
/**
* Testcase which demonstrates issue #1130.
*
* @author Hartmut Arlt (Xceptance Software Technologies GmbH)
*/
public class XMLSerializerTest
{
@Test
public void test() throws Throwable
{
try (final WebClient wc = new WebClient(BrowserVersion.CHROME))
{
wc.getOptions().setJavaScriptEnabled(true);
final String response = "<?xml version=\"1.0\" ?>\n" + "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n"
+ "<head><title>TEST</title></head>\n" + "<body></body>\n" + "</html>\n";
final MockWebConnection conn = new MockWebConnection();
conn.setDefaultResponse(response);
wc.setWebConnection(conn);
final String script = "var t = document.createElement('textarea'); new XMLSerializer().serializeToString(t);";
final HtmlPage page = wc.getPage("http://www.example.org");
final ScriptResult result = page.executeJavaScript(script);
Assert.assertEquals("<textarea xmlns=\"http://www.w3.org/1999/xhtml\"></textarea>", result.getJavaScriptResult());
}
}
}
|
923f696c3c6ef8145e57c057fa472029a07cab9b
| 267 |
java
|
Java
|
app/src/main/java/com/example/enactusapp/Event/BackCameraEvent.java
|
HolmesJJ/EnactusApp
|
e3c7103c4d139da3bacd72541b2af5a5b8fbd6c0
|
[
"MIT"
] | null | null | null |
app/src/main/java/com/example/enactusapp/Event/BackCameraEvent.java
|
HolmesJJ/EnactusApp
|
e3c7103c4d139da3bacd72541b2af5a5b8fbd6c0
|
[
"MIT"
] | null | null | null |
app/src/main/java/com/example/enactusapp/Event/BackCameraEvent.java
|
HolmesJJ/EnactusApp
|
e3c7103c4d139da3bacd72541b2af5a5b8fbd6c0
|
[
"MIT"
] | null | null | null | 17.8 | 47 | 0.681648 | 1,001,146 |
package com.example.enactusapp.Event;
public class BackCameraEvent {
private final boolean isEnabled;
public BackCameraEvent(boolean isEnabled) {
this.isEnabled = isEnabled;
}
public boolean isEnabled() {
return isEnabled;
}
}
|
923f69cc2b6f2909afd2b0eefc98a2cc2403c320
| 77 |
java
|
Java
|
src/main/java/VerificatorInterpritator/Tokens/TermType.java
|
bmstu-iu9/refal-type-verifier
|
8cd31a3289956eb38272d18a3625d6db79abbef3
|
[
"MIT"
] | null | null | null |
src/main/java/VerificatorInterpritator/Tokens/TermType.java
|
bmstu-iu9/refal-type-verifier
|
8cd31a3289956eb38272d18a3625d6db79abbef3
|
[
"MIT"
] | null | null | null |
src/main/java/VerificatorInterpritator/Tokens/TermType.java
|
bmstu-iu9/refal-type-verifier
|
8cd31a3289956eb38272d18a3625d6db79abbef3
|
[
"MIT"
] | null | null | null | 15.4 | 40 | 0.831169 | 1,001,147 |
package VerificatorInterpritator.Tokens;
public abstract class TermType {
}
|
923f69cd54750cb4126310525dfc6b8bb146f20c
| 607 |
java
|
Java
|
src/main/java/com/mine/management/BaseResult.java
|
radulacatusu/company-management
|
2cebebf82a56ac0b1c48ebba3548ff6c8ccf0068
|
[
"MIT"
] | null | null | null |
src/main/java/com/mine/management/BaseResult.java
|
radulacatusu/company-management
|
2cebebf82a56ac0b1c48ebba3548ff6c8ccf0068
|
[
"MIT"
] | null | null | null |
src/main/java/com/mine/management/BaseResult.java
|
radulacatusu/company-management
|
2cebebf82a56ac0b1c48ebba3548ff6c8ccf0068
|
[
"MIT"
] | null | null | null | 16.405405 | 40 | 0.584843 | 1,001,148 |
package com.mine.management;
import java.util.ArrayList;
import java.util.List;
/**
* @param <T>
*/
public class BaseResult<T> {
private List<String> errors;
private T result;
public BaseResult() {
errors = new ArrayList<>();
}
public List<String> getErrors() {
return errors;
}
public void addError(String error) {
errors.add(error);
}
public boolean isSuccess() {
return errors.isEmpty();
}
public T getResult() {
return result;
}
public void setResult(T result) {
this.result = result;
}
}
|
923f69ec401c5b313ed740f56ac574f4e79f3ee5
| 3,059 |
java
|
Java
|
extensions-core/kafka-indexing-service/src/main/java/io/druid/indexing/kafka/supervisor/TaskReportData.java
|
acdn-ekeddy/druid
|
b9b3be6965f86aded444ae9a0a2ef47da9d10fac
|
[
"Apache-2.0"
] | 142 |
2015-01-03T14:03:14.000Z
|
2022-03-07T18:17:13.000Z
|
extensions-core/kafka-indexing-service/src/main/java/io/druid/indexing/kafka/supervisor/TaskReportData.java
|
acdn-ekeddy/druid
|
b9b3be6965f86aded444ae9a0a2ef47da9d10fac
|
[
"Apache-2.0"
] | 17 |
2015-07-01T16:38:59.000Z
|
2019-06-28T14:46:02.000Z
|
extensions-core/kafka-indexing-service/src/main/java/io/druid/indexing/kafka/supervisor/TaskReportData.java
|
acdn-ekeddy/druid
|
b9b3be6965f86aded444ae9a0a2ef47da9d10fac
|
[
"Apache-2.0"
] | 34 |
2015-01-11T06:55:07.000Z
|
2021-06-10T03:54:27.000Z
| 25.280992 | 84 | 0.690749 | 1,001,149 |
/*
* Licensed to Metamarkets Group Inc. (Metamarkets) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. Metamarkets 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.druid.indexing.kafka.supervisor;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import org.joda.time.DateTime;
import javax.annotation.Nullable;
import java.util.Map;
public class TaskReportData
{
public enum TaskType
{
ACTIVE, PUBLISHING, UNKNOWN
}
private final String id;
private final Map<Integer, Long> startingOffsets;
private final DateTime startTime;
private final Long remainingSeconds;
private final TaskType type;
private final Map<Integer, Long> currentOffsets;
private final Map<Integer, Long> lag;
public TaskReportData(
String id,
@Nullable Map<Integer, Long> startingOffsets,
@Nullable Map<Integer, Long> currentOffsets,
DateTime startTime,
Long remainingSeconds,
TaskType type,
@Nullable Map<Integer, Long> lag
)
{
this.id = id;
this.startingOffsets = startingOffsets;
this.currentOffsets = currentOffsets;
this.startTime = startTime;
this.remainingSeconds = remainingSeconds;
this.type = type;
this.lag = lag;
}
@JsonProperty
public String getId()
{
return id;
}
@JsonProperty
@JsonInclude(JsonInclude.Include.NON_NULL)
public Map<Integer, Long> getStartingOffsets()
{
return startingOffsets;
}
@JsonProperty
@JsonInclude(JsonInclude.Include.NON_NULL)
public Map<Integer, Long> getCurrentOffsets()
{
return currentOffsets;
}
@JsonProperty
public DateTime getStartTime()
{
return startTime;
}
@JsonProperty
public Long getRemainingSeconds()
{
return remainingSeconds;
}
@JsonProperty
public TaskType getType()
{
return type;
}
@JsonProperty
@JsonInclude(JsonInclude.Include.NON_NULL)
public Map<Integer, Long> getLag()
{
return lag;
}
@Override
public String toString()
{
return "{" +
"id='" + id + '\'' +
(startingOffsets != null ? ", startingOffsets=" + startingOffsets : "") +
(currentOffsets != null ? ", currentOffsets=" + currentOffsets : "") +
", startTime=" + startTime +
", remainingSeconds=" + remainingSeconds +
(lag != null ? ", lag=" + lag : "") +
'}';
}
}
|
923f69f56ce0dd9181873f8760b3f3d20c6a32ec
| 2,179 |
java
|
Java
|
DomsCommands/src/com/domsplace/DomsCommands/Commands/HomesCommand.java
|
YourWishes/DomsCommands
|
ffa879cacf2e656285400f32311936eae2da5907
|
[
"Apache-2.0"
] | null | null | null |
DomsCommands/src/com/domsplace/DomsCommands/Commands/HomesCommand.java
|
YourWishes/DomsCommands
|
ffa879cacf2e656285400f32311936eae2da5907
|
[
"Apache-2.0"
] | null | null | null |
DomsCommands/src/com/domsplace/DomsCommands/Commands/HomesCommand.java
|
YourWishes/DomsCommands
|
ffa879cacf2e656285400f32311936eae2da5907
|
[
"Apache-2.0"
] | null | null | null | 32.044118 | 88 | 0.620009 | 1,001,150 |
/*
* Copyright 2013 Dominic.
*
* 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.domsplace.DomsCommands.Commands;
import com.domsplace.DomsCommands.Bases.BukkitCommand;
import com.domsplace.DomsCommands.Objects.DomsPlayer;
import com.domsplace.DomsCommands.Objects.Home;
import java.util.ArrayList;
import java.util.List;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
/**
* @author Dominic
* @since 24/10/2013
*/
public class HomesCommand extends BukkitCommand {
public HomesCommand() {
super("homes");
}
@Override
public boolean cmd(CommandSender sender, Command cmd, String label, String[] args) {
if(!isPlayer(sender) && args.length < 1) {
sendMessage(sender, ChatError + "Please enter a player name.");
return true;
}
DomsPlayer player = DomsPlayer.getPlayer(sender);
if(args.length > 0) {
player = DomsPlayer.guessOnlinePlayer(sender, args[0]);
}
if(player == null || player.isConsole()) {
sendMessage(sender, ChatError + "Player not found.");
return true;
}
List<String> msgs = new ArrayList<String>();
msgs.add(ChatImportant + "Homes: (" + player.getHomes().size() + ")");
String s = "";
List<Home> homes = player.getHomes();
for(int i = 0; i < homes.size(); i++) {
Home h = homes.get(i);
s += h.getName();
if(i < (homes.size() -1)) s += ", ";
}
msgs.add(s);
sendMessage(sender, msgs);
return true;
}
}
|
923f6a8589562b7b69b13b96561f964f516d3ce9
| 13,492 |
java
|
Java
|
core/src/main/java/org/bitcoinj/core/VersionMessage.java
|
bitcoincash-wallet/bitcoincashj
|
c3708f00dc947bf5d72c480390f92c640312379d
|
[
"Apache-2.0"
] | 32 |
2017-09-06T02:21:58.000Z
|
2021-07-05T03:43:14.000Z
|
core/src/main/java/org/bitcoinj/core/VersionMessage.java
|
bitcoincash-wallet/bitcoincashj
|
c3708f00dc947bf5d72c480390f92c640312379d
|
[
"Apache-2.0"
] | 13 |
2017-11-27T05:02:18.000Z
|
2019-12-24T03:57:28.000Z
|
core/src/main/java/org/bitcoinj/core/VersionMessage.java
|
bitcoincash-wallet/bitcoincashj
|
c3708f00dc947bf5d72c480390f92c640312379d
|
[
"Apache-2.0"
] | 21 |
2017-09-01T07:03:31.000Z
|
2020-12-25T00:22:16.000Z
| 45.123746 | 127 | 0.656092 | 1,001,151 |
/*
* Copyright 2011 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 org.bitcoinj.core;
import com.google.common.base.Objects;
import javax.annotation.Nullable;
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Locale;
/**
* <p>A VersionMessage holds information exchanged during connection setup with another peer. Most of the fields are not
* particularly interesting. The subVer field, since BIP 14, acts as a User-Agent string would. You can and should
* append to or change the subVer for your own software so other implementations can identify it, and you can look at
* the subVer field received from other nodes to see what they are running.</p>
*
* <p>After creating yourself a VersionMessage, you can pass it to {@link PeerGroup#setVersionMessage(VersionMessage)}
* to ensure it will be used for each new connection.</p>
*
* <p>Instances of this class are not safe for use by multiple threads.</p>
*/
public class VersionMessage extends Message {
/** A service bit that denotes whether the peer has a copy of the block chain or not. */
public static final int NODE_NETWORK = 1 << 0;
/** A service bit that denotes whether the peer supports the getutxos message or not. */
public static final int NODE_GETUTXOS = 1 << 1;
/** A service bit used by Bitcoin-ABC to announce Bitcoin Cash nodes. */
public static final int NODE_BITCOIN_CASH = 1 << 5;
/**
* The version number of the protocol spoken.
*/
public int clientVersion;
/**
* Flags defining what optional services are supported.
*/
public long localServices;
/**
* What the other side believes the current time to be, in seconds.
*/
public long time;
/**
* What the other side believes the address of this program is. Not used.
*/
public PeerAddress myAddr;
/**
* What the other side believes their own address is. Not used.
*/
public PeerAddress theirAddr;
/**
* User-Agent as defined in <a href="https://github.com/bitcoin/bips/blob/master/bip-0014.mediawiki">BIP 14</a>.
* Bitcoin Core sets it to something like "/Satoshi:0.9.1/".
*/
public String subVer;
/**
* How many blocks are in the chain, according to the other side.
*/
public long bestHeight;
/**
* Whether or not to relay tx invs before a filter is received.
* See <a href="https://github.com/bitcoin/bips/blob/master/bip-0037.mediawiki#extensions-to-existing-messages">BIP 37</a>.
*/
public boolean relayTxesBeforeFilter;
/** The version of this library release, as a string. */
public static final String BITCOINJ_VERSION = "0.14.5";
/** The value that is prepended to the subVer field of this application. */
public static final String LIBRARY_SUBVER = "/bitcoincashj:" + BITCOINJ_VERSION + "/";
public VersionMessage(NetworkParameters params, byte[] payload) throws ProtocolException {
super(params, payload, 0);
}
// It doesn't really make sense to ever lazily parse a version message or to retain the backing bytes.
// If you're receiving this on the wire you need to check the protocol version and it will never need to be sent
// back down the wire.
public VersionMessage(NetworkParameters params, int newBestHeight) {
super(params);
clientVersion = params.getProtocolVersionNum(NetworkParameters.ProtocolVersion.CURRENT);
localServices = 0;
time = System.currentTimeMillis() / 1000;
// Note that the Bitcoin Core doesn't do anything with these, and finding out your own external IP address
// is kind of tricky anyway, so we just put nonsense here for now.
try {
// We hard-code the IPv4 localhost address here rather than use InetAddress.getLocalHost() because some
// mobile phones have broken localhost DNS entries, also, this is faster.
final byte[] localhost = { 127, 0, 0, 1 };
myAddr = new PeerAddress(InetAddress.getByAddress(localhost), params.getPort(), 0);
theirAddr = new PeerAddress(InetAddress.getByAddress(localhost), params.getPort(), 0);
} catch (UnknownHostException e) {
throw new RuntimeException(e); // Cannot happen (illegal IP length).
}
subVer = LIBRARY_SUBVER;
bestHeight = newBestHeight;
relayTxesBeforeFilter = true;
length = 85;
if (protocolVersion > 31402)
length += 8;
length += VarInt.sizeOf(subVer.length()) + subVer.length();
}
@Override
protected void parse() throws ProtocolException {
clientVersion = (int) readUint32();
localServices = readUint64().longValue();
time = readUint64().longValue();
myAddr = new PeerAddress(params, payload, cursor, 0);
cursor += myAddr.getMessageSize();
theirAddr = new PeerAddress(params, payload, cursor, 0);
cursor += theirAddr.getMessageSize();
// uint64 localHostNonce (random data)
// We don't care about the localhost nonce. It's used to detect connecting back to yourself in cases where
// there are NATs and proxies in the way. However we don't listen for inbound connections so it's irrelevant.
readUint64();
try {
// Initialize default values for flags which may not be sent by old nodes
subVer = "";
bestHeight = 0;
relayTxesBeforeFilter = true;
if (!hasMoreBytes())
return;
// string subVer (currently "")
subVer = readStr();
if (!hasMoreBytes())
return;
// int bestHeight (size of known block chain).
bestHeight = readUint32();
if (!hasMoreBytes())
return;
relayTxesBeforeFilter = readBytes(1)[0] != 0;
} finally {
length = cursor - offset;
}
}
@Override
public void bitcoinSerializeToStream(OutputStream buf) throws IOException {
Utils.uint32ToByteStreamLE(clientVersion, buf);
Utils.uint32ToByteStreamLE(localServices, buf);
Utils.uint32ToByteStreamLE(localServices >> 32, buf);
Utils.uint32ToByteStreamLE(time, buf);
Utils.uint32ToByteStreamLE(time >> 32, buf);
try {
// My address.
myAddr.bitcoinSerialize(buf);
// Their address.
theirAddr.bitcoinSerialize(buf);
} catch (UnknownHostException e) {
throw new RuntimeException(e); // Can't happen.
} catch (IOException e) {
throw new RuntimeException(e); // Can't happen.
}
// Next up is the "local host nonce", this is to detect the case of connecting
// back to yourself. We don't care about this as we won't be accepting inbound
// connections.
Utils.uint32ToByteStreamLE(0, buf);
Utils.uint32ToByteStreamLE(0, buf);
// Now comes subVer.
byte[] subVerBytes = subVer.getBytes("UTF-8");
buf.write(new VarInt(subVerBytes.length).encode());
buf.write(subVerBytes);
// Size of known block chain.
Utils.uint32ToByteStreamLE(bestHeight, buf);
buf.write(relayTxesBeforeFilter ? 1 : 0);
}
/**
* Returns true if the version message indicates the sender has a full copy of the block chain,
* or if it's running in client mode (only has the headers).
*/
public boolean hasBlockChain() {
return (localServices & NODE_NETWORK) == NODE_NETWORK;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
VersionMessage other = (VersionMessage) o;
return other.bestHeight == bestHeight &&
other.clientVersion == clientVersion &&
other.localServices == localServices &&
other.time == time &&
other.subVer.equals(subVer) &&
other.myAddr.equals(myAddr) &&
other.theirAddr.equals(theirAddr) &&
other.relayTxesBeforeFilter == relayTxesBeforeFilter;
}
@Override
public int hashCode() {
return Objects.hashCode(bestHeight, clientVersion, localServices,
time, subVer, myAddr, theirAddr, relayTxesBeforeFilter);
}
@Override
public String toString() {
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("\n");
stringBuilder.append("client version: ").append(clientVersion).append("\n");
stringBuilder.append("local services: ").append(localServices).append("\n");
stringBuilder.append("time: ").append(time).append("\n");
stringBuilder.append("my addr: ").append(myAddr).append("\n");
stringBuilder.append("their addr: ").append(theirAddr).append("\n");
stringBuilder.append("sub version: ").append(subVer).append("\n");
stringBuilder.append("best height: ").append(bestHeight).append("\n");
stringBuilder.append("delay tx relay: ").append(!relayTxesBeforeFilter).append("\n");
return stringBuilder.toString();
}
public VersionMessage duplicate() {
VersionMessage v = new VersionMessage(params, (int) bestHeight);
v.clientVersion = clientVersion;
v.localServices = localServices;
v.time = time;
v.myAddr = myAddr;
v.theirAddr = theirAddr;
v.subVer = subVer;
v.relayTxesBeforeFilter = relayTxesBeforeFilter;
return v;
}
/**
* Appends the given user-agent information to the subVer field. The subVer is composed of a series of
* name:version pairs separated by slashes in the form of a path. For example a typical subVer field for bitcoinj
* users might look like "/bitcoinj:0.13/MultiBit:1.2/" where libraries come further to the left.<p>
*
* There can be as many components as you feel a need for, and the version string can be anything, but it is
* recommended to use A.B.C where A = major, B = minor and C = revision for software releases, and dates for
* auto-generated source repository snapshots. A valid subVer begins and ends with a slash, therefore name
* and version are not allowed to contain such characters. <p>
*
* Anything put in the "comments" field will appear in brackets and may be used for platform info, or anything
* else. For example, calling <tt>appendToSubVer("MultiBit", "1.0", "Windows")</tt> will result in a subVer being
* set of "/bitcoinj:1.0/MultiBit:1.0(Windows)/". Therefore the / ( and ) characters are reserved in all these
* components. If you don't want to add a comment (recommended), pass null.<p>
*
* See <a href="https://github.com/bitcoin/bips/blob/master/bip-0014.mediawiki">BIP 14</a> for more information.
*
* @param comments Optional (can be null) platform or other node specific information.
* @throws IllegalArgumentException if name, version or comments contains invalid characters.
*/
public void appendToSubVer(String name, String version, @Nullable String comments) {
checkSubVerComponent(name);
checkSubVerComponent(version);
if (comments != null) {
checkSubVerComponent(comments);
subVer = subVer.concat(String.format(Locale.US, "%s:%s(%s)/", name, version, comments));
} else {
subVer = subVer.concat(String.format(Locale.US, "%s:%s/", name, version));
}
}
private static void checkSubVerComponent(String component) {
if (component.contains("/") || component.contains("(") || component.contains(")"))
throw new IllegalArgumentException("name contains invalid characters");
}
/**
* Returns true if the clientVersion field is >= Pong.MIN_PROTOCOL_VERSION. If it is then ping() is usable.
*/
public boolean isPingPongSupported() {
return clientVersion >= params.getProtocolVersionNum(NetworkParameters.ProtocolVersion.PONG);
}
/**
* Returns true if the clientVersion field is >= FilteredBlock.MIN_PROTOCOL_VERSION. If it is then Bloom filtering
* is available and the memory pool of the remote peer will be queried when the downloadData property is true.
*/
public boolean isBloomFilteringSupported() {
return clientVersion >= params.getProtocolVersionNum(NetworkParameters.ProtocolVersion.BLOOM_FILTER);
}
/** Returns true if the protocol version and service bits both indicate support for the getutxos message. */
public boolean isGetUTXOsSupported() {
return clientVersion >= GetUTXOsMessage.MIN_PROTOCOL_VERSION &&
(localServices & NODE_GETUTXOS) == NODE_GETUTXOS;
}
}
|
923f6b81d7045453eaf2489246f92d992b209940
| 2,893 |
java
|
Java
|
src/main/java/com/baomidou/config/rules/QuerySQL.java
|
tuonioooo/mybatis-maven-plugin
|
e80cc0c00bf265ed8d4b337375ae8d214cee722f
|
[
"Apache-2.0"
] | 36 |
2018-11-30T09:55:27.000Z
|
2021-11-15T09:57:31.000Z
|
src/main/java/com/baomidou/config/rules/QuerySQL.java
|
zhangjunfang/mybatisplus-maven-plugin
|
e80cc0c00bf265ed8d4b337375ae8d214cee722f
|
[
"Apache-2.0"
] | 3 |
2019-06-01T10:45:29.000Z
|
2019-08-29T02:42:45.000Z
|
src/main/java/com/baomidou/config/rules/QuerySQL.java
|
zhangjunfang/mybatisplus-maven-plugin
|
e80cc0c00bf265ed8d4b337375ae8d214cee722f
|
[
"Apache-2.0"
] | 25 |
2018-12-13T14:18:37.000Z
|
2022-01-21T07:52:03.000Z
| 31.107527 | 121 | 0.636364 | 1,001,152 |
package com.baomidou.config.rules;
/**
* <p>
* 表数据查询
* </p>
*
* @author hubin
* @since 2016-04-25
*/
public enum QuerySQL {
MYSQL("mysql", "show tables", "show table status",
"show full fields from %s",
"NAME", "COMMENT", "FIELD", "TYPE", "COMMENT", "KEY"),
ORACLE("oracle", "SELECT * FROM USER_TABLES", "SELECT * FROM USER_TAB_COMMENTS",
"SELECT AB.COLUMN_NAME,AB.DATA_TYPE, AB.COMMENTS, DECODE(AC.POSITION, '1', 'PRI') KEY " +
"FROM (SELECT A.COLUMN_NAME, A.DATA_TYPE, B.COMMENTS FROM USER_TAB_COLUMNS A, USER_COL_COMMENTS B " +
"WHERE A.TABLE_NAME = B.TABLE_NAME AND A.COLUMN_NAME = B.COLUMN_NAME AND A.TABLE_NAME = '%s') AB " +
"LEFT JOIN(SELECT CU.COLUMN_NAME, CU.POSITION FROM USER_CONS_COLUMNS CU, USER_CONSTRAINTS AU " +
"WHERE CU.CONSTRAINT_NAME = AU.CONSTRAINT_NAME AND AU.CONSTRAINT_TYPE = 'P' " +
"AND AU.TABLE_NAME = '%s') AC ON AB.COLUMN_NAME = AC.COLUMN_NAME ",
"TABLE_NAME", "COMMENTS", "COLUMN_NAME", "DATA_TYPE", "COMMENTS", "KEY");
private final String dbType;
private final String tablesSql;
private final String tableCommentsSql;
private final String tableFieldsSql;
private final String tableName;
private final String tableComment;
private final String fieldName;
private final String fieldType;
private final String fieldComment;
private final String fieldKey;
QuerySQL(final String dbType, final String tablesSql, final String tableCommentsSql,
final String tableFieldsSql, final String tableName, final String tableComment, final String fieldName,
final String fieldType, final String fieldComment, final String fieldKey) {
this.dbType = dbType;
this.tablesSql = tablesSql;
this.tableCommentsSql = tableCommentsSql;
this.tableFieldsSql = tableFieldsSql;
this.tableName = tableName;
this.tableComment = tableComment;
this.fieldName = fieldName;
this.fieldType = fieldType;
this.fieldComment = fieldComment;
this.fieldKey = fieldKey;
}
public String getDbType() {
return dbType;
}
public String getTablesSql() {
return tablesSql;
}
public String getTableCommentsSql() {
return tableCommentsSql;
}
public String getTableFieldsSql() {
return tableFieldsSql;
}
public String getTableName() {
return tableName;
}
public String getTableComment() {
return tableComment;
}
public String getFieldName() {
return fieldName;
}
public String getFieldType() {
return fieldType;
}
public String getFieldComment() {
return fieldComment;
}
public String getFieldKey() {
return fieldKey;
}
}
|
923f6c91167a9fa86fc85cee6eda522148c279b5
| 1,512 |
java
|
Java
|
src/main/java/ruina/relics/Malice.java
|
Darkglade1/Ruina
|
61cb0f98e431a28f48ebac80c78647368c38bb72
|
[
"MIT"
] | 2 |
2021-02-23T04:21:42.000Z
|
2022-02-17T20:25:20.000Z
|
src/main/java/ruina/relics/Malice.java
|
Darkglade1/Ruina
|
61cb0f98e431a28f48ebac80c78647368c38bb72
|
[
"MIT"
] | 1 |
2021-02-15T16:04:08.000Z
|
2021-02-15T16:04:08.000Z
|
src/main/java/ruina/relics/Malice.java
|
Darkglade1/Ruina
|
61cb0f98e431a28f48ebac80c78647368c38bb72
|
[
"MIT"
] | 1 |
2021-02-12T01:35:16.000Z
|
2021-02-12T01:35:16.000Z
| 38.769231 | 172 | 0.733466 | 1,001,153 |
package ruina.relics;
import com.megacrit.cardcrawl.actions.AbstractGameAction;
import com.megacrit.cardcrawl.actions.common.DamageAllEnemiesAction;
import com.megacrit.cardcrawl.actions.common.RelicAboveCreatureAction;
import com.megacrit.cardcrawl.cards.DamageInfo;
import static ruina.RuinaMod.makeID;
import static ruina.util.Wiz.adp;
import static ruina.util.Wiz.atb;
public class Malice extends AbstractEasyRelic {
public static final String ID = makeID(Malice.class.getSimpleName());
private static final int DAMAGE = 2;
private static final int LOW_HP_DAMAGE = 5;
private static final int LOW_HP_THRESHOLD = 50;
public Malice() {
super(ID, RelicTier.SPECIAL, LandingSound.MAGICAL);
}
@Override
public void atTurnStart() {
this.flash();
atb(new RelicAboveCreatureAction(adp(), this));
if (adp().currentHealth <= adp().maxHealth * ((float) LOW_HP_THRESHOLD / 100)) {
atb(new DamageAllEnemiesAction(null, DamageInfo.createDamageMatrix(LOW_HP_DAMAGE, true), DamageInfo.DamageType.THORNS, AbstractGameAction.AttackEffect.POISON));
} else {
atb(new DamageAllEnemiesAction(null, DamageInfo.createDamageMatrix(DAMAGE, true), DamageInfo.DamageType.THORNS, AbstractGameAction.AttackEffect.POISON));
}
}
@Override
public String getUpdatedDescription() {
return DESCRIPTIONS[0] + DAMAGE + DESCRIPTIONS[1] + LOW_HP_THRESHOLD + DESCRIPTIONS[2] + LOW_HP_DAMAGE + DESCRIPTIONS[3];
}
}
|
923f6cb280b8ff7180abca9b3d304892c0fbb145
| 1,235 |
java
|
Java
|
moonrock/src/main/java/com/trogdor/moonrock/MRScriptLoader.java
|
cfraz89/MoonRock
|
e26b9fa3b14b96609c3965b5f9f462abe6f478ce
|
[
"Apache-2.0"
] | null | null | null |
moonrock/src/main/java/com/trogdor/moonrock/MRScriptLoader.java
|
cfraz89/MoonRock
|
e26b9fa3b14b96609c3965b5f9f462abe6f478ce
|
[
"Apache-2.0"
] | null | null | null |
moonrock/src/main/java/com/trogdor/moonrock/MRScriptLoader.java
|
cfraz89/MoonRock
|
e26b9fa3b14b96609c3965b5f9f462abe6f478ce
|
[
"Apache-2.0"
] | null | null | null | 25.729167 | 82 | 0.575709 | 1,001,154 |
package com.trogdor.moonrock;
import android.webkit.WebView;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
/**
* Created by chrisfraser on 7/07/15.
*/
public class MRScriptLoader {
WebView mWebView;
public MRScriptLoader(WebView webView) {
mWebView = webView;
}
public void loadScript(String fileName) {
String script = loadAsset(fileName);
if (script != null) {
mWebView.evaluateJavascript(script, null);
}
}
private String loadAsset(String fileName) {
String script = null;
BufferedReader reader = null;
try {
InputStream stream = mWebView.getContext().getAssets().open(fileName);
reader = new BufferedReader(new InputStreamReader(stream));
byte[] buffer = new byte[stream.available()];
stream.read(buffer);
script = new String(buffer);
} catch (IOException e) {
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
}
}
}
return script;
}
}
|
923f6cd40394fe3d3cda26fe8ab545e1bf633727
| 4,189 |
java
|
Java
|
corpus/class/eclipse.jdt.core/953.java
|
masud-technope/ACER-Replication-Package-ASE2017
|
cb7318a729eb1403004d451a164c851af2d81f7a
|
[
"MIT"
] | 15 |
2018-07-10T09:38:31.000Z
|
2021-11-29T08:28:07.000Z
|
corpus/class/eclipse.jdt.core/953.java
|
masud-technope/ACER-Replication-Package-ASE2017
|
cb7318a729eb1403004d451a164c851af2d81f7a
|
[
"MIT"
] | 3 |
2018-11-16T02:58:59.000Z
|
2021-01-20T16:03:51.000Z
|
corpus/class/eclipse.jdt.core/953.java
|
masud-technope/ACER-Replication-Package-ASE2017
|
cb7318a729eb1403004d451a164c851af2d81f7a
|
[
"MIT"
] | 6 |
2018-06-27T20:19:00.000Z
|
2022-02-19T02:29:53.000Z
| 35.483051 | 129 | 0.663721 | 1,001,155 |
/*******************************************************************************
* Copyright (c) 2007, 2014 BEA Systems, 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:
* [email protected] - initial API and implementation
* IBM Corporation - fix for 342936
*******************************************************************************/
package org.eclipse.jdt.compiler.apt.tests;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.lang.model.SourceVersion;
import javax.tools.JavaCompiler;
import javax.tools.ToolProvider;
import junit.framework.TestCase;
/**
* Tests of the language model utility APIs, e.g., javax.lang.model.util.*
*/
public class ModelUtilTests extends TestCase {
// Processor class names; see corresponding usage in the processor classes.
private static final String ELEMENTUTILSPROC = "org.eclipse.jdt.compiler.apt.tests.processors.elementutils.ElementUtilsProc";
private static final String TYPEUTILSPROC = "org.eclipse.jdt.compiler.apt.tests.processors.typeutils.TypeUtilsProc";
@Override
protected void setUp() throws Exception {
super.setUp();
BatchTestUtils.init();
}
/**
* Validate the testElements test against the javac compiler.
* @throws IOException
*/
public void testElementsWithSystemCompiler() throws IOException {
if (!canRunJava8()) {
return;
}
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
if (compiler == null) {
System.out.println("No system java compiler available");
return;
}
internalTest(compiler, ELEMENTUTILSPROC);
}
/**
* Test the Elements utility implementation.
* @throws IOException
*/
public void testElementsWithEclipseCompiler() throws IOException {
JavaCompiler compiler = BatchTestUtils.getEclipseCompiler();
internalTest(compiler, ELEMENTUTILSPROC);
}
/**
* Validate the testTypes test against the javac compiler.
* @throws IOException
*/
public void testTypesWithSystemCompiler() throws IOException {
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
if (compiler == null) {
System.out.println("No system java compiler available");
return;
}
internalTest(compiler, TYPEUTILSPROC);
}
/**
* Test the Types utility implementation.
* @throws IOException
*/
public void testTypesWithEclipseCompiler() throws IOException {
JavaCompiler compiler = BatchTestUtils.getEclipseCompiler();
internalTest(compiler, TYPEUTILSPROC);
}
/**
* Test functionality by running a particular processor against the types in
* resources/targets. The processor must support "*" (the set of all annotations)
* and must report its errors or success via the methods in BaseProcessor.
* @throws IOException
*/
private void internalTest(JavaCompiler compiler, String processorClass) throws IOException {
System.clearProperty(processorClass);
File targetFolder = TestUtils.concatPath(BatchTestUtils.getSrcFolderName(), "targets", "model");
BatchTestUtils.copyResources("targets/model", targetFolder);
List<String> options = new ArrayList<String>();
options.add("-A" + processorClass);
BatchTestUtils.compileTree(compiler, options, targetFolder);
// If it succeeded, the processor will have set this property to "succeeded";
// if not, it will set it to an error value.
assertEquals("succeeded", System.getProperty(processorClass));
}
private boolean canRunJava8() {
try {
SourceVersion.valueOf("RELEASE_8");
} catch (IllegalArgumentException iae) {
return false;
}
return true;
}
@Override
protected void tearDown() throws Exception {
super.tearDown();
}
}
|
923f6d306aafaf65d537f1d0bd5812cfaa25926a
| 4,266 |
java
|
Java
|
CastleSiegePom/CastleSiegeApp/src/test/java/com/pilaf/cs/tests/steps/users/UserRegistrationSteps.java
|
rakocz88/castlesiege2.0
|
ad867917036afdf88c28bc6762f3d9d46767607f
|
[
"Apache-2.0"
] | null | null | null |
CastleSiegePom/CastleSiegeApp/src/test/java/com/pilaf/cs/tests/steps/users/UserRegistrationSteps.java
|
rakocz88/castlesiege2.0
|
ad867917036afdf88c28bc6762f3d9d46767607f
|
[
"Apache-2.0"
] | null | null | null |
CastleSiegePom/CastleSiegeApp/src/test/java/com/pilaf/cs/tests/steps/users/UserRegistrationSteps.java
|
rakocz88/castlesiege2.0
|
ad867917036afdf88c28bc6762f3d9d46767607f
|
[
"Apache-2.0"
] | null | null | null | 47.4 | 160 | 0.756212 | 1,001,156 |
package com.pilaf.cs.tests.steps.users;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.notNullValue;
import static org.hamcrest.Matchers.nullValue;
import com.pilaf.cs.tests.state.UserRegistrationTestState;
import cucumber.api.java.en.Given;
import cucumber.api.java.en.Then;
import cucumber.api.java.en.When;;
public class UserRegistrationSteps extends AbstractUserRegistrationTestCase {
@Given("^AB- I am a person who wants to create a account$")
public void ab_I_am_a_person_who_wants_to_create_a_account() throws Throwable {
UserRegistrationTestState.resetData();
}
@When("^AB- A user with username \"([^\"]*)\" exists in the database$")
public void ab_A_user_with_username_exists_in_the_database(String name) throws Throwable {
assertThat("User should exist in database", userRepository.findByUsername(name), is(notNullValue()));
}
@Then("^AB- I should get a response with status (\\d+)$")
public void ab_I_should_get_a_response_with_status(int statusCode) throws Throwable {
assertThat("Wrong status code", UserRegistrationTestState.getInstance().getCurrentHttpStatus(),
equalTo(statusCode));
}
@Then("^AB- I should get the response status (\\d+)$")
public void ab_I_should_get_the_response_status(int statusCode) throws Throwable {
assertThat("Wrong status code", UserRegistrationTestState.getInstance().getCurrentHttpStatus(),
equalTo(statusCode));
}
@When("^AB- User \"([^\"]*)\" does not exist in the database$")
public void ab_User_does_not_exist_in_the_database(String username) throws Throwable {
assertThat("User should not exist in the database", userRepository.findByUsername(username), is(nullValue()));
}
@Then("^AB- User \"([^\"]*)\" enabled flag should be \"([^\"]*)\"$")
public void ab_User_enabled_flag_should_be(String name, String enabled) throws Throwable {
assertThat("User enabled flag should be", userRepository.findByUsername(name).getEnabled(),
equalTo(Boolean.parseBoolean(enabled)));
}
@Then("^AB- in the output msg there should be an entry for user \"([^\"]*)\" and it should not be empty$")
public void ab_in_the_output_msg_there_should_be_an_entry_for_user_and_it_should_not_be_empty(String username)
throws Throwable {
assertThat("Email should be send to user", emailBiz.findAllByUser(username).isEmpty(), equalTo(false));
}
@When("^AB- I try to perform a log in with the user \"([^\"]*)\" with password \"([^\"]*)\"$")
public void ab_I_try_to_perform_a_log_in_with_the_user_with_password(String username, String password)
throws Throwable {
loginTestHelper.logInWithUser(username, password, UserRegistrationTestState.getInstance(), port);
}
@Then("^AB- I should get the response (\\d+)$")
public void ab_I_should_get_the_response(int resposeCode) throws Throwable {
assertThat("Wrong status code", UserRegistrationTestState.getInstance().getCurrentHttpStatus(),
equalTo(resposeCode));
}
@Then("^AB- User \"([^\"]*)\" should be in the database$")
public void ab_User_should_be_in_the_database(String username) throws Throwable {
assertThat("User should exist in the database", userRepository.findByUsername(username), is(notNullValue()));
}
@Then("^AB- the response should contain a not empty token$")
public void ab_the_response_should_contain_a_not_empty_token() throws Throwable {
assertThat("Token should not be empty", UserRegistrationTestState.getInstance().getAuthorizationToken(),
is(notNullValue()));
}
@When("^AB- I register a user with login \"([^\"]*)\" and password \"([^\"]*)\" and firstname \"([^\"]*)\" and surname \"([^\"]*)\" and email \"([^\"]*)\"$")
public void ab_I_register_a_user_with_login_and_password_and_firstname_and_surname_and_email(String login,
String password, String firstname, String surname, String email) throws Throwable {
registerUser(login, password, firstname, surname, email, UserRegistrationTestState.getInstance());
}
@When("^AB- I click the link then was send to \"([^\"]*)\"$")
public void ab_I_click_the_link_then_was_send_to(String email) throws Throwable {
clickTheLinkThatWasSendOnEmail(email, UserRegistrationTestState.getInstance());
}
}
|
923f6d6a5811b4ac6b6d840cb8d62f586c31b630
| 2,828 |
java
|
Java
|
app/src/main/java/com/karry/tool/Bean/PoetryBean.java
|
Karry1121/Tool
|
24b81abe44109db8752b117728905b3683b419e7
|
[
"Apache-2.0"
] | null | null | null |
app/src/main/java/com/karry/tool/Bean/PoetryBean.java
|
Karry1121/Tool
|
24b81abe44109db8752b117728905b3683b419e7
|
[
"Apache-2.0"
] | null | null | null |
app/src/main/java/com/karry/tool/Bean/PoetryBean.java
|
Karry1121/Tool
|
24b81abe44109db8752b117728905b3683b419e7
|
[
"Apache-2.0"
] | null | null | null | 17.349693 | 62 | 0.693069 | 1,001,157 |
package com.karry.tool.Bean;
public class PoetryBean {
private String status;
private dataDetail data;
private String token;
private String ipAddress;
private String warning;
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public dataDetail getData() {
return data;
}
public void setData(dataDetail data) {
this.data = data;
}
public String getToken() {
return token;
}
public void setToken(String token) {
this.token = token;
}
public String getIpAddress() {
return ipAddress;
}
public void setIpAddress(String ipAddress) {
this.ipAddress = ipAddress;
}
public String getWarning() {
return warning;
}
public void setWarning(String warning) {
this.warning = warning;
}
public static class originDetail {
private String title;
private String dynasty;
private String author;
private String[] content;
private String[] translate;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDynasty() {
return dynasty;
}
public void setDynasty(String dynasty) {
this.dynasty = dynasty;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public String[] getContent() {
return content;
}
public void setContent(String[] content) {
this.content = content;
}
public String[] getTranslate() {
return translate;
}
public void setTranslate(String[] translate) {
this.translate = translate;
}
}
public static class dataDetail {
private String id;
private String content;
private String popularity;
private originDetail origin;
private String[] matchTags;
private String recommendedReason;
private String cacheAt;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public String getPopularity() {
return popularity;
}
public void setPopularity(String popularity) {
this.popularity = popularity;
}
public originDetail getOrigin() {
return origin;
}
public void setOrigin(originDetail origin) {
this.origin = origin;
}
public String[] getMatchTags() {
return matchTags;
}
public void setMatchTags(String[] matchTags) {
this.matchTags = matchTags;
}
public String getRecommendedReason() {
return recommendedReason;
}
public void setRecommendedReason(String recommendedReason) {
this.recommendedReason = recommendedReason;
}
public String getCacheAt() {
return cacheAt;
}
public void setCacheAt(String cacheAt) {
this.cacheAt = cacheAt;
}
}
}
|
923f6dc75e3383dea539c20bde750a1d5ab85376
| 1,050 |
java
|
Java
|
grow-budget-advisor-service/src/main/java/com/mindthehippo/budget/application/BudgetApplicationService.java
|
morgade/grow-budget-advisor
|
f175c94b788cb726dc033990628f3e7e46c6f20b
|
[
"MIT"
] | null | null | null |
grow-budget-advisor-service/src/main/java/com/mindthehippo/budget/application/BudgetApplicationService.java
|
morgade/grow-budget-advisor
|
f175c94b788cb726dc033990628f3e7e46c6f20b
|
[
"MIT"
] | null | null | null |
grow-budget-advisor-service/src/main/java/com/mindthehippo/budget/application/BudgetApplicationService.java
|
morgade/grow-budget-advisor
|
f175c94b788cb726dc033990628f3e7e46c6f20b
|
[
"MIT"
] | null | null | null | 29.166667 | 91 | 0.730476 | 1,001,158 |
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.mindthehippo.budget.application;
import com.mindthehippo.account.AccountEvent;
import com.mindthehippo.budget.aggregate.budget.Category;
import com.mindthehippo.budget.application.dto.BudgetDTO;
import com.mindthehippo.budget.application.dto.GoalDTO;
import com.mindthehippo.budget.application.dto.ItemDTO;
import java.util.List;
import java.util.UUID;
/**
*
* @author Lucas
*/
public interface BudgetApplicationService {
BudgetDTO get(UUID account, int startWeekForRealizedData, int endWeekForRealizedData);
List<Category> getItemCagories();
void store(UUID account, ItemDTO itemDTO);
void store(UUID account, GoalDTO goalDTO);
//Finds and stores the budget item related to the received event
void processAccountEvent(AccountEvent accountEvent);
}
|
923f6f4af0a2cadd97a84f3c6ddd0ffff92fd73f
| 1,714 |
java
|
Java
|
bullet/src/gen/java/org/bytedeco/bullet/BulletCollision/btCollisionObjectWrapper.java
|
mode89/javacpp-presets
|
ed5fe63614b09e4fd9579c3f2acd8737e2107c72
|
[
"Apache-2.0"
] | null | null | null |
bullet/src/gen/java/org/bytedeco/bullet/BulletCollision/btCollisionObjectWrapper.java
|
mode89/javacpp-presets
|
ed5fe63614b09e4fd9579c3f2acd8737e2107c72
|
[
"Apache-2.0"
] | null | null | null |
bullet/src/gen/java/org/bytedeco/bullet/BulletCollision/btCollisionObjectWrapper.java
|
mode89/javacpp-presets
|
ed5fe63614b09e4fd9579c3f2acd8737e2107c72
|
[
"Apache-2.0"
] | null | null | null | 51.939394 | 144 | 0.812719 | 1,001,159 |
// Targeted by JavaCPP version 1.5.8-SNAPSHOT: DO NOT EDIT THIS FILE
package org.bytedeco.bullet.BulletCollision;
import java.nio.*;
import org.bytedeco.javacpp.*;
import org.bytedeco.javacpp.annotation.*;
import static org.bytedeco.javacpp.presets.javacpp.*;
import org.bytedeco.bullet.LinearMath.*;
import static org.bytedeco.bullet.global.LinearMath.*;
import static org.bytedeco.bullet.global.BulletCollision.*;
@NoOffset @Properties(inherit = org.bytedeco.bullet.presets.BulletCollision.class)
public class btCollisionObjectWrapper extends Pointer {
static { Loader.load(); }
/** Pointer cast constructor. Invokes {@link Pointer#Pointer(Pointer)}. */
public btCollisionObjectWrapper(Pointer p) { super(p); }
public native @Const btCollisionObjectWrapper m_parent(); public native btCollisionObjectWrapper m_parent(btCollisionObjectWrapper setter);
public native @Const btCollisionShape m_shape(); public native btCollisionObjectWrapper m_shape(btCollisionShape setter);
public native @Const btCollisionObject m_collisionObject(); public native btCollisionObjectWrapper m_collisionObject(btCollisionObject setter);
@MemberGetter public native @Const @ByRef btTransform m_worldTransform();
public native @Const btTransform m_preTransform(); public native btCollisionObjectWrapper m_preTransform(btTransform setter);
public native int m_partId(); public native btCollisionObjectWrapper m_partId(int setter);
public native int m_index(); public native btCollisionObjectWrapper m_index(int setter);
public native @Const @ByRef btTransform getWorldTransform();
public native @Const btCollisionObject getCollisionObject();
public native @Const btCollisionShape getCollisionShape();
}
|
923f6fbc025ecd098de2d4b397787c45d44b89de
| 3,369 |
java
|
Java
|
hypervisor/src/test/java/io/leafage/basic/hypervisor/service/impl/UserGroupServiceImplTest.java
|
little3201/abeille-basic
|
793fd0e27f32ca9e9ce04becc496fd7cbb225b60
|
[
"Apache-2.0"
] | 3 |
2021-04-27T07:36:20.000Z
|
2021-09-10T16:49:45.000Z
|
hypervisor/src/test/java/io/leafage/basic/hypervisor/service/impl/UserGroupServiceImplTest.java
|
little3201/leafage-basic
|
793fd0e27f32ca9e9ce04becc496fd7cbb225b60
|
[
"Apache-2.0"
] | 60 |
2021-01-28T04:39:37.000Z
|
2022-03-28T08:15:25.000Z
|
hypervisor/src/test/java/io/leafage/basic/hypervisor/service/impl/UserGroupServiceImplTest.java
|
little3201/abeille-basic
|
793fd0e27f32ca9e9ce04becc496fd7cbb225b60
|
[
"Apache-2.0"
] | 1 |
2021-04-19T21:38:14.000Z
|
2021-04-19T21:38:14.000Z
| 37.433333 | 130 | 0.730781 | 1,001,160 |
package io.leafage.basic.hypervisor.service.impl;
import io.leafage.basic.hypervisor.document.Group;
import io.leafage.basic.hypervisor.document.User;
import io.leafage.basic.hypervisor.document.UserGroup;
import io.leafage.basic.hypervisor.repository.GroupRepository;
import io.leafage.basic.hypervisor.repository.UserGroupRepository;
import io.leafage.basic.hypervisor.repository.UserRepository;
import org.bson.types.ObjectId;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.junit.jupiter.MockitoExtension;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import reactor.test.StepVerifier;
import java.util.Collections;
import static org.mockito.BDDMockito.given;
/**
* user-group接口测试
*
* @author liwenqiang 2021/6/14 11:10
**/
@ExtendWith(MockitoExtension.class)
class UserGroupServiceImplTest {
@Mock
private UserRepository userRepository;
@Mock
private UserGroupRepository userGroupRepository;
@Mock
private GroupRepository groupRepository;
@InjectMocks
private UserGroupServiceImpl userGroupService;
@Test
void users() {
Group group = new Group();
ObjectId id = new ObjectId();
group.setId(id);
given(this.groupRepository.getByCodeAndEnabledTrue(Mockito.anyString())).willReturn(Mono.just(group));
UserGroup userGroup = new UserGroup();
userGroup.setGroupId(id);
userGroup.setUserId(new ObjectId());
given(this.userGroupRepository.findByGroupIdAndEnabledTrue(Mockito.any(ObjectId.class))).willReturn(Flux.just(userGroup));
given(this.userRepository.findById(Mockito.any(ObjectId.class))).willReturn(Mono.just(Mockito.mock(User.class)));
StepVerifier.create(userGroupService.users("21612OL34")).expectNextCount(1).verifyComplete();
}
@Test
void groups() {
User user = new User();
ObjectId id = new ObjectId();
user.setId(id);
given(this.userRepository.getByUsername(Mockito.anyString())).willReturn(Mono.just(user));
UserGroup userGroup = new UserGroup();
userGroup.setGroupId(new ObjectId());
userGroup.setUserId(id);
given(this.userGroupRepository.findByUserIdAndEnabledTrue(Mockito.any(ObjectId.class))).willReturn(Flux.just(userGroup));
given(this.groupRepository.findById(Mockito.any(ObjectId.class))).willReturn(Mono.just(Mockito.mock(Group.class)));
StepVerifier.create(userGroupService.groups("21612OL34")).expectNextCount(1).verifyComplete();
}
@Test
void relation() {
User user = new User();
ObjectId id = new ObjectId();
user.setId(id);
given(this.userRepository.getByUsername(Mockito.anyString())).willReturn(Mono.just(user));
Group group = new Group();
group.setId(new ObjectId());
given(this.groupRepository.findByCodeInAndEnabledTrue(Mockito.anyCollection())).willReturn(Flux.just(group));
given(this.userGroupRepository.saveAll(Mockito.anyCollection())).willReturn(Flux.just(Mockito.mock(UserGroup.class)));
StepVerifier.create(userGroupService.relation("little3201", Collections.singleton("21612OL34")))
.expectNextCount(1).verifyComplete();
}
}
|
923f6ff62da37c05a15ff004b8ef2a590d83182c
| 9,571 |
java
|
Java
|
formObjects/Athlete.java
|
marioalvarez32/LuckyLanes
|
184bba3076d14e9a4251b42c99258cb088b4d04b
|
[
"Apache-2.0"
] | null | null | null |
formObjects/Athlete.java
|
marioalvarez32/LuckyLanes
|
184bba3076d14e9a4251b42c99258cb088b4d04b
|
[
"Apache-2.0"
] | null | null | null |
formObjects/Athlete.java
|
marioalvarez32/LuckyLanes
|
184bba3076d14e9a4251b42c99258cb088b4d04b
|
[
"Apache-2.0"
] | null | null | null | 23.86783 | 272 | 0.519068 | 1,001,161 |
/*
* 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 main.formObjects;
import java.util.Date;
import main.java.Database;
/**
*
* @author Ian
*/
public class Athlete {
private String name;
private String date;
private String dateOfBirth;
private String address;
private String city;
private String state;
private int zip;
private String phone;
private String school;
private double height;
private double weight;
private int age;
private String gender;
private String handDominance;
private String legDominance;
private String primarySport;
private String primaryPosition;
/**
* Creates an html table representation of this object.
* @return
*/
public String toHTML(){
String rowStart = "<tr><td>";
String rowMid = "</td><td>";
String rowEnd = "</td></tr>";
String html = "</br></br></br><table><tr><th>Bowler Information</th><th></th></tr>";
html+= rowStart + "Name" + rowMid + this.name + rowEnd
+ rowStart + "Date" + rowMid + this.date + rowEnd
+ rowStart + "Date of Birth" + rowMid + this.dateOfBirth + rowEnd
+ rowStart + "Address" + rowMid + this.address + rowEnd
+ rowStart + "City" + rowMid + this.city + rowEnd
+ rowStart + "State" + rowMid + this.state + rowEnd
+ rowStart + "Zip Code" + rowMid + this.zip + rowEnd
+ rowStart + "Phone" + rowMid + this.phone + rowEnd
+ rowStart + "School" + rowMid + this.school + rowEnd
+ rowStart + "Height" + rowMid + this.height + rowEnd
+ rowStart + "Weight" + rowMid + this.weight + rowEnd
+ rowStart + "Age" + rowMid + this.age + rowEnd
+ rowStart + "Sex" + rowMid + this.gender + rowEnd
+ rowStart + "Hand Dominance" + rowMid + this.handDominance + rowEnd
+ rowStart + "Leg Dominance" + rowMid + this.legDominance + rowEnd
+ rowStart + "Primary Sport" + rowMid + this.primarySport + rowEnd
+ rowStart + "Primary Position" + rowMid + this.primaryPosition + rowEnd + "</table>";
return html;
}
/**
* Constructor of the Athlete class.
*
* @param name
* @param date
* @param dateOfBirth
* @param address
* @param city
* @param state
* @param zip
* @param phone
* @param school
* @param height
* @param weight
* @param age
* @param gender
* @param handDominance
* @param legDominance
* @param primarySport
* @param primaryPosition
*/
public Athlete(String name,String date,String dateOfBirth,String address,String city,String state,int zip,String phone,String school,double height,double weight,int age,String gender,String handDominance,String legDominance,String primarySport,String primaryPosition){
this.name = name;
this.date = date;
this.dateOfBirth = dateOfBirth;
this.address = address;
this.city = city;
this.state = state;
this.zip = zip;
this.phone = phone;
this.school = school;
this.height = height;
this.weight = weight;
this.age = age;
this.gender = gender;
this.handDominance = handDominance;
this.legDominance = legDominance;
this.primarySport = primarySport;
this.primaryPosition = primaryPosition;
}
/**
*
*/
public Athlete(){
this.name = "";
this.date = null;
this.dateOfBirth = null;
this.address = "";
this.city = "";
this.state = "";
this.zip = 0;
this.phone = "";
this.school = "";
this.height = 0;
this.weight = 0;
this.age = 0;
this.gender = "";
this.handDominance = "";
this.legDominance = "";
this.primarySport = "";
this.primaryPosition = "";
}
/**
* @return the name
*/
public String getName() {
return name;
}
/**
* @param name the name to set
*/
public void setName(String name) {
this.name = name;
}
/**
* @return the date
*/
public String getDate() {
return date;
}
/**
* @param date the date to set
*/
public void setDate(String date) {
this.date = date;
}
/**
* @return the dateOfBirth
*/
public String getDateOfBirth() {
return dateOfBirth;
}
/**
* @param dateOfBirth the dateOfBirth to set
*/
public void setDateOfBirth(String dateOfBirth) {
this.dateOfBirth = dateOfBirth;
}
/**
* @return the address
*/
public String getAddress() {
return address;
}
/**
* @param address the address to set
*/
public void setAddress(String address) {
this.address = address;
}
/**
* @return the city
*/
public String getCity() {
return city;
}
/**
* @param city the city to set
*/
public void setCity(String city) {
this.city = city;
}
/**
* @return the state
*/
public String getState() {
return state;
}
/**
* @param state the state to set
*/
public void setState(String state) {
this.state = state;
}
/**
* @return the zip
*/
public int getZip() {
return zip;
}
/**
* @param zip the zip to set
*/
public void setZip(int zip) {
this.zip = zip;
}
/**
* @return the phone
*/
public String getPhone() {
return phone;
}
/**
* @param phone the phone to set
*/
public void setPhone(String phone) {
this.phone = phone;
}
/**
* @return the school
*/
public String getSchool() {
return school;
}
/**
* @param school the school to set
*/
public void setSchool(String school) {
this.school = school;
}
/**
* @return the height
*/
public double getHeight() {
return height;
}
/**
* @param height the height to set
*/
public void setHeight(double height) {
this.height = height;
}
/**
* @return the weight
*/
public double getWeight() {
return weight;
}
/**
* @param weight the weight to set
*/
public void setWeight(double weight) {
this.weight = weight;
}
/**
* @return the age
*/
public int getAge() {
return age;
}
/**
* @param age the age to set
*/
public void setAge(int age) {
this.age = age;
}
/**
* @return the gender
*/
public String getGender() {
return gender;
}
/**
* @param gender the gender to set
*/
public void setGender(String gender) {
this.gender = gender;
}
/**
* @return the handDominance
*/
public String getHandDominance() {
return handDominance;
}
/**
* @param handDominance the handDominance to set
*/
public void setHandDominance(String handDominance) {
this.handDominance = handDominance;
}
/**
* @return the legDominance
*/
public String getLegDominance() {
return legDominance;
}
/**
* @param legDominance the legDominace to set
*/
public void setLegDominance(String legDominance) {
this.legDominance = legDominance;
}
/**
* @return the primarySport
*/
public String getPrimarySport() {
return primarySport;
}
/**
* @param primarySport the primarySport to set
*/
public void setPrimarySport(String primarySport) {
this.primarySport = primarySport;
}
/**
* @return the primaryPosition
*/
public String getPrimaryPosition() {
return primaryPosition;
}
/**
* @param primaryPosition the primaryPosition to set
*/
public void setPrimaryPosition(String primaryPosition) {
this.primaryPosition = primaryPosition;
}
/**
* Adds a row to the database class.
* It is used in conjunction with the other forms, since the value for
* each table is autoincremented.
*/
public void addRow() {
String sql;
sql = "INSERT INTO ATHLETE VALUES ("
+ "null,"
+ "'" + name + "'" + ","
+ "'" + date + "'" + ","
+ "'" + dateOfBirth+ "'" + ","
+ "'" + address + "'" + ","
+ "'" + city + "'" + ","
+ "'" + state +"'" + ","
+ Integer.toString(zip) + ","
+ "'" + phone +"'" + ","
+ "'" + school + "'" + ","
+ Double.toString(height) + ","
+ Double.toString(weight) + ","
+ Integer.toString(age) + ","
+ "'" + gender + "'" + ","
+ "'" + handDominance + "'" + ","
+ "'" + legDominance + "'" + ","
+ "'" + primarySport + "'" + ","
+ "'" + primaryPosition + "'" + ","
+ ");";
Database.executeUpdate(sql);
}
}
|
923f70241f840108cea4ff8ec5dc4dfa0af8756f
| 3,298 |
java
|
Java
|
jhipster-framework/src/main/java/io/github/jhipster/web/util/PaginationUtil.java
|
AutoscanForJavaFork/jhipster
|
b3d85e0b39fa3dabacaf486deaff1508484f2935
|
[
"Apache-2.0"
] | 450 |
2016-12-12T19:11:54.000Z
|
2022-02-07T13:28:44.000Z
|
jhipster-framework/src/main/java/io/github/jhipster/web/util/PaginationUtil.java
|
AutoscanForJavaFork/jhipster
|
b3d85e0b39fa3dabacaf486deaff1508484f2935
|
[
"Apache-2.0"
] | 464 |
2020-07-27T06:55:53.000Z
|
2022-03-31T06:03:42.000Z
|
jhipster-framework/src/main/java/io/github/jhipster/web/util/PaginationUtil.java
|
atomfrede/jhipster
|
9e2ed902177de5db24a00695f80d1bee39f5d2de
|
[
"Apache-2.0"
] | 346 |
2016-12-14T22:23:57.000Z
|
2022-02-11T18:10:11.000Z
| 39.73494 | 118 | 0.67738 | 1,001,162 |
/*
* Copyright 2016-2020 the original author or authors from the JHipster project.
*
* This file is part of the JHipster project, see https://www.jhipster.tech/
* for more information.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.github.jhipster.web.util;
import org.springframework.data.domain.Page;
import org.springframework.http.HttpHeaders;
import org.springframework.web.util.UriComponentsBuilder;
import java.text.MessageFormat;
/**
* Utility class for handling pagination.
*
* <p>
* Pagination uses the same principles as the <a href="https://developer.github.com/v3/#pagination">GitHub API</a>,
* and follow <a href="http://tools.ietf.org/html/rfc5988">RFC 5988 (Link header)</a>.
*/
public final class PaginationUtil {
private static final String HEADER_X_TOTAL_COUNT = "X-Total-Count";
private static final String HEADER_LINK_FORMAT = "<{0}>; rel=\"{1}\"";
private PaginationUtil() {
}
/**
* Generate pagination headers for a Spring Data {@link org.springframework.data.domain.Page} object.
*
* @param uriBuilder The URI builder.
* @param page The page.
* @param <T> The type of object.
* @return http header.
*/
public static <T> HttpHeaders generatePaginationHttpHeaders(UriComponentsBuilder uriBuilder, Page<T> page) {
HttpHeaders headers = new HttpHeaders();
headers.add(HEADER_X_TOTAL_COUNT, Long.toString(page.getTotalElements()));
int pageNumber = page.getNumber();
int pageSize = page.getSize();
StringBuilder link = new StringBuilder();
if (pageNumber < page.getTotalPages() - 1) {
link.append(prepareLink(uriBuilder, pageNumber + 1, pageSize, "next"))
.append(",");
}
if (pageNumber > 0) {
link.append(prepareLink(uriBuilder, pageNumber - 1, pageSize, "prev"))
.append(",");
}
link.append(prepareLink(uriBuilder, page.getTotalPages() - 1, pageSize, "last"))
.append(",")
.append(prepareLink(uriBuilder, 0, pageSize, "first"));
headers.add(HttpHeaders.LINK, link.toString());
return headers;
}
private static String prepareLink(UriComponentsBuilder uriBuilder, int pageNumber, int pageSize, String relType) {
return MessageFormat.format(HEADER_LINK_FORMAT, preparePageUri(uriBuilder, pageNumber, pageSize), relType);
}
private static String preparePageUri(UriComponentsBuilder uriBuilder, int pageNumber, int pageSize) {
return uriBuilder.replaceQueryParam("page", Integer.toString(pageNumber))
.replaceQueryParam("size", Integer.toString(pageSize))
.toUriString()
.replace(",", "%2C")
.replace(";", "%3B");
}
}
|
923f7153979d92afdcee4267ea3270fdf5507040
| 632 |
java
|
Java
|
java_old2/turretmod_old/client/gui/tcu/tooltip/TooltipLine.java
|
SanAndreasP/TurretModRebirth
|
033f9ccb695b9ee73682763ab181b348bae0d592
|
[
"BSD-3-Clause"
] | 5 |
2015-05-15T03:45:11.000Z
|
2020-08-31T19:05:07.000Z
|
java_old2/turretmod_old/client/gui/tcu/tooltip/TooltipLine.java
|
SanAndreasP/TurretModRebirth
|
033f9ccb695b9ee73682763ab181b348bae0d592
|
[
"BSD-3-Clause"
] | 30 |
2016-06-27T12:05:02.000Z
|
2022-03-25T20:38:35.000Z
|
java_old2/turretmod_old/client/gui/tcu/tooltip/TooltipLine.java
|
SanAndreasP/TurretModRebirth
|
033f9ccb695b9ee73682763ab181b348bae0d592
|
[
"BSD-3-Clause"
] | 2 |
2016-03-04T17:20:42.000Z
|
2017-11-04T23:46:34.000Z
| 42.133333 | 117 | 0.469937 | 1,001,163 |
/*******************************************************************************************************************
* Authors: SanAndreasP
* Copyright: SanAndreasP
* License: Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International
* http://creativecommons.org/licenses/by-nc-sa/4.0/
*******************************************************************************************************************/
package de.sanandrew.mods.turretmod.client.gui.tcu.tooltip;
public interface TooltipLine<T>
{
int getWidth(T object);
int getHeight(T object);
void renderLine(int x, int y, float partTicks);
}
|
923f72cfa1dc170204e985ad236ee53871b8462f
| 106 |
java
|
Java
|
app/src/main/java/com/siziksu/gallery/common/functions/FunGen.java
|
Siziksu/AndroidGallery
|
e34cfa5d5c5b0b1a44679c9a4cc8ba374e0f7916
|
[
"Apache-2.0"
] | null | null | null |
app/src/main/java/com/siziksu/gallery/common/functions/FunGen.java
|
Siziksu/AndroidGallery
|
e34cfa5d5c5b0b1a44679c9a4cc8ba374e0f7916
|
[
"Apache-2.0"
] | null | null | null |
app/src/main/java/com/siziksu/gallery/common/functions/FunGen.java
|
Siziksu/AndroidGallery
|
e34cfa5d5c5b0b1a44679c9a4cc8ba374e0f7916
|
[
"Apache-2.0"
] | 1 |
2020-12-16T16:29:30.000Z
|
2020-12-16T16:29:30.000Z
| 13.25 | 45 | 0.726415 | 1,001,164 |
package com.siziksu.gallery.common.functions;
public interface FunGen<O> {
void apply(O object);
}
|
923f72f662a237853d4069cbb0a7360f083cb84a
| 819 |
java
|
Java
|
src/RemoveDuplicateId.java
|
GarimaM92/JavaPracticeJenkins
|
f45f64476b8d2e00f18f5bbca677f8370b405b38
|
[
"MIT"
] | null | null | null |
src/RemoveDuplicateId.java
|
GarimaM92/JavaPracticeJenkins
|
f45f64476b8d2e00f18f5bbca677f8370b405b38
|
[
"MIT"
] | null | null | null |
src/RemoveDuplicateId.java
|
GarimaM92/JavaPracticeJenkins
|
f45f64476b8d2e00f18f5bbca677f8370b405b38
|
[
"MIT"
] | null | null | null | 24.818182 | 78 | 0.639805 | 1,001,165 |
import java.util.ArrayList;
import java.util.Comparator;
import java.util.TreeSet;
public class RemoveDuplicateId {
public static void main(String[] args) {
Employee e1 = new Employee(1, "garima", "Consultant");
Employee e2 = new Employee(2, "ankur","Risk engineer");
Employee e3 = new Employee(1, "mahajan","lead");
ArrayList<Employee> list = new ArrayList<Employee>();
list.add(e1);
list.add(e2);
list.add(e3);
System.out.println(list);
TreeSet<Employee> set = new TreeSet<Employee>(new Comparator<Employee>() {
@Override
public int compare(Employee e1, Employee e2) {
if(e1.id == e2.id)
return 0;
else {
return e1.name.compareTo(e2.name);
}
}
}) ;
set.addAll(list);
System.out.println("set------");
System.out.println(set);
}
}
|
923f7311006a033e450835183dd73ee8cda7a33b
| 987 |
java
|
Java
|
src/main/java/org/sagebionetworks/web/client/jsinterop/EvaluationCardProps.java
|
marcomarasca/SynapseWebClient
|
d641b0e129dc5c73bac30f9096abd98d38fb2a9d
|
[
"Apache-2.0"
] | 11 |
2015-04-06T06:06:12.000Z
|
2022-03-21T20:12:28.000Z
|
src/main/java/org/sagebionetworks/web/client/jsinterop/EvaluationCardProps.java
|
marcomarasca/SynapseWebClient
|
d641b0e129dc5c73bac30f9096abd98d38fb2a9d
|
[
"Apache-2.0"
] | 264 |
2015-01-07T19:12:45.000Z
|
2022-03-31T21:49:28.000Z
|
src/main/java/org/sagebionetworks/web/client/jsinterop/EvaluationCardProps.java
|
marcomarasca/SynapseWebClient
|
d641b0e129dc5c73bac30f9096abd98d38fb2a9d
|
[
"Apache-2.0"
] | 17 |
2015-01-29T03:16:11.000Z
|
2022-02-21T22:41:15.000Z
| 29.029412 | 161 | 0.809524 | 1,001,166 |
package org.sagebionetworks.web.client.jsinterop;
import jsinterop.annotations.JsFunction;
import jsinterop.annotations.JsOverlay;
import jsinterop.annotations.JsPackage;
import jsinterop.annotations.JsType;
@JsType(isNative = true, namespace = JsPackage.GLOBAL, name="Object")
public class EvaluationCardProps extends ReactComponentProps {
@JsFunction
public interface Callback {
void run();
}
public EvaluationJSObject evaluation;
public Callback onEdit;
public Callback onModifyAccess;
public Callback onSubmit;
public Callback onDeleteSuccess;
@JsOverlay
public static EvaluationCardProps create(EvaluationJSObject evaluation, Callback onEdit, Callback onModifyAccess, Callback onSubmit, Callback onDeleteSuccess) {
EvaluationCardProps props = new EvaluationCardProps();
props.evaluation = evaluation;
props.onEdit = onEdit;
props.onModifyAccess = onModifyAccess;
props.onSubmit = onSubmit;
props.onDeleteSuccess = onDeleteSuccess;
return props;
}
}
|
923f733eeb9a5e23bce1dfb3cba1930b8c549cb9
| 24,040 |
java
|
Java
|
core/src/main/java/org/apache/brooklyn/util/core/text/TemplateProcessor.java
|
johnmccabe/PRESPLIT-incubator-brooklyn
|
e6235d9bcfce0829e3160302a568422c1429c5ae
|
[
"MIT",
"Apache-2.0",
"BSD-3-Clause"
] | 128 |
2015-01-06T13:58:09.000Z
|
2021-11-10T19:24:40.000Z
|
core/src/main/java/org/apache/brooklyn/util/core/text/TemplateProcessor.java
|
johnmccabe/PRESPLIT-incubator-brooklyn
|
e6235d9bcfce0829e3160302a568422c1429c5ae
|
[
"MIT",
"Apache-2.0",
"BSD-3-Clause"
] | 743 |
2015-01-05T13:24:33.000Z
|
2016-05-26T13:16:54.000Z
|
core/src/main/java/org/apache/brooklyn/util/core/text/TemplateProcessor.java
|
johnmccabe/PRESPLIT-incubator-brooklyn
|
e6235d9bcfce0829e3160302a568422c1429c5ae
|
[
"MIT",
"Apache-2.0",
"BSD-3-Clause"
] | 118 |
2015-01-06T15:30:12.000Z
|
2021-11-10T19:24:30.000Z
| 44.767225 | 161 | 0.636938 | 1,001,167 |
/*
* 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.brooklyn.util.core.text;
import static com.google.common.base.Preconditions.checkNotNull;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.Map;
import org.apache.brooklyn.api.entity.Entity;
import org.apache.brooklyn.api.entity.drivers.EntityDriver;
import org.apache.brooklyn.api.location.Location;
import org.apache.brooklyn.api.mgmt.ManagementContext;
import org.apache.brooklyn.api.sensor.AttributeSensor;
import org.apache.brooklyn.core.config.ConfigKeys;
import org.apache.brooklyn.core.entity.Entities;
import org.apache.brooklyn.core.entity.EntityInternal;
import org.apache.brooklyn.core.location.internal.LocationInternal;
import org.apache.brooklyn.core.mgmt.internal.ManagementContextInternal;
import org.apache.brooklyn.core.sensor.DependentConfiguration;
import org.apache.brooklyn.core.sensor.Sensors;
import org.apache.brooklyn.util.collections.MutableMap;
import org.apache.brooklyn.util.exceptions.Exceptions;
import org.apache.brooklyn.util.text.Strings;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.base.Charsets;
import com.google.common.collect.Iterables;
import com.google.common.io.Files;
import freemarker.cache.StringTemplateLoader;
import freemarker.template.Configuration;
import freemarker.template.ObjectWrapper;
import freemarker.template.Template;
import freemarker.template.TemplateHashModel;
import freemarker.template.TemplateModel;
import freemarker.template.TemplateModelException;
/** A variety of methods to assist in Freemarker template processing,
* including passing in maps with keys flattened (dot-separated namespace),
* and accessing {@link ManagementContext} brooklyn.properties
* and {@link Entity}, {@link EntityDriver}, and {@link Location} methods and config.
* <p>
* See {@link #processTemplateContents(String, ManagementContextInternal, Map)} for
* a description of how management access is done.
*/
public class TemplateProcessor {
private static final Logger log = LoggerFactory.getLogger(TemplateProcessor.class);
protected static TemplateModel wrapAsTemplateModel(Object o) throws TemplateModelException {
if (o instanceof Map) return new DotSplittingTemplateModel((Map<?,?>)o);
return ObjectWrapper.DEFAULT_WRAPPER.wrap(o);
}
/** @deprecated since 0.7.0 use {@link #processTemplateFile(String, Map)} */ @Deprecated
public static String processTemplate(String templateFileName, Map<String, ? extends Object> substitutions) {
return processTemplateFile(templateFileName, substitutions);
}
/** As per {@link #processTemplateContents(String, Map)}, but taking a file. */
public static String processTemplateFile(String templateFileName, Map<String, ? extends Object> substitutions) {
String templateContents;
try {
templateContents = Files.toString(new File(templateFileName), Charsets.UTF_8);
} catch (IOException e) {
log.warn("Error loading file " + templateFileName, e);
throw Exceptions.propagate(e);
}
return processTemplateContents(templateContents, substitutions);
}
/** @deprecated since 0.7.0 use {@link #processTemplateFile(String, EntityDriver, Map)} */ @Deprecated
public static String processTemplate(String templateFileName, EntityDriver driver, Map<String, ? extends Object> extraSubstitutions) {
return processTemplateFile(templateFileName, driver, extraSubstitutions);
}
/** Processes template contents according to {@link EntityAndMapTemplateModel}. */
public static String processTemplateFile(String templateFileName, EntityDriver driver, Map<String, ? extends Object> extraSubstitutions) {
String templateContents;
try {
templateContents = Files.toString(new File(templateFileName), Charsets.UTF_8);
} catch (IOException e) {
log.warn("Error loading file " + templateFileName, e);
throw Exceptions.propagate(e);
}
return processTemplateContents(templateContents, driver, extraSubstitutions);
}
/** Processes template contents according to {@link EntityAndMapTemplateModel}. */
public static String processTemplateContents(String templateContents, EntityDriver driver, Map<String,? extends Object> extraSubstitutions) {
return processTemplateContents(templateContents, new EntityAndMapTemplateModel(driver, extraSubstitutions));
}
/** Processes template contents according to {@link EntityAndMapTemplateModel}. */
public static String processTemplateContents(String templateContents, ManagementContext managementContext, Map<String,? extends Object> extraSubstitutions) {
return processTemplateContents(templateContents, new EntityAndMapTemplateModel(managementContext, extraSubstitutions));
}
/** Processes template contents according to {@link EntityAndMapTemplateModel}. */
public static String processTemplateContents(String templateContents, Location location, Map<String,? extends Object> extraSubstitutions) {
return processTemplateContents(templateContents, new LocationAndMapTemplateModel((LocationInternal)location, extraSubstitutions));
}
/**
* A Freemarker {@link TemplateHashModel} which will correctly handle entries of the form "a.b" in this map,
* matching against template requests for "${a.b}".
* <p>
* Freemarker requests "a" in a map when given such a request, and expects that to point to a map
* with a key "b". This model provides such maps even for "a.b" in a map.
* <p>
* However if "a" <b>and</b> "a.b" are in the map, this will <b>not</b> currently do the deep mapping.
* (It does not have enough contextual information from Freemarker to handle this case.) */
public static final class DotSplittingTemplateModel implements TemplateHashModel {
protected final Map<?,?> map;
protected DotSplittingTemplateModel(Map<?,?> map) {
this.map = map;
}
@Override
public boolean isEmpty() { return map!=null && map.isEmpty(); }
public boolean contains(String key) {
if (map==null) return false;
if (map.containsKey(key)) return true;
for (Map.Entry<?,?> entry: map.entrySet()) {
String k = Strings.toString(entry.getKey());
if (k.startsWith(key+".")) {
// contains this prefix
return true;
}
}
return false;
}
@Override
public TemplateModel get(String key) throws TemplateModelException {
if (map==null) return null;
try {
if (map.containsKey(key))
return wrapAsTemplateModel( map.get(key) );
Map<String,Object> result = MutableMap.of();
for (Map.Entry<?,?> entry: map.entrySet()) {
String k = Strings.toString(entry.getKey());
if (k.startsWith(key+".")) {
String k2 = Strings.removeFromStart(k, key+".");
result.put(k2, entry.getValue());
}
}
if (!result.isEmpty())
return wrapAsTemplateModel( result );
} catch (Exception e) {
Exceptions.propagateIfFatal(e);
throw new IllegalStateException("Error accessing config '"+key+"'"+": "+e, e);
}
return null;
}
@Override
public String toString() {
return getClass().getName()+"["+map+"]";
}
}
/** FreeMarker {@link TemplateHashModel} which resolves keys inside the given entity or management context.
* Callers are required to include dots for dot-separated keys.
* Freemarker will only do this when in inside bracket notation in an outer map, as in <code>${outer['a.b.']}</code>;
* as a result this is intended only for use by {@link EntityAndMapTemplateModel} where
* a caller has used bracked notation, as in <code>${mgmt['key.subkey']}</code>. */
protected static final class EntityConfigTemplateModel implements TemplateHashModel {
protected final EntityInternal entity;
protected final ManagementContext mgmt;
protected EntityConfigTemplateModel(EntityInternal entity) {
this.entity = checkNotNull(entity, "entity");
this.mgmt = entity.getManagementContext();
}
@Override
public boolean isEmpty() { return false; }
@Override
public TemplateModel get(String key) throws TemplateModelException {
try {
Object result = entity.getConfig(ConfigKeys.builder(Object.class).name(key).build());
if (result==null)
result = mgmt.getConfig().getConfig(ConfigKeys.builder(Object.class).name(key).build());
if (result!=null)
return wrapAsTemplateModel( result );
} catch (Exception e) {
Exceptions.propagateIfFatal(e);
throw new IllegalStateException("Error accessing config '"+key+"'"+" on "+entity+": "+e, e);
}
return null;
}
@Override
public String toString() {
return getClass().getName()+"["+entity+"]";
}
}
/** FreeMarker {@link TemplateHashModel} which resolves keys inside the given management context.
* Callers are required to include dots for dot-separated keys.
* Freemarker will only do this when in inside bracket notation in an outer map, as in <code>${outer['a.b.']}</code>;
* as a result this is intended only for use by {@link EntityAndMapTemplateModel} where
* a caller has used bracked notation, as in <code>${mgmt['key.subkey']}</code>. */
protected static final class MgmtConfigTemplateModel implements TemplateHashModel {
protected final ManagementContext mgmt;
protected MgmtConfigTemplateModel(ManagementContext mgmt) {
this.mgmt = checkNotNull(mgmt, "mgmt");
}
@Override
public boolean isEmpty() { return false; }
@Override
public TemplateModel get(String key) throws TemplateModelException {
try {
Object result = mgmt.getConfig().getConfig(ConfigKeys.builder(Object.class).name(key).build());
if (result!=null)
return wrapAsTemplateModel( result );
} catch (Exception e) {
Exceptions.propagateIfFatal(e);
throw new IllegalStateException("Error accessing config '"+key+"': "+e, e);
}
return null;
}
@Override
public String toString() {
return getClass().getName()+"["+mgmt+"]";
}
}
/** FreeMarker {@link TemplateHashModel} which resolves keys inside the given location.
* Callers are required to include dots for dot-separated keys.
* Freemarker will only do this when in inside bracket notation in an outer map, as in <code>${outer['a.b.']}</code>;
* as a result this is intended only for use by {@link LocationAndMapTemplateModel} where
* a caller has used bracked notation, as in <code>${mgmt['key.subkey']}</code>. */
protected static final class LocationConfigTemplateModel implements TemplateHashModel {
protected final LocationInternal location;
protected final ManagementContext mgmt;
protected LocationConfigTemplateModel(LocationInternal location) {
this.location = checkNotNull(location, "location");
this.mgmt = location.getManagementContext();
}
@Override
public boolean isEmpty() { return false; }
@Override
public TemplateModel get(String key) throws TemplateModelException {
try {
Object result = null;
result = location.getConfig(ConfigKeys.builder(Object.class).name(key).build());
if (result==null && mgmt!=null)
result = mgmt.getConfig().getConfig(ConfigKeys.builder(Object.class).name(key).build());
if (result!=null)
return wrapAsTemplateModel( result );
} catch (Exception e) {
Exceptions.propagateIfFatal(e);
throw new IllegalStateException("Error accessing config '"+key+"'"
+ (location!=null ? " on "+location : "")+": "+e, e);
}
return null;
}
@Override
public String toString() {
return getClass().getName()+"["+location+"]";
}
}
protected final static class EntityAttributeTemplateModel implements TemplateHashModel {
protected final EntityInternal entity;
protected EntityAttributeTemplateModel(EntityInternal entity) {
this.entity = entity;
}
@Override
public boolean isEmpty() throws TemplateModelException {
return false;
}
@Override
public TemplateModel get(String key) throws TemplateModelException {
Object result;
try {
result = Entities.submit(entity, DependentConfiguration.attributeWhenReady(entity,
Sensors.builder(Object.class, key).persistence(AttributeSensor.SensorPersistenceMode.NONE).build())).get();
} catch (Exception e) {
throw Exceptions.propagate(e);
}
if (result == null) {
return null;
} else {
return wrapAsTemplateModel(result);
}
}
@Override
public String toString() {
return getClass().getName()+"["+entity+"]";
}
}
/**
* Provides access to config on an entity or management context, using
* <code>${config['entity.config.key']}</code> or <code>${mgmt['brooklyn.properties.key']}</code> notation,
* and also allowing access to <code>getX()</code> methods on entity (interface) or driver
* using <code>${entity.x}</code> or <code><${driver.x}</code>.
* Optional extra properties can be supplied, treated as per {@link DotSplittingTemplateModel}.
*/
protected static final class EntityAndMapTemplateModel implements TemplateHashModel {
protected final EntityInternal entity;
protected final EntityDriver driver;
protected final ManagementContext mgmt;
protected final DotSplittingTemplateModel extraSubstitutionsModel;
protected EntityAndMapTemplateModel(ManagementContext mgmt, Map<String,? extends Object> extraSubstitutions) {
this.entity = null;
this.driver = null;
this.mgmt = mgmt;
this.extraSubstitutionsModel = new DotSplittingTemplateModel(extraSubstitutions);
}
protected EntityAndMapTemplateModel(EntityDriver driver, Map<String,? extends Object> extraSubstitutions) {
this.driver = driver;
this.entity = (EntityInternal) driver.getEntity();
this.mgmt = entity.getManagementContext();
this.extraSubstitutionsModel = new DotSplittingTemplateModel(extraSubstitutions);
}
protected EntityAndMapTemplateModel(EntityInternal entity, Map<String,? extends Object> extraSubstitutions) {
this.entity = entity;
this.driver = null;
this.mgmt = entity.getManagementContext();
this.extraSubstitutionsModel = new DotSplittingTemplateModel(extraSubstitutions);
}
@Override
public boolean isEmpty() { return false; }
@Override
public TemplateModel get(String key) throws TemplateModelException {
if (extraSubstitutionsModel.contains(key))
return wrapAsTemplateModel( extraSubstitutionsModel.get(key) );
if ("entity".equals(key) && entity!=null)
return wrapAsTemplateModel( entity );
if ("config".equals(key)) {
if (entity!=null)
return new EntityConfigTemplateModel(entity);
else
return new MgmtConfigTemplateModel(mgmt);
}
if ("mgmt".equals(key)) {
return new MgmtConfigTemplateModel(mgmt);
}
if ("driver".equals(key) && driver!=null)
return wrapAsTemplateModel( driver );
if ("location".equals(key)) {
if (driver!=null && driver.getLocation()!=null)
return wrapAsTemplateModel( driver.getLocation() );
if (entity!=null)
return wrapAsTemplateModel( Iterables.getOnlyElement( entity.getLocations() ) );
}
if ("attribute".equals(key)) {
return new EntityAttributeTemplateModel(entity);
}
if (mgmt!=null) {
// TODO deprecated in 0.7.0, remove after next version
// ie not supported to access global props without qualification
Object result = mgmt.getConfig().getConfig(ConfigKeys.builder(Object.class).name(key).build());
if (result!=null) {
log.warn("Deprecated access of global brooklyn.properties value for "+key+"; should be qualified with 'mgmt.'");
return wrapAsTemplateModel( result );
}
}
if ("javaSysProps".equals(key))
return wrapAsTemplateModel( System.getProperties() );
return null;
}
@Override
public String toString() {
return getClass().getName()+"["+(entity!=null ? entity : mgmt)+"]";
}
}
/**
* Provides access to config on an entity or management context, using
* <code>${config['entity.config.key']}</code> or <code>${mgmt['brooklyn.properties.key']}</code> notation,
* and also allowing access to <code>getX()</code> methods on entity (interface) or driver
* using <code>${entity.x}</code> or <code><${driver.x}</code>.
* Optional extra properties can be supplied, treated as per {@link DotSplittingTemplateModel}.
*/
protected static final class LocationAndMapTemplateModel implements TemplateHashModel {
protected final LocationInternal location;
protected final ManagementContext mgmt;
protected final DotSplittingTemplateModel extraSubstitutionsModel;
protected LocationAndMapTemplateModel(LocationInternal location, Map<String,? extends Object> extraSubstitutions) {
this.location = checkNotNull(location, "location");
this.mgmt = location.getManagementContext();
this.extraSubstitutionsModel = new DotSplittingTemplateModel(extraSubstitutions);
}
@Override
public boolean isEmpty() { return false; }
@Override
public TemplateModel get(String key) throws TemplateModelException {
if (extraSubstitutionsModel.contains(key))
return wrapAsTemplateModel( extraSubstitutionsModel.get(key) );
if ("location".equals(key))
return wrapAsTemplateModel( location );
if ("config".equals(key)) {
return new LocationConfigTemplateModel(location);
}
if ("mgmt".equals(key)) {
return new MgmtConfigTemplateModel(mgmt);
}
if (mgmt!=null) {
// TODO deprecated in 0.7.0, remove after next version
// ie not supported to access global props without qualification
Object result = mgmt.getConfig().getConfig(ConfigKeys.builder(Object.class).name(key).build());
if (result!=null) {
log.warn("Deprecated access of global brooklyn.properties value for "+key+"; should be qualified with 'mgmt.'");
return wrapAsTemplateModel( result );
}
}
if ("javaSysProps".equals(key))
return wrapAsTemplateModel( System.getProperties() );
return null;
}
@Override
public String toString() {
return getClass().getName()+"["+location+"]";
}
}
/** Processes template contents with the given items in scope as per {@link EntityAndMapTemplateModel}. */
public static String processTemplateContents(String templateContents, final EntityInternal entity, Map<String,? extends Object> extraSubstitutions) {
return processTemplateContents(templateContents, new EntityAndMapTemplateModel(entity, extraSubstitutions));
}
/** Processes template contents using the given map, passed to freemarker,
* with dot handling as per {@link DotSplittingTemplateModel}. */
public static String processTemplateContents(String templateContents, final Map<String, ? extends Object> substitutions) {
TemplateHashModel root;
try {
root = substitutions != null
? (TemplateHashModel)wrapAsTemplateModel(substitutions)
: null;
} catch (TemplateModelException e) {
throw new IllegalStateException("Unable to set up TemplateHashModel to parse template, given "+substitutions+": "+e, e);
}
return processTemplateContents(templateContents, root);
}
/** Processes template contents against the given {@link TemplateHashModel}. */
public static String processTemplateContents(String templateContents, final TemplateHashModel substitutions) {
try {
Configuration cfg = new Configuration();
StringTemplateLoader templateLoader = new StringTemplateLoader();
templateLoader.putTemplate("config", templateContents);
cfg.setTemplateLoader(templateLoader);
Template template = cfg.getTemplate("config");
// TODO could expose CAMP '$brooklyn:' style dsl, based on template.createProcessingEnvironment
ByteArrayOutputStream baos = new ByteArrayOutputStream();
Writer out = new OutputStreamWriter(baos);
template.process(substitutions, out);
out.flush();
return new String(baos.toByteArray());
} catch (Exception e) {
log.warn("Error processing template (propagating): "+e, e);
log.debug("Template which could not be parsed (causing "+e+") is:"
+ (Strings.isMultiLine(templateContents) ? "\n"+templateContents : templateContents));
throw Exceptions.propagate(e);
}
}
}
|
923f7385387b5bd73ddd07e2301ea22617f695e4
| 1,159 |
java
|
Java
|
event-service/event-service-persist-log-impl/src/main/java/de/adorsys/psd2/event/persist/logger/EventLogger.java
|
dberadze/xs2a
|
71334ba664c6f87719ffa8fa48b486b9d726ce7c
|
[
"Apache-2.0"
] | 120 |
2018-04-19T13:15:59.000Z
|
2022-03-27T21:50:38.000Z
|
event-service/event-service-persist-log-impl/src/main/java/de/adorsys/psd2/event/persist/logger/EventLogger.java
|
dberadze/xs2a
|
71334ba664c6f87719ffa8fa48b486b9d726ce7c
|
[
"Apache-2.0"
] | 72 |
2018-05-04T14:03:18.000Z
|
2022-03-10T14:00:22.000Z
|
event-service/event-service-persist-log-impl/src/main/java/de/adorsys/psd2/event/persist/logger/EventLogger.java
|
dberadze/xs2a
|
71334ba664c6f87719ffa8fa48b486b9d726ce7c
|
[
"Apache-2.0"
] | 85 |
2018-05-07T09:56:46.000Z
|
2022-03-09T10:10:29.000Z
| 28.268293 | 75 | 0.714409 | 1,001,168 |
/*
* Copyright 2018-2019 adorsys GmbH & Co KG
*
* 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 de.adorsys.psd2.event.persist.logger;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import org.slf4j.Logger;
import org.springframework.stereotype.Service;
@Slf4j(topic = "event-log")
@Service
public class EventLogger {
/**
* Logs given message to the event-log
*
* @param logMessage message to be logged
*/
public void logMessage(EventLogMessage logMessage) {
getLogger().info(logMessage.getMessage());
}
@NotNull
Logger getLogger() {
return log;
}
}
|
923f75b63a44c81375d5bf48f35ce627c15b2a15
| 7,269 |
java
|
Java
|
QuickStart/src/main/java/pubsubsql/QuickStart.java
|
pubsubsql/java
|
b4d2048de38c13f1a70b7bdd2077c7bb628da36c
|
[
"Apache-2.0"
] | null | null | null |
QuickStart/src/main/java/pubsubsql/QuickStart.java
|
pubsubsql/java
|
b4d2048de38c13f1a70b7bdd2077c7bb628da36c
|
[
"Apache-2.0"
] | null | null | null |
QuickStart/src/main/java/pubsubsql/QuickStart.java
|
pubsubsql/java
|
b4d2048de38c13f1a70b7bdd2077c7bb628da36c
|
[
"Apache-2.0"
] | null | null | null | 42.017341 | 109 | 0.376393 | 1,001,169 |
/* Copyright (C) 2014 CompleteDB LLC.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the Apache License Version 2.0 http://www.apache.org/licenses.
*
* 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.
*
*/
package pubsubsql;
import pubsubsql.Client;
/* MAKE SURE TO RUN PUBSUBSQL SERVER WHEN RUNNING THE EXAMPLE */
public class QuickStart {
public static void main(String[] args) {
try {
quickStart();
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
private static void quickStart() throws Exception {
Client client = new Client();
Client subscriber = new Client();
//----------------------------------------------------------------------------------------------------
// CONNECT
//----------------------------------------------------------------------------------------------------
String address = "localhost:7777";
client.connect(address);
subscriber.connect(address);
//----------------------------------------------------------------------------------------------------
// SQL MUST-KNOW RULES
//
// All commands must be in lower case.
//
// Identifiers can only begin with alphabetic characters and may contain any alphanumeric characters.
//
// The only available (but optional) data definition commands are
// key (unique index) - key table_name column_name
// tag (non-unique index) - tag table_name column_name
//
// Tables and columns are auto-created when accessed.
//
// The underlying data type for all columns is String.
// Strings do not have to be enclosed in single quotes as long as they have no special characters.
// The special characters are
// , - comma
// - white space characters (space, tab, new line)
// ) - right parenthesis
// ' - single quote
//----------------------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------------------
// INDEX
//----------------------------------------------------------------------------------------------------
try {
client.execute("key Stocks Ticker");
client.execute("tag Stocks MarketCap");
} catch (IllegalArgumentException e) {
// key or tag may have already been defined, so its ok
}
//----------------------------------------------------------------------------------------------------
// SUBSCRIBE
//----------------------------------------------------------------------------------------------------
subscriber.execute("subscribe * from Stocks where MarketCap = 'MEGA CAP'");
String pubsubid = subscriber.getPubSubId();
System.out.println("subscribed to Stocks pubsubid: " + pubsubid);
//----------------------------------------------------------------------------------------------------
// PUBLISH INSERT
//----------------------------------------------------------------------------------------------------
client.execute("insert into Stocks (Ticker, Price, MarketCap) values (GOOG, '1,200.22', 'MEGA CAP')");
client.execute("insert into Stocks (Ticker, Price, MarketCap) values (MSFT, 38,'MEGA CAP')");
//----------------------------------------------------------------------------------------------------
// SELECT
//----------------------------------------------------------------------------------------------------
client.execute("select id, Ticker from Stocks");
while (client.nextRow()) {
System.out.println("*********************************");
System.out.println(String.format("id:%s Ticker:%s \n", client.getValue("id"), client.getValue("Ticker")));
}
//----------------------------------------------------------------------------------------------------
// PROCESS PUBLISHED INSERT
//----------------------------------------------------------------------------------------------------
int timeout = 100;
while (subscriber.waitForPubSub(timeout)) {
System.out.println("*********************************");
System.out.println("Action:" + subscriber.getAction());
while (subscriber.nextRow()) {
System.out.println("New MEGA CAP stock:" + subscriber.getValue("Ticker"));
System.out.println("Price:" + subscriber.getValue("Price"));
}
}
//----------------------------------------------------------------------------------------------------
// PUBLISH UPDATE
//----------------------------------------------------------------------------------------------------
client.execute("update Stocks set Price = '1,500.00' where Ticker = GOOG");
//----------------------------------------------------------------------------------------------------
// SERVER WILL NOT PUBLISH INSERT BECAUSE WE ONLY SUBSCRIBED TO 'MEGA CAP'
//----------------------------------------------------------------------------------------------------
client.execute("insert into Stocks (Ticker, Price, MarketCap) values (IBM, 168, 'LARGE CAP')");
//----------------------------------------------------------------------------------------------------
// PUBLISH ADD
//----------------------------------------------------------------------------------------------------
client.execute("update Stocks set Price = 230.45, MarketCap = 'MEGA CAP' where Ticker = IBM");
//----------------------------------------------------------------------------------------------------
// PUBLISH REMOVE
//----------------------------------------------------------------------------------------------------
client.execute("update Stocks set Price = 170, MarketCap = 'LARGE CAP' where Ticker = IBM");
//----------------------------------------------------------------------------------------------------
// PUBLISH DELETE
//----------------------------------------------------------------------------------------------------
client.execute("delete from Stocks");
//----------------------------------------------------------------------------------------------------
// PROCESS ALL PUBLISHED
//----------------------------------------------------------------------------------------------------
while (subscriber.waitForPubSub(timeout)) {
System.out.println("*********************************");
System.out.println("Action:" + subscriber.getAction());
while (subscriber.nextRow()) {
int ordinal = 0;
for (String column : subscriber.getColumns()) {
System.out.print(String.format("%s:%s ", column, subscriber.getValue(ordinal)));
ordinal++;
}
System.out.println();
}
}
//----------------------------------------------------------------------------------------------------
// UNSUBSCRIBE
//----------------------------------------------------------------------------------------------------
subscriber.execute("unsubscribe from Stocks");
//----------------------------------------------------------------------------------------------------
// DISCONNECT
//----------------------------------------------------------------------------------------------------
client.disconnect();
}
}
|
923f76b1ee92d37db66cbca1823816359aa0c7b5
| 690 |
java
|
Java
|
multiton/src/test/java/com/iluwatar/multiton/NazgulTest.java
|
brusic/java-design-patterns
|
ab2aad32260a02e71c475b39c27b65d0c15df73b
|
[
"MIT"
] | 3 |
2019-06-23T13:04:45.000Z
|
2020-05-05T12:57:34.000Z
|
multiton/src/test/java/com/iluwatar/multiton/NazgulTest.java
|
pankajan05/java-design-patterns
|
150c4e0d5d6f4e1831f997cfbb018ede3b6bd8d1
|
[
"MIT"
] | null | null | null |
multiton/src/test/java/com/iluwatar/multiton/NazgulTest.java
|
pankajan05/java-design-patterns
|
150c4e0d5d6f4e1831f997cfbb018ede3b6bd8d1
|
[
"MIT"
] | 3 |
2016-12-17T19:28:45.000Z
|
2021-07-25T08:47:45.000Z
| 23 | 98 | 0.704348 | 1,001,170 |
package com.iluwatar.multiton;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertSame;
/**
* Date: 12/22/15 - 22:28 AM
*
* @author Jeroen Meulemeester
*/
public class NazgulTest {
/**
* Verify if {@link Nazgul#getInstance(NazgulName)} returns the correct Nazgul multiton instance
*/
@Test
public void testGetInstance() {
for (final NazgulName name : NazgulName.values()) {
final Nazgul nazgul = Nazgul.getInstance(name);
assertNotNull(nazgul);
assertSame(nazgul, Nazgul.getInstance(name));
assertEquals(name, nazgul.getName());
}
}
}
|
923f774bdd4e3e7a1b8b4be956cde2c2ac57c9f5
| 1,175 |
java
|
Java
|
tests/EntityMappingActionTest.java
|
lasiaylo/VoogaPeaches
|
55b6a94f5df989447bc51ea51c6ec5bbb8710f0e
|
[
"MIT"
] | null | null | null |
tests/EntityMappingActionTest.java
|
lasiaylo/VoogaPeaches
|
55b6a94f5df989447bc51ea51c6ec5bbb8710f0e
|
[
"MIT"
] | null | null | null |
tests/EntityMappingActionTest.java
|
lasiaylo/VoogaPeaches
|
55b6a94f5df989447bc51ea51c6ec5bbb8710f0e
|
[
"MIT"
] | null | null | null | 33.571429 | 92 | 0.733617 | 1,001,171 |
import database.jsonhelpers.JSONDataFolders;
import database.jsonhelpers.JSONDataManager;
import database.jsonhelpers.JSONToObjectConverter;
import engine.entities.Entity;
import engine.events.KeyPressEvent;
import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.input.KeyEvent;
import javafx.stage.Stage;
import org.json.JSONObject;
public class EntityMappingActionTest extends Application{
public static void main(String[] args) {
launch(args);
}
@Override
public void start(Stage primaryStage) throws Exception {
JSONDataManager manager = new JSONDataManager(JSONDataFolders.ENTITY_BLUEPRINT);
JSONObject blueprint = manager.readJSONFile("test");
JSONToObjectConverter<Entity> converter = new JSONToObjectConverter<>(Entity.class);
Entity entityFromFile = converter.createObjectFromJSON(Entity.class,blueprint);
Group group = new Group();
Scene s = new Scene(group);
s.setOnKeyPressed(e -> {
new KeyPressEvent(e).fire(entityFromFile);
});
primaryStage.setScene(s);
primaryStage.show();
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.