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
3e0ba8f7d74ca61e618625b3accaa426143bc020
21,808
java
Java
aws-java-sdk-batch/src/main/java/com/amazonaws/services/batch/model/RegisterJobDefinitionRequest.java
vprus/aws-sdk-java
af5c13133d936aa0586772b14847064118150b27
[ "Apache-2.0" ]
1
2019-02-08T21:30:20.000Z
2019-02-08T21:30:20.000Z
aws-java-sdk-batch/src/main/java/com/amazonaws/services/batch/model/RegisterJobDefinitionRequest.java
vprus/aws-sdk-java
af5c13133d936aa0586772b14847064118150b27
[ "Apache-2.0" ]
16
2018-05-15T05:35:42.000Z
2018-05-15T07:54:48.000Z
aws-java-sdk-batch/src/main/java/com/amazonaws/services/batch/model/RegisterJobDefinitionRequest.java
vprus/aws-sdk-java
af5c13133d936aa0586772b14847064118150b27
[ "Apache-2.0" ]
1
2021-09-08T09:31:32.000Z
2021-09-08T09:31:32.000Z
41.697897
132
0.654714
4,923
/* * Copyright 2013-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package com.amazonaws.services.batch.model; import java.io.Serializable; import javax.annotation.Generated; import com.amazonaws.AmazonWebServiceRequest; /** * * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/batch-2016-08-10/RegisterJobDefinition" target="_top">AWS API * Documentation</a> */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class RegisterJobDefinitionRequest extends com.amazonaws.AmazonWebServiceRequest implements Serializable, Cloneable { /** * <p> * The name of the job definition to register. Up to 128 letters (uppercase and lowercase), numbers, hyphens, and * underscores are allowed. * </p> */ private String jobDefinitionName; /** * <p> * The type of job definition. * </p> */ private String type; /** * <p> * Default parameter substitution placeholders to set in the job definition. Parameters are specified as a key-value * pair mapping. Parameters in a <code>SubmitJob</code> request override any corresponding parameter defaults from * the job definition. * </p> */ private java.util.Map<String, String> parameters; /** * <p> * An object with various properties specific for container-based jobs. This parameter is required if the * <code>type</code> parameter is <code>container</code>. * </p> */ private ContainerProperties containerProperties; /** * <p> * The retry strategy to use for failed jobs that are submitted with this job definition. Any retry strategy that is * specified during a <a>SubmitJob</a> operation overrides the retry strategy defined here. If a job is terminated * due to a timeout, it is not retried. * </p> */ private RetryStrategy retryStrategy; /** * <p> * The timeout configuration for jobs that are submitted with this job definition, after which AWS Batch terminates * your jobs if they have not finished. If a job is terminated due to a timeout, it is not retried. The minimum * value for the timeout is 60 seconds. Any timeout configuration that is specified during a <a>SubmitJob</a> * operation overrides the timeout configuration defined here. For more information, see <a * href="http://docs.aws.amazon.com/AmazonECS/latest/developerguide/job_timeouts.html">Job Timeouts</a> in the * <i>Amazon Elastic Container Service Developer Guide</i>. * </p> */ private JobTimeout timeout; /** * <p> * The name of the job definition to register. Up to 128 letters (uppercase and lowercase), numbers, hyphens, and * underscores are allowed. * </p> * * @param jobDefinitionName * The name of the job definition to register. Up to 128 letters (uppercase and lowercase), numbers, hyphens, * and underscores are allowed. */ public void setJobDefinitionName(String jobDefinitionName) { this.jobDefinitionName = jobDefinitionName; } /** * <p> * The name of the job definition to register. Up to 128 letters (uppercase and lowercase), numbers, hyphens, and * underscores are allowed. * </p> * * @return The name of the job definition to register. Up to 128 letters (uppercase and lowercase), numbers, * hyphens, and underscores are allowed. */ public String getJobDefinitionName() { return this.jobDefinitionName; } /** * <p> * The name of the job definition to register. Up to 128 letters (uppercase and lowercase), numbers, hyphens, and * underscores are allowed. * </p> * * @param jobDefinitionName * The name of the job definition to register. Up to 128 letters (uppercase and lowercase), numbers, hyphens, * and underscores are allowed. * @return Returns a reference to this object so that method calls can be chained together. */ public RegisterJobDefinitionRequest withJobDefinitionName(String jobDefinitionName) { setJobDefinitionName(jobDefinitionName); return this; } /** * <p> * The type of job definition. * </p> * * @param type * The type of job definition. * @see JobDefinitionType */ public void setType(String type) { this.type = type; } /** * <p> * The type of job definition. * </p> * * @return The type of job definition. * @see JobDefinitionType */ public String getType() { return this.type; } /** * <p> * The type of job definition. * </p> * * @param type * The type of job definition. * @return Returns a reference to this object so that method calls can be chained together. * @see JobDefinitionType */ public RegisterJobDefinitionRequest withType(String type) { setType(type); return this; } /** * <p> * The type of job definition. * </p> * * @param type * The type of job definition. * @see JobDefinitionType */ public void setType(JobDefinitionType type) { withType(type); } /** * <p> * The type of job definition. * </p> * * @param type * The type of job definition. * @return Returns a reference to this object so that method calls can be chained together. * @see JobDefinitionType */ public RegisterJobDefinitionRequest withType(JobDefinitionType type) { this.type = type.toString(); return this; } /** * <p> * Default parameter substitution placeholders to set in the job definition. Parameters are specified as a key-value * pair mapping. Parameters in a <code>SubmitJob</code> request override any corresponding parameter defaults from * the job definition. * </p> * * @return Default parameter substitution placeholders to set in the job definition. Parameters are specified as a * key-value pair mapping. Parameters in a <code>SubmitJob</code> request override any corresponding * parameter defaults from the job definition. */ public java.util.Map<String, String> getParameters() { return parameters; } /** * <p> * Default parameter substitution placeholders to set in the job definition. Parameters are specified as a key-value * pair mapping. Parameters in a <code>SubmitJob</code> request override any corresponding parameter defaults from * the job definition. * </p> * * @param parameters * Default parameter substitution placeholders to set in the job definition. Parameters are specified as a * key-value pair mapping. Parameters in a <code>SubmitJob</code> request override any corresponding * parameter defaults from the job definition. */ public void setParameters(java.util.Map<String, String> parameters) { this.parameters = parameters; } /** * <p> * Default parameter substitution placeholders to set in the job definition. Parameters are specified as a key-value * pair mapping. Parameters in a <code>SubmitJob</code> request override any corresponding parameter defaults from * the job definition. * </p> * * @param parameters * Default parameter substitution placeholders to set in the job definition. Parameters are specified as a * key-value pair mapping. Parameters in a <code>SubmitJob</code> request override any corresponding * parameter defaults from the job definition. * @return Returns a reference to this object so that method calls can be chained together. */ public RegisterJobDefinitionRequest withParameters(java.util.Map<String, String> parameters) { setParameters(parameters); return this; } public RegisterJobDefinitionRequest addParametersEntry(String key, String value) { if (null == this.parameters) { this.parameters = new java.util.HashMap<String, String>(); } if (this.parameters.containsKey(key)) throw new IllegalArgumentException("Duplicated keys (" + key.toString() + ") are provided."); this.parameters.put(key, value); return this; } /** * Removes all the entries added into Parameters. * * @return Returns a reference to this object so that method calls can be chained together. */ public RegisterJobDefinitionRequest clearParametersEntries() { this.parameters = null; return this; } /** * <p> * An object with various properties specific for container-based jobs. This parameter is required if the * <code>type</code> parameter is <code>container</code>. * </p> * * @param containerProperties * An object with various properties specific for container-based jobs. This parameter is required if the * <code>type</code> parameter is <code>container</code>. */ public void setContainerProperties(ContainerProperties containerProperties) { this.containerProperties = containerProperties; } /** * <p> * An object with various properties specific for container-based jobs. This parameter is required if the * <code>type</code> parameter is <code>container</code>. * </p> * * @return An object with various properties specific for container-based jobs. This parameter is required if the * <code>type</code> parameter is <code>container</code>. */ public ContainerProperties getContainerProperties() { return this.containerProperties; } /** * <p> * An object with various properties specific for container-based jobs. This parameter is required if the * <code>type</code> parameter is <code>container</code>. * </p> * * @param containerProperties * An object with various properties specific for container-based jobs. This parameter is required if the * <code>type</code> parameter is <code>container</code>. * @return Returns a reference to this object so that method calls can be chained together. */ public RegisterJobDefinitionRequest withContainerProperties(ContainerProperties containerProperties) { setContainerProperties(containerProperties); return this; } /** * <p> * The retry strategy to use for failed jobs that are submitted with this job definition. Any retry strategy that is * specified during a <a>SubmitJob</a> operation overrides the retry strategy defined here. If a job is terminated * due to a timeout, it is not retried. * </p> * * @param retryStrategy * The retry strategy to use for failed jobs that are submitted with this job definition. Any retry strategy * that is specified during a <a>SubmitJob</a> operation overrides the retry strategy defined here. If a job * is terminated due to a timeout, it is not retried. */ public void setRetryStrategy(RetryStrategy retryStrategy) { this.retryStrategy = retryStrategy; } /** * <p> * The retry strategy to use for failed jobs that are submitted with this job definition. Any retry strategy that is * specified during a <a>SubmitJob</a> operation overrides the retry strategy defined here. If a job is terminated * due to a timeout, it is not retried. * </p> * * @return The retry strategy to use for failed jobs that are submitted with this job definition. Any retry strategy * that is specified during a <a>SubmitJob</a> operation overrides the retry strategy defined here. If a job * is terminated due to a timeout, it is not retried. */ public RetryStrategy getRetryStrategy() { return this.retryStrategy; } /** * <p> * The retry strategy to use for failed jobs that are submitted with this job definition. Any retry strategy that is * specified during a <a>SubmitJob</a> operation overrides the retry strategy defined here. If a job is terminated * due to a timeout, it is not retried. * </p> * * @param retryStrategy * The retry strategy to use for failed jobs that are submitted with this job definition. Any retry strategy * that is specified during a <a>SubmitJob</a> operation overrides the retry strategy defined here. If a job * is terminated due to a timeout, it is not retried. * @return Returns a reference to this object so that method calls can be chained together. */ public RegisterJobDefinitionRequest withRetryStrategy(RetryStrategy retryStrategy) { setRetryStrategy(retryStrategy); return this; } /** * <p> * The timeout configuration for jobs that are submitted with this job definition, after which AWS Batch terminates * your jobs if they have not finished. If a job is terminated due to a timeout, it is not retried. The minimum * value for the timeout is 60 seconds. Any timeout configuration that is specified during a <a>SubmitJob</a> * operation overrides the timeout configuration defined here. For more information, see <a * href="http://docs.aws.amazon.com/AmazonECS/latest/developerguide/job_timeouts.html">Job Timeouts</a> in the * <i>Amazon Elastic Container Service Developer Guide</i>. * </p> * * @param timeout * The timeout configuration for jobs that are submitted with this job definition, after which AWS Batch * terminates your jobs if they have not finished. If a job is terminated due to a timeout, it is not * retried. The minimum value for the timeout is 60 seconds. Any timeout configuration that is specified * during a <a>SubmitJob</a> operation overrides the timeout configuration defined here. For more * information, see <a * href="http://docs.aws.amazon.com/AmazonECS/latest/developerguide/job_timeouts.html">Job Timeouts</a> in * the <i>Amazon Elastic Container Service Developer Guide</i>. */ public void setTimeout(JobTimeout timeout) { this.timeout = timeout; } /** * <p> * The timeout configuration for jobs that are submitted with this job definition, after which AWS Batch terminates * your jobs if they have not finished. If a job is terminated due to a timeout, it is not retried. The minimum * value for the timeout is 60 seconds. Any timeout configuration that is specified during a <a>SubmitJob</a> * operation overrides the timeout configuration defined here. For more information, see <a * href="http://docs.aws.amazon.com/AmazonECS/latest/developerguide/job_timeouts.html">Job Timeouts</a> in the * <i>Amazon Elastic Container Service Developer Guide</i>. * </p> * * @return The timeout configuration for jobs that are submitted with this job definition, after which AWS Batch * terminates your jobs if they have not finished. If a job is terminated due to a timeout, it is not * retried. The minimum value for the timeout is 60 seconds. Any timeout configuration that is specified * during a <a>SubmitJob</a> operation overrides the timeout configuration defined here. For more * information, see <a * href="http://docs.aws.amazon.com/AmazonECS/latest/developerguide/job_timeouts.html">Job Timeouts</a> in * the <i>Amazon Elastic Container Service Developer Guide</i>. */ public JobTimeout getTimeout() { return this.timeout; } /** * <p> * The timeout configuration for jobs that are submitted with this job definition, after which AWS Batch terminates * your jobs if they have not finished. If a job is terminated due to a timeout, it is not retried. The minimum * value for the timeout is 60 seconds. Any timeout configuration that is specified during a <a>SubmitJob</a> * operation overrides the timeout configuration defined here. For more information, see <a * href="http://docs.aws.amazon.com/AmazonECS/latest/developerguide/job_timeouts.html">Job Timeouts</a> in the * <i>Amazon Elastic Container Service Developer Guide</i>. * </p> * * @param timeout * The timeout configuration for jobs that are submitted with this job definition, after which AWS Batch * terminates your jobs if they have not finished. If a job is terminated due to a timeout, it is not * retried. The minimum value for the timeout is 60 seconds. Any timeout configuration that is specified * during a <a>SubmitJob</a> operation overrides the timeout configuration defined here. For more * information, see <a * href="http://docs.aws.amazon.com/AmazonECS/latest/developerguide/job_timeouts.html">Job Timeouts</a> in * the <i>Amazon Elastic Container Service Developer Guide</i>. * @return Returns a reference to this object so that method calls can be chained together. */ public RegisterJobDefinitionRequest withTimeout(JobTimeout timeout) { setTimeout(timeout); return this; } /** * Returns a string representation of this object; useful for testing and debugging. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); if (getJobDefinitionName() != null) sb.append("JobDefinitionName: ").append(getJobDefinitionName()).append(","); if (getType() != null) sb.append("Type: ").append(getType()).append(","); if (getParameters() != null) sb.append("Parameters: ").append(getParameters()).append(","); if (getContainerProperties() != null) sb.append("ContainerProperties: ").append(getContainerProperties()).append(","); if (getRetryStrategy() != null) sb.append("RetryStrategy: ").append(getRetryStrategy()).append(","); if (getTimeout() != null) sb.append("Timeout: ").append(getTimeout()); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof RegisterJobDefinitionRequest == false) return false; RegisterJobDefinitionRequest other = (RegisterJobDefinitionRequest) obj; if (other.getJobDefinitionName() == null ^ this.getJobDefinitionName() == null) return false; if (other.getJobDefinitionName() != null && other.getJobDefinitionName().equals(this.getJobDefinitionName()) == false) return false; if (other.getType() == null ^ this.getType() == null) return false; if (other.getType() != null && other.getType().equals(this.getType()) == false) return false; if (other.getParameters() == null ^ this.getParameters() == null) return false; if (other.getParameters() != null && other.getParameters().equals(this.getParameters()) == false) return false; if (other.getContainerProperties() == null ^ this.getContainerProperties() == null) return false; if (other.getContainerProperties() != null && other.getContainerProperties().equals(this.getContainerProperties()) == false) return false; if (other.getRetryStrategy() == null ^ this.getRetryStrategy() == null) return false; if (other.getRetryStrategy() != null && other.getRetryStrategy().equals(this.getRetryStrategy()) == false) return false; if (other.getTimeout() == null ^ this.getTimeout() == null) return false; if (other.getTimeout() != null && other.getTimeout().equals(this.getTimeout()) == false) return false; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getJobDefinitionName() == null) ? 0 : getJobDefinitionName().hashCode()); hashCode = prime * hashCode + ((getType() == null) ? 0 : getType().hashCode()); hashCode = prime * hashCode + ((getParameters() == null) ? 0 : getParameters().hashCode()); hashCode = prime * hashCode + ((getContainerProperties() == null) ? 0 : getContainerProperties().hashCode()); hashCode = prime * hashCode + ((getRetryStrategy() == null) ? 0 : getRetryStrategy().hashCode()); hashCode = prime * hashCode + ((getTimeout() == null) ? 0 : getTimeout().hashCode()); return hashCode; } @Override public RegisterJobDefinitionRequest clone() { return (RegisterJobDefinitionRequest) super.clone(); } }
3e0ba9090168c0fc71f9a6bf148e97b9c69d4d00
5,766
java
Java
MLN-Android/mlnservics/src/main/java/com/immomo/mls/fun/other/GridLayoutItemDecoration.java
xuejingfei/MLN
f5268f8c6e2f8e89cb29720424eb703676a3ed7c
[ "MIT" ]
1
2020-04-08T08:25:45.000Z
2020-04-08T08:25:45.000Z
MLN-Android/mlnservics/src/main/java/com/immomo/mls/fun/other/GridLayoutItemDecoration.java
dingpuyu/MLN
32124e5f261ef360f8c97688a4391fda9605389b
[ "MIT" ]
null
null
null
MLN-Android/mlnservics/src/main/java/com/immomo/mls/fun/other/GridLayoutItemDecoration.java
dingpuyu/MLN
32124e5f261ef360f8c97688a4391fda9605389b
[ "MIT" ]
null
null
null
40.893617
165
0.627992
4,924
/** * Created by MomoLuaNative. * Copyright (c) 2019, Momo Group. All rights reserved. * * This source code is licensed under the MIT. * For the full copyright and license information,please view the LICENSE file in the root directory of this source tree. */ package com.immomo.mls.fun.other; import android.view.View; import com.immomo.mls.fun.ud.view.recycler.UDCollectionGridLayout; import com.immomo.mls.fun.ud.view.recycler.UDCollectionLayout; import androidx.recyclerview.widget.GridLayoutManager; import androidx.recyclerview.widget.RecyclerView; @Deprecated public class GridLayoutItemDecoration extends RecyclerView.ItemDecoration { private static final String TAG = GridLayoutItemDecoration.class.getSimpleName(); public int horizontalSpace; public int verticalSpace; private int orientation = RecyclerView.VERTICAL; private int spanCount = UDCollectionLayout.DEFAULT_SPAN_COUNT; UDCollectionGridLayout mUDCollectionGridLayout; /* public GridLayoutItemDecoration(int d) { this(d, d, RecyclerView.VERTICAL, UDCollectionLayout.DEFAULT_SPAN_COUNT); }*/ public GridLayoutItemDecoration(int hs, int vs, int orientation, int spanCount, UDCollectionGridLayout udCollectionGridLayout) { this.horizontalSpace = hs; this.verticalSpace = vs; this.orientation = orientation; this.spanCount = spanCount; this.mUDCollectionGridLayout = udCollectionGridLayout; } public boolean isSame(int h, int v) { return ((h) == horizontalSpace) && ((v) == verticalSpace); } @Override public void getItemOffsets(android.graphics.Rect outRect, View view, RecyclerView parent, RecyclerView.State state) { GridLayoutManager layoutManager = (GridLayoutManager) parent.getLayoutManager(); final GridLayoutManager.LayoutParams lp = (GridLayoutManager.LayoutParams) view.getLayoutParams(); final int spanCount = layoutManager.getSpanCount(); super.getItemOffsets(outRect, view, parent, state); int childPosition = parent.getChildAdapterPosition(view); int currentColumn = layoutManager.getSpanSizeLookup().getSpanGroupIndex(childPosition, spanCount); boolean canScroll2ScreenLeft = mUDCollectionGridLayout.isCanScrollTolScreenLeft(); int totalColumn = layoutManager.getSpanSizeLookup().getSpanGroupIndex(parent.getAdapter().getItemCount() - 1, spanCount); int layoutInSetLeft = (int) mUDCollectionGridLayout.getPaddingValues()[0]; int layoutInSetTop = (int) mUDCollectionGridLayout.getPaddingValues()[1]; int layoutInSetRight = (int) mUDCollectionGridLayout.getPaddingValues()[2]; int layoutInSetBottom = (int) mUDCollectionGridLayout.getPaddingValues()[3]; if (orientation == RecyclerView.VERTICAL) { if (layoutManager.getSpanSizeLookup().getSpanGroupIndex(childPosition, spanCount) == 0) { //第一行 outRect.top = verticalSpace; } outRect.bottom = verticalSpace; if (lp.getSpanSize() == spanCount) { //占满 outRect.left = horizontalSpace; outRect.right = horizontalSpace; } else { outRect.left = Math.abs((int) (((float) (spanCount - lp.getSpanIndex())) / spanCount * horizontalSpace) ); if (lp.getSpanIndex() != 0) { // 不是最左侧一列 outRect.left = Math.abs((int) (((float) (spanCount - lp.getSpanIndex())) / spanCount * horizontalSpace) + layoutInSetLeft - horizontalSpace ); } outRect.right = (int) (((float) horizontalSpace * (spanCount + 1) / spanCount) - outRect.left); } if (lp.getSpanIndex() == spanCount - 1 || lp.getSpanSize() == spanCount) outRect.right = layoutInSetRight; if (lp.getSpanIndex() == 0 || lp.getSpanSize() == spanCount) { outRect.left = layoutInSetLeft; } if (currentColumn == 0 && canScroll2ScreenLeft) { // 第一行 outRect.top = layoutInSetTop; } else if (currentColumn == totalColumn && canScroll2ScreenLeft) { // 最后一行 outRect.bottom = layoutInSetBottom; } } else { outRect.right = horizontalSpace; if (lp.getSpanSize() == spanCount) { //占满 outRect.top = verticalSpace; outRect.bottom = verticalSpace; } else { outRect.top = (int) (((float) (spanCount - lp.getSpanIndex())) / spanCount * verticalSpace); outRect.bottom = (int) (((float) verticalSpace * (spanCount + 1) / spanCount) - outRect.top) + verticalSpace / 2; } /* if (lp.getSpanIndex() == 0 || lp.getSpanSize() == spanCount) { outRect.left = layoutInSetLeft; }*/ if (currentColumn == 0 && canScroll2ScreenLeft) { // 第一列 outRect.left = layoutInSetLeft; //outRect.top = layoutInSetTop; } else if (currentColumn == totalColumn && canScroll2ScreenLeft) { // 最后一列 outRect.right = layoutInSetRight; } } // LogUtil.d(TAG, " columns = " + layoutManager.getSpanSizeLookup().getSpanGroupIndex(childPosition, spanCount)); // // LogUtil.d(TAG, "childPosition = " + childPosition + " left = " + outRect.left + " " + // " right = " + outRect.right + " itemCount = " + spanCount); // // LogUtil.d(TAG, "childPosition = " + childPosition + " top = " + outRect.top + " " + // " bottom = " + outRect.bottom + " itemCount = " + spanCount); } }
3e0ba933651cbba9f706437279b7e9b4b0979568
1,248
java
Java
Rest/alm-tfs-client/src/main/generated/com/microsoft/alm/teamfoundation/workitemtracking/webapi/models/WitBatchResponse.java
Bhaskers-Blu-Org2/vso-httpclient-java
7b6329238498d7ad1934243150f955bea594df37
[ "MIT" ]
2
2021-10-20T11:35:54.000Z
2021-11-08T09:50:00.000Z
Rest/alm-tfs-client/src/main/generated/com/microsoft/alm/teamfoundation/workitemtracking/webapi/models/WitBatchResponse.java
JetBrains/vso-httpclient-java
7b6329238498d7ad1934243150f955bea594df37
[ "MIT" ]
null
null
null
Rest/alm-tfs-client/src/main/generated/com/microsoft/alm/teamfoundation/workitemtracking/webapi/models/WitBatchResponse.java
JetBrains/vso-httpclient-java
7b6329238498d7ad1934243150f955bea594df37
[ "MIT" ]
1
2022-03-19T08:36:49.000Z
2022-03-19T08:36:49.000Z
24
72
0.53766
4,925
// @formatter:off /* * --------------------------------------------------------- * Copyright(C) Microsoft Corporation. All rights reserved. * Licensed under the MIT license. See License.txt in the project root. * --------------------------------------------------------- * * --------------------------------------------------------- * Generated file, DO NOT EDIT * --------------------------------------------------------- * * See following wiki page for instructions on how to regenerate: * https://vsowiki.com/index.php?title=Rest_Client_Generation */ package com.microsoft.alm.teamfoundation.workitemtracking.webapi.models; import java.util.HashMap; /** */ public class WitBatchResponse { private String body; private int code; private HashMap<String, String> headers; public String getBody() { return body; } public void setBody(final String body) { this.body = body; } public int getCode() { return code; } public void setCode(final int code) { this.code = code; } public HashMap<String, String> getHeaders() { return headers; } public void setHeaders(final HashMap<String, String> headers) { this.headers = headers; } }
3e0ba9457e53240bea9310646de3f68ddbf575a5
1,610
java
Java
src/main/java/seraphaestus/xp_ore/ModConfig.java
Seraphaestus/xp_ore
cc1fd6bdf81fb4f19ac5b30a4fbd3b7f766785c4
[ "MIT" ]
null
null
null
src/main/java/seraphaestus/xp_ore/ModConfig.java
Seraphaestus/xp_ore
cc1fd6bdf81fb4f19ac5b30a4fbd3b7f766785c4
[ "MIT" ]
null
null
null
src/main/java/seraphaestus/xp_ore/ModConfig.java
Seraphaestus/xp_ore
cc1fd6bdf81fb4f19ac5b30a4fbd3b7f766785c4
[ "MIT" ]
null
null
null
41.282051
169
0.654658
4,926
package seraphaestus.xp_ore; import org.apache.logging.log4j.Level; import net.minecraftforge.common.config.Configuration; import seraphaestus.xp_ore.proxy.CommonProxy; public class ModConfig { private static final String CATEGORY_GENERAL = "general"; // This values below you can access elsewhere in your mod: public static int numOreTiers = 3; public static int xpBase = 1; public static int xpMultiplier = 2; // Call this from CommonProxy.preInit(). It will create our config if it doesn't // exist yet and read the values if it does exist. public static void readConfig() { Configuration cfg = CommonProxy.config; try { cfg.load(); initConfig(cfg); } catch (Exception e1) { ModMain.logger.log(Level.ERROR, "Problem loading config file!", e1); } finally { if (cfg.hasChanged()) { cfg.save(); } } } private static void initConfig(Configuration cfg) { cfg.addCustomCategoryComment(CATEGORY_GENERAL, "Configure the mod"); numOreTiers = cfg.getInt("numOreTiers", CATEGORY_GENERAL, numOreTiers, 0, 10, "How many different tiers of ore there wll be. Maximum of 10."); xpBase = cfg.getInt("xpBase", CATEGORY_GENERAL, xpBase, 0, Integer.MAX_VALUE, "The base amount of xp that the first tier of ore starts with."); xpMultiplier = cfg.getInt("xpMultiplier", CATEGORY_GENERAL, xpMultiplier, 0, Integer.MAX_VALUE, "Each tier of ore will increase the xp gained by this amount."); } }
3e0ba9cfdbff8391cf3cf678150a83d19062350c
1,547
java
Java
src/main/java/com/stellar/client/block/CreativeCrateBlockEntityRenderer.java
spiloxnet/Stellarisation-1.18
d0cc7f11fea3fb59b05baeeee92422ed0000b94e
[ "MIT" ]
null
null
null
src/main/java/com/stellar/client/block/CreativeCrateBlockEntityRenderer.java
spiloxnet/Stellarisation-1.18
d0cc7f11fea3fb59b05baeeee92422ed0000b94e
[ "MIT" ]
null
null
null
src/main/java/com/stellar/client/block/CreativeCrateBlockEntityRenderer.java
spiloxnet/Stellarisation-1.18
d0cc7f11fea3fb59b05baeeee92422ed0000b94e
[ "MIT" ]
null
null
null
48.34375
175
0.763413
4,927
package com.stellar.client.block; import com.stellar.blockentity.CreativeCrateBlockEntity; import net.minecraft.client.MinecraftClient; import net.minecraft.client.render.VertexConsumerProvider; import net.minecraft.client.render.block.entity.BlockEntityRenderer; import net.minecraft.client.render.block.entity.BlockEntityRendererFactory; import net.minecraft.client.render.model.json.ModelTransformation; import net.minecraft.client.util.math.MatrixStack; import net.minecraft.item.ItemStack; import net.minecraft.util.math.Vec3f; public class CreativeCrateBlockEntityRenderer<T extends CreativeCrateBlockEntity> implements BlockEntityRenderer<T> { public CreativeCrateBlockEntityRenderer(BlockEntityRendererFactory.Context context) { } @Override public void render(CreativeCrateBlockEntity blockEntity, float tickDelta, MatrixStack matrixStack, VertexConsumerProvider vertexConsumerProvider, int light, int overlay) { int k = (int)blockEntity.getPos().asLong(); ItemStack itemStack = blockEntity.creative_item; if (itemStack != ItemStack.EMPTY) { matrixStack.push(); matrixStack.translate(0.5, (1.0 / 16.0) * 14.0, 0.5); matrixStack.multiply(Vec3f.POSITIVE_X.getDegreesQuaternion(90.0F)); matrixStack.scale(0.375F, 0.375F, 0.375F); MinecraftClient.getInstance().getItemRenderer().renderItem(itemStack, ModelTransformation.Mode.FIXED, light, overlay, matrixStack, vertexConsumerProvider, k); matrixStack.pop(); } } }
3e0bab1eb0fc24eec69f6b0b09a3a33cfb03ea60
488
java
Java
addressbook-tests/src/test/java/com/tr/exmpl/GroupData.java
TriadaBack/Akopova
e0f4a48489eae9679282848b1fd7c2c999258b96
[ "Apache-2.0" ]
null
null
null
addressbook-tests/src/test/java/com/tr/exmpl/GroupData.java
TriadaBack/Akopova
e0f4a48489eae9679282848b1fd7c2c999258b96
[ "Apache-2.0" ]
null
null
null
addressbook-tests/src/test/java/com/tr/exmpl/GroupData.java
TriadaBack/Akopova
e0f4a48489eae9679282848b1fd7c2c999258b96
[ "Apache-2.0" ]
null
null
null
18.769231
65
0.604508
4,928
package com.tr.exmpl; public class GroupData { private final String name; private final String header; private final String footer; public GroupData(String name, String header, String footer) { this.name = name; this.header = header; this.footer = footer; } public String getName() { return name; } public String getHeader() { return header; } public String getFooter() { return footer; } }
3e0bab8b1fd9e9fd9cb8257f494fe76197b57a77
3,191
java
Java
drools-model/drools-model-compiler/src/main/java/org/drools/modelcompiler/builder/PackageSources.java
rongbo-j/drools
f1da5923a02854dcc01a34e5fe18543d56ba820c
[ "Apache-2.0" ]
1
2019-10-09T12:19:19.000Z
2019-10-09T12:19:19.000Z
drools-model/drools-model-compiler/src/main/java/org/drools/modelcompiler/builder/PackageSources.java
rongbo-j/drools
f1da5923a02854dcc01a34e5fe18543d56ba820c
[ "Apache-2.0" ]
null
null
null
drools-model/drools-model-compiler/src/main/java/org/drools/modelcompiler/builder/PackageSources.java
rongbo-j/drools
f1da5923a02854dcc01a34e5fe18543d56ba820c
[ "Apache-2.0" ]
null
null
null
32.896907
129
0.716076
4,929
/* * Copyright 2005 JBoss Inc * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.drools.modelcompiler.builder; import java.util.ArrayList; import java.util.Collection; import java.util.List; public class PackageSources { private List<GeneratedFile> pojoSources = new ArrayList<>(); private List<GeneratedFile> accumulateSources = new ArrayList<>(); private List<GeneratedFile> ruleSources = new ArrayList<>(); private GeneratedFile mainSource; private GeneratedFile domainClassSource; private String modelName; private Collection<Class<?>> ruleUnits; private String rulesFileName; public static PackageSources dumpSources(PackageModel pkgModel) { PackageSources sources = new PackageSources(); PackageModelWriter packageModelWriter = new PackageModelWriter(pkgModel); for (DeclaredTypeWriter declaredType : packageModelWriter.getDeclaredTypes()) { sources.pojoSources.add(new GeneratedFile(declaredType.getName(), declaredType.getSource())); } for (AccumulateClassWriter accumulateClassWriter : packageModelWriter.getAccumulateClasses()) { sources.accumulateSources.add(new GeneratedFile(accumulateClassWriter.getName(), accumulateClassWriter.getSource())); } RuleWriter rules = packageModelWriter.getRules(); sources.mainSource = new GeneratedFile(rules.getName(), rules.getMainSource()); sources.modelName = rules.getClassName(); for (RuleWriter.RuleFileSource ruleSource : rules.getRuleSources()) { sources.ruleSources.add(new GeneratedFile(ruleSource.getName(), ruleSource.getSource())); } PackageModelWriter.DomainClassesMetadata domainClassesMetadata = packageModelWriter.getDomainClassesMetadata(); sources.domainClassSource = new GeneratedFile(domainClassesMetadata.getName(), domainClassesMetadata.getSource()); sources.rulesFileName = pkgModel.getRulesFileName(); return sources; } public List<GeneratedFile> getPojoSources() { return pojoSources; } public List<GeneratedFile> getAccumulateSources() { return accumulateSources; } public List<GeneratedFile> getRuleSources() { return ruleSources; } public String getModelName() { return modelName; } public GeneratedFile getMainSource() { return mainSource; } public GeneratedFile getDomainClassSource() { return domainClassSource; } public Collection<Class<?>> getRuleUnits() { return ruleUnits; } public String getRulesFileName() { return rulesFileName; } }
3e0bac1560b3ca20a69ea1cc371f923798d258ff
8,329
java
Java
jms-core/src/main/java/au/gov/qld/fire/jms/domain/entity/Owner.java
totemsoft/jms
3bf3a3cd1d8de579daad25ddf7457d34c11b0c14
[ "Apache-2.0" ]
null
null
null
jms-core/src/main/java/au/gov/qld/fire/jms/domain/entity/Owner.java
totemsoft/jms
3bf3a3cd1d8de579daad25ddf7457d34c11b0c14
[ "Apache-2.0" ]
null
null
null
jms-core/src/main/java/au/gov/qld/fire/jms/domain/entity/Owner.java
totemsoft/jms
3bf3a3cd1d8de579daad25ddf7457d34c11b0c14
[ "Apache-2.0" ]
null
null
null
23.528249
120
0.564173
4,930
package au.gov.qld.fire.jms.domain.entity; import java.util.Date; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.Table; import javax.persistence.Temporal; import javax.persistence.TemporalType; import javax.persistence.Transient; import org.apache.commons.lang.ArrayUtils; import org.codehaus.jackson.annotate.JsonProperty; import org.hibernate.annotations.Type; import au.gov.qld.fire.domain.Auditable; import au.gov.qld.fire.domain.entity.Contact; import au.gov.qld.fire.domain.location.Address; import au.gov.qld.fire.domain.security.User; import au.gov.qld.fire.jms.domain.file.File; import au.gov.qld.fire.jms.domain.refdata.OwnerType; import au.gov.qld.fire.jms.domain.refdata.OwnerTypeEnum; /* * @hibernate.class table="OWNER" dynamic-update="true" */ @Entity @Table(name = "OWNER") public class Owner extends Auditable<Long> { /** serialVersionUID */ private static final long serialVersionUID = -5610709351171241637L; public static final String[] IGNORE = (String[]) ArrayUtils.addAll(Auditable.IGNORE, new String[] {"ownerId", "ownerType", "address", "contact", "archBy", "file", "nextOwner"}); private OwnerType ownerType; private boolean ownerOccupied; private String legalName; private String abn; private String reference; private String management; private boolean defaultContact; private Date archDate; private User archBy; private File file; private Owner nextOwner; private Contact contact; private Address address; /** * */ public Owner() { super(); } /** * @param id */ public Owner(Long id) { super(id); } /** * @param id */ public Owner(OwnerTypeEnum ownerType) { getOwnerType().setId(new Long(ownerType.ordinal())); } /* (non-Javadoc) * @see au.gov.qld.fire.jms.domain.BaseModel#getId() */ @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "OWNER_ID") public Long getOwnerId() { return super.getId(); } /* (non-Javadoc) * @see au.gov.qld.fire.jms.domain.BaseModel#setId(java.lang.Object) */ public void setOwnerId(Long ownerId) { super.setId(ownerId); } /** * @hibernate.many-to-one * not-null="true" * @hibernate.column name="OWNER_TYPE_ID" * */ @ManyToOne//(fetch = FetchType.LAZY) @JoinColumn(name = "OWNER_TYPE_ID", nullable = false) @JsonProperty public OwnerType getOwnerType() { if (ownerType == null) { ownerType = new OwnerType(); } return ownerType; } public void setOwnerType(OwnerType ownerType) { this.ownerType = ownerType; } @Transient public boolean isBodyCorporate() { return ownerType != null && ownerType.getId() != null && ownerType.getId() == OwnerTypeEnum.BODY_CORPORATE.ordinal(); } @Column(name = "OWNER_OCCUPIED", nullable = false) @Type(type = "yes_no") public boolean isOwnerOccupied() { return ownerOccupied; } public void setOwnerOccupied(boolean ownerOccupied) { this.ownerOccupied = ownerOccupied; } /** * @hibernate.property * column="LEGAL_NAME" * length="255" * not-null="true" * */ @Column(name = "LEGAL_NAME", nullable = false) @JsonProperty public String getLegalName() { return this.legalName; } public void setLegalName(String legalName) { this.legalName = legalName; } /** * @hibernate.property * column="ABN" * length="20" * not-null="false" * */ @Column(name = "ABN", nullable = true) @JsonProperty public String getAbn() { return abn; } public void setAbn(String abn) { this.abn = abn; } @Column(name = "REFERENCE", nullable = true, length = 20) @JsonProperty public String getReference() { return reference; } public void setReference(String reference) { this.reference = reference; } @Column(name = "MANAGEMENT", nullable = true, length = 50) @JsonProperty public String getManagement() { return management; } public void setManagement(String management) { this.management = management; } /** * @hibernate.property * column="DEFAULT_CONTACT" * length="1" * not-null="true" * */ @Column(name = "DEFAULT_CONTACT", nullable = false) @Type(type = "yes_no") public boolean isDefaultContact() { return defaultContact; } public void setDefaultContact(boolean defaultContact) { this.defaultContact = defaultContact; getContact().setDefaultContact(defaultContact); // transient property } /** * @hibernate.property * column="ARCH_DATE" * length="23" * */ @Temporal(TemporalType.DATE) @Column(name = "ARCH_DATE", nullable = true) public Date getArchDate() { return this.archDate; } public void setArchDate(Date ownerArchDate) { this.archDate = ownerArchDate; } /** * @hibernate.many-to-one * @hibernate.column name="ARCH_BY" * */ @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "ARCH_BY", nullable = true) public User getArchBy() { return this.archBy; } public void setArchBy(User ownerArchBy) { this.archBy = ownerArchBy; } /** * @hibernate.many-to-one * not-null="true" * @hibernate.column name="FILE_ID" * */ @ManyToOne(fetch = FetchType.EAGER) // used in UI - need to be eager loaded @JoinColumn(name = "FILE_ID", nullable = false) public File getFile() { return this.file; } public void setFile(File file) { this.file = file; } /** * @hibernate.many-to-one * not-null="false" * @hibernate.column name="NEXT_OWNER_ID" * */ @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "NEXT_OWNER_ID", nullable = true) public Owner getNextOwner() { return this.nextOwner; } public void setNextOwner(Owner nextOwner) { this.nextOwner = nextOwner; } /** * @hibernate.many-to-one * not-null="true" * @hibernate.column name="CONTACT_ID" * */ @ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL) @JoinColumn(name = "CONTACT_ID", nullable = false) @JsonProperty public Contact getContact() { if (contact == null) { contact = new Contact(); } return this.contact; } public void setContact(Contact contact) { this.contact = contact; } /** * @hibernate.many-to-one * not-null="true" * @hibernate.column name="ADDRESS_ID" * */ @ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL) @JoinColumn(name = "ADDRESS_ID", nullable = false) @JsonProperty public Address getAddress() { if (address == null) { address = new Address(); } return this.address; } public void setAddress(Address address) { this.address = address; } }
3e0bac8ac652ae3d4eaee053d370ba35f15f51da
4,939
java
Java
foundation/eclipselink.core.test/src/org/eclipse/persistence/testing/tests/validation/NoAttributeValueConversionToFieldValueProvidedTest.java
brettdavidson3/eclipselink.runtime
a992a67ce49ca56117df4632c9c0c70938a0b28e
[ "BSD-3-Clause" ]
null
null
null
foundation/eclipselink.core.test/src/org/eclipse/persistence/testing/tests/validation/NoAttributeValueConversionToFieldValueProvidedTest.java
brettdavidson3/eclipselink.runtime
a992a67ce49ca56117df4632c9c0c70938a0b28e
[ "BSD-3-Clause" ]
null
null
null
foundation/eclipselink.core.test/src/org/eclipse/persistence/testing/tests/validation/NoAttributeValueConversionToFieldValueProvidedTest.java
brettdavidson3/eclipselink.runtime
a992a67ce49ca56117df4632c9c0c70938a0b28e
[ "BSD-3-Clause" ]
null
null
null
48.421569
195
0.702369
4,931
/******************************************************************************* * Copyright (c) 1998, 2013 Oracle and/or its affiliates. All rights reserved. * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0 * which accompanies this distribution. * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html * and the Eclipse Distribution License is available at * http://www.eclipse.org/org/documents/edl-v10.php. * * Contributors: * Oracle - initial API and implementation from Oracle TopLink ******************************************************************************/ package org.eclipse.persistence.testing.tests.validation; import org.eclipse.persistence.descriptors.ClassDescriptor; import org.eclipse.persistence.descriptors.RelationalDescriptor; import org.eclipse.persistence.exceptions.DescriptorException; import org.eclipse.persistence.exceptions.IntegrityChecker; import org.eclipse.persistence.exceptions.EclipseLinkException; import org.eclipse.persistence.mappings.DirectToFieldMapping; import org.eclipse.persistence.mappings.converters.ObjectTypeConverter; import org.eclipse.persistence.sessions.DatabaseSession; import org.eclipse.persistence.sessions.UnitOfWork; //Created by Ian Reid //Date: Feb 17, 2k3 //uses class org.eclipse.persistence.testing.tests.validation.EmployeeWithProblems public class NoAttributeValueConversionToFieldValueProvidedTest extends ExceptionTest { public NoAttributeValueConversionToFieldValueProvidedTest() { super(); setDescription("This tests No Attribute Value Conversion To Field Value Provided (TL-ERROR 115) "); } protected void setup() { expectedException = DescriptorException.noAttributeValueConversionToFieldValueProvided(null, null); orgDescriptor = getSession().getDescriptor(org.eclipse.persistence.testing.tests.validation.EmployeeWithProblems.class); orgIntegrityChecker = getSession().getIntegrityChecker(); getSession().setIntegrityChecker(new IntegrityChecker()); getSession().getIntegrityChecker().dontCatchExceptions(); ((DatabaseSession)getSession()).addDescriptor(descriptor()); } ClassDescriptor orgDescriptor; IntegrityChecker orgIntegrityChecker; public void reset() { getSession().getDescriptors().remove(org.eclipse.persistence.testing.tests.validation.EmployeeWithProblems.class); if (orgDescriptor != null) { ((DatabaseSession)getSession()).addDescriptor(orgDescriptor); } if (orgIntegrityChecker != null) { getSession().setIntegrityChecker(orgIntegrityChecker); } // getAbstractSession().rollbackTransaction(); // getSession().getIdentityMapAccessor().initializeAllIdentityMaps(); } public void test() { Object employee = getSession().readObject(org.eclipse.persistence.testing.tests.validation.EmployeeWithProblems.class); UnitOfWork uow = getSession().acquireUnitOfWork(); org.eclipse.persistence.testing.tests.validation.EmployeeWithProblems employeeClone = (org.eclipse.persistence.testing.tests.validation.EmployeeWithProblems)uow.registerObject(employee); //the following causes the correct error to occure. employeeClone.setGender("Other"); try { uow.commit(); } catch (EclipseLinkException exception) { caughtException = exception; } } public RelationalDescriptor descriptor() { RelationalDescriptor descriptor = new RelationalDescriptor(); descriptor.setJavaClass(org.eclipse.persistence.testing.tests.validation.EmployeeWithProblems.class); descriptor.addTableName("EMPLOYEE"); descriptor.addPrimaryKeyFieldName("EMPLOYEE.EMP_ID"); // Descriptor properties. descriptor.useFullIdentityMap(); descriptor.setIdentityMapSize(100); descriptor.useRemoteFullIdentityMap(); descriptor.setRemoteIdentityMapSize(100); DirectToFieldMapping idMapping = new DirectToFieldMapping(); idMapping.setAttributeName("id"); idMapping.setFieldName("EMPLOYEE.EMP_ID"); descriptor.addMapping(idMapping); DirectToFieldMapping genderMapping = new DirectToFieldMapping(); genderMapping.setAttributeName("gender"); genderMapping.setFieldName("EMPLOYEE.GENDER"); ObjectTypeConverter genderConverter = new ObjectTypeConverter(); genderConverter.addConversionValue("M", "Male"); genderConverter.addConversionValue("F", "Female"); genderMapping.setConverter(genderConverter); descriptor.addMapping(genderMapping); return descriptor; } }
3e0bae1d290f2066d4e1fa33679c2809a4bb45b4
1,004
java
Java
Applets_Awt/EventHandling/EventHandlingTenth.java
AlphaBAT69/Java-Programs
d4e5e8ce7d3c24fc57e817f887e6ee1c52314ef4
[ "MIT" ]
3
2017-08-26T11:40:11.000Z
2018-01-26T12:33:16.000Z
Applets_Awt/EventHandling/EventHandlingTenth.java
tanaytoshniwal/Java-Programs
d4e5e8ce7d3c24fc57e817f887e6ee1c52314ef4
[ "MIT" ]
null
null
null
Applets_Awt/EventHandling/EventHandlingTenth.java
tanaytoshniwal/Java-Programs
d4e5e8ce7d3c24fc57e817f887e6ee1c52314ef4
[ "MIT" ]
null
null
null
23.348837
47
0.702191
4,932
import java.applet.Applet; import java.awt.Button; import java.awt.Color; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; public class EventHandlingTenth extends Applet{ Button b1,b2,b3,b4; @Override public void init() { setSize(500,500); b1=new Button("RED"); b2=new Button("GREEN"); b3=new Button("BLUE"); b4=new Button("WHITE"); add(b1);add(b2);add(b3);add(b4); b1.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { setBackground(Color.red); } }); b2.addActionListener(new ActionListener(){ @Override public void actionPerformed(ActionEvent e){ setBackground(Color.green); } }); b3.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { setBackground(Color.blue); } }); b4.addActionListener(new ActionListener(){ @Override public void actionPerformed(ActionEvent e){ setBackground(Color.white); } }); } }
3e0bae74bd01786ca966df7c89858596e2aaf1b0
5,295
java
Java
modules/dfp_appengine/src/main/java/com/google/api/ads/admanager/jaxws/v201802/ProgressRule.java
nwbirnie/googleads-java-lib
3d38daadf66e5d9c3db220559f099fd5c5b19e70
[ "Apache-2.0" ]
1
2019-11-30T23:41:48.000Z
2019-11-30T23:41:48.000Z
modules/dfp_appengine/src/main/java/com/google/api/ads/admanager/jaxws/v201802/ProgressRule.java
nwbirnie/googleads-java-lib
3d38daadf66e5d9c3db220559f099fd5c5b19e70
[ "Apache-2.0" ]
null
null
null
modules/dfp_appengine/src/main/java/com/google/api/ads/admanager/jaxws/v201802/ProgressRule.java
nwbirnie/googleads-java-lib
3d38daadf66e5d9c3db220559f099fd5c5b19e70
[ "Apache-2.0" ]
null
null
null
27.015306
148
0.609065
4,933
// Copyright 2018 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.api.ads.admanager.jaxws.v201802; import java.util.ArrayList; import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlSchemaType; import javax.xml.bind.annotation.XmlType; /** * * Describes a rule in a workflow step. * * * <p>Java class for ProgressRule complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="ProgressRule"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="actions" type="{https://www.google.com/apis/ads/publisher/v201802}ProgressAction" maxOccurs="unbounded" minOccurs="0"/> * &lt;element name="name" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="evaluationStatus" type="{https://www.google.com/apis/ads/publisher/v201802}WorkflowEvaluationStatus" minOccurs="0"/> * &lt;element name="evaluationTime" type="{https://www.google.com/apis/ads/publisher/v201802}DateTime" minOccurs="0"/> * &lt;element name="isExternal" type="{http://www.w3.org/2001/XMLSchema}boolean" minOccurs="0"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "ProgressRule", propOrder = { "actions", "name", "evaluationStatus", "evaluationTime", "isExternal" }) public class ProgressRule { protected List<ProgressAction> actions; protected String name; @XmlSchemaType(name = "string") protected WorkflowEvaluationStatus evaluationStatus; protected DateTime evaluationTime; protected Boolean isExternal; /** * Gets the value of the actions property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the actions property. * * <p> * For example, to add a new item, do as follows: * <pre> * getActions().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link ProgressAction } * * */ public List<ProgressAction> getActions() { if (actions == null) { actions = new ArrayList<ProgressAction>(); } return this.actions; } /** * Gets the value of the name property. * * @return * possible object is * {@link String } * */ public String getName() { return name; } /** * Sets the value of the name property. * * @param value * allowed object is * {@link String } * */ public void setName(String value) { this.name = value; } /** * Gets the value of the evaluationStatus property. * * @return * possible object is * {@link WorkflowEvaluationStatus } * */ public WorkflowEvaluationStatus getEvaluationStatus() { return evaluationStatus; } /** * Sets the value of the evaluationStatus property. * * @param value * allowed object is * {@link WorkflowEvaluationStatus } * */ public void setEvaluationStatus(WorkflowEvaluationStatus value) { this.evaluationStatus = value; } /** * Gets the value of the evaluationTime property. * * @return * possible object is * {@link DateTime } * */ public DateTime getEvaluationTime() { return evaluationTime; } /** * Sets the value of the evaluationTime property. * * @param value * allowed object is * {@link DateTime } * */ public void setEvaluationTime(DateTime value) { this.evaluationTime = value; } /** * Gets the value of the isExternal property. * * @return * possible object is * {@link Boolean } * */ public Boolean isIsExternal() { return isExternal; } /** * Sets the value of the isExternal property. * * @param value * allowed object is * {@link Boolean } * */ public void setIsExternal(Boolean value) { this.isExternal = value; } }
3e0baed184c97289a8aec4590a28f8b945cd9da5
313
java
Java
inject-java/src/test/groovy/io/micronaut/inject/annotation/repeatable/Topic.java
auke-/micronaut-core
49af63fedde1436034a440124087d4f0d714761b
[ "Apache-2.0" ]
5,607
2018-05-23T10:39:16.000Z
2022-03-31T04:40:39.000Z
inject-java/src/test/groovy/io/micronaut/inject/annotation/repeatable/Topic.java
auke-/micronaut-core
49af63fedde1436034a440124087d4f0d714761b
[ "Apache-2.0" ]
4,570
2018-05-23T10:32:30.000Z
2022-03-31T15:37:42.000Z
inject-java/src/test/groovy/io/micronaut/inject/annotation/repeatable/Topic.java
ashishkujoy/micronaut-core
ca3bfa89c7319987ac5982d7788105e881eaf521
[ "Apache-2.0" ]
1,083
2018-05-23T13:09:44.000Z
2022-03-31T20:42:27.000Z
22.357143
50
0.789137
4,934
package io.micronaut.inject.annotation.repeatable; import java.lang.annotation.Repeatable; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; @Retention(RetentionPolicy.RUNTIME) @Repeatable(Topics.class) public @interface Topic { String value(); int qos() default 1; }
3e0bb0803fe9e68cf34477456168598985eb570a
1,852
java
Java
src/test/java/edu/illinois/library/cantaloupe/resource/iiif/v1/IdentifierResourceTest.java
BossaNova/cantaloupe
bd4031ec963b9608cd980ccb734e64076f26cd8a
[ "NCSA" ]
1
2021-01-21T21:23:09.000Z
2021-01-21T21:23:09.000Z
src/test/java/edu/illinois/library/cantaloupe/resource/iiif/v1/IdentifierResourceTest.java
BossaNova/cantaloupe
bd4031ec963b9608cd980ccb734e64076f26cd8a
[ "NCSA" ]
null
null
null
src/test/java/edu/illinois/library/cantaloupe/resource/iiif/v1/IdentifierResourceTest.java
BossaNova/cantaloupe
bd4031ec963b9608cd980ccb734e64076f26cd8a
[ "NCSA" ]
3
2018-02-15T14:16:05.000Z
2018-11-20T19:40:38.000Z
33.672727
82
0.725162
4,935
package edu.illinois.library.cantaloupe.resource.iiif.v1; import edu.illinois.library.cantaloupe.config.Configuration; import edu.illinois.library.cantaloupe.config.Key; import edu.illinois.library.cantaloupe.resource.ResourceTest; import edu.illinois.library.cantaloupe.resource.Route; import edu.illinois.library.cantaloupe.resource.iiif.InformationResourceTester; import org.junit.Test; import java.net.URI; public class IdentifierResourceTest extends ResourceTest { private static final String IMAGE = "jpg-rgb-64x56x8-baseline.jpg"; private InformationResourceTester tester = new InformationResourceTester(); @Override protected String getEndpointPath() { return Route.IIIF_1_PATH; } @Test public void testGETRedirectToInfoJSON() { URI fromURI = getHTTPURI("/" + IMAGE); URI toURI = getHTTPURI("/" + IMAGE + "/info.json"); tester.testRedirectToInfoJSON(fromURI, toURI); } @Test public void testGETRedirectToInfoJSONWithEncodedCharacters() { Configuration config = Configuration.getInstance(); config.setProperty(Key.SLASH_SUBSTITUTE, ":"); URI fromURI = getHTTPURI("/subfolder%3A" + IMAGE); URI toURI = getHTTPURI("/subfolder%3A" + IMAGE + "/info.json"); tester.testRedirectToInfoJSONWithEncodedCharacters(fromURI, toURI); } @Test public void testGETRedirectToInfoJSONWithDifferentPublicIdentifier() throws Exception { URI uri = getHTTPURI("/" + IMAGE); tester.testRedirectToInfoJSONWithDifferentPublicIdentifier(uri); } @Test public void testGETRedirectToInfoJSONWithDifferentDeprecatedPublicIdentifier() throws Exception { URI uri = getHTTPURI("/" + IMAGE); tester.testRedirectToInfoJSONWithDifferentDeprecatedPublicIdentifier(uri); } }
3e0bb0895b303c7a86021caa9694f42d39c18e4e
554
java
Java
ICC/SOOT-Nightly/soot-github/systests/java_tests/SimpleFields.java
dongy6/type-inference
90d002a1e2d0a3d160ab204084da9d5be5fdd971
[ "Apache-2.0" ]
1
2019-12-07T16:13:03.000Z
2019-12-07T16:13:03.000Z
ICC/SOOT-Nightly/soot-github/systests/java_tests/SimpleFields.java
dongy6/type-inference
90d002a1e2d0a3d160ab204084da9d5be5fdd971
[ "Apache-2.0" ]
null
null
null
ICC/SOOT-Nightly/soot-github/systests/java_tests/SimpleFields.java
dongy6/type-inference
90d002a1e2d0a3d160ab204084da9d5be5fdd971
[ "Apache-2.0" ]
null
null
null
14.972973
45
0.413357
4,936
public class SimpleFields { Point p1 = new Point(); Point p2 = new Point(); public static void main(String [] args){ SimpleFields sf = new SimpleFields(); sf.run(); } public void run(){ int i = 3; p1.x = 9; p1.y = 8; p2.x = i; p2.y = 4; if ((p1.x - p2.x) > (p1.y - p2.y)){ p1.x = p1.y; } } public void test(Point p){ if (p.x > 3){ p.y = 3; } } } class Point { public int x; public int y; }
3e0bb0a6d74c62df2aee1a33bafe93839b137fe2
4,147
java
Java
sdks/java/io/kinesis/src/test/java/org/apache/beam/sdk/io/kinesis/KinesisProducerMock.java
Ardagan/beam
8c28d3e7d06fdd16ffcb570ba33b272e9b53a218
[ "Apache-2.0" ]
2
2020-08-30T14:49:58.000Z
2020-08-30T15:02:38.000Z
sdks/java/io/kinesis/src/test/java/org/apache/beam/sdk/io/kinesis/KinesisProducerMock.java
Ardagan/beam
8c28d3e7d06fdd16ffcb570ba33b272e9b53a218
[ "Apache-2.0" ]
11
2018-05-22T06:08:39.000Z
2018-10-05T15:02:21.000Z
sdks/java/io/kinesis/src/test/java/org/apache/beam/sdk/io/kinesis/KinesisProducerMock.java
Ardagan/beam
8c28d3e7d06fdd16ffcb570ba33b272e9b53a218
[ "Apache-2.0" ]
1
2019-09-23T08:45:00.000Z
2019-09-23T08:45:00.000Z
32.147287
90
0.750663
4,937
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.beam.sdk.io.kinesis; import static com.google.common.collect.Lists.newArrayList; import com.amazonaws.services.kinesis.producer.IKinesisProducer; import com.amazonaws.services.kinesis.producer.KinesisProducerConfiguration; import com.amazonaws.services.kinesis.producer.Metric; import com.amazonaws.services.kinesis.producer.UserRecord; import com.amazonaws.services.kinesis.producer.UserRecordResult; import com.google.common.util.concurrent.ListenableFuture; import com.google.common.util.concurrent.SettableFuture; import java.nio.ByteBuffer; import java.util.List; import java.util.concurrent.ExecutionException; import org.joda.time.DateTime; /** Simple mock implementation of {@link IKinesisProducer} for testing. */ public class KinesisProducerMock implements IKinesisProducer { private boolean isFailedFlush = false; private List<UserRecord> addedRecords = newArrayList(); private KinesisServiceMock kinesisService = KinesisServiceMock.getInstance(); public KinesisProducerMock() {} public KinesisProducerMock(KinesisProducerConfiguration config, boolean isFailedFlush) { this.isFailedFlush = isFailedFlush; } @Override public ListenableFuture<UserRecordResult> addUserRecord( String stream, String partitionKey, ByteBuffer data) { throw new RuntimeException("Not implemented"); } @Override public ListenableFuture<UserRecordResult> addUserRecord(UserRecord userRecord) { throw new RuntimeException("Not implemented"); } @Override public ListenableFuture<UserRecordResult> addUserRecord( String stream, String partitionKey, String explicitHashKey, ByteBuffer data) { SettableFuture<UserRecordResult> f = SettableFuture.create(); if (kinesisService.getExistedStream().equals(stream)) { addedRecords.add(new UserRecord(stream, partitionKey, explicitHashKey, data)); } return f; } @Override public int getOutstandingRecordsCount() { return addedRecords.size(); } @Override public List<Metric> getMetrics(String metricName, int windowSeconds) throws InterruptedException, ExecutionException { throw new RuntimeException("Not implemented"); } @Override public List<Metric> getMetrics(String metricName) throws InterruptedException, ExecutionException { throw new RuntimeException("Not implemented"); } @Override public List<Metric> getMetrics() throws InterruptedException, ExecutionException { throw new RuntimeException("Not implemented"); } @Override public List<Metric> getMetrics(int windowSeconds) throws InterruptedException, ExecutionException { throw new RuntimeException("Not implemented"); } @Override public void destroy() {} @Override public void flush(String stream) { throw new RuntimeException("Not implemented"); } @Override public void flush() { if (isFailedFlush) { // don't flush return; } DateTime arrival = DateTime.now(); for (int i = 0; i < addedRecords.size(); i++) { UserRecord record = addedRecords.get(i); arrival = arrival.plusSeconds(1); kinesisService.addShardedData(record.getData(), arrival); addedRecords.remove(i); } } @Override public synchronized void flushSync() { if (getOutstandingRecordsCount() > 0) { flush(); } } }
3e0bb12a9561e72ca0d7bb53c5b3b1594f236b12
5,112
java
Java
subprojects/internal-integ-testing/src/main/groovy/org/gradle/test/fixtures/server/http/SendPartialResponseThenBlock.java
stefanleh/gradle
c48e1c7bc796f7f3f6d207b7f635f0783965ab3d
[ "Apache-2.0" ]
2
2018-09-29T05:42:34.000Z
2018-12-12T05:15:10.000Z
subprojects/internal-integ-testing/src/main/groovy/org/gradle/test/fixtures/server/http/SendPartialResponseThenBlock.java
stefanleh/gradle
c48e1c7bc796f7f3f6d207b7f635f0783965ab3d
[ "Apache-2.0" ]
2
2020-07-17T08:52:17.000Z
2021-05-09T06:16:13.000Z
subprojects/internal-integ-testing/src/main/groovy/org/gradle/test/fixtures/server/http/SendPartialResponseThenBlock.java
stefanleh/gradle
c48e1c7bc796f7f3f6d207b7f635f0783965ab3d
[ "Apache-2.0" ]
2
2017-12-03T17:46:23.000Z
2022-01-11T02:33:52.000Z
33.631579
131
0.595266
4,938
/* * Copyright 2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gradle.test.fixtures.server.http; import com.sun.net.httpserver.HttpExchange; import org.gradle.internal.UncheckedException; import org.gradle.internal.time.Clock; import org.gradle.internal.time.Time; import java.io.IOException; import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.Lock; class SendPartialResponseThenBlock implements BlockingHttpServer.BlockingRequest, ResourceHandler, ResourceExpectation { private final String path; private final byte[] content; private final Lock lock; private final int timeoutMs; private final Condition condition; private boolean requestStarted; private boolean released; private final Clock clock = Time.clock(); private WaitPrecondition precondition; private long mostRecentEvent; private AssertionError failure; SendPartialResponseThenBlock(Lock lock, int timeoutMs, String path, byte[] content) { this.lock = lock; this.timeoutMs = timeoutMs; this.path = ExpectGetAndSendFixedContent.removeLeadingSlash(path); this.content = content; condition = lock.newCondition(); } @Override public String getPath() { return path; } @Override public String getMethod() { return "GET"; } @Override public ResourceHandler create(WaitPrecondition precondition) { this.precondition = precondition; return this; } @Override public void writeTo(int requestId, HttpExchange exchange) throws IOException { exchange.sendResponseHeaders(200, content.length); exchange.getResponseBody().write(content, 0, 1024); exchange.getResponseBody().flush(); lock.lock(); try { long now = clock.getCurrentTime(); if (mostRecentEvent < now) { mostRecentEvent = now; } requestStarted = true; condition.signalAll(); while (!released && failure == null) { long waitMs = mostRecentEvent + timeoutMs - clock.getCurrentTime(); if (waitMs < 0) { System.out.println(String.format("[%d] timeout waiting to be released after sending some content", requestId)); failure = new AssertionError("Timeout waiting to be released after sending some content."); condition.signalAll(); throw failure; } try { condition.await(waitMs, TimeUnit.MILLISECONDS); } catch (InterruptedException e) { throw UncheckedException.throwAsUncheckedException(e); } } if (failure != null) { throw failure; } } finally { lock.unlock(); } exchange.getResponseBody().write(content, 1024, content.length - 1024); } @Override public void waitUntilBlocked() { lock.lock(); try { precondition.assertCanWait(); if (released) { throw new IllegalStateException("Response has already been released."); } long now = clock.getCurrentTime(); if (mostRecentEvent < now) { mostRecentEvent = now; } while (!requestStarted && failure == null) { long waitMs = mostRecentEvent + timeoutMs - clock.getCurrentTime(); if (waitMs < 0) { failure = new AssertionError("Timeout waiting request to block."); condition.signalAll(); throw failure; } try { condition.await(waitMs, TimeUnit.MILLISECONDS); } catch (InterruptedException e) { throw UncheckedException.throwAsUncheckedException(e); } } if (failure != null) { throw failure; } } finally { lock.unlock(); } } @Override public void release() { lock.lock(); try { if (!requestStarted) { throw new IllegalStateException("Response is not blocked, should call waitUntilBlocked() first."); } released = true; condition.signalAll(); } finally { lock.unlock(); } } }
3e0bb13583802a8d7104587b022148cc56da350a
344
java
Java
msr-parent/msr-edu/src/main/java/com/msr/edu/controller/CourseDescriptionController.java
chuyangyang776/msr_admin_class11
b72c254058dd4561d84c392b9407d77f9d13c2ad
[ "Apache-2.0" ]
null
null
null
msr-parent/msr-edu/src/main/java/com/msr/edu/controller/CourseDescriptionController.java
chuyangyang776/msr_admin_class11
b72c254058dd4561d84c392b9407d77f9d13c2ad
[ "Apache-2.0" ]
2
2021-04-22T17:09:52.000Z
2021-09-20T20:59:50.000Z
msr-parent/msr-edu/src/main/java/com/msr/edu/controller/CourseDescriptionController.java
chuyangyang776/msr_admin_class11
b72c254058dd4561d84c392b9407d77f9d13c2ad
[ "Apache-2.0" ]
null
null
null
15.636364
62
0.741279
4,939
package com.msr.edu.controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; /** * <p> * 课程简介 前端控制器 * </p> * * @author tom * @since 2020-06-05 */ @RestController @RequestMapping("/edu/course-description") public class CourseDescriptionController { }
3e0bb21ec5cfa83753761fee81fc842a9da12475
1,018
java
Java
src/main/java/com/github/maybeec/lexeme/merge/attribute/AttributeMerger.java
maybeec/lexeme
5d35ba97fd0fc75de1952d787570c4a1c2bb0532
[ "Apache-2.0" ]
1
2016-05-06T13:14:23.000Z
2016-05-06T13:14:23.000Z
src/main/java/com/github/maybeec/lexeme/merge/attribute/AttributeMerger.java
maybeec/lexeme
5d35ba97fd0fc75de1952d787570c4a1c2bb0532
[ "Apache-2.0" ]
8
2016-05-17T10:53:32.000Z
2021-06-29T10:39:43.000Z
src/main/java/com/github/maybeec/lexeme/merge/attribute/AttributeMerger.java
may-bee/lexeme
5d35ba97fd0fc75de1952d787570c4a1c2bb0532
[ "Apache-2.0" ]
2
2019-08-22T12:45:15.000Z
2020-05-11T09:28:13.000Z
30.848485
104
0.681729
4,940
package com.github.maybeec.lexeme.merge.attribute; import com.github.maybeec.lexeme.ConflictHandlingType; import com.github.maybeec.lexeme.mergeschema.Attribute; /** * Merges an attribute of two xml elements * @author Steffen Holzer */ public interface AttributeMerger { /** * Merges the values of two attributes of a given name into one. * @param attribute1 * String value of the attribute of the first element * @param attribute2 * String value of the attribute of the second element * @param conflictHandling * {@link ConflictHandlingType} specifying how conflicts will be handled during the merge * process * @return String merged value */ public String merge(String attribute1, String attribute2, ConflictHandlingType conflictHandling); /** * Returns the stored Attribute object * @return Attribute object * @author sholzer (13.02.2015) */ public Attribute getAttribute(); }
3e0bb233aff114883df7743c60653a6d56b0428e
3,724
java
Java
examples/src/main/java/org/bitcoinj/examples/TxSigner.java
alfonsoegio/bitcoinj
d83461e29cb504d5bee958614a64899f34e2a021
[ "Apache-2.0" ]
null
null
null
examples/src/main/java/org/bitcoinj/examples/TxSigner.java
alfonsoegio/bitcoinj
d83461e29cb504d5bee958614a64899f34e2a021
[ "Apache-2.0" ]
null
null
null
examples/src/main/java/org/bitcoinj/examples/TxSigner.java
alfonsoegio/bitcoinj
d83461e29cb504d5bee958614a64899f34e2a021
[ "Apache-2.0" ]
null
null
null
35.132075
95
0.673738
4,941
/* * Copyright 2013 Google Inc. * Copyright 2014 Andreas Schildbach * * 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.examples; import org.bitcoinj.core.*; import org.bitcoinj.crypto.TransactionSignature; import org.bitcoinj.params.TestNet3Params; import org.bitcoinj.script.Script; import org.bitcoinj.script.ScriptBuilder; import org.bitcoinj.script.ScriptOpCodes; import javax.xml.bind.DatatypeConverter; /** * SignTx on testnet ... does not work yet */ public class TxSigner { public static void main(String[] args) throws Exception { NetworkParameters params; params = TestNet3Params.get(); // Initial data containing destination and unspent output address hashes String destinationPubKeyHash = "mrB5ZczDEMJtJ7xGXuD2tE2Qn4XX8RDRjX"; String wif = "cRvcTPJtAxsYvn7Jnxw4BnymC7VfYF1HifVMh6uf7HbhsBXfyDqM"; // Transaction containing the UTXO String originTxId = "8e213ee647d60de7bcb145cbf5f75527e892a459423b248c4ef610c2183b86b8"; // Build the ECKey from the Wallet Interchange Format (wif) string DumpedPrivateKey dpk = DumpedPrivateKey.fromBase58(null, wif); ECKey key = dpk.getKey(); String check = key.getPrivateKeyAsWiF(params); System.out.println(check); // Building addresses Address destinationAddress = Address.fromString(params, destinationPubKeyHash); // Initialize testnet transaction Transaction tx = new Transaction(params); // Add output spending the UTXO Long amount = new Long(8800000); tx.addOutput(Coin.valueOf(amount - 5000), destinationAddress); // Add some data in a second non-standard output String msg = "https://arxiv.org/abs/quant-ph/0012067"; tx.addOutput(Coin.ZERO, ScriptBuilder.createOpReturnScript(msg.getBytes())); System.out.println(key.getPublicKeyAsHex()); // Previous script ScriptBuilder redeemScriptBuilder = new ScriptBuilder(); redeemScriptBuilder.op(ScriptOpCodes.OP_DUP) .op(ScriptOpCodes.OP_HASH160) .data(key.getPubKeyHash()) .op(ScriptOpCodes.OP_EQUALVERIFY) .op(ScriptOpCodes.OP_CHECKSIG); Script redeemScript = redeemScriptBuilder.build(); // Add originTxId as input with redeem script tx.addInput(Sha256Hash.wrap(originTxId), 0, redeemScript); TransactionSignature txSignature = tx.calculateSignature( 0, key, key.getPubKey(), Transaction.SigHash.ALL, false); Script scriptSig = new ScriptBuilder() .data(txSignature.encodeToBitcoin()) .data(key.getPubKey()) .build(); assert (TransactionSignature.isEncodingCanonical(txSignature.encodeToBitcoin())); tx.getInput(0).setScriptSig(scriptSig); tx.verify(); // Obtaining the hexadecimal raw transaction (does not validate) String tx_hex = DatatypeConverter.printHexBinary(tx.bitcoinSerialize()); System.out.println(tx_hex); } }
3e0bb2c80e68476754d1ba81f6a3c0e7ff4d71b9
224
java
Java
src/test/java/aitoa/searchSpaces/bitstrings/TestBitStringSpace4.java
thomasWeise/aitoa-code
97666709e6ea4b473742cd8f032a16993c341410
[ "MIT" ]
4
2019-05-22T01:17:22.000Z
2022-03-19T21:56:19.000Z
src/test/java/aitoa/searchSpaces/bitstrings/TestBitStringSpace4.java
thomasWeise/aitoa-code
97666709e6ea4b473742cd8f032a16993c341410
[ "MIT" ]
1
2020-04-06T00:05:10.000Z
2020-04-11T12:30:26.000Z
src/test/java/aitoa/searchSpaces/bitstrings/TestBitStringSpace4.java
thomasWeise/aitoa-code
97666709e6ea4b473742cd8f032a16993c341410
[ "MIT" ]
2
2020-11-04T13:54:42.000Z
2022-02-24T09:21:37.000Z
22.4
61
0.727679
4,942
package aitoa.searchSpaces.bitstrings; /** Test the bit string space problem of length 4 */ public class TestBitStringSpace4 extends TestBitStringSpace { /** create */ public TestBitStringSpace4() { super(4); } }
3e0bb3471cce565490f73a07416634c50979bb26
414
java
Java
app/src/main/java/com/ronakmanglani/watchlist/data/MovieDatabase.java
Ronak-LM/Watchlist
fc6f8c312ebe031e4068b093e84de4ee769cd9db
[ "Apache-2.0" ]
126
2016-05-13T19:17:13.000Z
2016-07-24T21:06:34.000Z
app/src/main/java/com/ronakmanglani/watchlist/data/MovieDatabase.java
Ronak-LM/WatchList
fc6f8c312ebe031e4068b093e84de4ee769cd9db
[ "Apache-2.0" ]
7
2016-06-19T19:15:18.000Z
2016-07-25T11:00:28.000Z
app/src/main/java/com/ronakmanglani/watchlist/data/MovieDatabase.java
Ronak-LM/Watchlist
fc6f8c312ebe031e4068b093e84de4ee769cd9db
[ "Apache-2.0" ]
28
2016-05-14T04:11:43.000Z
2016-07-08T20:57:32.000Z
29.571429
78
0.777778
4,943
package com.ronakmanglani.watchlist.data; import net.simonvt.schematic.annotation.Database; import net.simonvt.schematic.annotation.Table; @Database(version = MovieDatabase.VERSION) public class MovieDatabase { public static final int VERSION = 1; @Table(MovieColumns.class) public static final String WATCHED = "watched"; @Table(MovieColumns.class) public static final String TO_SEE = "to_see"; }
3e0bb42e4e98658cd466ea366138b5b56138aff7
2,017
java
Java
algorithm/java-zuocy/class2/Problem_07_RemoveRepetition.java
wuguang/handWrite
ae97a40de4e0aafc24fe527038b211b39b2dc86e
[ "MIT" ]
null
null
null
algorithm/java-zuocy/class2/Problem_07_RemoveRepetition.java
wuguang/handWrite
ae97a40de4e0aafc24fe527038b211b39b2dc86e
[ "MIT" ]
null
null
null
algorithm/java-zuocy/class2/Problem_07_RemoveRepetition.java
wuguang/handWrite
ae97a40de4e0aafc24fe527038b211b39b2dc86e
[ "MIT" ]
null
null
null
22.164835
61
0.627169
4,944
package class2; import java.util.HashSet; public class Problem_07_RemoveRepetition { public static class Node { public int value; public Node next; public Node(int data) { this.value = data; } } public static void removeRep1(Node head) { if (head == null) { return; } HashSet<Integer> set = new HashSet<Integer>(); Node pre = head; Node cur = head.next; set.add(head.value); while (cur != null) { if (set.contains(cur.value)) { pre.next = cur.next; } else { set.add(cur.value); pre = cur; } cur = cur.next; } } public static void removeRep2(Node head) { Node cur = head; Node pre = null; Node next = null; while (cur != null) { pre = cur; next = cur.next; while (next != null) { if (cur.value == next.value) { pre.next = next.next; } else { pre = next; } next = next.next; } cur = cur.next; } } public static void printLinkedList(Node head) { System.out.print("Linked List: "); while (head != null) { System.out.print(head.value + " "); head = head.next; } System.out.println(); } public static void main(String[] args) { Node head = new Node(1); head.next = new Node(2); head.next.next = new Node(3); head.next.next.next = new Node(3); head.next.next.next.next = new Node(4); head.next.next.next.next.next = new Node(4); head.next.next.next.next.next.next = new Node(2); head.next.next.next.next.next.next.next = new Node(1); head.next.next.next.next.next.next.next.next = new Node(1); removeRep1(head); printLinkedList(head); head = new Node(1); head.next = new Node(1); head.next.next = new Node(3); head.next.next.next = new Node(3); head.next.next.next.next = new Node(4); head.next.next.next.next.next = new Node(4); head.next.next.next.next.next.next = new Node(2); head.next.next.next.next.next.next.next = new Node(1); head.next.next.next.next.next.next.next.next = new Node(1); removeRep2(head); printLinkedList(head); } }
3e0bb47bebebca940f1e055bf39e9cb3a9a32c64
21,565
java
Java
src/main/java/com/lothrazar/cyclicmagic/util/UtilEntity.java
SwadicalRag/Cyclic
5782e0f79bd4f67d52cb03659b97771a315fc83a
[ "MIT" ]
null
null
null
src/main/java/com/lothrazar/cyclicmagic/util/UtilEntity.java
SwadicalRag/Cyclic
5782e0f79bd4f67d52cb03659b97771a315fc83a
[ "MIT" ]
null
null
null
src/main/java/com/lothrazar/cyclicmagic/util/UtilEntity.java
SwadicalRag/Cyclic
5782e0f79bd4f67d52cb03659b97771a315fc83a
[ "MIT" ]
null
null
null
38.30373
160
0.684581
4,945
/******************************************************************************* * The MIT License (MIT) * * Copyright (C) 2014-2018 Sam Bassett (aka Lothrazar) * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. ******************************************************************************/ package com.lothrazar.cyclicmagic.util; import java.util.ArrayList; import java.util.List; import java.util.UUID; import com.lothrazar.cyclicmagic.ModCyclic; import com.lothrazar.cyclicmagic.data.Vector3; import com.lothrazar.cyclicmagic.net.PacketPlayerFalldamage; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.EnumCreatureType; import net.minecraft.entity.SharedMonsterAttributes; import net.minecraft.entity.ai.attributes.AttributeModifier; import net.minecraft.entity.ai.attributes.IAttributeInstance; import net.minecraft.entity.item.EntityItem; import net.minecraft.entity.item.EntityXPOrb; import net.minecraft.entity.passive.EntityVillager; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.Item; import net.minecraft.potion.PotionEffect; import net.minecraft.server.MinecraftServer; import net.minecraft.util.EnumFacing; import net.minecraft.util.ResourceLocation; import net.minecraft.util.math.AxisAlignedBB; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.MathHelper; import net.minecraft.util.math.Vec3d; import net.minecraft.world.World; import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.event.entity.living.EnderTeleportEvent; import net.minecraftforge.fml.common.FMLCommonHandler; import net.minecraftforge.fml.common.ObfuscationReflectionHelper; import net.minecraftforge.fml.common.registry.EntityRegistry; import net.minecraftforge.fml.common.registry.ForgeRegistries; public class UtilEntity { private static final double ENTITY_PULL_DIST = 0.4;//closer than this and nothing happens private static final double ENTITY_PULL_SPEED_CUTOFF = 3;//closer than this and it slows down public static final UUID HEALTH_MODIFIER_ID = UUID.fromString("60b1b9b5-dc5d-43a2-aa4e-655353070dbe"); public static final String HEALTH_MODIFIER_NAME = "Cyclic Health Modifier"; private final static float ITEMSPEEDFAR = 0.9F; private final static float ITEMSPEEDCLOSE = 0.2F; /** * * @return true if teleport was a success */ public static boolean enderTeleportEvent(EntityLivingBase player, World world, double x, double y, double z) { EnderTeleportEvent event = new EnderTeleportEvent(player, x, y, z, 0); boolean wasCancelled = MinecraftForge.EVENT_BUS.post(event); if (wasCancelled == false) { //new target? maybe, maybe not. https://github.com/PrinceOfAmber/Cyclic/issues/438 UtilEntity.teleportWallSafe(player, world, event.getTargetX(), event.getTargetY(), event.getTargetZ()); } return !wasCancelled; } /** * * @return true if teleport was a success */ public static boolean enderTeleportEvent(EntityLivingBase player, World world, BlockPos target) { return enderTeleportEvent(player, world, target.getX(), target.getY(), target.getZ()); } public static void teleportWallSafe(EntityLivingBase player, World world, double x, double y, double z) { BlockPos coords = new BlockPos(x, y, z); world.markBlockRangeForRenderUpdate(coords, coords); world.getChunk(coords).setModified(true); player.setPositionAndUpdate(x, y, z); moveEntityWallSafe(player, world); } public static void teleportWallSafe(EntityLivingBase player, World world, BlockPos coords) { teleportWallSafe(player, world, coords.getX(), coords.getY(), coords.getZ()); } public static void moveEntityWallSafe(EntityLivingBase entity, World world) { while (world.collidesWithAnyBlock(entity.getEntityBoundingBox())) { entity.setPositionAndUpdate(entity.posX, entity.posY + 1.0D, entity.posZ); } } public static void setMaxHealth(EntityLivingBase living, double max) { IAttributeInstance healthAttribute = living.getEntityAttribute(SharedMonsterAttributes.MAX_HEALTH); double amount = max - healthAttribute.getBaseValue(); AttributeModifier modifier = healthAttribute.getModifier(HEALTH_MODIFIER_ID); // Need to remove modifier to apply a new one if (modifier != null) { healthAttribute.removeModifier(modifier); } // Operation 0 is a flat increase modifier = new AttributeModifier(HEALTH_MODIFIER_ID, HEALTH_MODIFIER_NAME, amount, 0); healthAttribute.applyModifier(modifier); } public static double getMaxHealth(EntityLivingBase living) { IAttributeInstance healthAttribute = living.getEntityAttribute(SharedMonsterAttributes.MAX_HEALTH); double maxHealth = healthAttribute.getBaseValue(); AttributeModifier modifier = healthAttribute.getModifier(HEALTH_MODIFIER_ID); if (modifier != null) { maxHealth += modifier.getAmount(); } return maxHealth; } public static int incrementMaxHealth(EntityLivingBase living, int by) { int newVal = (int) getMaxHealth(living) + by; setMaxHealth(living, newVal); return newVal; } public static EnumFacing getFacing(EntityLivingBase entity) { int yaw = (int) entity.rotationYaw; if (yaw < 0) // due to the yaw running a -360 to positive 360 yaw += 360; // not sure why it's that way yaw += 22; // centers coordinates you may want to drop this line yaw %= 360; // and this one if you want a strict interpretation of the // zones int facing = yaw / 45; // 360degrees divided by 45 == 8 zones return EnumFacing.byHorizontalIndex(facing / 2); } public static double getSpeedTranslated(double speed) { return speed * 100; } public static double getJumpTranslated(double jump) { // double jump = horse.getHorseJumpStrength(); // convert from scale factor to blocks double jumpHeight = 0; double gravity = 0.98; while (jump > 0) { jumpHeight += jump; jump -= 0.08; jump *= gravity; } return jumpHeight; } /** * Launch entity in the fixed facing direction given * * @param entity * @param rotationPitch * @param power * @param facing */ public static void launchDirection(Entity entity, float power, EnumFacing facing) { double velX = 0; double velZ = 0; double velY = 0; switch (facing) { case EAST: velX = Math.abs(power); velZ = 0; break; case WEST: velX = -1 * Math.abs(power); velZ = 0; break; case NORTH: velX = 0; velZ = -1 * Math.abs(power); break; case SOUTH: velX = 0; velZ = Math.abs(power); break; case UP: case DOWN: default: break; } Entity ridingEntity = entity.getRidingEntity(); if (ridingEntity != null) { // boost power a bit, horses are heavy as F ridingEntity.motionY = 0; ridingEntity.fallDistance = 0; ridingEntity.addVelocity(velX, velY, velZ); } else { entity.motionY = 0; entity.fallDistance = 0; entity.addVelocity(velX, velY, velZ); } } /** * Launch entity in the direction it is already facing * * @param entity * @param rotationPitch * @param power */ public static void launch(Entity entity, float rotationPitch, float power) { float rotationYaw = entity.rotationYaw; launch(entity, rotationPitch, rotationYaw, power); } static final float lowEnough = 0.001F; // float LIMIT = 180F; public static void setVelocity(Entity entity, float rotationPitch, float rotationYaw, float power) { entity.motionX = 0; entity.motionY = 0; entity.motionZ = 0; double velX = -MathHelper.sin(rotationYaw / 180.0F * (float) Math.PI) * MathHelper.cos(rotationPitch / 180.0F * (float) Math.PI) * power; double velZ = MathHelper.cos(rotationYaw / 180.0F * (float) Math.PI) * MathHelper.cos(rotationPitch / 180.0F * (float) Math.PI) * power; double velY = MathHelper.sin((rotationPitch) / 180.0F * (float) Math.PI) * power; // if (velY < 0) { // velY *= -1;// make it always up never down // } if (Math.abs(velX) < lowEnough) velX = 0; if (Math.abs(velY) < lowEnough) velY = 0; if (Math.abs(velZ) < lowEnough) velZ = 0; // if(entity.getEntityWorld().isRemote){ // ModCyclic.logger.info("(angle,yaw,power) = " + rotationPitch + "," + rotationYaw + "," + power); // ModCyclic.logger.info("!setvelocity " + velX + "," + velY + "," + velZ); //// ModCyclic.logger.info("!onground " + entity.onGround); // ModCyclic.logger.info("!posY " + entity.posY); // } //setting to zero first then using add, pretty much the same as set entity.addVelocity(velX, velY, velZ); } public static void launch(Entity entity, float rotationPitch, float rotationYaw, float power) { float mountPower = (float) (power + 0.5); double velX = -MathHelper.sin(rotationYaw / 180.0F * (float) Math.PI) * MathHelper.cos(rotationPitch / 180.0F * (float) Math.PI) * power; double velZ = MathHelper.cos(rotationYaw / 180.0F * (float) Math.PI) * MathHelper.cos(rotationPitch / 180.0F * (float) Math.PI) * power; double velY = -MathHelper.sin((rotationPitch) / 180.0F * (float) Math.PI) * power; // launch the player up and forward at minimum angle // regardless of look vector if (velY < 0) { velY *= -1;// make it always up never down } Entity ridingEntity = entity.getRidingEntity(); if (ridingEntity != null) { // boost power a bit, horses are heavy as F ridingEntity.motionY = 0; ridingEntity.fallDistance = 0; ridingEntity.addVelocity(velX * mountPower, velY * mountPower, velZ * mountPower); } else { entity.motionY = 0; entity.fallDistance = 0; entity.addVelocity(velX, velY, velZ); } } public static AxisAlignedBB makeBoundingBox(BlockPos center, int hRadius, int vRadius) { //so if radius is 1, it goes 1 in each direction, and boom, 3x3 selected return new AxisAlignedBB(center).expand(hRadius, vRadius, hRadius); } public static AxisAlignedBB makeBoundingBox(double x, double y, double z, int hRadius, int vRadius) { return new AxisAlignedBB( x - hRadius, y - vRadius, z - hRadius, x + hRadius, y + vRadius, z + hRadius); } public static int moveEntityItemsInRegion(World world, BlockPos pos, int hRadius, int vRadius) { return moveEntityItemsInRegion(world, pos.getX(), pos.getY(), pos.getZ(), hRadius, vRadius, true); } public static int moveEntityItemsInRegion(World world, double x, double y, double z, int hRadius, int vRadius, boolean towardsPos) { AxisAlignedBB range = makeBoundingBox(x, y, z, hRadius, vRadius); List<Entity> all = getItemExp(world, range); return pullEntityList(x, y, z, towardsPos, all); } public static List<Entity> getItemExp(World world, AxisAlignedBB range) { List<Entity> all = new ArrayList<Entity>(); all.addAll(world.getEntitiesWithinAABB(EntityItem.class, range)); all.addAll(world.getEntitiesWithinAABB(EntityXPOrb.class, range)); return all; } public static boolean speedupEntityIfMoving(EntityLivingBase entity, float factor) { if (entity.moveForward > 0) { if (entity.getRidingEntity() != null && entity.getRidingEntity() instanceof EntityLivingBase) { speedupEntity((EntityLivingBase) entity.getRidingEntity(), factor); return true; } else { speedupEntity(entity, factor); return true; } } return false; } public static void speedupEntity(EntityLivingBase entity, float factor) { entity.motionX += MathHelper.sin(-entity.rotationYaw * 0.017453292F) * factor; entity.motionZ += MathHelper.cos(entity.rotationYaw * 0.017453292F) * factor; } public static int moveEntityLivingNonplayers(World world, double x, double y, double z, int ITEM_HRADIUS, int ITEM_VRADIUS, boolean towardsPos, float speed) { AxisAlignedBB range = UtilEntity.makeBoundingBox(x, y, z, ITEM_HRADIUS, ITEM_VRADIUS); List<EntityLivingBase> nonPlayer = getLivingHostile(world, range); return pullEntityList(x, y, z, towardsPos, nonPlayer, speed, speed); } public static List<EntityLivingBase> getLivingHostile(World world, AxisAlignedBB range) { List<EntityLivingBase> all = world.getEntitiesWithinAABB(EntityLivingBase.class, range); List<EntityLivingBase> nonPlayer = new ArrayList<EntityLivingBase>(); for (EntityLivingBase ent : all) { if (ent instanceof EntityPlayer == false && ent.isCreatureType(EnumCreatureType.MONSTER, false)) {//players are not monsters so, redundant? nonPlayer.add(ent); } } return nonPlayer; } public static int pullEntityList(double x, double y, double z, boolean towardsPos, List<? extends Entity> all) { return pullEntityList(x, y, z, towardsPos, all, ITEMSPEEDCLOSE, ITEMSPEEDFAR); } public static int pullEntityList(double x, double y, double z, boolean towardsPos, List<? extends Entity> all, float speedClose, float speedFar) { int moved = 0; double hdist, xDist, zDist; float speed; int direction = (towardsPos) ? 1 : -1;//negative to flip the vector and push it away for (Entity entity : all) { if (entity == null) { continue; } //being paranoid if (entity instanceof EntityPlayer && ((EntityPlayer) entity).isSneaking()) { continue;//sneak avoid feature } xDist = Math.abs(x - entity.getPosition().getX()); zDist = Math.abs(z - entity.getPosition().getZ()); hdist = Math.sqrt(xDist * xDist + zDist * zDist); if (hdist > ENTITY_PULL_DIST) { speed = (hdist > ENTITY_PULL_SPEED_CUTOFF) ? speedFar : speedClose; // if (lockHorizontal) { // entity.motionY = -1 * direction * speed; // } // else { Vector3.setEntityMotionFromVector(entity, x, y, z, direction * speed); // } moved++; } //else its basically on it, no point } return moved; } public static void addOrMergePotionEffect(EntityLivingBase player, PotionEffect newp) { // this could be in a utilPotion class i guess... if (player.isPotionActive(newp.getPotion())) { // do not use built in 'combine' function, just add up duration PotionEffect p = player.getActivePotionEffect(newp.getPotion()); int ampMax = Math.max(p.getAmplifier(), newp.getAmplifier()); int dur = newp.getDuration() + p.getDuration(); player.addPotionEffect(new PotionEffect(newp.getPotion(), dur, ampMax)); } else { player.addPotionEffect(newp); } } /** * Force horizontal centering, so move from 2.9, 6.2 => 2.5,6.5 * * @param entity * @param pos */ public static void centerEntityHoriz(Entity entity, BlockPos pos) { float fixedX = pos.getX() + 0.5F;//((float) (MathHelper.floor_double(entity.posX) + MathHelper.ceiling_double_int(entity.posX)) )/ 2; float fixedZ = pos.getZ() + 0.5F;//((float) (MathHelper.floor_double(entity.posX) + MathHelper.ceiling_double_int(entity.posX)) )/ 2; entity.setPosition(fixedX, entity.posY, fixedZ); } private static final int TICKS_FALLDIST_SYNC = 22;//tick every so often public static void tryMakeEntityClimb(World worldIn, EntityLivingBase entity, double climbSpeed) { if (entity.isSneaking()) { entity.motionY = 0.0D; } else if (entity.moveForward > 0.0F && entity.motionY < climbSpeed) { entity.motionY = climbSpeed; } if (worldIn.isRemote && //setting fall distance on clientside wont work entity instanceof EntityPlayer && entity.ticksExisted % TICKS_FALLDIST_SYNC == 0) { ModCyclic.network.sendToServer(new PacketPlayerFalldamage()); } } public static List<EntityVillager> getVillagers(World world, BlockPos p, int r) { BlockPos start = p.add(-r, -r, -r); BlockPos end = p.add(r, r, r); return world.getEntitiesWithinAABB(EntityVillager.class, new AxisAlignedBB(start, end)); } public static EntityLivingBase getClosestEntity(World world, EntityPlayer player, List<? extends EntityLivingBase> list) { EntityLivingBase closest = null; double minDist = 999999; double dist, xDistance, zDistance; for (EntityLivingBase ent : list) { xDistance = Math.abs(player.posX - ent.posX); zDistance = Math.abs(player.posZ - ent.posZ); dist = Math.sqrt(xDistance * xDistance + zDistance * zDistance); if (dist < minDist) { minDist = dist; closest = ent; } } return closest; } public static EntityVillager getVillager(World world, int x, int y, int z) { List<EntityVillager> all = world.getEntitiesWithinAABB(EntityVillager.class, new AxisAlignedBB(new BlockPos(x, y, z))); if (all.size() == 0) return null; else return all.get(0); } @SuppressWarnings("deprecation") public static int getVillagerCareer(EntityVillager merchant) { return ObfuscationReflectionHelper.getPrivateValue(EntityVillager.class, merchant, "careerId", "field_175563_bv"); } @SuppressWarnings("deprecation") public static void setVillagerCareer(EntityVillager merchant, int c) { ObfuscationReflectionHelper.setPrivateValue(EntityVillager.class, merchant, c, "careerId", "field_175563_bv"); } public static String getCareerName(EntityVillager merchant) { return merchant.getDisplayName().getFormattedText();//getProfessionForge().getCareer(maybeC).getName(); } public static float yawDegreesBetweenPoints(double posX, double posY, double posZ, double posX2, double posY2, double posZ2) { float f = (float) ((180.0f * Math.atan2(posX2 - posX, posZ2 - posZ)) / (float) Math.PI); return f; } public static float pitchDegreesBetweenPoints(double posX, double posY, double posZ, double posX2, double posY2, double posZ2) { return (float) Math.toDegrees(Math.atan2(posY2 - posY, Math.sqrt((posX2 - posX) * (posX2 - posX) + (posZ2 - posZ) * (posZ2 - posZ)))); } public static Vec3d lookVector(float rotYaw, float rotPitch) { return new Vec3d( Math.sin(rotYaw) * Math.cos(rotPitch), Math.sin(rotPitch), Math.cos(rotYaw) * Math.cos(rotPitch)); } public static float getYawFromFacing(EnumFacing currentFacing) { switch (currentFacing) { case DOWN: case UP: case SOUTH: default: return 0; case EAST: return 270F; case NORTH: return 180F; case WEST: return 90F; } } public static void setEntityFacing(EntityLivingBase entity, EnumFacing currentFacing) { float yaw = 0; switch (currentFacing) { case EAST: yaw = 270F; break; case NORTH: yaw = 180F; break; case WEST: yaw = 90F; break; case DOWN: case UP: case SOUTH: default: yaw = 0; } entity.rotationYaw = yaw; } /** * used by bounce potion and vector plate * * @param entity * @param verticalMomentumFactor */ public static void dragEntityMomentum(EntityLivingBase entity, double verticalMomentumFactor) { entity.motionX = entity.motionX / verticalMomentumFactor; entity.motionZ = entity.motionZ / verticalMomentumFactor; } public static ResourceLocation getResourceLocation(Entity entityHit) { try { return ForgeRegistries.ENTITIES.getKey(EntityRegistry.getEntry(entityHit.getClass())); } catch (Exception e) { return null; } } private static void setCooldownItemInternal(EntityPlayer player, Item item, int cooldown) { player.getCooldownTracker().setCooldown(item, cooldown); } /** * Threadsafe * * https://github.com/SpongePowered/SpongeForge/issues/2301 * * https://github.com/Lothrazar/Cyclic/issues/1065 * * @param player * @param item * @param cooldown */ public static void setCooldownItem(EntityPlayer player, Item item, int cooldown) { if (player.world.isRemote) { //client setCooldownItemInternal(player, item, cooldown); } else { //server final MinecraftServer s = FMLCommonHandler.instance().getMinecraftServerInstance(); s.addScheduledTask(new Runnable() { @Override public void run() { setCooldownItemInternal(player, item, cooldown); } }); } } }
3e0bb5082a34d2f3f455777f3226bbfb2ec5a3d5
703
java
Java
base/src/main/java/org/timux/ports/PortsCommand.java
trohlfs/ports
a93b0aadde13deccb5ead2b32d45de4de4285209
[ "Apache-2.0" ]
2
2019-03-06T20:15:10.000Z
2019-12-19T17:11:14.000Z
base/src/main/java/org/timux/ports/PortsCommand.java
trohlfs/ports
a93b0aadde13deccb5ead2b32d45de4de4285209
[ "Apache-2.0" ]
1
2021-04-20T07:39:45.000Z
2021-04-20T07:39:45.000Z
base/src/main/java/org/timux/ports/PortsCommand.java
trohlfs/ports
a93b0aadde13deccb5ead2b32d45de4de4285209
[ "Apache-2.0" ]
null
null
null
29.291667
75
0.738265
4,946
/* * Copyright 2018-2020 Tim Rohlfs * * 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.timux.ports; @FunctionalInterface public interface PortsCommand { void execute(); }
3e0bb68cc6ab3ec5ac3b4df5edc06ca928e6e093
1,005
java
Java
src/generated/java/fi/riista/integration/common/export/observations/COBS_ObservedGameState.java
suomenriistakeskus/oma-riista-web
4b641df6b80384ed36bc3e284f104b98f8a84afd
[ "MIT" ]
14
2017-01-11T23:22:36.000Z
2022-02-09T06:49:46.000Z
src/generated/java/fi/riista/integration/common/export/observations/COBS_ObservedGameState.java
suomenriistakeskus/oma-riista-web
4b641df6b80384ed36bc3e284f104b98f8a84afd
[ "MIT" ]
4
2018-04-16T13:00:49.000Z
2021-02-15T11:56:06.000Z
src/generated/java/fi/riista/integration/common/export/observations/COBS_ObservedGameState.java
suomenriistakeskus/oma-riista-web
4b641df6b80384ed36bc3e284f104b98f8a84afd
[ "MIT" ]
4
2017-01-20T10:34:24.000Z
2021-02-09T14:41:46.000Z
22.333333
95
0.658706
4,947
package fi.riista.integration.common.export.observations; import javax.xml.bind.annotation.XmlEnum; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for observedGameState. * * <p>The following schema fragment specifies the expected content contained within this class. * <p> * <pre> * &lt;simpleType name="observedGameState"&gt; * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}token"&gt; * &lt;enumeration value="HEALTHY"/&gt; * &lt;enumeration value="ILL"/&gt; * &lt;enumeration value="WOUNDED"/&gt; * &lt;enumeration value="CARCASS"/&gt; * &lt;enumeration value="DEAD"/&gt; * &lt;/restriction&gt; * &lt;/simpleType&gt; * </pre> * */ @XmlType(name = "observedGameState") @XmlEnum public enum COBS_ObservedGameState { HEALTHY, ILL, WOUNDED, CARCASS, DEAD; public String value() { return name(); } public static COBS_ObservedGameState fromValue(String v) { return valueOf(v); } }
3e0bb6c89d90b4c0a217c7ee3d0aceb5c69ce302
1,717
java
Java
spring-boot-demo-120-ehcache-cache/src/main/java/com/funsonli/springbootdemo120ehcachecache/controller/StudentController.java
funsonli/spring-boot-demo
eba67168d38bb2444280034a6e90c17f876786b3
[ "MIT" ]
94
2019-10-23T03:21:56.000Z
2022-03-16T03:52:19.000Z
spring-boot-demo-120-ehcache-cache/src/main/java/com/funsonli/springbootdemo120ehcachecache/controller/StudentController.java
Mithzyl/spring-boot-demo
eba67168d38bb2444280034a6e90c17f876786b3
[ "MIT" ]
null
null
null
spring-boot-demo-120-ehcache-cache/src/main/java/com/funsonli/springbootdemo120ehcachecache/controller/StudentController.java
Mithzyl/spring-boot-demo
eba67168d38bb2444280034a6e90c17f876786b3
[ "MIT" ]
29
2019-11-15T01:23:17.000Z
2022-03-16T03:51:06.000Z
27.693548
105
0.710542
4,948
package com.funsonli.springbootdemo120ehcachecache.controller; import com.funsonli.springbootdemo120ehcachecache.entity.Student; import com.funsonli.springbootdemo120ehcachecache.service.StudentService; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import javax.servlet.http.HttpServletRequest; import java.util.Optional; /** * Student Controller * * @author Funson * @date 2019/10/12 */ @Slf4j @RestController @RequestMapping("/student") public class StudentController { @Autowired StudentService studentService; @GetMapping({"", "/", "index"}) public String index() { return studentService.index().toString(); } @GetMapping("/add/{name}/{age}") public String add(HttpServletRequest request, @PathVariable String name, @PathVariable Integer age) { Student model = new Student(); model.setName(name); model.setAge(age); model = studentService.save(model); return model.toString(); } @GetMapping("/view/{id}") public String view(@PathVariable String id) { Optional<Student> optionalStudent = studentService.findById(id); if (optionalStudent.isPresent()) { return optionalStudent.get().toString(); } return "null"; } @GetMapping("/delete/{id}") public String delete(@PathVariable String id) { studentService.deleteById(id); return "ok"; } }
3e0bb6f90fa5631d924ccb9a20caccc095c03730
4,444
java
Java
webanno-api-dao/src/main/java/de/tudarmstadt/ukp/clarin/webanno/api/dao/initializers/DependencyLayerInitializer.java
thomaskrause/webanno
81d6613ac578eba87934e20bd2f8ab0794f18de3
[ "Apache-2.0" ]
null
null
null
webanno-api-dao/src/main/java/de/tudarmstadt/ukp/clarin/webanno/api/dao/initializers/DependencyLayerInitializer.java
thomaskrause/webanno
81d6613ac578eba87934e20bd2f8ab0794f18de3
[ "Apache-2.0" ]
null
null
null
webanno-api-dao/src/main/java/de/tudarmstadt/ukp/clarin/webanno/api/dao/initializers/DependencyLayerInitializer.java
thomaskrause/webanno
81d6613ac578eba87934e20bd2f8ab0794f18de3
[ "Apache-2.0" ]
null
null
null
43.145631
97
0.730873
4,949
/* * Copyright 2018 * Ubiquitous Knowledge Processing (UKP) Lab and FG Language Technology * Technische Universität Darmstadt * * 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.tudarmstadt.ukp.clarin.webanno.api.dao.initializers; import static de.tudarmstadt.ukp.clarin.webanno.api.WebAnnoConst.RELATION_TYPE; import static de.tudarmstadt.ukp.clarin.webanno.model.AnchoringMode.SINGLE_TOKEN; import static de.tudarmstadt.ukp.clarin.webanno.model.OverlapMode.OVERLAP_ONLY; import static java.util.Arrays.asList; import java.io.IOException; import java.util.List; import org.apache.uima.cas.CAS; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.io.ClassPathResource; import org.springframework.stereotype.Component; import de.tudarmstadt.ukp.clarin.webanno.api.AnnotationSchemaService; import de.tudarmstadt.ukp.clarin.webanno.api.dao.JsonImportUtil; import de.tudarmstadt.ukp.clarin.webanno.model.AnnotationFeature; import de.tudarmstadt.ukp.clarin.webanno.model.AnnotationLayer; import de.tudarmstadt.ukp.clarin.webanno.model.Project; import de.tudarmstadt.ukp.clarin.webanno.model.TagSet; import de.tudarmstadt.ukp.dkpro.core.api.segmentation.type.Token; import de.tudarmstadt.ukp.dkpro.core.api.syntax.type.dependency.Dependency; import de.tudarmstadt.ukp.dkpro.core.api.syntax.type.dependency.DependencyFlavor; @Component public class DependencyLayerInitializer implements LayerInitializer { private final AnnotationSchemaService annotationSchemaService; @Autowired public DependencyLayerInitializer(AnnotationSchemaService aAnnotationSchemaService) { annotationSchemaService = aAnnotationSchemaService; } @Override public List<Class<? extends ProjectInitializer>> getDependencies() { return asList( // Because locks to token boundaries TokenLayerInitializer.class, // Because attaches to POS annotations in the UI PartOfSpeechLayerInitializer.class); } @Override public void configure(Project aProject) throws IOException { TagSet depTagSet = JsonImportUtil.importTagSetFromJson(aProject, new ClassPathResource("/tagsets/mul-dep-ud2.json").getInputStream(), annotationSchemaService); // Dependency Layer AnnotationLayer depLayer = new AnnotationLayer(Dependency.class.getName(), "Dependency", RELATION_TYPE, aProject, true, SINGLE_TOKEN, OVERLAP_ONLY); AnnotationLayer tokenLayer = annotationSchemaService.findLayer(aProject, Token.class.getName()); List<AnnotationFeature> tokenFeatures = annotationSchemaService .listAnnotationFeature(tokenLayer); AnnotationFeature tokenPosFeature = null; for (AnnotationFeature feature : tokenFeatures) { if (feature.getName().equals("pos")) { tokenPosFeature = feature; break; } } depLayer.setAttachType(tokenLayer); depLayer.setAttachFeature(tokenPosFeature); annotationSchemaService.createLayer(depLayer); annotationSchemaService .createFeature(new AnnotationFeature(aProject, depLayer, "DependencyType", "Relation", CAS.TYPE_NAME_STRING, "Dependency relation", depTagSet)); String[] flavors = { DependencyFlavor.BASIC, DependencyFlavor.ENHANCED }; String[] flavorDesc = { DependencyFlavor.BASIC, DependencyFlavor.ENHANCED }; TagSet flavorsTagset = annotationSchemaService.createTagSet("Dependency flavors", "Dependency flavors", "mul", flavors, flavorDesc, aProject); annotationSchemaService.createFeature(new AnnotationFeature(aProject, depLayer, "flavor", "Flavor", CAS.TYPE_NAME_STRING, "Dependency relation", flavorsTagset)); } }
3e0bb7c0aa13a4db6e16033acb40fc6ac1173b88
442
java
Java
core/src/main/java/com/liyangbin/cartrofit/flow/FlowTimer.java
li-yangbin/Cartrofit
599ccfa2fd64f1860d94102e79efb5a05d257c86
[ "Apache-2.0" ]
null
null
null
core/src/main/java/com/liyangbin/cartrofit/flow/FlowTimer.java
li-yangbin/Cartrofit
599ccfa2fd64f1860d94102e79efb5a05d257c86
[ "Apache-2.0" ]
null
null
null
core/src/main/java/com/liyangbin/cartrofit/flow/FlowTimer.java
li-yangbin/Cartrofit
599ccfa2fd64f1860d94102e79efb5a05d257c86
[ "Apache-2.0" ]
null
null
null
22.1
78
0.687783
4,950
package com.liyangbin.cartrofit.flow; import java.util.Timer; import java.util.TimerTask; class FlowTimer { private static final Timer TIMER = new Timer("flow-timer"); FlowTimer() { } static void schedule(TimerTask task, long delay) { TIMER.schedule(task, delay); } static void scheduleAtFixedRate(TimerTask task, long delay, long period) { TIMER.scheduleAtFixedRate(task, delay, period); } }
3e0bb868c936528ca9aadfb5e4b2c1d86e55c3f3
2,380
java
Java
app/src/main/java/com/kidozh/discuzhub/viewModels/ViewHistoryViewModel.java
qzznbbs/DiscuzHub
83f3ae0850cc6ac37eeb040d47196cc7532fb454
[ "MIT" ]
null
null
null
app/src/main/java/com/kidozh/discuzhub/viewModels/ViewHistoryViewModel.java
qzznbbs/DiscuzHub
83f3ae0850cc6ac37eeb040d47196cc7532fb454
[ "MIT" ]
null
null
null
app/src/main/java/com/kidozh/discuzhub/viewModels/ViewHistoryViewModel.java
qzznbbs/DiscuzHub
83f3ae0850cc6ac37eeb040d47196cc7532fb454
[ "MIT" ]
null
null
null
37.1875
160
0.748739
4,951
package com.kidozh.discuzhub.viewModels; import android.app.Application; import android.content.Context; import androidx.annotation.NonNull; import androidx.lifecycle.AndroidViewModel; import androidx.lifecycle.LifecycleOwner; import androidx.lifecycle.LiveData; import androidx.lifecycle.ViewModel; import androidx.paging.DataSource; import androidx.paging.LivePagedListBuilder; import androidx.paging.PagedList; import com.kidozh.discuzhub.daos.ViewHistoryDao; import com.kidozh.discuzhub.database.ViewHistoryDatabase; import com.kidozh.discuzhub.entities.ViewHistory; import com.kidozh.discuzhub.entities.bbsInformation; public class ViewHistoryViewModel extends AndroidViewModel { public LiveData<PagedList<ViewHistory>> pagedListLiveData; private ViewHistoryDao viewHistoryDao; PagedList.Config myPagingConfig = new PagedList.Config.Builder() .setEnablePlaceholders(true) .setPageSize(10) .build(); private bbsInformation bbsInfo; public ViewHistoryViewModel(Application application){ super(application); viewHistoryDao = ViewHistoryDatabase.getInstance(application).getDao(); pagedListLiveData = new LivePagedListBuilder<>(viewHistoryDao.getViewHistoryPageList(),myPagingConfig).build(); } public void setBBSInfo(bbsInformation bbsInfo){ this.bbsInfo = bbsInfo; pagedListLiveData = new LivePagedListBuilder<>(viewHistoryDao.getViewHistoryPageListByBBSId(bbsInfo.getId()),myPagingConfig).build(); } public void setSearchText(bbsInformation bbsInfo, String text){ this.bbsInfo = bbsInfo; pagedListLiveData = new LivePagedListBuilder<>(viewHistoryDao.getViewHistoryPageListByBBSIdWithSearchText(bbsInfo.getId(),text),myPagingConfig).build(); } // public ViewHistoryViewModel(ViewHistoryDatabase viewHistoryDatabase){ // DataSource.Factory<Integer,ViewHistory> factory = // viewHistoryDatabase.getDao().getViewHistoryPageList(); // PagedList.Config myPagingConfig = new PagedList.Config.Builder() // .setEnablePlaceholders(true) // .build(); // pagedListLiveData = new LivePagedListBuilder<>(factory,myPagingConfig) // .build(); // } public LiveData<PagedList<ViewHistory>> getPagedListLiveData() { return pagedListLiveData; } }
3e0bb9267fc08d9e4a0a5bec22a7a4216c71b81d
3,182
java
Java
src/main/java/org/datanucleus/exceptions/NucleusCanRetryException.java
tear-gas/datanucleus-core
ffc9561ab2ec318d39f8ecd099b66fededc5c6f8
[ "Apache-2.0" ]
103
2015-03-01T01:13:29.000Z
2022-03-17T16:10:54.000Z
src/main/java/org/datanucleus/exceptions/NucleusCanRetryException.java
tear-gas/datanucleus-core
ffc9561ab2ec318d39f8ecd099b66fededc5c6f8
[ "Apache-2.0" ]
412
2016-02-03T07:20:32.000Z
2022-03-31T09:41:04.000Z
src/main/java/org/datanucleus/exceptions/NucleusCanRetryException.java
tear-gas/datanucleus-core
ffc9561ab2ec318d39f8ecd099b66fededc5c6f8
[ "Apache-2.0" ]
69
2015-02-07T01:19:59.000Z
2022-02-01T19:19:10.000Z
32.804124
104
0.62665
4,952
/********************************************************************** Copyright (c) 2011 Andy Jefferson and others. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. Contributors: ... **********************************************************************/ package org.datanucleus.exceptions; /** * Exception thrown when a retriable error occurs. */ public class NucleusCanRetryException extends NucleusException { private static final long serialVersionUID = 2772116140793944515L; /** * Constructs a new exception without a detail message. */ public NucleusCanRetryException() { super(); } /** * Constructs a new exception with the specified detail message. * @param msg the detail message. */ public NucleusCanRetryException(String msg) { super(msg); } /** * Constructs a new exception with the specified detail message and nested <code>Throwable</code>s. * @param msg the detail message. * @param nested the nested <code>Throwable[]</code>. */ public NucleusCanRetryException(String msg, Throwable[] nested) { super(msg, nested); } /** * Constructs a new exception with the specified detail message and nested <code>Throwable</code>. * @param msg the detail message. * @param nested the nested <code>Throwable</code>. */ public NucleusCanRetryException(String msg, Throwable nested) { super(msg, nested); } /** * Constructs a new exception with the specified detail message and failed object. * @param msg the detail message. * @param failed the failed object. */ public NucleusCanRetryException(String msg, Object failed) { super(msg, failed); } /** * Constructs a new exception with the specified detail * message, nested <code>Throwable</code>s, and failed object. * @param msg the detail message. * @param nested the nested <code>Throwable[]</code>. * @param failed the failed object. */ public NucleusCanRetryException(String msg, Throwable[] nested, Object failed) { super(msg, nested, failed); } /** * Constructs a new exception with the specified detail message, nested <code>Throwable</code>, * and failed object. * @param msg the detail message. * @param nested the nested <code>Throwable</code>. * @param failed the failed object. */ public NucleusCanRetryException(String msg, Throwable nested, Object failed) { super(msg, nested, failed); } }
3e0bba0905f2a8db6df8581ad8327856fba26402
1,948
java
Java
app/src/main/java/com/thedeveloperworldisyours/hellorxjava/simple/subjects/SubjectsFragment.java
CabezasGonzalezJavier/HelloRxJavaRetrolambda
b7d88b82d08e87d824fa68c2dfaa8d8a7cdb3e40
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/thedeveloperworldisyours/hellorxjava/simple/subjects/SubjectsFragment.java
CabezasGonzalezJavier/HelloRxJavaRetrolambda
b7d88b82d08e87d824fa68c2dfaa8d8a7cdb3e40
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/thedeveloperworldisyours/hellorxjava/simple/subjects/SubjectsFragment.java
CabezasGonzalezJavier/HelloRxJavaRetrolambda
b7d88b82d08e87d824fa68c2dfaa8d8a7cdb3e40
[ "Apache-2.0" ]
null
null
null
25.973333
80
0.702772
4,953
package com.thedeveloperworldisyours.hellorxjava.simple.subjects; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.thedeveloperworldisyours.hellorxjava.R; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.OnClick; public class SubjectsFragment extends Fragment implements SubjectsContract.View{ @BindView(R.id.subjects_frag_counter_display) public TextView mCounterDisplay; private SubjectsContract.Presenter mPresenter; public SubjectsFragment() { // Required empty public constructor } public static SubjectsFragment newInstance() { SubjectsFragment fragment = new SubjectsFragment(); return fragment; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment View view = inflater.inflate(R.layout.subjects_frag, container, false); ButterKnife.bind(this, view); mCounterDisplay.setText(String.valueOf(0)); return view; } @OnClick(R.id.subjects_frag_increment_button) public void configureIncrementButton() { mPresenter.onIncrementButtonClick(); } @Override public void setInfo(String info) { mCounterDisplay.setText(info); } @Override public void setPresenter(SubjectsContract.Presenter presenter) { mPresenter = presenter; } @Override public void onResume() { super.onResume(); mPresenter.subscribe(); } @Override public void onPause() { super.onPause(); mPresenter.unsubscribe(); } }
3e0bba880f4362fd9ce175977a745a4d1282eb49
1,945
java
Java
library/library/src/main/java/apincer/android/dialog/UtilsLibrary.java
thawee/musicmate
fb2b150e7c9b06567238ceb9c66101c71b781d11
[ "Apache-2.0" ]
null
null
null
library/library/src/main/java/apincer/android/dialog/UtilsLibrary.java
thawee/musicmate
fb2b150e7c9b06567238ceb9c66101c71b781d11
[ "Apache-2.0" ]
null
null
null
library/library/src/main/java/apincer/android/dialog/UtilsLibrary.java
thawee/musicmate
fb2b150e7c9b06567238ceb9c66101c71b781d11
[ "Apache-2.0" ]
null
null
null
39.693878
117
0.742931
4,954
package apincer.android.dialog; import android.annotation.TargetApi; import android.content.Context; import android.content.res.ColorStateList; import android.graphics.Color; import android.graphics.drawable.Drawable; import android.graphics.drawable.GradientDrawable; import android.graphics.drawable.RippleDrawable; import android.os.Build; import android.util.TypedValue; import androidx.annotation.NonNull; import apincer.android.library.R; public class UtilsLibrary { static int dpToPixels(Context context, int dp) { final float scale = context.getResources().getDisplayMetrics().density; return (int) (dp * scale + 0.5f); } static Drawable createButtonBackgroundDrawable(@NonNull Context context, int fillColor) { int buttonCornerRadius = dpToPixels(context, 2); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { TypedValue v = new TypedValue(); boolean hasAttribute = context.getTheme().resolveAttribute(R.attr.colorControlHighlight, v, true); int rippleColor = hasAttribute ? v.data : Color.parseColor("#88CCCCCC"); return createButtonBackgroundDrawableLollipop(fillColor, rippleColor, buttonCornerRadius); } return createButtonBackgroundDrawableBase(fillColor, buttonCornerRadius); } @TargetApi(Build.VERSION_CODES.LOLLIPOP) private static Drawable createButtonBackgroundDrawableLollipop(int fillColor, int rippleColor,int cornerRadius) { Drawable d = createButtonBackgroundDrawableBase(fillColor, cornerRadius); return new RippleDrawable(ColorStateList.valueOf(rippleColor), d, null); } private static Drawable createButtonBackgroundDrawableBase(int color, int cornerRadius) { GradientDrawable d = new GradientDrawable(); d.setShape(GradientDrawable.RECTANGLE); d.setCornerRadius(cornerRadius); d.setColor(color); return d; } }
3e0bbb45349cd5358e1f7f7cb52fd6c4d8234255
1,761
java
Java
src/main/java/org/apache/commons/compress/harmony/unpack200/bytecode/CPMethod.java
cactiphonics/commons-compress
4246b887ba88dc0b2bc09e92c63fff97381b4a12
[ "Apache-2.0" ]
240
2015-01-06T19:14:44.000Z
2022-03-03T03:11:26.000Z
src/main/java/org/apache/commons/compress/harmony/unpack200/bytecode/CPMethod.java
cactiphonics/commons-compress
4246b887ba88dc0b2bc09e92c63fff97381b4a12
[ "Apache-2.0" ]
214
2015-10-27T18:48:23.000Z
2022-03-24T07:28:33.000Z
src/main/java/org/apache/commons/compress/harmony/unpack200/bytecode/CPMethod.java
cactiphonics/commons-compress
4246b887ba88dc0b2bc09e92c63fff97381b4a12
[ "Apache-2.0" ]
260
2015-01-29T23:11:07.000Z
2022-03-16T10:39:50.000Z
31.446429
106
0.679727
4,955
/* * 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.commons.compress.harmony.unpack200.bytecode; import java.util.List; /** * Method constant pool entry. */ public class CPMethod extends CPMember { public CPMethod(final CPUTF8 name, final CPUTF8 descriptor, final long flags, final List attributes) { super(name, descriptor, flags, attributes); } @Override public String toString() { return "Method: " + name + "(" + descriptor + ")"; } private boolean hashcodeComputed; private int cachedHashCode; private void generateHashCode() { hashcodeComputed = true; final int PRIME = 31; int result = 1; result = PRIME * result + name.hashCode(); result = PRIME * result + descriptor.hashCode(); cachedHashCode = result; } @Override public int hashCode() { if (!hashcodeComputed) { generateHashCode(); } return cachedHashCode; } }
3e0bbbbd65475819386237673593c9807009179c
5,168
java
Java
plugins/eCommerce/src/main/java/com/skytala/eCommerce/domain/product/relations/product/control/geo/ProductGeoController.java
ArcticReal/eCommerce
ea4c82442acdc9e663571e2d07e1f1ddc844f135
[ "Apache-2.0" ]
1
2020-09-28T08:23:11.000Z
2020-09-28T08:23:11.000Z
plugins/eCommerce/src/main/java/com/skytala/eCommerce/domain/product/relations/product/control/geo/ProductGeoController.java
ArcticReal/eCommerce
ea4c82442acdc9e663571e2d07e1f1ddc844f135
[ "Apache-2.0" ]
null
null
null
plugins/eCommerce/src/main/java/com/skytala/eCommerce/domain/product/relations/product/control/geo/ProductGeoController.java
ArcticReal/eCommerce
ea4c82442acdc9e663571e2d07e1f1ddc844f135
[ "Apache-2.0" ]
null
null
null
34.684564
147
0.772252
4,956
package com.skytala.eCommerce.domain.product.relations.product.control.geo; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import javax.servlet.http.HttpServletRequest; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import com.google.common.base.Splitter; import com.skytala.eCommerce.domain.product.relations.product.command.geo.AddProductGeo; import com.skytala.eCommerce.domain.product.relations.product.command.geo.DeleteProductGeo; import com.skytala.eCommerce.domain.product.relations.product.command.geo.UpdateProductGeo; import com.skytala.eCommerce.domain.product.relations.product.event.geo.ProductGeoAdded; import com.skytala.eCommerce.domain.product.relations.product.event.geo.ProductGeoDeleted; import com.skytala.eCommerce.domain.product.relations.product.event.geo.ProductGeoFound; import com.skytala.eCommerce.domain.product.relations.product.event.geo.ProductGeoUpdated; import com.skytala.eCommerce.domain.product.relations.product.mapper.geo.ProductGeoMapper; import com.skytala.eCommerce.domain.product.relations.product.model.geo.ProductGeo; import com.skytala.eCommerce.domain.product.relations.product.query.geo.FindProductGeosBy; import com.skytala.eCommerce.framework.exceptions.RecordNotFoundException; import com.skytala.eCommerce.framework.pubsub.Scheduler; import static com.skytala.eCommerce.framework.pubsub.ResponseUtil.*; @RestController @RequestMapping("/product/product/productGeos") public class ProductGeoController { private static Map<String, RequestMethod> validRequests = new HashMap<>(); public ProductGeoController() { validRequests.put("find", RequestMethod.GET); validRequests.put("add", RequestMethod.POST); validRequests.put("update", RequestMethod.PUT); validRequests.put("removeById", RequestMethod.DELETE); } /** * * @param allRequestParams * all params by which you want to find a ProductGeo * @return a List with the ProductGeos * @throws Exception */ @GetMapping("/find") public ResponseEntity<List<ProductGeo>> findProductGeosBy(@RequestParam(required = false) Map<String, String> allRequestParams) throws Exception { FindProductGeosBy query = new FindProductGeosBy(allRequestParams); if (allRequestParams == null) { query.setFilter(new HashMap<>()); } List<ProductGeo> productGeos =((ProductGeoFound) Scheduler.execute(query).data()).getProductGeos(); return ResponseEntity.ok().body(productGeos); } /** * creates a new ProductGeo entry in the ofbiz database * * @param productGeoToBeAdded * the ProductGeo thats to be added * @return true on success; false on fail */ @RequestMapping(method = RequestMethod.POST, value = "/add", consumes = MediaType.APPLICATION_JSON_UTF8_VALUE) public ResponseEntity<ProductGeo> createProductGeo(@RequestBody ProductGeo productGeoToBeAdded) throws Exception { AddProductGeo command = new AddProductGeo(productGeoToBeAdded); ProductGeo productGeo = ((ProductGeoAdded) Scheduler.execute(command).data()).getAddedProductGeo(); if (productGeo != null) return successful(productGeo); else return conflict(null); } /** * Updates the ProductGeo with the specific Id * * @param productGeoToBeUpdated * the ProductGeo thats to be updated * @return true on success, false on fail * @throws Exception */ @RequestMapping(method = RequestMethod.PUT, value = "/{nullVal}", consumes = MediaType.APPLICATION_JSON_UTF8_VALUE) public ResponseEntity<String> updateProductGeo(@RequestBody ProductGeo productGeoToBeUpdated, @PathVariable String nullVal) throws Exception { // productGeoToBeUpdated.setnull(null); UpdateProductGeo command = new UpdateProductGeo(productGeoToBeUpdated); try { if(((ProductGeoUpdated) Scheduler.execute(command).data()).isSuccess()) return noContent(); } catch (RecordNotFoundException e) { return notFound(); } return conflict(); } @GetMapping("/{productGeoId}") public ResponseEntity<ProductGeo> findById(@PathVariable String productGeoId) throws Exception { HashMap<String, String> requestParams = new HashMap<String, String>(); requestParams.put("productGeoId", productGeoId); try { List<ProductGeo> foundProductGeo = findProductGeosBy(requestParams).getBody(); if(foundProductGeo.size()==1){ return successful(foundProductGeo.get(0)); }else{ return notFound(); } } catch (RecordNotFoundException e) { return notFound(); } } @DeleteMapping("/{productGeoId}") public ResponseEntity<String> deleteProductGeoByIdUpdated(@PathVariable String productGeoId) throws Exception { DeleteProductGeo command = new DeleteProductGeo(productGeoId); try { if (((ProductGeoDeleted) Scheduler.execute(command).data()).isSuccess()) return noContent(); } catch (RecordNotFoundException e) { return notFound(); } return conflict(); } }
3e0bbc1e7875c67000e9e3c97b9b4e5670cd37fc
747
java
Java
ecmall-member/src/main/java/com/immor/ecmall/member/entity/MemberCollectSubjectEntity.java
xImmor/ECMall
d2545e4b5ca95f4fea71649bf44ce3708ea837f5
[ "MIT" ]
1
2021-01-06T03:30:28.000Z
2021-01-06T03:30:28.000Z
ecmall-member/src/main/java/com/immor/ecmall/member/entity/MemberCollectSubjectEntity.java
xImmor/ECMall
d2545e4b5ca95f4fea71649bf44ce3708ea837f5
[ "MIT" ]
null
null
null
ecmall-member/src/main/java/com/immor/ecmall/member/entity/MemberCollectSubjectEntity.java
xImmor/ECMall
d2545e4b5ca95f4fea71649bf44ce3708ea837f5
[ "MIT" ]
null
null
null
16.622222
65
0.704545
4,957
package com.immor.ecmall.member.entity; import com.baomidou.mybatisplus.annotation.TableId; import com.baomidou.mybatisplus.annotation.TableName; import java.io.Serializable; import java.util.Date; import lombok.Data; /** * ??Ա?ղص?ר??? * * @author shenxian * @email hzdkv@example.com * @date 2020-12-02 10:32:20 */ @Data @TableName("ums_member_collect_subject") public class MemberCollectSubjectEntity implements Serializable { private static final long serialVersionUID = 1L; /** * id */ @TableId private Long id; /** * subject_id */ private Long subjectId; /** * subject_name */ private String subjectName; /** * subject_img */ private String subjectImg; /** * ?url */ private String subjectUrll; }
3e0bbcb56f83f190d79e0a107e7bfca4cf798e07
903
java
Java
MatCalcitePlugin/src/com/github/vlsi/mat/calcite/functions/HeapFunctionsBase.java
maisi/mat-calcite-plugin
a43a1378ac9f3c6759efdcc36169715ab9c15ce9
[ "Apache-2.0" ]
106
2015-01-21T03:49:16.000Z
2022-02-25T04:00:03.000Z
MatCalcitePlugin/src/com/github/vlsi/mat/calcite/functions/HeapFunctionsBase.java
maisi/mat-calcite-plugin
a43a1378ac9f3c6759efdcc36169715ab9c15ce9
[ "Apache-2.0" ]
18
2017-09-18T09:36:12.000Z
2022-02-11T11:25:35.000Z
MatCalcitePlugin/src/com/github/vlsi/mat/calcite/functions/HeapFunctionsBase.java
maisi/mat-calcite-plugin
a43a1378ac9f3c6759efdcc36169715ab9c15ce9
[ "Apache-2.0" ]
17
2015-12-01T10:31:21.000Z
2021-12-13T11:10:51.000Z
25.8
85
0.703212
4,958
package com.github.vlsi.mat.calcite.functions; import com.github.vlsi.mat.calcite.HeapReference; import org.eclipse.mat.snapshot.model.IObject; import java.lang.reflect.Method; public class HeapFunctionsBase { protected static Object resolveReference(Object value) { return value instanceof IObject ? HeapReference.valueOf((IObject) value) : value; } protected static HeapReference ensureHeapReference(Object r) { return r instanceof HeapReference ? (HeapReference) r : null; } protected static String toString(IObject o) { String classSpecific = o.getClassSpecificName(); if (classSpecific != null) { return classSpecific; } return o.getDisplayName(); } protected static Method findMethod(Class<?> cls, String name) { for (Method m : cls.getMethods()) { if (m.getName().equals(name)) { return m; } } return null; } }
3e0bbcfa8805139bf652b2e0bef313a60e340465
1,961
java
Java
client/spring-zeebe/src/main/java/io/camunda/zeebe/spring/client/bean/MethodInfo.java
rob2universe/spring-zeebe
0bd85fd473fb13c04d9e7b058bbec069c3819eb8
[ "Apache-2.0" ]
75
2017-09-08T19:45:17.000Z
2021-05-14T05:46:06.000Z
client/spring-zeebe/src/main/java/io/camunda/zeebe/spring/client/bean/MethodInfo.java
rob2universe/spring-zeebe
0bd85fd473fb13c04d9e7b058bbec069c3819eb8
[ "Apache-2.0" ]
115
2017-09-08T14:25:41.000Z
2021-07-13T10:05:52.000Z
client/spring-zeebe/src/main/java/io/camunda/zeebe/spring/client/bean/MethodInfo.java
rob2universe/spring-zeebe
0bd85fd473fb13c04d9e7b058bbec069c3819eb8
[ "Apache-2.0" ]
47
2018-03-03T10:39:35.000Z
2021-07-19T03:22:58.000Z
25.467532
100
0.703723
4,959
package io.camunda.zeebe.spring.client.bean; import static org.springframework.core.annotation.AnnotationUtils.findAnnotation; import java.lang.annotation.Annotation; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.Optional; public class MethodInfo implements BeanInfo { private ClassInfo classInfo; private Method method; private MethodInfo(ClassInfo classInfo, Method method) { this.classInfo = classInfo; this.method = method; } @Override public Object getBean() { return classInfo.getBean(); } @Override public String getBeanName() { return classInfo.getBeanName(); } public Object invoke(final Object... args) { try { return method.invoke(getBean(), args); } catch (InvocationTargetException e) { final Throwable targetException = e.getTargetException(); if (targetException instanceof RuntimeException) { throw (RuntimeException) targetException; } else { throw new RuntimeException("Failed to invoke method: " + method.getName(), targetException); } } catch (IllegalAccessException e) { throw new RuntimeException("Failed to invoke method: " + method.getName(), e); } } public <T extends Annotation> Optional<T> getAnnotation(final Class<T> type) { return Optional.ofNullable(findAnnotation(method, type)); } public static MethodInfoBuilder builder() { return new MethodInfoBuilder(); } public static final class MethodInfoBuilder { private ClassInfo classInfo; private Method method; private MethodInfoBuilder() { } public MethodInfoBuilder classInfo(ClassInfo classInfo) { this.classInfo = classInfo; return this; } public MethodInfoBuilder method(Method method) { this.method = method; return this; } public MethodInfo build() { return new MethodInfo(classInfo, method); } } }
3e0bbe6864450279faa954265b949f9b37951f9d
3,122
java
Java
src/main/java/com/suneee/threads/CountDownLatchDemo.java
manageryangbo/springmvcboot2
72c41eafb8b1f9c23d2839bfb052a0d1b1e2d413
[ "Apache-2.0" ]
null
null
null
src/main/java/com/suneee/threads/CountDownLatchDemo.java
manageryangbo/springmvcboot2
72c41eafb8b1f9c23d2839bfb052a0d1b1e2d413
[ "Apache-2.0" ]
null
null
null
src/main/java/com/suneee/threads/CountDownLatchDemo.java
manageryangbo/springmvcboot2
72c41eafb8b1f9c23d2839bfb052a0d1b1e2d413
[ "Apache-2.0" ]
null
null
null
25.801653
95
0.439142
4,960
/** * Copyright (C), 2015-2018, XXX有限公司 * FileName: CountDownLatchDemo * Author: martin * Date: 2018/8/30 15:08 * Description: * CountDownLatch 【共享锁】 * 实现所有线程等待某个事件发生才会执行 * mainThread.join(aThread); 执行后面的操作 * History: * <author> <time> <version> <desc> * 作者姓名 修改时间 版本号 描述 */ package com.suneee.threads; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ForkJoinTask; public class CountDownLatchDemo { /** * 模拟爸爸去公司 */ public static void fatherToCompany() { System.out.println("爸爸步行去公司。"); } /** * 模拟妈妈挤公交去商场 */ public static void motherToShopping() { System.out.println("妈妈挤公交去商场。"); } /** * 模拟我乘地铁回家 */ public static void meToHome() { System.out.println("我乘地铁回家。"); } /** * 一家人吃饭 */ public static void togetherToEat() { System.out.println("一家人开始吃饭,再去干各自的事"); } /** * 一家人唱歌 */ public static void togetherToKTV() { System.out.println("一家人开始唱歌,再去各自的事"); } private static CountDownLatch latch = new CountDownLatch(2); // (countDown调用次数,await才继续执行) public static void main(String[] args) throws InterruptedException { new Thread() { public void run() { try { latch.await(); } catch (InterruptedException e) { e.printStackTrace(); } fatherToCompany(); }; }.start(); new Thread() { public void run() { try { latch.await(); } catch (InterruptedException e) { e.printStackTrace(); } motherToShopping(); }; }.start(); new Thread() { public void run() { try { latch.await(); } catch (InterruptedException e) { e.printStackTrace(); } meToHome(); }; }.start(); new Thread() { public void run() { togetherToEat(); try { System.out.println("吃饭进行中......"); Thread.sleep(2000); System.out.println("吃饭完成......"); } catch (InterruptedException e) { e.printStackTrace(); } latch.countDown(); }; }.start(); new Thread() { public void run() { togetherToKTV(); try { System.out.println("KTV进行中......"); Thread.sleep(5000); System.out.println("KTV完成......"); } catch (InterruptedException e) { e.printStackTrace(); } latch.countDown(); }; }.start(); System.out.println("=======结束========"); } }
3e0bbfb5c45de957b99a49141af8f3c078482ac3
3,590
java
Java
revolsys-swing/src/main/java/com/revolsys/swing/map/layer/record/table/model/RecordLayerErrors.java
pauldaustin/gba-revolsys
561c5a2f858b54ab4503e7ae5cffeac11d5d8952
[ "Apache-2.0" ]
5
2015-02-23T04:53:44.000Z
2021-03-03T17:18:24.000Z
revolsys-swing/src/main/java/com/revolsys/swing/map/layer/record/table/model/RecordLayerErrors.java
pauldaustin/gba-revolsys
561c5a2f858b54ab4503e7ae5cffeac11d5d8952
[ "Apache-2.0" ]
5
2021-08-13T23:45:14.000Z
2022-03-31T19:59:23.000Z
revolsys-swing/src/main/java/com/revolsys/swing/map/layer/record/table/model/RecordLayerErrors.java
pauldaustin/gba-revolsys
561c5a2f858b54ab4503e7ae5cffeac11d5d8952
[ "Apache-2.0" ]
8
2015-02-23T04:53:45.000Z
2022-03-26T22:35:36.000Z
33.867925
99
0.713649
4,961
package com.revolsys.swing.map.layer.record.table.model; import java.awt.Dimension; import java.awt.Rectangle; import java.awt.Window; import java.util.ArrayList; import java.util.Collection; import java.util.List; import javax.swing.JDialog; import javax.swing.JLabel; import javax.swing.JOptionPane; import org.jdesktop.swingx.VerticalLayout; import com.revolsys.beans.ObjectPropertyException; import com.revolsys.record.Record; import com.revolsys.swing.Dialogs; import com.revolsys.swing.SwingUtil; import com.revolsys.swing.component.BasePanel; import com.revolsys.swing.map.layer.record.AbstractRecordLayer; import com.revolsys.swing.map.layer.record.LayerRecord; import com.revolsys.swing.parallel.Invoke; import com.revolsys.util.Property; public class RecordLayerErrors { private final String title; private final List<Throwable> exceptions = new ArrayList<>(); private final AbstractRecordLayer layer; private final List<String> messages = new ArrayList<>(); private final List<Record> records = new ArrayList<>(); private final Collection<String> fieldNames; public RecordLayerErrors(final String title, final AbstractRecordLayer layer) { this(title, layer, layer.getFieldNames()); } public RecordLayerErrors(final String title, final AbstractRecordLayer layer, final Collection<String> fieldNames) { this.title = title; this.layer = layer; this.fieldNames = fieldNames; } public void addRecord(final LayerRecord record, final String errorMessage) { this.records.add(record); this.messages.add(errorMessage); this.exceptions.add(null); } public void addRecord(final LayerRecord record, final Throwable exception) { this.records.add(record); String message; if (exception instanceof ObjectPropertyException) { final ObjectPropertyException objectPropertyException = (ObjectPropertyException)exception; message = objectPropertyException.getPropertyName() + ": " + objectPropertyException.getMessage(); } else { message = exception.getMessage(); } if (!Property.hasValue(message)) { message = exception.getClass().getSimpleName(); } this.messages.add(message); this.exceptions.add(exception); } public boolean showErrorDialog() { if (this.records.isEmpty()) { return true; } else { Invoke.later(() -> { final RecordLayerErrorsTableModel tableModel = new RecordLayerErrorsTableModel(this.layer, this.records, this.messages, this.exceptions, this.fieldNames); final String layerPath = this.layer.getPath(); final BasePanel panel = new BasePanel(new VerticalLayout(), new JLabel("<html><p><b style=\"color:red\">Error " + this.title + " for layer:</b></p><p>" + layerPath + "</p>"), tableModel.newPanel()); final Rectangle screenBounds = SwingUtil.getScreenBounds(); panel.setPreferredSize( new Dimension(screenBounds.width - 300, tableModel.getRowCount() * 22 + 75)); final Window window = Dialogs.getWindow(); final JOptionPane pane = new JOptionPane(panel, JOptionPane.ERROR_MESSAGE, JOptionPane.DEFAULT_OPTION, null, null, null); pane.setComponentOrientation(window.getComponentOrientation()); final JDialog dialog = pane.createDialog(window, "Error " + this.title + ": " + layerPath); dialog.pack(); SwingUtil.setLocationCentre(screenBounds, dialog); dialog.setVisible(true); SwingUtil.dispose(dialog); }); return false; } } }
3e0bc017afbf81c2635fc8361d3e837a6241fc79
3,904
java
Java
src/Main.java
HaiweiLu/Calculator
d0b4301b27eb13378f05c70d0204a943c2e6e7ae
[ "MIT" ]
null
null
null
src/Main.java
HaiweiLu/Calculator
d0b4301b27eb13378f05c70d0204a943c2e6e7ae
[ "MIT" ]
null
null
null
src/Main.java
HaiweiLu/Calculator
d0b4301b27eb13378f05c70d0204a943c2e6e7ae
[ "MIT" ]
null
null
null
39.04
119
0.436475
4,962
import java.util.Stack; import static java.lang.Math.*; public class Main { private static String[] op = {"+", "-", "*", "/"};// Operation set public static void main(String[] args) { for (int i = 0; i < 10000000; i++) { String question = makeFormula(); String ret = solve(question); } // String question = makeFormula(); // System.out.println(question); // String ret = solve(question); // System.out.println(ret); } public static String makeFormula() { StringBuilder build = new StringBuilder(); int count = (int) (random() * 2) + 1; // generate random count int start = 0; int number1 = (int) (random() * 99) + 1; build.append(number1); while (start <= count) { int operation = (int) (random() * 3); // generate operator int number2 = (int) (random() * 99) + 1; build.append(op[operation]).append(number2); start++; } return build.toString(); } public static String solve(String formula) { Stack<String> tempStack = new Stack<>();//Store number or operator Stack<Character> operatorStack = new Stack<>();//Store operator int len = formula.length(); int k = 0; for (int j = -1; j < len - 1; j++) { char formulaChar = formula.charAt(j + 1); if (j == len - 2 || formulaChar == '+' || formulaChar == '-' || formulaChar == '/' || formulaChar == '*') { if (j == len - 2) { tempStack.push(formula.substring(k)); } else { if (k < j) { tempStack.push(formula.substring(k, j + 1)); } if (operatorStack.empty()) { operatorStack.push(formulaChar); //if operatorStack is empty, store it } else { char stackChar = operatorStack.peek(); if ((stackChar == '+' || stackChar == '-') && (formulaChar == '*' || formulaChar == '/')) { operatorStack.push(formulaChar); } else { tempStack.push(operatorStack.pop().toString()); operatorStack.push(formulaChar); } } } k = j + 2; } } while (!operatorStack.empty()) { // Append remaining operators tempStack.push(operatorStack.pop().toString()); } Stack<String> calcStack = new Stack<>(); for (String peekChar : tempStack) { // Reverse traversing of stack if (!"+".equals(peekChar) && !"-".equals(peekChar) && !"/".equals(peekChar) && !"*".equals(peekChar)) { calcStack.push(peekChar); // Push number to stack } else { int a1 = 0; int b1 = 0; if (!calcStack.empty()) { b1 = Integer.parseInt(calcStack.pop()); } if (!calcStack.empty()) { a1 = Integer.parseInt(calcStack.pop()); } switch (peekChar) { case "+": calcStack.push(String.valueOf(a1 + b1)); break; case "-": calcStack.push(String.valueOf(a1 - b1)); break; case "*": calcStack.push(String.valueOf(a1 * b1)); break; default: calcStack.push(String.valueOf(a1 / b1)); break; } } } return formula + "=" + calcStack.pop(); } }
3e0bc04f555af3fb9012182a453a0a7db00fc17f
9,794
java
Java
output/e699bf9554414854bcf4134f0c530617.java
comprakt/comprakt-fuzz-tests
c0082d105d7c54ad31ab4ea461c3b8319358eaaa
[ "Apache-2.0", "MIT" ]
null
null
null
output/e699bf9554414854bcf4134f0c530617.java
comprakt/comprakt-fuzz-tests
c0082d105d7c54ad31ab4ea461c3b8319358eaaa
[ "Apache-2.0", "MIT" ]
null
null
null
output/e699bf9554414854bcf4134f0c530617.java
comprakt/comprakt-fuzz-tests
c0082d105d7c54ad31ab4ea461c3b8319358eaaa
[ "Apache-2.0", "MIT" ]
null
null
null
36.544776
290
0.483561
4,963
class lY_tKTAMBQhPb { public static void a6 (String[] W) throws WD { ; while ( ---!-!( this.d7d7()).E5ilvd7b()) return; yRn_pzfT tTTqx0vbgep5B = ( !!( true[ pVL4dc7ZjyA().Q()]).LQnFSY4WG).kX; { KV_GljQE[] qvJwcdv6Ikha; boolean[][][] Ne; int[] L; } void[][][][] af8rfQt; while ( ---true[ !( --new ukFW1ujLaG[ null._XSlrbG3KuT()].gW6Vq).Epecl6]) return; C8whYlzLwh.C84; int Zb = -this[ new int[ this.UM3vx3_()].nN] = !PbmmYwtZ.MVYHe2WJw9LIpz; void[][] kItj0HiNUcBybY = -null.wv1NwdWgVc(); void[] cQWUdpy4oz; boolean[][] Gez = -61[ 09.wy6cF_nOyrv()] = paIp_gQ5qA.BKRJmTCxkK(); { boolean[] XUzDO; while ( ( -!!!new paCuar0oI9OGcj().IFWUsC5tCLrWR).cA8xBpEQ()) if ( !null.I) if ( 69598.XSpR) ; return; int pguFYec0; while ( true[ this.HI]) return; return; void[][][][] ePaT; _Thw6QrB6[][] Mhy7OH_8waX; while ( new P7MYL7Cu9().cr()) while ( -!!58295.YNKJ7es) !!new void[ !null.XolQL_Y()].ov(); J8y4sXUXh4L2g QbOq4jyh; boolean[][] h; int[][][][] Z8xJa8; ; boolean rqWC; } void[] p8tprZ = k9iHBMlJ_Zrg().Ufhd5wY() = 13253507.lTINor1i(); } public int LRz; public static void Ys (String[] wh80uYzj50) { if ( ( 80[ !this[ false.XFZzHb1qO()]]).WSsoj9S0Q()) { ; }else !Yto9WscW().DWbUqGxG(); --this.zaqs(); if ( y3qEgwgXwv4m.XdPyT) ; } public SoahoLsyes pHh92J; public G mdbAnKuY; public boolean[] qV91cy7teOvA () { P21SbQ0zCaNznn[] d0tXPEg11p2n = true.rnSgSGCykP; boolean[] V7aLhsMUgbsQr; boolean rp; void M3m8Bxg3lWTb8; boolean[][][][][][] sodsXNuVH75; g[][] KNkQd; boolean[][] _tM7pz = null.IrGkl; ; void baxjhk0; !!null.U3(); nVM3zmLK[][] TD; } public int[][] QQXOT9TL_wA3; public static void Xl (String[] lU) { ; eBsCfR rh9O5l2; void[][] I1b56evx; { gn1_H[][] xTmaOKyd; return; while ( ( -!!!!( -new rve3EiYRb()[ --new boolean[ new _r3GkrzywqW().SK3].D0FL3()])[ new hv()[ --this.bleJS4BAK3vRk()]])[ -new lGZv7()[ !TS[ !this[ -!!( !new void[ this.hfgG()].mYN7kLy()).t4UKvWlfj6iF]]]]) if ( 95[ !ZDN0PCUtC9()[ -true[ new bdAq()[ new void[ !this.ZDBe].B]]]]) ; boolean[] J_p; int[] DiW; ; void kmq; boolean emvV2kz_Ksa3nB; g[][] d0GV; int[] QN2fE; cQed_nP YkokFzElDUXn; cKVqhuCJ[][][] hPCdyJf; ; int i; return; int mKsPRalc1; void d6GmhEKqC; while ( !!--107[ new WQC_If()[ new Butxn2hhFP().NYF7LGbSXF5gH4]]) if ( new JOoRgFWz()[ -( new int[ ( new void[ -new SMiV().xA7NcOa8r()].VFgIUwjLKfoB_N).ONZkmzkzlMCO()][ -null.N70]).Agh()]) ; a4ni_t xtLbvMJ8cw; int RmL; } boolean[] tsWWdfPVeAh7C = ---mIioLw6.k7UKpRuN() = -!true.Hu7Ftj0(); boolean IZrZJsm = new boolean[ -!-false[ -true.no9q9()]][ !!35665122[ !this[ this.bdfjjxDxlMrp8()]]]; void[] sKITCqTQV = new KB[ !true[ -!null[ ( !false.cIp_u9dD_B).tSGpg9XW()]]][ XaBFXsd()[ this[ -new Uo13Db5ml()[ -new wRx_uk()[ new xGar()[ -new P0ewC().BVmIE]]]]]] = --true.oliZailBz; -!( true.v9jKk)[ ( -true.r)[ 96051419._PcX6H()]]; void[][] Z4; true[ 6153563.dtGDqV]; if ( -null.L3ufOkd()) while ( -new CQmjL7OTF[ false.g()].fbcMUSzK3ODK) { M[][][][][][] TJQsVgAR; } ; return -null.Nif4; DV0Pgw8.hwUNQow9yzySF; { boolean Q6GYPg9; !new exqWRWybNOa[ new SUzDmxgzIwg().gL()].VbKDa4bKr; } { !-new dyZdcaSf().deO1vC0JFEb6; } { if ( null.VteBSRTGUP7A()) { while ( !null.aKk7om_TsZ) ; } return; int tifey4RJwxiX; { ; } Lenaq q1JH7w; void[] XoJgs; while ( 667287[ 13216.ij()]) if ( true.qytNZ82M5rxwzr()) return; void[][] zeeS; vWy2KJC z9cPsQ; int[] tL1Iv8b9grCRz; tXNZXV0f saOfK; void QYDU4u; boolean iwGsNj6; while ( true.tKIPYQ9Dd6ReF()) gg7oj9lOy8waUg().it1QsI8; } mIHVjs93pxMu[] USKdAlMLygpC3; int[][][] y0qt = 486701[ null.YYYFQGEf] = zsXMaWs[ 91775.xczXfzX]; } public static void d (String[] IPIkyO) { boolean[][] bik = !kqB().aVv4j() = !--42.tzeAeP6NSKMr; -!!( -this[ aoFkirFI_LLZ7_().kCruwq47a])[ this.HFuAC3()]; void[][][] UGDA; boolean rwZqgg3QL9Efl; if ( -!!----!( !false.zQgv).U8tMJ) while ( !-false.JUDIibxng2qP4) if ( 39860770.cy6KWv()) { Ufy[][][] LkelusjudbmO; } { boolean utSI7V1mFIn; ; boolean f_TjgYSIk; WNWkNx8t QjzhjU_7V1bd; void _X7Eh; ; !( !ftdJ0Tnh07CFM()[ -new hyMn7nV9cpsWXW[ null.pRnBSfB][ -!-new void[ 38.Id1Xic4JI()].NaDonTnCQHs()]]).c7VZp00rl; int kFVQ; !!!-!false.jPqY2guK6; int[] R; int[] OIwo; boolean[] NWFw; x5ssXzkFqaTqa[][] Gs; int AQZA; int[][][] fpoevB0; { void lYCJd99; } { int V1; } } return c().McJic3bUVMpi2t(); void ITgpr91n = !!null.znJXpk; ; ; { int JjK0cMws; ; int[][][][] N4By; boolean Ta_2w87IZr; ; int[] BL4PYSMOU43Jv; int[] iPtgdEF_4; boolean PiU8Q; return; d[][] kItt1sX; void[] J50iQ; KDBWV[] TZPrb0M0jr; boolean[][][][][][] j94PVmKHfkXF6; boolean s; boolean WvXYULUhxh0FJ2; { while ( new hIQiBLgq7Wb().j5tT9Nnshr) { ; } } { int[] _H; } ; boolean[][][] XKxz4YegN; } TRGBv03xUZXj6[][][][] UqJBERCp3U4Oc_ = !new boolean[ -!!!!-new int[ this[ ( !( aqn31XkrI().susRDPuIsqhteV()).fef()).K10gNGD6J()]].uVthOWSmKc][ !--this.KCbxCxlS75()] = !this.lMj(); boolean[][] dneQHqv7T6aX; } public static void JSFJLrSIAs (String[] nnm) { void[] C6tHUO = !-null[ 451.xsROfi3()]; return this[ new int[ new boolean[ false.OS2AeD].QIrU5fAUrNa][ -!--zZb8().EQqqFq]]; boolean WUnCi51wkE9g = !true.TGfZ8JfSA_(); boolean oRhJfkHO7odQa = false[ 05.yUAiieGg_AqJ()] = ( !-new boolean[ ( 9.yQbIkh6cIeTm8()).QAk39MVSG].j()).QgD9Du9_6Sq8(); ; int[][] FdDiZcPlEO; void[] kUuoEFxllAykcV; boolean iEvlD3g07BFmO; { ; boolean LikihNTZ0j82; no2Ac3gQWzWj3[][][] LUVLSGBtK9P3; while ( -true[ -!!b48Pzz0dI92[ !!q0XM2JFcg8y.eu4hnV53m]]) if ( new J4IzxSyLkfu_xT().AKDflgmCqfq()) ; boolean B6_COHpCk; YB2AJ[][] MGD4; int mEc; int[] _sVXALr1NtI; Va1vQOJK1y ZOuAPedqoMIM; if ( Hp2u.etsDYLsK) return; -!true.kjV3LZ_eqXoT; while ( -false.KW7) { while ( false.AxkalmYWpPRJ) return; } X8dZDu[][][] WFFjYSacjlie; return; void[] pH_4cy8Qh; int St5l; while ( null[ -false.MtqnP5o9UqMh()]) !( new QiBQPvI[ !!-new void[ new void[ A_sz9().vHU7kcQlZ1Pmb].XX63C5iXWisV].tTzUyzGFr].PjvUEesxMyGoUK)[ new nzfLHT[ !!!( false.TNnozie()).rqTzmaALf].lrgEKWD7zofo]; } 08568.vNns2Cl(); boolean hhIhvtX6een0u = --null[ WP9pr4v()[ !new int[ new RHHaQuGDHmyH().Rt5DyU2j][ --( !--!false.s())[ ( -YGfrVCytkRhzZc[ null[ 59930[ -99687.M4BLiErTOj]]]).pyGunzAEccjTjv]]]] = !kRk500()[ new hpSw9WAuTJG()[ -_TTQeP[ null[ !null.wmQE2g]]]]; } public void U0Xykae; public sxh_EHzm0kuRN Gu_29HfZSgIZ () throws n8BVP { int auN2FjB3a7; { boolean _; while ( j[ -!!this.nBPGOz2EbMNJW()]) ; boolean[] qtI; P[][] fyVOsS; void Pp; while ( !true.jHeX3Mp()) ; jX AqKxdPr3umvC; while ( !Xbr.jiXYkH10c) return; int[][] u; } int QwBN4Lb6Thoj; return -!-null.Hp2QapW2b; return; if ( true[ !this[ ---( -false.L())[ cUAfP().kDXbs]]]) -!this.PrDK;else while ( !false.cmfwxNGoRe5()) this[ 843237[ P1aqlSpLAaPxz.yaDzCj]]; } public void[] tOo__IpeuKI; public void[][][] o0VBCc1D () throws lo117yyG { int rK; { { int[] YU8UYcA; } while ( !1.cI9Td_9I2nEKe()) ; !new void[ new h5Cu1sNTTMHRV().kEIUARjB][ !-855573528.y]; int[] BNUuVk6VbRin; while ( new boolean[ !--false.GgcKf()].q) if ( true.U()) ; } nSTfhKRj[] FfxHK_k = -!!true[ -null.BHG69pA0lRt] = new ovxWRmyMq8XMXp().ol8q1DEGn4mc; while ( --xxDDxM83aF._bCjlmcppo) false.OLZ7Pb(); boolean n; } public boolean iJocc () { ; boolean z = -null.FXY__9Se3Yj_5b(); a6NmQyN9F0yU OJdX1JnDeucqa; !new FHH_grbrZg_qD[ 6729.R9V()][ --( ( !new Kz5UpFFRto8UZ9()[ true.HS])[ false.kgvodZkB()]).FMg]; } }
3e0bc0738cd83ece4db501909355738596d8daec
625
java
Java
src/main/java/com/example/cricket/core/team/web/TeamBaseReq.java
DamianArado/Cricket-Standings
7828f833fe8412365650e55a2857f99af1402abc
[ "MIT" ]
null
null
null
src/main/java/com/example/cricket/core/team/web/TeamBaseReq.java
DamianArado/Cricket-Standings
7828f833fe8412365650e55a2857f99af1402abc
[ "MIT" ]
null
null
null
src/main/java/com/example/cricket/core/team/web/TeamBaseReq.java
DamianArado/Cricket-Standings
7828f833fe8412365650e55a2857f99af1402abc
[ "MIT" ]
null
null
null
16.447368
46
0.656
4,964
package com.example.cricket.core.team.web; import com.example.cricket.base.BaseRequest; import javax.validation.constraints.NotEmpty; import javax.validation.constraints.NotNull; public class TeamBaseReq extends BaseRequest { @NotEmpty private String name; @NotNull private int numPlayers; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getNumPlayers() { return numPlayers; } public void setNumPlayers(int numPlayers) { this.numPlayers = numPlayers; } }
3e0bc0d422f8c3943d197422ec3cb16b88f22ca7
500
java
Java
L5/02_FactoryMethod/src/PizzaStore.java
DeirdreHegarty/advanced_OOP
e62d8f2274422d3da9064e2576e2adc414eccee1
[ "MIT" ]
null
null
null
L5/02_FactoryMethod/src/PizzaStore.java
DeirdreHegarty/advanced_OOP
e62d8f2274422d3da9064e2576e2adc414eccee1
[ "MIT" ]
null
null
null
L5/02_FactoryMethod/src/PizzaStore.java
DeirdreHegarty/advanced_OOP
e62d8f2274422d3da9064e2576e2adc414eccee1
[ "MIT" ]
null
null
null
29.411765
81
0.624
4,965
public abstract class PizzaStore { // <--------- abstract /* * Implemented method: refers to abstract method below * which will be DEFINED BY SUB-CLASSES */ public Pizza orderPizza(String type) { Pizza pizza = createPizza(type); // <------------- call to method in own class System.out.println("--- Making a " + pizza.getName() + " ---"); return pizza; } /* * ABSTRACT METHOD: to be defined by sub-class */ abstract Pizza createPizza(String item); // <----------- abstract }
3e0bc0da6ab435713a25e50f373fb6823b83bb49
1,393
java
Java
client/src/generated/java/com/influxdb/client/domain/Node.java
bonitoo-io/influxdata-platform-java
52a781aeec4074284ac02eaf01c20f00319d91a3
[ "MIT" ]
6
2019-04-25T07:44:56.000Z
2019-07-05T10:27:40.000Z
client/src/generated/java/com/influxdb/client/domain/Node.java
bonitoo-io/influxdb-client-java
0e166e6754c6551ab4d30c7357dbad27392b20b6
[ "MIT" ]
31
2019-02-18T06:16:56.000Z
2019-07-18T09:50:43.000Z
client/src/generated/java/com/influxdb/client/domain/Node.java
bonitoo-io/influxdata-platform-java
52a781aeec4074284ac02eaf01c20f00319d91a3
[ "MIT" ]
1
2019-04-25T07:44:57.000Z
2019-04-25T07:44:57.000Z
20.791045
148
0.651113
4,966
/* * InfluxDB OSS API Service * The InfluxDB v2 API provides a programmatic interface for all interactions with InfluxDB. Access the InfluxDB API using the `/api/v2/` endpoint. * * OpenAPI spec version: 2.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ package com.influxdb.client.domain; import java.util.Objects; import java.util.Arrays; import com.influxdb.client.domain.Block; import com.influxdb.client.domain.Expression; import com.influxdb.client.domain.Statement; import java.util.List; /** * Node */ public class Node { @Override public boolean equals(java.lang.Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } return true; } @Override public int hashCode() { return Objects.hash(); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class Node {\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
3e0bc100c0f51230cf381a7fb609f6029ecb09f2
1,467
java
Java
app/src/main/java/cupkovic/fesb/hr/filmoteka/interfaces/IDataProvider.java
gcupko00/Filmoteka
32a2d50d915e8dcff2bb33a88fa9aface12d12a4
[ "MIT" ]
null
null
null
app/src/main/java/cupkovic/fesb/hr/filmoteka/interfaces/IDataProvider.java
gcupko00/Filmoteka
32a2d50d915e8dcff2bb33a88fa9aface12d12a4
[ "MIT" ]
null
null
null
app/src/main/java/cupkovic/fesb/hr/filmoteka/interfaces/IDataProvider.java
gcupko00/Filmoteka
32a2d50d915e8dcff2bb33a88fa9aface12d12a4
[ "MIT" ]
null
null
null
32.6
100
0.693933
4,967
package cupkovic.fesb.hr.filmoteka.interfaces; import java.util.ArrayList; import java.util.NoSuchElementException; /** * This interface should be implemented by all data provider classes. It specifies methods used * to modify and access data. All the methods do their operations over the list of objects of type T */ public interface IDataProvider<T> { /** * Gets the element from the data storage list * @param id Element identification number (or string) * @return Element of type T * @throws NoSuchElementException Raised if element is not found */ T getById(String id) throws NoSuchElementException; /** * Adds new elements to the storage list * @param newData List of elements of type T to add */ void putData(ArrayList<T> newData); /** * Sets the storage list * @param value List of objects of type T to which storage list should be set */ void setData(ArrayList<T> value); /** * Returns object of type T stored at the specified position in the list * @param position Position of the object in the list * @return Element at the specified location * @throws NoSuchElementException Raised if requested position is out of bounds of the list */ T getAtPosition(int position) throws NoSuchElementException; /** * Gets all the stored data * @return The list of the stored objects of type T */ ArrayList<T> getAllData(); }
3e0bc213f1bf7e7d5893d196461fdf502d8235aa
1,709
java
Java
ide/xml.text/src/org/netbeans/modules/xml/text/syntax/javacc/lib/UCode_CharStream.java
tusharvjoshi/incubator-netbeans
a61bd21f4324f7e73414633712522811cb20ac93
[ "Apache-2.0" ]
1,056
2019-04-25T20:00:35.000Z
2022-03-30T04:46:14.000Z
ide/xml.text/src/org/netbeans/modules/xml/text/syntax/javacc/lib/UCode_CharStream.java
Marc382/netbeans
4bee741d24a3fdb05baf135de5e11a7cd95bd64e
[ "Apache-2.0" ]
1,846
2019-04-25T20:50:05.000Z
2022-03-31T23:40:41.000Z
ide/xml.text/src/org/netbeans/modules/xml/text/syntax/javacc/lib/UCode_CharStream.java
Marc382/netbeans
4bee741d24a3fdb05baf135de5e11a7cd95bd64e
[ "Apache-2.0" ]
550
2019-04-25T20:04:33.000Z
2022-03-25T17:43:01.000Z
34.877551
86
0.732592
4,968
/* * 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.netbeans.modules.xml.text.syntax.javacc.lib; /** * This class has the same name as JavaCC generated CharStream for * <pre> * UNICODE_INPUT = TRUE * <pre> * but it behaves as a user char stream. Reason is that * <pre> * USER_CHAR_STREAM = TRUE * <pre> * disables generation of unicode aware code i.e. unicode aware code is generated only * for <tt>UNICODE_INPUT</tt> which is mutually exclusive with user char input. * <p> * Note: Delete JavaCC generated UCode_CharStream and add import statement * that makes this class visible. * * @see https://javacc.dev.java.net/issues/show_bug.cgi?id=77 * @author Petr Kuzel */ public final class UCode_CharStream extends StringParserInput { /** this implementation is dynamic, I hope so. */ public static final boolean staticFlag = false; /** Creates new UCode_CharStream */ public UCode_CharStream() { } }
3e0bc2953498b97fcb917539a2accc171750d515
3,241
java
Java
net/minecraft/block/BlockWallSign.java
BantorSchwanzVor/plotscanner-leak
cbf130076159711d939affb4b0343c46c3466107
[ "MIT" ]
null
null
null
net/minecraft/block/BlockWallSign.java
BantorSchwanzVor/plotscanner-leak
cbf130076159711d939affb4b0343c46c3466107
[ "MIT" ]
null
null
null
net/minecraft/block/BlockWallSign.java
BantorSchwanzVor/plotscanner-leak
cbf130076159711d939affb4b0343c46c3466107
[ "MIT" ]
null
null
null
40.012346
136
0.743289
4,969
package net.minecraft.block; import net.minecraft.block.properties.IProperty; import net.minecraft.block.properties.PropertyDirection; import net.minecraft.block.state.BlockStateContainer; import net.minecraft.block.state.IBlockState; import net.minecraft.util.EnumFacing; import net.minecraft.util.Mirror; import net.minecraft.util.Rotation; import net.minecraft.util.math.AxisAlignedBB; import net.minecraft.util.math.BlockPos; import net.minecraft.world.IBlockAccess; import net.minecraft.world.World; public class BlockWallSign extends BlockSign { public static final PropertyDirection FACING = BlockHorizontal.FACING; protected static final AxisAlignedBB SIGN_EAST_AABB = new AxisAlignedBB(0.0D, 0.28125D, 0.0D, 0.125D, 0.78125D, 1.0D); protected static final AxisAlignedBB SIGN_WEST_AABB = new AxisAlignedBB(0.875D, 0.28125D, 0.0D, 1.0D, 0.78125D, 1.0D); protected static final AxisAlignedBB SIGN_SOUTH_AABB = new AxisAlignedBB(0.0D, 0.28125D, 0.0D, 1.0D, 0.78125D, 0.125D); protected static final AxisAlignedBB SIGN_NORTH_AABB = new AxisAlignedBB(0.0D, 0.28125D, 0.875D, 1.0D, 0.78125D, 1.0D); public BlockWallSign() { setDefaultState(this.blockState.getBaseState().withProperty((IProperty)FACING, (Comparable)EnumFacing.NORTH)); } public AxisAlignedBB getBoundingBox(IBlockState state, IBlockAccess source, BlockPos pos) { switch ((EnumFacing)state.getValue((IProperty)FACING)) { default: return SIGN_NORTH_AABB; case SOUTH: return SIGN_SOUTH_AABB; case WEST: return SIGN_WEST_AABB; case EAST: break; } return SIGN_EAST_AABB; } public void neighborChanged(IBlockState state, World worldIn, BlockPos pos, Block blockIn, BlockPos p_189540_5_) { EnumFacing enumfacing = (EnumFacing)state.getValue((IProperty)FACING); if (!worldIn.getBlockState(pos.offset(enumfacing.getOpposite())).getMaterial().isSolid()) { dropBlockAsItem(worldIn, pos, state, 0); worldIn.setBlockToAir(pos); } super.neighborChanged(state, worldIn, pos, blockIn, p_189540_5_); } public IBlockState getStateFromMeta(int meta) { EnumFacing enumfacing = EnumFacing.getFront(meta); if (enumfacing.getAxis() == EnumFacing.Axis.Y) enumfacing = EnumFacing.NORTH; return getDefaultState().withProperty((IProperty)FACING, (Comparable)enumfacing); } public int getMetaFromState(IBlockState state) { return ((EnumFacing)state.getValue((IProperty)FACING)).getIndex(); } public IBlockState withRotation(IBlockState state, Rotation rot) { return state.withProperty((IProperty)FACING, (Comparable)rot.rotate((EnumFacing)state.getValue((IProperty)FACING))); } public IBlockState withMirror(IBlockState state, Mirror mirrorIn) { return state.withRotation(mirrorIn.toRotation((EnumFacing)state.getValue((IProperty)FACING))); } protected BlockStateContainer createBlockState() { return new BlockStateContainer(this, new IProperty[] { (IProperty)FACING }); } } /* Location: C:\Users\BSV\AppData\Local\Temp\Rar$DRa6216.20396\Preview\Preview.jar!\net\minecraft\block\BlockWallSign.class * Java compiler version: 8 (52.0) * JD-Core Version: 1.1.3 */
3e0bc3b6617fa29a36dddb52757ca1e319fd1fd4
3,308
java
Java
Product/Production/Common/CONNECTCoreLib/src/test/java/gov/hhs/fha/nhinc/messaging/service/decorator/URLServiceEndpointDecoratorTest.java
teruyukimorimura/CONNECT
63a4a0f731511c3a668de354bcef08da64a7e92b
[ "BSD-3-Clause" ]
null
null
null
Product/Production/Common/CONNECTCoreLib/src/test/java/gov/hhs/fha/nhinc/messaging/service/decorator/URLServiceEndpointDecoratorTest.java
teruyukimorimura/CONNECT
63a4a0f731511c3a668de354bcef08da64a7e92b
[ "BSD-3-Clause" ]
null
null
null
Product/Production/Common/CONNECTCoreLib/src/test/java/gov/hhs/fha/nhinc/messaging/service/decorator/URLServiceEndpointDecoratorTest.java
teruyukimorimura/CONNECT
63a4a0f731511c3a668de354bcef08da64a7e92b
[ "BSD-3-Clause" ]
null
null
null
44.106667
115
0.746372
4,970
/* * Copyright (c) 2009-2016, United States Government, as represented by the Secretary of Health and Human Services. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above * copyright notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * Neither the name of the United States Government 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 UNITED STATES GOVERNMENT 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 gov.hhs.fha.nhinc.messaging.service.decorator; import gov.hhs.fha.nhinc.messaging.client.CONNECTClient; import gov.hhs.fha.nhinc.messaging.client.CONNECTTestClient; import gov.hhs.fha.nhinc.messaging.service.ServiceEndpoint; import gov.hhs.fha.nhinc.messaging.service.port.TestServicePortDescriptor; import gov.hhs.fha.nhinc.messaging.service.port.TestServicePortType; import java.util.Map; import static org.junit.Assert.assertEquals; import org.junit.Test; /** * @author akong * */ public class URLServiceEndpointDecoratorTest { @Test public void testURLConfiguration() { String url = "url"; CONNECTClient<TestServicePortType> client = createClient(url); verifyURLConfiguration(client, url); } /** * Verifies that the client has the given url set. * * @param client * @param url */ public void verifyURLConfiguration(CONNECTClient<?> client, String url) { Map<String, Object> requestContext = ((javax.xml.ws.BindingProvider) client.getPort()).getRequestContext(); assertEquals(url, requestContext.get(javax.xml.ws.BindingProvider.ENDPOINT_ADDRESS_PROPERTY)); } private CONNECTClient<TestServicePortType> createClient(String url) { CONNECTTestClient<TestServicePortType> testClient = new CONNECTTestClient<>( new TestServicePortDescriptor()); ServiceEndpoint<TestServicePortType> serviceEndpoint = testClient.getServiceEndpoint(); serviceEndpoint = new URLServiceEndpointDecorator<>(serviceEndpoint, url); serviceEndpoint.configure(); return testClient; } }
3e0bc6034063b7ab8e16c4bbf0a1e98c3545a541
1,014
java
Java
plugins/yaml/src/org/jetbrains/yaml/psi/impl/YAMLDocumentImpl.java
dunno99/intellij-community
aa656a5d874b947271b896b2105e4370827b9149
[ "Apache-2.0" ]
1
2018-10-03T12:35:12.000Z
2018-10-03T12:35:12.000Z
plugins/yaml/src/org/jetbrains/yaml/psi/impl/YAMLDocumentImpl.java
dunno99/intellij-community
aa656a5d874b947271b896b2105e4370827b9149
[ "Apache-2.0" ]
173
2018-07-05T13:59:39.000Z
2018-08-09T01:12:03.000Z
plugins/yaml/src/org/jetbrains/yaml/psi/impl/YAMLDocumentImpl.java
dunno99/intellij-community
aa656a5d874b947271b896b2105e4370827b9149
[ "Apache-2.0" ]
1
2020-09-19T21:21:18.000Z
2020-09-19T21:21:18.000Z
24.731707
82
0.752465
4,971
package org.jetbrains.yaml.psi.impl; import com.intellij.lang.ASTNode; import com.intellij.psi.PsiElementVisitor; import com.intellij.psi.util.PsiTreeUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.yaml.psi.YAMLDocument; import org.jetbrains.yaml.psi.YAMLValue; import org.jetbrains.yaml.psi.YamlPsiElementVisitor; /** * @author oleg */ public class YAMLDocumentImpl extends YAMLPsiElementImpl implements YAMLDocument { public YAMLDocumentImpl(@NotNull final ASTNode node) { super(node); } @Override public String toString() { return "YAML document"; } @Nullable @Override public YAMLValue getTopLevelValue() { return PsiTreeUtil.findChildOfType(this, YAMLValue.class); } @Override public void accept(@NotNull PsiElementVisitor visitor) { if (visitor instanceof YamlPsiElementVisitor) { ((YamlPsiElementVisitor)visitor).visitDocument(this); } else { super.accept(visitor); } } }
3e0bc665da245db0eb0018b3b022c33063460e86
5,786
java
Java
ether-core/src/main/java/ch/fhnw/ether/platform/GLFWPlatform.java
arisona/ether
29bc86589ce979af081e72a7bb78d49879d00464
[ "BSD-3-Clause" ]
20
2016-08-07T15:33:19.000Z
2021-08-04T07:17:00.000Z
ether-core/src/main/java/ch/fhnw/ether/platform/GLFWPlatform.java
arisona/ether
29bc86589ce979af081e72a7bb78d49879d00464
[ "BSD-3-Clause" ]
2
2016-05-18T13:19:19.000Z
2016-09-17T12:47:34.000Z
ether-core/src/main/java/ch/fhnw/ether/platform/GLFWPlatform.java
arisona/ether
29bc86589ce979af081e72a7bb78d49879d00464
[ "BSD-3-Clause" ]
13
2016-03-25T14:18:19.000Z
2021-02-04T02:37:12.000Z
27.552381
84
0.721051
4,972
/* * Copyright (c) 2013 - 2016 Stefan Muller Arisona, Simon Schubiger * Copyright (c) 2013 - 2016 FHNW & ETH Zurich * All rights reserved. * * Contributions by: Filip Schramka, Samuel von Stachelski * * 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 FHNW / ETH Zurich nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER 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 ch.fhnw.ether.platform; import java.util.LinkedList; import java.util.List; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.atomic.AtomicBoolean; import org.lwjgl.PointerBuffer; import org.lwjgl.glfw.GLFW; import org.lwjgl.glfw.GLFWErrorCallback; import ch.fhnw.ether.render.gl.GLContextManager; import ch.fhnw.ether.view.IWindow; import ch.fhnw.util.CollectionUtilities; import ch.fhnw.util.IDisposable; import ch.fhnw.util.Log; import ch.fhnw.util.math.Vec2; class GLFWPlatform implements IPlatform { private static final Log log = Log.create(); private final BlockingQueue<Runnable> queue = new LinkedBlockingQueue<>(); private final GLFWErrorCallback errorCallback; private final IImageSupport imageSupport; private final Thread mainThread; private List<Runnable> shutdownTasks = new LinkedList<>(); private List<IDisposable> disposeTasks = new LinkedList<>(); private AtomicBoolean exiting = new AtomicBoolean(); public GLFWPlatform() { this(new STBImageSupport()); } protected GLFWPlatform(IImageSupport imageSupport) { this.errorCallback = GLFWErrorCallback.createPrint(System.err); this.imageSupport = imageSupport; this.mainThread = Thread.currentThread(); } @Override public final void init() { GLFW.glfwSetErrorCallback(errorCallback); if (!GLFW.glfwInit()) throw new IllegalStateException("unable to initialize glfw"); initInternal(); GLContextManager.init(); } @Override public final void run() { try { while (true) { waitForEvents(); Runnable runnable; while ((runnable = queue.poll()) != null) { try { runnable.run(); } catch (Exception e) { e.printStackTrace(); } } } } catch (Exception e) { e.printStackTrace(); } exit(); } @Override public final void exit() { if(!(exiting.getAndSet(true))) { runOnMainThread(()->{ exitInternal(); errorCallback.free(); // XXX commented out for now, seems to frequently lead to crashes... // GLFW.glfwTerminate(); System.exit(0); }); } } @Override public boolean isMainThread() { return Thread.currentThread().equals(mainThread); } @Override public final void runOnMainThread(Runnable runnable) { queue.offer(runnable); GLFW.glfwPostEmptyEvent(); } @Override public IWindow createWindow(Vec2 size, String title, boolean decorated) { return new GLFWWindow(size, title, decorated); } @Override public IWindow createWindow(IMonitor monitor, String title) { return new GLFWWindow(monitor, title); } @Override public IImageSupport getImageSupport() { return imageSupport; } protected void initInternal() { } protected void exitInternal() { synchronized (disposeTasks) { for(IDisposable d : disposeTasks.toArray(new IDisposable[disposeTasks.size()])) { try { d.dispose(); } catch(Throwable t) { log.warning(t); } } } synchronized (shutdownTasks) { for(Runnable r : shutdownTasks.toArray(new Runnable[shutdownTasks.size()])) { try { r.run(); } catch(Throwable t) { log.warning(t); } } } } protected void waitForEvents() { GLFW.glfwWaitEvents(); } @Override public IMonitor[] getMonitors() { PointerBuffer monitors = GLFW.glfwGetMonitors(); IMonitor[] result = new IMonitor[monitors.limit()]; for(int i = 0; i < result.length; i++) result[i] = new GLFWMonitor(monitors.get(i), i); return result; } @Override public void addShutdownTask(Runnable r) { synchronized (shutdownTasks) { shutdownTasks.add(0, r); } } @Override public void addShutdownDispose(IDisposable d) { synchronized (disposeTasks) { disposeTasks.add(0, d); } } @Override public void removeShutdownTask(Object o) { if(o instanceof Runnable) { synchronized (shutdownTasks) { CollectionUtilities.removeAll(shutdownTasks, (Runnable)o); } } if(o instanceof IDisposable) { synchronized (disposeTasks) { CollectionUtilities.removeAll(disposeTasks, (IDisposable)o); } } } }
3e0bc6d9c99e2995ccedaa76b3f5c0c17070e9f8
6,633
java
Java
cloud-paas-db/src/test/java/com/francetelecom/clara/cloud/db/liquibase/CompareChangeLogWithHibernateAutoCreateIT.java
orange-cloudfoundry/elpaaso-core
6257e26ba018eba4abf9087e3388cdb16fa25c48
[ "Apache-2.0" ]
null
null
null
cloud-paas-db/src/test/java/com/francetelecom/clara/cloud/db/liquibase/CompareChangeLogWithHibernateAutoCreateIT.java
orange-cloudfoundry/elpaaso-core
6257e26ba018eba4abf9087e3388cdb16fa25c48
[ "Apache-2.0" ]
2
2016-10-19T10:33:51.000Z
2021-04-22T07:30:23.000Z
cloud-paas-db/src/test/java/com/francetelecom/clara/cloud/db/liquibase/CompareChangeLogWithHibernateAutoCreateIT.java
orange-cloudfoundry/elpaaso-core
6257e26ba018eba4abf9087e3388cdb16fa25c48
[ "Apache-2.0" ]
4
2017-06-14T02:00:20.000Z
2022-02-16T04:52:52.000Z
46.384615
218
0.717322
4,973
/** * Copyright (C) 2015 Orange * 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.francetelecom.clara.cloud.db.liquibase; import com.francetelecom.clara.cloud.test.database.DbaasDatabase; import liquibase.database.Database; import liquibase.diff.DiffResult; import liquibase.diff.ObjectDifferences; import liquibase.diff.output.DiffOutputControl; import liquibase.diff.output.ObjectChangeFilter; import liquibase.diff.output.StandardObjectChangeFilter; import liquibase.diff.output.changelog.DiffToChangeLog; import liquibase.exception.LiquibaseException; import liquibase.structure.DatabaseObject; import liquibase.structure.core.Column; import org.apache.commons.io.FileUtils; import org.junit.Test; import org.junit.runner.RunWith; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.core.io.Resource; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.xml.sax.SAXException; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import java.io.*; import java.sql.SQLException; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; /** * This test compare a DB initialized using liquibase change log with a db initialiazed using hibernate automatic schema creation (hbm2ddl.auto = create) */ @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration() public abstract class CompareChangeLogWithHibernateAutoCreateIT { private static final Logger LOGGER = LoggerFactory.getLogger(CompareChangeLogWithHibernateAutoCreateIT.class.getName()); // 1st test DB initialized using hibernate in create-drop mode @Autowired DbaasDatabase db1; // 2nd test DB initialized using liquibase @Autowired DbaasDatabase db2; private final LiquibaseTestWrapper liquibaseWrapper = new LiquibaseTestWrapper(); @Test public void compare() throws SQLException, LiquibaseException, IOException, ParserConfigurationException { // Test exercise: Run diff DiffResult diffResult = liquibaseWrapper.diff( db1.getUrl(), db1.getUser(), db1.getPassword(), db2.getUrl(), db2.getUser(), db2.getPassword()); if (diffResult != null) { DiffOutputControl diffOutputControl = liquibaseWrapper.getTablespaceOnlyDiff(); ObjectChangeFilter customFilter = new ObjectChangeFilter() { StandardObjectChangeFilter columnWithDefaultValueFilter = new StandardObjectChangeFilter(StandardObjectChangeFilter.FilterType.EXCLUDE, "Column:middlewareprofileversion,Column:path,Column:servicename"); @Override public boolean includeMissing(DatabaseObject object, Database referenceDatabase, Database comparisionDatabase) { return true; } @Override public boolean includeUnexpected(DatabaseObject object, Database referenceDatabase, Database comparisionDatabase) { return true; } @Override public boolean includeChanged(DatabaseObject object, ObjectDifferences differences, Database referenceDatabase, Database comparisionDatabase) { LOGGER.debug("Check default value for {} - {} difference(s) found(s)", object, differences.getDifferences().size()); if (!(object instanceof Column)) { return true; } if (!columnWithDefaultValueFilter.includeChanged(object, differences, referenceDatabase, comparisionDatabase)) { differences.removeDifference("defaultValue"); } boolean includeChangeOnlyIfHasDifferences = differences.hasDifferences(); return includeChangeOnlyIfHasDifferences; } }; diffOutputControl.setObjectChangeFilter(customFilter); DiffToChangeLog changeLogWriter = new DiffToChangeLog(diffResult, diffOutputControl); changeLogWriter.setChangeSetAuthor("paas"); File shouldBeAnEmptyChangelog = File.createTempFile("changelogDiff-", ".xml", new File("target/")); try (PrintStream ps = new PrintStream(new FileOutputStream(shouldBeAnEmptyChangelog), true)) { changeLogWriter.print(ps); } boolean differenceFound = searchForDifferenceInXml(shouldBeAnEmptyChangelog);//FileUtils.contentEqualsIgnoreEOL(emptyChangelogFile, shouldBeAnEmptyChangelog, "UTF-8"); assertFalse("They are differences: \n" + FileUtils.readFileToString(shouldBeAnEmptyChangelog, "UTF-8"), differenceFound); } } private boolean searchForDifferenceInXml(File xmlFile) { boolean differenceFound = false; DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setValidating(false); factory.setIgnoringElementContentWhitespace(true); try { DocumentBuilder builder = factory.newDocumentBuilder(); Document document = builder.parse(xmlFile); Element databaseChangeLogRoot=document.getDocumentElement(); differenceFound=databaseChangeLogRoot.hasChildNodes(); // Do something with the document here. } catch (ParserConfigurationException | IOException |SAXException e) { LOGGER.info("Failed to parse xml file: {}",xmlFile,e); } return differenceFound; } private boolean hasDifference(DiffResult diffResult) { if (diffResult == null) { return false; } return diffResult.getChangedObjects().size() > 0 || diffResult.getMissingObjects().size() > 0 || diffResult.getUnexpectedObjects().size() > 0; } }
3e0bc736fc81ed7b1792dc8964dc58c7ea091b42
4,559
java
Java
geode-core/src/main/java/org/apache/geode/internal/logging/SortLogFile.java
Kris-10-0/geode
7ccdc8297b1ded06175f41543884d945d5995c60
[ "Apache-2.0" ]
1,475
2016-12-06T06:10:53.000Z
2022-03-30T09:55:23.000Z
geode-core/src/main/java/org/apache/geode/internal/logging/SortLogFile.java
Kris-10-0/geode
7ccdc8297b1ded06175f41543884d945d5995c60
[ "Apache-2.0" ]
2,809
2016-12-06T19:24:26.000Z
2022-03-31T22:02:20.000Z
geode-core/src/main/java/org/apache/geode/internal/logging/SortLogFile.java
Kris-10-0/geode
7ccdc8297b1ded06175f41543884d945d5995c60
[ "Apache-2.0" ]
531
2016-12-06T05:48:47.000Z
2022-03-31T23:06:37.000Z
31.659722
108
0.673174
4,974
/* * 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.geode.internal.logging; import static java.lang.System.lineSeparator; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintStream; import java.io.PrintWriter; import java.util.Collection; import java.util.TreeSet; import org.apache.geode.LogWriter; import org.apache.geode.annotations.Immutable; import org.apache.geode.internal.ExitCode; /** * This program sorts the entries in a GemFire log file (one written using a {@link LogWriter}) by * their timestamps. Note that in order to do so, we have to read the entire file into memory. * * @see MergeLogFiles * @see LogFileParser * @since GemFire 3.0 */ public class SortLogFile { @Immutable private static final PrintStream out = System.out; @Immutable private static final PrintStream err = System.err; /** * Parses a log file from a given source and writes the sorted entries to a given destination. */ public static void sortLogFile(InputStream logFile, PrintWriter sortedFile) throws IOException { Collection<LogFileParser.LogEntry> sorted = new TreeSet<>((entry1, entry2) -> { String stamp1 = entry1.getTimestamp(); String stamp2 = entry2.getTimestamp(); if (stamp1.equals(stamp2)) { if (entry1.getContents().equals(entry2.getContents())) { // Timestamps and contents are both equal - compare hashCode() return Integer.compare(entry1.hashCode(), entry2.hashCode()); } return entry1.getContents().compareTo(entry2.getContents()); } return stamp1.compareTo(stamp2); }); BufferedReader br = new BufferedReader(new InputStreamReader(logFile)); LogFileParser parser = new LogFileParser(null, br); while (parser.hasMoreEntries()) { sorted.add(parser.getNextEntry()); } for (LogFileParser.LogEntry entry : sorted) { entry.writeTo(sortedFile); } } /** * Prints usage information about this program */ private static void usage(String s) { err.println(lineSeparator() + "** " + s + lineSeparator()); err.println("Usage: java SortLogFile logFile"); err.println("-sortedFile file " + "File in which to put sorted log"); err.println(); err.println( "Sorts a GemFire log file by timestamp. The merged log file is written to System.out (or a file)."); err.println(); ExitCode.FATAL.doSystemExit(); } public static void main(String... args) throws IOException { File logFile = null; File sortedFile = null; for (int i = 0; i < args.length; i++) { if (args[i].equals("-sortedFile")) { if (++i >= args.length) { usage("Missing sorted file name"); } sortedFile = new File(args[i]); } else if (logFile == null) { File file = new File(args[i]); if (!file.exists()) { usage(String.format("File %s does not exist", file)); } logFile = file; } else { usage(String.format("Extraneous command line: %s", args[i])); } } if (logFile == null) { usage("Missing filename"); } try (InputStream logFileStream = new FileInputStream(logFile)) { PrintStream ps; if (sortedFile != null) { FileOutputStream fileOutputStream = new FileOutputStream(sortedFile); try { ps = new PrintStream(fileOutputStream, true); } catch (Exception ex) { fileOutputStream.close(); throw ex; } } else { ps = out; } sortLogFile(logFileStream, new PrintWriter(ps, true)); } ExitCode.NORMAL.doSystemExit(); } }
3e0bc78100521304f539cd6ae8332761581c8d87
1,619
java
Java
bundles/core/src/main/java/com/adobe/cq/commerce/core/components/internal/storefrontcontext/CategoryStorefrontContextImpl.java
vsaini603dev/aem-core-cif-components
a6be0dc36f0f6a330f876484539434fccba2aa35
[ "Apache-2.0" ]
81
2019-05-06T06:12:18.000Z
2022-03-29T19:38:20.000Z
bundles/core/src/main/java/com/adobe/cq/commerce/core/components/internal/storefrontcontext/CategoryStorefrontContextImpl.java
vsaini603dev/aem-core-cif-components
a6be0dc36f0f6a330f876484539434fccba2aa35
[ "Apache-2.0" ]
785
2019-05-06T06:26:47.000Z
2022-03-31T08:55:43.000Z
bundles/core/src/main/java/com/adobe/cq/commerce/core/components/internal/storefrontcontext/CategoryStorefrontContextImpl.java
vsaini603dev/aem-core-cif-components
a6be0dc36f0f6a330f876484539434fccba2aa35
[ "Apache-2.0" ]
68
2019-05-06T14:32:01.000Z
2022-03-11T00:45:47.000Z
34.446809
123
0.671402
4,975
/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~ Copyright 2021 Adobe ~ ~ 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.adobe.cq.commerce.core.components.internal.storefrontcontext; import org.apache.sling.api.resource.Resource; import com.adobe.cq.commerce.core.components.storefrontcontext.CategoryStorefrontContext; import com.adobe.cq.commerce.magento.graphql.CategoryInterface; public class CategoryStorefrontContextImpl extends AbstractCommerceStorefrontContext implements CategoryStorefrontContext { private final CategoryInterface category; public CategoryStorefrontContextImpl(CategoryInterface category, Resource resource) { super(resource); this.category = category; } @Override public String getName() { return category.getName(); } @Override public String getUrlKey() { return category.getUrlKey(); } @Override public String getUrlPath() { return category.getUrlPath(); } }
3e0bc7b0ae2f505b8a3f3e4d32fe24de12e9ab20
1,537
java
Java
lc81_SearchInRotatedArrII.java
Jcih/lc2021
dda93cee54aea094741705ef3c42e1af36ce3393
[ "MIT" ]
null
null
null
lc81_SearchInRotatedArrII.java
Jcih/lc2021
dda93cee54aea094741705ef3c42e1af36ce3393
[ "MIT" ]
null
null
null
lc81_SearchInRotatedArrII.java
Jcih/lc2021
dda93cee54aea094741705ef3c42e1af36ce3393
[ "MIT" ]
null
null
null
34.931818
104
0.427456
4,976
class Solution { public boolean search(int[] nums, int target) { //[1,2,3,4,5,6] -> [5,6,1,2,3,4], [3,4,5,6,1,2] //if (nums[mid] > nums[left]), left half is incresing //else right half is increasing //when left is increasing, need to check if target in left: nums[0] < target < num[mid] //when right is increasing, need to check if target is in right : num[mid] < target < num[right] //what need think: why miss the case that nums[left] == nums[mid] //if (nums[mid] == nums[left]) left++; //what happened if nums[mid] == nums[left], means remove duplicate, use left++ int left = 0; int right = nums.length - 1; if (nums == null || nums.length == 0) return false; while (left <= right) { int mid = left + (right - left) / 2; if (nums[mid] == target) return true; if (nums[mid] > nums[left]) { if (nums[left] <= target && nums[mid] > target) { right = mid - 1; } else { left = mid + 1; } } else if (nums[mid] < nums[left]) { if (nums[right] >= target && nums[mid] < target) { left = mid + 1; } else { right = mid - 1; } } else { left++; } } return false; } }
3e0bc7ed8a14c5670e531450f9b09c82cd8ab991
237
java
Java
hello/src/test/java/jp/co/kokou/sample/FirstJUnit5Tests.java
koko-u/junit5-sample
52d7f362f01f667a2a8419109d5c836bff2f937b
[ "MIT" ]
null
null
null
hello/src/test/java/jp/co/kokou/sample/FirstJUnit5Tests.java
koko-u/junit5-sample
52d7f362f01f667a2a8419109d5c836bff2f937b
[ "MIT" ]
null
null
null
hello/src/test/java/jp/co/kokou/sample/FirstJUnit5Tests.java
koko-u/junit5-sample
52d7f362f01f667a2a8419109d5c836bff2f937b
[ "MIT" ]
null
null
null
16.928571
57
0.691983
4,977
package jp.co.kokou.sample; import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; public class FirstJUnit5Tests { @Test void はじめてのテスト() { assertThat(1 + 1).isEqualTo(2); } }
3e0bc86c269de1457dae741bcdce43c289284056
6,334
java
Java
hekate-core/src/test/java/io/hekate/cluster/seed/jdbc/JdbcSeedNodeProviderTest.java
Inkon/hekate
abe6ec59edeaa83f0016da9ed16aae4ded7e5cab
[ "Apache-2.0" ]
null
null
null
hekate-core/src/test/java/io/hekate/cluster/seed/jdbc/JdbcSeedNodeProviderTest.java
Inkon/hekate
abe6ec59edeaa83f0016da9ed16aae4ded7e5cab
[ "Apache-2.0" ]
null
null
null
hekate-core/src/test/java/io/hekate/cluster/seed/jdbc/JdbcSeedNodeProviderTest.java
Inkon/hekate
abe6ec59edeaa83f0016da9ed16aae4ded7e5cab
[ "Apache-2.0" ]
null
null
null
30.451923
112
0.673508
4,978
/* * Copyright 2019 The Hekate Project * * The Hekate Project licenses this file to you under the Apache License, * version 2.0 (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package io.hekate.cluster.seed.jdbc; import io.hekate.cluster.seed.PersistentSeedNodeProviderTestBase; import io.hekate.core.HekateException; import io.hekate.test.JdbcTestDataSources; import java.net.InetSocketAddress; import java.sql.Connection; import java.sql.SQLException; import java.sql.Statement; import java.util.Collection; import javax.sql.DataSource; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; @RunWith(Parameterized.class) public class JdbcSeedNodeProviderTest extends PersistentSeedNodeProviderTestBase<JdbcSeedNodeProvider> { private final DataSource ds; private Connection keepDbAlive; public JdbcSeedNodeProviderTest(DataSource ds) { this.ds = ds; } @Parameters(name = "{index}:{0}") public static Collection<DataSource> getDataSources() { return JdbcTestDataSources.all(); } public static void initializeDatabase(DataSource ds, JdbcSeedNodeProviderConfig cfg) throws SQLException { try (Connection conn = ds.getConnection()) { initializeDatabase(conn, cfg); } } public static void initializeDatabase(Connection conn, JdbcSeedNodeProviderConfig cfg) throws SQLException { try ( Statement st = conn.createStatement() ) { String sql = "CREATE TABLE IF NOT EXISTS " + cfg.getTable() + " (" + cfg.getHostColumn() + " VARCHAR(255)," + cfg.getPortColumn() + " INT, " + cfg.getClusterColumn() + " VARCHAR(255) " + ")"; st.execute(sql); } } @Override public void setUp() throws Exception { super.setUp(); keepDbAlive = datasource().getConnection(); } @Override public void tearDown() throws Exception { super.tearDown(); if (keepDbAlive != null) { try { keepDbAlive.close(); } finally { keepDbAlive = null; } } } @Test public void testDbErrorOnStopDiscovery() throws Exception { BrokenDataSourceMock errDs = new BrokenDataSourceMock(datasource()); JdbcSeedNodeProvider provider = createProvider(errDs); errDs.scheduleErrors(1); InetSocketAddress address = newSocketAddress(10001); try { provider.startDiscovery(CLUSTER_1, address); fail(); } catch (HekateException e) { assertTrue("Cause:" + e.getCause(), e.isCausedBy(SQLException.class)); } assertTrue(provider.findSeedNodes(CLUSTER_1).isEmpty()); provider.startDiscovery(CLUSTER_1, address); assertEquals(address, provider.findSeedNodes(CLUSTER_1).get(0)); provider.stopDiscovery(CLUSTER_1, address); assertTrue(provider.findSeedNodes(CLUSTER_1).isEmpty()); } @Test public void testDbErrorOnStartDiscovery() throws Exception { BrokenDataSourceMock errDs = new BrokenDataSourceMock(datasource()); JdbcSeedNodeProvider provider = createProvider(errDs); InetSocketAddress address = newSocketAddress(10001); provider.startDiscovery(CLUSTER_1, address); assertFalse(provider.findSeedNodes(CLUSTER_1).isEmpty()); assertEquals(address, provider.findSeedNodes(CLUSTER_1).get(0)); errDs.scheduleErrors(1); try { provider.stopDiscovery(CLUSTER_1, address); fail(); } catch (HekateException e) { assertTrue("Cause:" + e.getCause(), e.isCausedBy(SQLException.class)); } assertFalse(provider.findSeedNodes(CLUSTER_1).isEmpty()); assertEquals(address, provider.findSeedNodes(CLUSTER_1).get(0)); provider.stopDiscovery(CLUSTER_1, address); assertTrue(provider.findSeedNodes(CLUSTER_1).isEmpty()); } @Test public void testDbErrorOnGetNodes() throws Exception { BrokenDataSourceMock errDs = new BrokenDataSourceMock(datasource()); JdbcSeedNodeProvider provider = createProvider(errDs); InetSocketAddress address = newSocketAddress(10001); provider.startDiscovery(CLUSTER_1, address); assertFalse(provider.findSeedNodes(CLUSTER_1).isEmpty()); assertEquals(address, provider.findSeedNodes(CLUSTER_1).get(0)); errDs.scheduleErrors(1); try { provider.findSeedNodes(CLUSTER_1); fail(); } catch (HekateException e) { assertTrue("Cause:" + e.getCause(), e.isCausedBy(SQLException.class)); } assertFalse(provider.findSeedNodes(CLUSTER_1).isEmpty()); assertEquals(address, provider.findSeedNodes(CLUSTER_1).get(0)); provider.stopDiscovery(CLUSTER_1, address); assertTrue(provider.findSeedNodes(CLUSTER_1).isEmpty()); } public DataSource datasource() { return ds; } protected JdbcSeedNodeProviderConfig createConfig() { return new JdbcSeedNodeProviderConfig(); } @Override protected JdbcSeedNodeProvider createProvider() throws Exception { return createProvider(datasource()); } private JdbcSeedNodeProvider createProvider(DataSource ds) throws Exception { JdbcSeedNodeProviderConfig cfg = createConfig(); initializeDatabase(ds, cfg); cfg.setDataSource(ds); cfg.setCleanupInterval(100); return new JdbcSeedNodeProvider(cfg); } }
3e0bc8befe66e253f8111f00a751bb8509c0c6a3
2,778
java
Java
src/main/java/org/javarosa/core/util/PropertyUtils.java
neal0892/javarosa
72d1c1942f12548723e637c8c65e3efbd2a3f447
[ "Apache-2.0" ]
38
2017-04-05T18:11:27.000Z
2020-01-06T17:28:43.000Z
src/main/java/org/javarosa/core/util/PropertyUtils.java
neal0892/javarosa
72d1c1942f12548723e637c8c65e3efbd2a3f447
[ "Apache-2.0" ]
428
2016-11-23T18:31:26.000Z
2020-04-18T02:29:21.000Z
src/main/java/org/javarosa/core/util/PropertyUtils.java
GetODK/javarosa
adde512b7e7098e111f39eec1ae648f7e5d01475
[ "Apache-2.0" ]
105
2017-02-01T08:29:50.000Z
2020-04-15T10:16:27.000Z
34.296296
165
0.643269
4,979
/* * Copyright (C) 2009 JavaRosa * * 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.javarosa.core.util; import java.util.ArrayList; import java.util.List; import java.util.Random; import org.javarosa.core.services.PropertyManager; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class PropertyUtils { private static final Logger logger = LoggerFactory.getLogger(PropertyUtils.class); //need 'addpropery' too. public static String initializeProperty(String propName, String defaultValue) { List<String> propVal = PropertyManager.__().getProperty(propName); if (propVal == null || propVal.size() == 0) { propVal = new ArrayList<String>(1); propVal.add(defaultValue); PropertyManager.__().setProperty(propName, propVal); logger.info("No default value for [{}]; setting to [{}]", propName, defaultValue); // debug return defaultValue; } return propVal.get(0); } /** * Generate an RFC 4122 Version 4 UUID. * * @return a uuid */ public static String genUUID() { return randHex(8) + "-" + randHex(4) + "-4" + randHex(3) + "-" + Integer.toString(8 + MathUtils.getRand().nextInt(4), 16) + randHex(3) + "-" + randHex(12); } /** * Create a globally unique identifier string in no particular format * with len characters of randomness. * * @param len The length of the string identifier requested. * @return A string containing len characters of random data. */ public static String genGUID(int len) { StringBuilder b = new StringBuilder(); for (int i = 0; i < len; i++) { // 25 == 128 bits of entropy b.append(Integer.toString(MathUtils.getRand().nextInt(36), 36)); } return b.toString().toUpperCase(); } public static String randHex(int len) { StringBuilder b = new StringBuilder(); Random r = MathUtils.getRand(); for(int i = 0 ; i < len; ++i) { b.append(Integer.toString(r.nextInt(16), 16)); } return b.toString(); } public static String trim (String guid, int len) { return guid.substring(0, Math.min(len, guid.length())); } }
3e0bc9b5b4968ab53f3b59ed8175489f890b7b98
1,717
java
Java
samples/src/main/java/tk/zielony/carbonsamples/animation/WidgetAnimationsActivity.java
geniusgeek/Carbon
2c149b11fa9497e28d1e123ff228893eb2bc59cd
[ "Apache-2.0" ]
null
null
null
samples/src/main/java/tk/zielony/carbonsamples/animation/WidgetAnimationsActivity.java
geniusgeek/Carbon
2c149b11fa9497e28d1e123ff228893eb2bc59cd
[ "Apache-2.0" ]
null
null
null
samples/src/main/java/tk/zielony/carbonsamples/animation/WidgetAnimationsActivity.java
geniusgeek/Carbon
2c149b11fa9497e28d1e123ff228893eb2bc59cd
[ "Apache-2.0" ]
1
2018-10-19T14:50:52.000Z
2018-10-19T14:50:52.000Z
32.396226
63
0.584741
4,980
package tk.zielony.carbonsamples.animation; import android.app.Activity; import android.os.Bundle; import android.view.View; import android.widget.Button; import tk.zielony.carbonsamples.R; /** * Created by Marcin on 2014-12-15. */ public class WidgetAnimationsActivity extends Activity { int fabVisibility = View.VISIBLE; int buttonVisibility = View.VISIBLE; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_animations); final View fab = findViewById(R.id.fab); Button button = (Button) findViewById(R.id.button); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (fabVisibility != View.VISIBLE) { fab.setVisibility(View.VISIBLE); fabVisibility = View.VISIBLE; } else { fab.setVisibility(View.INVISIBLE); fabVisibility = View.INVISIBLE; } } }); final View button2 = findViewById(R.id.button2); Button button3 = (Button) findViewById(R.id.button3); button3.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (buttonVisibility != View.VISIBLE) { button2.setVisibility(View.VISIBLE); buttonVisibility = View.VISIBLE; } else { button2.setVisibility(View.INVISIBLE); buttonVisibility = View.INVISIBLE; } } }); } }
3e0bc9dd0822e49442152876dda34a00c04f9cfc
1,112
java
Java
1.1/src/cz/mg/vulkan/PFNvkFreeCommandBuffers.java
Gekoncze/MgVulkan
2d2ebc0d3df6640d1f18cff32e9782542b0a441e
[ "BSD-3-Clause" ]
null
null
null
1.1/src/cz/mg/vulkan/PFNvkFreeCommandBuffers.java
Gekoncze/MgVulkan
2d2ebc0d3df6640d1f18cff32e9782542b0a441e
[ "BSD-3-Clause" ]
null
null
null
1.1/src/cz/mg/vulkan/PFNvkFreeCommandBuffers.java
Gekoncze/MgVulkan
2d2ebc0d3df6640d1f18cff32e9782542b0a441e
[ "BSD-3-Clause" ]
null
null
null
34.75
286
0.741906
4,981
package cz.mg.vulkan; public class PFNvkFreeCommandBuffers extends VkFunctionPointer { public PFNvkFreeCommandBuffers() { } protected PFNvkFreeCommandBuffers(VkMemory vkmemory) { super(vkmemory); } protected PFNvkFreeCommandBuffers(VkMemory vkmemory, long vkaddress) { super(vkmemory, vkaddress); } public PFNvkFreeCommandBuffers(long value) { setValue(value); } public PFNvkFreeCommandBuffers(VkInstance instance) { super(instance, new VkString("vkFreeCommandBuffers")); } public void call(VkDevice device, VkCommandPool commandPool, int commandBufferCount, VkCommandBuffer pCommandBuffers){ callNative(getValue(), device != null ? device.getVkAddress() : VkPointer.getNullAddressNative(), commandPool != null ? commandPool.getVkAddress() : VkPointer.getNullAddressNative(), commandBufferCount, pCommandBuffers != null ? pCommandBuffers.getVkAddress() : VkPointer.NULL); } protected static native void callNative(long vkaddress, long device, long commandPool, int commandBufferCount, long pCommandBuffers); }
3e0bca11989c5248cb8a0ae9daa01708565f4737
8,467
java
Java
meta/src/main/java/org/jboss/hal/meta/description/ResourceDescription.java
yersan/console
f191b056f853628813909524c40ff9d6846c8c2e
[ "Apache-2.0" ]
25
2018-04-02T13:35:05.000Z
2021-11-28T03:28:35.000Z
meta/src/main/java/org/jboss/hal/meta/description/ResourceDescription.java
yersan/console
f191b056f853628813909524c40ff9d6846c8c2e
[ "Apache-2.0" ]
160
2018-03-29T07:23:42.000Z
2022-03-24T13:13:49.000Z
meta/src/main/java/org/jboss/hal/meta/description/ResourceDescription.java
yersan/console
f191b056f853628813909524c40ff9d6846c8c2e
[ "Apache-2.0" ]
63
2018-03-30T06:47:58.000Z
2021-11-11T16:06:06.000Z
36.65368
120
0.609779
4,982
/* * Copyright 2015-2016 Red Hat, Inc, and individual contributors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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.jboss.hal.meta.description; import java.util.List; import jsinterop.annotations.JsIgnore; import jsinterop.annotations.JsMethod; import jsinterop.annotations.JsProperty; import jsinterop.annotations.JsType; import org.jboss.hal.dmr.ModelNode; import org.jboss.hal.dmr.ModelNodeHelper; import org.jboss.hal.dmr.ModelType; import org.jboss.hal.dmr.Property; import org.jboss.hal.spi.EsReturn; import static java.util.Collections.emptyList; import static java.util.stream.Collectors.toList; import static org.jboss.hal.dmr.ModelDescriptionConstants.*; /** Contains the resource and attribute descriptions from the read-resource-description operation. */ /* TODO Refactor methods which use the 'path' parameter (too error prone). Instead use a fluent API: * * ResourceDescription description = ...; * * // attributes from the resource description * Property attribute = description.atrributes().get("foo"); * List<Property> attributes = description.atrributes().group("bar"); * List<Property> attributes = description.atrributes().required(); * * // request properties of the ADD operation * Property attribute = description.requestProperties().get("foo"); * List<Property> attributes = description.requestProperties().group("bar"); * List<Property> attributes = description.requestProperties().required(); */ @JsType(namespace = "hal.meta") public class ResourceDescription extends ModelNode { @JsIgnore public ResourceDescription(ModelNode payload) { set(payload); } /** @return the resource description */ @JsProperty public String getDescription() { return get(DESCRIPTION).asString(); } @JsIgnore public List<Property> getAttributes(String path) { ModelNode attributes = ModelNodeHelper.failSafeGet(this, path); if (attributes.isDefined()) { return attributes.asPropertyList(); } return emptyList(); } @JsIgnore public List<Property> getAttributes(String path, String group) { List<Property> attributes = getAttributes(path); return attributes.stream() .filter(property -> { ModelNode attributeDescription = property.getValue(); return attributeDescription.hasDefined(ATTRIBUTE_GROUP) && group.equals(attributeDescription.get(ATTRIBUTE_GROUP).asString()); }) .collect(toList()); } @JsIgnore public List<Property> getRequiredAttributes(String path) { return getAttributes(path).stream() .filter(property -> { ModelNode attributeDescription = property.getValue(); if (attributeDescription.hasDefined(REQUIRED)) { return attributeDescription.get(REQUIRED).asBoolean(); } else if (attributeDescription.hasDefined(NILLABLE)) { return !attributeDescription.get(NILLABLE).asBoolean(); } return false; }) .collect(toList()); } @JsIgnore public List<Property> getOperations() { return hasDefined(OPERATIONS) ? get(OPERATIONS).asPropertyList() : emptyList(); } @JsIgnore public Property findOperation(String name) { if (hasDefined(OPERATIONS)) { for (Property property : get(OPERATIONS).asPropertyList()) { if (name.equals(property.getName())) { return property; } } } return null; } @JsIgnore public Property findAttribute(String path, String name) { for (Property property : getAttributes(path)) { if (name.equals(property.getName())) { return property; } } return null; } /** * Returns the alternatives for the specified attribute. * * @param path the path to look for the attribute * @param name the name of the attribute * * @return the alternatives for {@code name} or an empty list if {@code name} has no alternatives or if there's no * attribute {@code name} */ @JsIgnore public List<String> findAlternatives(String path, String name) { Property attribute = findAttribute(path, name); if (attribute != null) { if (attribute.getValue().hasDefined(ALTERNATIVES)) { return attribute.getValue().get(ALTERNATIVES).asList().stream() .map(ModelNode::asString) .collect(toList()); } } return emptyList(); } /** * Returns the attributes which require the specified attribute. * * @param path the path to look for the attribute * @param name the name of the attribute which is required by the matching attributes * * @return the attributes which require {@code} or an empty list if no attributes require {@code name} or if there's * no attribute {@code name} */ @JsIgnore public List<String> findRequires(String path, String name) { return getAttributes(path).stream() .filter(attribute -> { if (attribute.getValue().hasDefined(REQUIRES)) { List<String> requires = attribute.getValue().get(REQUIRES).asList().stream() .map(ModelNode::asString) .collect(toList()); return requires.contains(name); } return false; }) .map(Property::getName) .collect(toList()); } @JsIgnore public boolean isDefaultValue(String path, String name, Object value) { Property property = findAttribute(path, name); if (property != null) { ModelNode attribute = property.getValue(); if (attribute.hasDefined(DEFAULT)) { if (value == null) { return true; } else { ModelType type = attribute.get(TYPE).asType(); if (type.equals(ModelType.INT)) { type = ModelType.LONG; } Object defaultValue = attribute.get(DEFAULT).as(type); return value.equals(defaultValue); } } } return false; } @JsIgnore public boolean isDeprecated(String path, String name) { Property property = findAttribute(path, name); if (property != null) { ModelNode attribute = property.getValue(); return ModelNodeHelper.failSafeBoolean(attribute, DEPRECATED); } return false; } // ------------------------------------------------------ JS methods /** @return the attribute descriptions */ @JsMethod(name = "getAttributes") @EsReturn("Property[]") public Property[] jsGetAttributes() { List<Property> attributes = getAttributes(ATTRIBUTES); return attributes.toArray(new Property[attributes.size()]); } /** @return the request properties of the add operation */ @JsMethod(name = "getRequestProperties") @EsReturn("Property[]") public Property[] jsGetRequestProperties() { List<Property> attributes = getAttributes(OPERATIONS + "/" + ADD + "/" + REQUEST_PROPERTIES); return attributes.toArray(new Property[attributes.size()]); } /** @return the operation descriptions */ @JsProperty(name = "operations") @EsReturn("Property[]") public Property[] jsOperations() { List<Property> operations = getOperations(); return operations.toArray(new Property[operations.size()]); } }
3e0bcc0d1506d37467ac79c4487ac6469b8a5cbb
136,761
java
Java
sdk/cosmos/microsoft-azure-cosmos/src/main/java/com/azure/data/cosmos/internal/RxDocumentClientImpl.java
minaltolpadi/azure-sdk-for-java
a6bb33fc71f21ee92d4246d6b5fe30ad8a5689cb
[ "MIT" ]
2
2019-09-08T18:59:20.000Z
2019-09-25T20:09:53.000Z
sdk/cosmos/microsoft-azure-cosmos/src/main/java/com/azure/data/cosmos/internal/RxDocumentClientImpl.java
minaltolpadi/azure-sdk-for-java
a6bb33fc71f21ee92d4246d6b5fe30ad8a5689cb
[ "MIT" ]
1
2019-09-24T09:52:55.000Z
2019-09-24T09:52:55.000Z
sdk/cosmos/microsoft-azure-cosmos/src/main/java/com/azure/data/cosmos/internal/RxDocumentClientImpl.java
minaltolpadi/azure-sdk-for-java
a6bb33fc71f21ee92d4246d6b5fe30ad8a5689cb
[ "MIT" ]
1
2019-10-05T04:59:12.000Z
2019-10-05T04:59:12.000Z
49.425732
195
0.648101
4,983
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. package com.azure.data.cosmos.internal; import com.azure.data.cosmos.AccessConditionType; import com.azure.data.cosmos.BridgeInternal; import com.azure.data.cosmos.ChangeFeedOptions; import com.azure.data.cosmos.ConnectionMode; import com.azure.data.cosmos.ConnectionPolicy; import com.azure.data.cosmos.ConsistencyLevel; import com.azure.data.cosmos.CosmosKeyCredential; import com.azure.data.cosmos.CosmosResourceType; import com.azure.data.cosmos.DatabaseAccount; import com.azure.data.cosmos.FeedOptions; import com.azure.data.cosmos.FeedResponse; import com.azure.data.cosmos.JsonSerializable; import com.azure.data.cosmos.PartitionKey; import com.azure.data.cosmos.PartitionKeyDefinition; import com.azure.data.cosmos.Resource; import com.azure.data.cosmos.SqlQuerySpec; import com.azure.data.cosmos.TokenResolver; import com.azure.data.cosmos.internal.caches.RxClientCollectionCache; import com.azure.data.cosmos.internal.caches.RxCollectionCache; import com.azure.data.cosmos.internal.caches.RxPartitionKeyRangeCache; import com.azure.data.cosmos.internal.directconnectivity.GatewayServiceConfigurationReader; import com.azure.data.cosmos.internal.directconnectivity.GlobalAddressResolver; import com.azure.data.cosmos.internal.directconnectivity.ServerStoreModel; import com.azure.data.cosmos.internal.directconnectivity.StoreClient; import com.azure.data.cosmos.internal.directconnectivity.StoreClientFactory; import com.azure.data.cosmos.internal.http.HttpClient; import com.azure.data.cosmos.internal.http.HttpClientConfig; import com.azure.data.cosmos.internal.query.DocumentQueryExecutionContextFactory; import com.azure.data.cosmos.internal.query.IDocumentQueryClient; import com.azure.data.cosmos.internal.query.IDocumentQueryExecutionContext; import com.azure.data.cosmos.internal.query.Paginator; import com.azure.data.cosmos.internal.routing.PartitionKeyAndResourceTokenPair; import com.azure.data.cosmos.internal.routing.PartitionKeyInternal; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ObjectNode; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.URI; import java.net.URISyntaxException; import java.net.URLEncoder; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.UUID; import java.util.function.BiFunction; import java.util.function.Function; import static com.azure.data.cosmos.BridgeInternal.documentFromObject; import static com.azure.data.cosmos.BridgeInternal.getAltLink; import static com.azure.data.cosmos.BridgeInternal.toDatabaseAccount; import static com.azure.data.cosmos.BridgeInternal.toFeedResponsePage; import static com.azure.data.cosmos.BridgeInternal.toResourceResponse; import static com.azure.data.cosmos.BridgeInternal.toStoredProcedureResponse; /** * While this class is public, but it is not part of our published public APIs. * This is meant to be internally used only by our sdk. */ public class RxDocumentClientImpl implements AsyncDocumentClient, IAuthorizationTokenProvider { private final static ObjectMapper mapper = Utils.getSimpleObjectMapper(); private final Logger logger = LoggerFactory.getLogger(RxDocumentClientImpl.class); private final String masterKeyOrResourceToken; private final URI serviceEndpoint; private final ConnectionPolicy connectionPolicy; private final ConsistencyLevel consistencyLevel; private final BaseAuthorizationTokenProvider authorizationTokenProvider; private final UserAgentContainer userAgentContainer; private final boolean hasAuthKeyResourceToken; private final Configs configs; private CosmosKeyCredential cosmosKeyCredential; private TokenResolver tokenResolver; private SessionContainer sessionContainer; private String firstResourceTokenFromPermissionFeed = StringUtils.EMPTY; private RxClientCollectionCache collectionCache; private RxStoreModel gatewayProxy; private RxStoreModel storeModel; private GlobalAddressResolver addressResolver; private RxPartitionKeyRangeCache partitionKeyRangeCache; private Map<String, List<PartitionKeyAndResourceTokenPair>> resourceTokensMap; // RetryPolicy retries a request when it encounters session unavailable (see ClientRetryPolicy). // Once it exhausts all write regions it clears the session container, then it uses RxClientCollectionCache // to resolves the request's collection name. If it differs from the session container's resource id it // explains the session unavailable exception: somebody removed and recreated the collection. In this // case we retry once again (with empty session token) otherwise we return the error to the client // (see RenameCollectionAwareClientRetryPolicy) private IRetryPolicyFactory resetSessionTokenRetryPolicy; /** * Compatibility mode: Allows to specify compatibility mode used by client when * making query requests. Should be removed when application/sql is no longer * supported. */ private final QueryCompatibilityMode queryCompatibilityMode = QueryCompatibilityMode.Default; private final HttpClient reactorHttpClient; private final GlobalEndpointManager globalEndpointManager; private final RetryPolicy retryPolicy; private volatile boolean useMultipleWriteLocations; // creator of TransportClient is responsible for disposing it. private StoreClientFactory storeClientFactory; private GatewayServiceConfigurationReader gatewayConfigurationReader; public RxDocumentClientImpl(URI serviceEndpoint, String masterKeyOrResourceToken, List<Permission> permissionFeed, ConnectionPolicy connectionPolicy, ConsistencyLevel consistencyLevel, Configs configs, TokenResolver tokenResolver, CosmosKeyCredential cosmosKeyCredential) { this(serviceEndpoint, masterKeyOrResourceToken, permissionFeed, connectionPolicy, consistencyLevel, configs, cosmosKeyCredential); this.tokenResolver = tokenResolver; } private RxDocumentClientImpl(URI serviceEndpoint, String masterKeyOrResourceToken, List<Permission> permissionFeed, ConnectionPolicy connectionPolicy, ConsistencyLevel consistencyLevel, Configs configs, CosmosKeyCredential cosmosKeyCredential) { this(serviceEndpoint, masterKeyOrResourceToken, connectionPolicy, consistencyLevel, configs, cosmosKeyCredential); if (permissionFeed != null && permissionFeed.size() > 0) { this.resourceTokensMap = new HashMap<>(); for (Permission permission : permissionFeed) { String[] segments = StringUtils.split(permission.getResourceLink(), Constants.Properties.PATH_SEPARATOR.charAt(0)); if (segments.length <= 0) { throw new IllegalArgumentException("resourceLink"); } List<PartitionKeyAndResourceTokenPair> partitionKeyAndResourceTokenPairs = null; PathInfo pathInfo = new PathInfo(false, StringUtils.EMPTY, StringUtils.EMPTY, false); if (!PathsHelper.tryParsePathSegments(permission.getResourceLink(), pathInfo, null)) { throw new IllegalArgumentException(permission.getResourceLink()); } partitionKeyAndResourceTokenPairs = resourceTokensMap.get(pathInfo.resourceIdOrFullName); if (partitionKeyAndResourceTokenPairs == null) { partitionKeyAndResourceTokenPairs = new ArrayList<>(); this.resourceTokensMap.put(pathInfo.resourceIdOrFullName, partitionKeyAndResourceTokenPairs); } PartitionKey partitionKey = permission.getResourcePartitionKey(); partitionKeyAndResourceTokenPairs.add(new PartitionKeyAndResourceTokenPair( partitionKey != null ? partitionKey.getInternalPartitionKey() : PartitionKeyInternal.Empty, permission.getToken())); logger.debug("Initializing resource token map , with map key [{}] , partition key [{}] and resource token", pathInfo.resourceIdOrFullName, partitionKey != null ? partitionKey.toString() : null, permission.getToken()); } if(this.resourceTokensMap.isEmpty()) { throw new IllegalArgumentException("permissionFeed"); } String firstToken = permissionFeed.get(0).getToken(); if(ResourceTokenAuthorizationHelper.isResourceToken(firstToken)) { this.firstResourceTokenFromPermissionFeed = firstToken; } } } RxDocumentClientImpl(URI serviceEndpoint, String masterKeyOrResourceToken, ConnectionPolicy connectionPolicy, ConsistencyLevel consistencyLevel, Configs configs, CosmosKeyCredential cosmosKeyCredential) { logger.info( "Initializing DocumentClient with" + " serviceEndpoint [{}], connectionPolicy [{}], consistencyLevel [{}], directModeProtocol [{}]", serviceEndpoint, connectionPolicy, consistencyLevel, configs.getProtocol()); this.configs = configs; this.masterKeyOrResourceToken = masterKeyOrResourceToken; this.serviceEndpoint = serviceEndpoint; this.cosmosKeyCredential = cosmosKeyCredential; if (this.cosmosKeyCredential != null) { hasAuthKeyResourceToken = false; this.authorizationTokenProvider = new BaseAuthorizationTokenProvider(this.cosmosKeyCredential); } else if (masterKeyOrResourceToken != null && ResourceTokenAuthorizationHelper.isResourceToken(masterKeyOrResourceToken)) { this.authorizationTokenProvider = null; hasAuthKeyResourceToken = true; } else if(masterKeyOrResourceToken != null && !ResourceTokenAuthorizationHelper.isResourceToken(masterKeyOrResourceToken)){ this.cosmosKeyCredential = new CosmosKeyCredential(this.masterKeyOrResourceToken); hasAuthKeyResourceToken = false; this.authorizationTokenProvider = new BaseAuthorizationTokenProvider(this.cosmosKeyCredential); } else { hasAuthKeyResourceToken = false; this.authorizationTokenProvider = null; } if (connectionPolicy != null) { this.connectionPolicy = connectionPolicy; } else { this.connectionPolicy = new ConnectionPolicy(); } this.sessionContainer = new SessionContainer(this.serviceEndpoint.getHost()); this.consistencyLevel = consistencyLevel; this.userAgentContainer = new UserAgentContainer(); String userAgentSuffix = this.connectionPolicy.userAgentSuffix(); if (userAgentSuffix != null && userAgentSuffix.length() > 0) { userAgentContainer.setSuffix(userAgentSuffix); } this.reactorHttpClient = httpClient(); this.globalEndpointManager = new GlobalEndpointManager(asDatabaseAccountManagerInternal(), this.connectionPolicy, /**/configs); this.retryPolicy = new RetryPolicy(this.globalEndpointManager, this.connectionPolicy); this.resetSessionTokenRetryPolicy = retryPolicy; } private void initializeGatewayConfigurationReader() { String resourceToken; if(this.tokenResolver != null) { resourceToken = this.tokenResolver.getAuthorizationToken("GET", "", CosmosResourceType.System, null); } else if(!this.hasAuthKeyResourceToken && this.authorizationTokenProvider == null) { resourceToken = this.firstResourceTokenFromPermissionFeed; } else { assert this.masterKeyOrResourceToken != null || this.cosmosKeyCredential != null; resourceToken = this.masterKeyOrResourceToken; } this.gatewayConfigurationReader = new GatewayServiceConfigurationReader(this.serviceEndpoint, this.hasAuthKeyResourceToken, resourceToken, this.connectionPolicy, this.authorizationTokenProvider, this.reactorHttpClient); DatabaseAccount databaseAccount = this.gatewayConfigurationReader.initializeReaderAsync().block(); this.useMultipleWriteLocations = this.connectionPolicy.usingMultipleWriteLocations() && BridgeInternal.isEnableMultipleWriteLocations(databaseAccount); // TODO: add support for openAsync // https://msdata.visualstudio.com/CosmosDB/_workitems/edit/332589 this.globalEndpointManager.refreshLocationAsync(databaseAccount).block(); } public void init() { // TODO: add support for openAsync // https://msdata.visualstudio.com/CosmosDB/_workitems/edit/332589 this.gatewayProxy = createRxGatewayProxy(this.sessionContainer, this.consistencyLevel, this.queryCompatibilityMode, this.userAgentContainer, this.globalEndpointManager, this.reactorHttpClient); this.globalEndpointManager.init(); this.initializeGatewayConfigurationReader(); this.collectionCache = new RxClientCollectionCache(this.sessionContainer, this.gatewayProxy, this, this.retryPolicy); this.resetSessionTokenRetryPolicy = new ResetSessionTokenRetryPolicyFactory(this.sessionContainer, this.collectionCache, this.retryPolicy); this.partitionKeyRangeCache = new RxPartitionKeyRangeCache(RxDocumentClientImpl.this, collectionCache); if (this.connectionPolicy.connectionMode() == ConnectionMode.GATEWAY) { this.storeModel = this.gatewayProxy; } else { this.initializeDirectConnectivity(); } } private void initializeDirectConnectivity() { this.storeClientFactory = new StoreClientFactory( this.configs, this.connectionPolicy.requestTimeoutInMillis() / 1000, // this.maxConcurrentConnectionOpenRequests, 0, this.userAgentContainer ); this.addressResolver = new GlobalAddressResolver( this.reactorHttpClient, this.globalEndpointManager, this.configs.getProtocol(), this, this.collectionCache, this.partitionKeyRangeCache, userAgentContainer, // TODO: GATEWAY Configuration Reader // this.gatewayConfigurationReader, null, this.connectionPolicy); this.createStoreModel(true); } DatabaseAccountManagerInternal asDatabaseAccountManagerInternal() { return new DatabaseAccountManagerInternal() { @Override public URI getServiceEndpoint() { return RxDocumentClientImpl.this.getServiceEndpoint(); } @Override public Flux<DatabaseAccount> getDatabaseAccountFromEndpoint(URI endpoint) { logger.info("Getting database account endpoint from {}", endpoint); return RxDocumentClientImpl.this.getDatabaseAccountFromEndpoint(endpoint); } @Override public ConnectionPolicy getConnectionPolicy() { return RxDocumentClientImpl.this.getConnectionPolicy(); } }; } RxGatewayStoreModel createRxGatewayProxy(ISessionContainer sessionContainer, ConsistencyLevel consistencyLevel, QueryCompatibilityMode queryCompatibilityMode, UserAgentContainer userAgentContainer, GlobalEndpointManager globalEndpointManager, HttpClient httpClient) { return new RxGatewayStoreModel(sessionContainer, consistencyLevel, queryCompatibilityMode, userAgentContainer, globalEndpointManager, httpClient); } private HttpClient httpClient() { HttpClientConfig httpClientConfig = new HttpClientConfig(this.configs) .withMaxIdleConnectionTimeoutInMillis(this.connectionPolicy.idleConnectionTimeoutInMillis()) .withPoolSize(this.connectionPolicy.maxPoolSize()) .withHttpProxy(this.connectionPolicy.proxy()) .withRequestTimeoutInMillis(this.connectionPolicy.requestTimeoutInMillis()); return HttpClient.createFixed(httpClientConfig); } private void createStoreModel(boolean subscribeRntbdStatus) { // EnableReadRequestsFallback, if not explicitly set on the connection policy, // is false if the account's consistency is bounded staleness, // and true otherwise. StoreClient storeClient = this.storeClientFactory.createStoreClient( this.addressResolver, this.sessionContainer, this.gatewayConfigurationReader, this, false ); this.storeModel = new ServerStoreModel(storeClient); } @Override public URI getServiceEndpoint() { return this.serviceEndpoint; } @Override public URI getWriteEndpoint() { return globalEndpointManager.getWriteEndpoints().stream().findFirst().map(loc -> { try { return loc.toURI(); } catch (URISyntaxException e) { throw new IllegalStateException(e); } }).orElse(null); } @Override public URI getReadEndpoint() { return globalEndpointManager.getReadEndpoints().stream().findFirst().map(loc -> { try { return loc.toURI(); } catch (URISyntaxException e) { throw new IllegalStateException(e); } }).orElse(null); } @Override public ConnectionPolicy getConnectionPolicy() { return this.connectionPolicy; } @Override public Flux<ResourceResponse<Database>> createDatabase(Database database, RequestOptions options) { IDocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> createDatabaseInternal(database, options, retryPolicyInstance), retryPolicyInstance); } private Flux<ResourceResponse<Database>> createDatabaseInternal(Database database, RequestOptions options, IDocumentClientRetryPolicy retryPolicyInstance) { try { if (database == null) { throw new IllegalArgumentException("Database"); } logger.debug("Creating a Database. id: [{}]", database.id()); validateResource(database); Map<String, String> requestHeaders = this.getRequestHeaders(options); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(OperationType.Create, ResourceType.Database, Paths.DATABASES_ROOT, database, requestHeaders, options); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } return this.create(request).map(response -> toResourceResponse(response, Database.class)); } catch (Exception e) { logger.debug("Failure in creating a database. due to [{}]", e.getMessage(), e); return Flux.error(e); } } @Override public Flux<ResourceResponse<Database>> deleteDatabase(String databaseLink, RequestOptions options) { IDocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> deleteDatabaseInternal(databaseLink, options, retryPolicyInstance), retryPolicyInstance); } private Flux<ResourceResponse<Database>> deleteDatabaseInternal(String databaseLink, RequestOptions options, IDocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(databaseLink)) { throw new IllegalArgumentException("databaseLink"); } logger.debug("Deleting a Database. databaseLink: [{}]", databaseLink); String path = Utils.joinPath(databaseLink, null); Map<String, String> requestHeaders = this.getRequestHeaders(options); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(OperationType.Delete, ResourceType.Database, path, requestHeaders, options); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } return this.delete(request).map(response -> toResourceResponse(response, Database.class)); } catch (Exception e) { logger.debug("Failure in deleting a database. due to [{}]", e.getMessage(), e); return Flux.error(e); } } @Override public Flux<ResourceResponse<Database>> readDatabase(String databaseLink, RequestOptions options) { IDocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> readDatabaseInternal(databaseLink, options, retryPolicyInstance), retryPolicyInstance); } private Flux<ResourceResponse<Database>> readDatabaseInternal(String databaseLink, RequestOptions options, IDocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(databaseLink)) { throw new IllegalArgumentException("databaseLink"); } logger.debug("Reading a Database. databaseLink: [{}]", databaseLink); String path = Utils.joinPath(databaseLink, null); Map<String, String> requestHeaders = this.getRequestHeaders(options); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(OperationType.Read, ResourceType.Database, path, requestHeaders, options); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } return this.read(request).map(response -> toResourceResponse(response, Database.class)); } catch (Exception e) { logger.debug("Failure in reading a database. due to [{}]", e.getMessage(), e); return Flux.error(e); } } @Override public Flux<FeedResponse<Database>> readDatabases(FeedOptions options) { return readFeed(options, ResourceType.Database, Database.class, Paths.DATABASES_ROOT); } private String parentResourceLinkToQueryLink(String parentResouceLink, ResourceType resourceTypeEnum) { switch (resourceTypeEnum) { case Database: return Paths.DATABASES_ROOT; case DocumentCollection: return Utils.joinPath(parentResouceLink, Paths.COLLECTIONS_PATH_SEGMENT); case Document: return Utils.joinPath(parentResouceLink, Paths.DOCUMENTS_PATH_SEGMENT); case Offer: return Paths.OFFERS_ROOT; case User: return Utils.joinPath(parentResouceLink, Paths.USERS_PATH_SEGMENT); case Permission: return Utils.joinPath(parentResouceLink, Paths.PERMISSIONS_PATH_SEGMENT); case Attachment: return Utils.joinPath(parentResouceLink, Paths.ATTACHMENTS_PATH_SEGMENT); case StoredProcedure: return Utils.joinPath(parentResouceLink, Paths.STORED_PROCEDURES_PATH_SEGMENT); case Trigger: return Utils.joinPath(parentResouceLink, Paths.TRIGGERS_PATH_SEGMENT); case UserDefinedFunction: return Utils.joinPath(parentResouceLink, Paths.USER_DEFINED_FUNCTIONS_PATH_SEGMENT); default: throw new IllegalArgumentException("resource type not supported"); } } private <T extends Resource> Flux<FeedResponse<T>> createQuery( String parentResourceLink, SqlQuerySpec sqlQuery, FeedOptions options, Class<T> klass, ResourceType resourceTypeEnum) { String queryResourceLink = parentResourceLinkToQueryLink(parentResourceLink, resourceTypeEnum); UUID activityId = Utils.randomUUID(); IDocumentQueryClient queryClient = DocumentQueryClientImpl(RxDocumentClientImpl.this); Flux<? extends IDocumentQueryExecutionContext<T>> executionContext = DocumentQueryExecutionContextFactory.createDocumentQueryExecutionContextAsync(queryClient, resourceTypeEnum, klass, sqlQuery , options, queryResourceLink, false, activityId); return executionContext.flatMap(IDocumentQueryExecutionContext::executeAsync); } @Override public Flux<FeedResponse<Database>> queryDatabases(String query, FeedOptions options) { return queryDatabases(new SqlQuerySpec(query), options); } @Override public Flux<FeedResponse<Database>> queryDatabases(SqlQuerySpec querySpec, FeedOptions options) { return createQuery(Paths.DATABASES_ROOT, querySpec, options, Database.class, ResourceType.Database); } @Override public Flux<ResourceResponse<DocumentCollection>> createCollection(String databaseLink, DocumentCollection collection, RequestOptions options) { IDocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> this.createCollectionInternal(databaseLink, collection, options, retryPolicyInstance), retryPolicyInstance); } private Flux<ResourceResponse<DocumentCollection>> createCollectionInternal(String databaseLink, DocumentCollection collection, RequestOptions options, IDocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(databaseLink)) { throw new IllegalArgumentException("databaseLink"); } if (collection == null) { throw new IllegalArgumentException("collection"); } logger.debug("Creating a Collection. databaseLink: [{}], Collection id: [{}]", databaseLink, collection.id()); validateResource(collection); String path = Utils.joinPath(databaseLink, Paths.COLLECTIONS_PATH_SEGMENT); Map<String, String> requestHeaders = this.getRequestHeaders(options); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(OperationType.Create, ResourceType.DocumentCollection, path, collection, requestHeaders, options); if (retryPolicyInstance != null){ retryPolicyInstance.onBeforeSendRequest(request); } return this.create(request).map(response -> toResourceResponse(response, DocumentCollection.class)) .doOnNext(resourceResponse -> { // set the session token this.sessionContainer.setSessionToken(resourceResponse.getResource().resourceId(), getAltLink(resourceResponse.getResource()), resourceResponse.getResponseHeaders()); }); } catch (Exception e) { logger.debug("Failure in creating a collection. due to [{}]", e.getMessage(), e); return Flux.error(e); } } @Override public Flux<ResourceResponse<DocumentCollection>> replaceCollection(DocumentCollection collection, RequestOptions options) { IDocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> replaceCollectionInternal(collection, options, retryPolicyInstance), retryPolicyInstance); } private Flux<ResourceResponse<DocumentCollection>> replaceCollectionInternal(DocumentCollection collection, RequestOptions options, IDocumentClientRetryPolicy retryPolicyInstance) { try { if (collection == null) { throw new IllegalArgumentException("collection"); } logger.debug("Replacing a Collection. id: [{}]", collection.id()); validateResource(collection); String path = Utils.joinPath(collection.selfLink(), null); Map<String, String> requestHeaders = this.getRequestHeaders(options); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(OperationType.Replace, ResourceType.DocumentCollection, path, collection, requestHeaders, options); // TODO: .Net has some logic for updating session token which we don't // have here if (retryPolicyInstance != null){ retryPolicyInstance.onBeforeSendRequest(request); } return this.replace(request).map(response -> toResourceResponse(response, DocumentCollection.class)) .doOnNext(resourceResponse -> { if (resourceResponse.getResource() != null) { // set the session token this.sessionContainer.setSessionToken(resourceResponse.getResource().resourceId(), getAltLink(resourceResponse.getResource()), resourceResponse.getResponseHeaders()); } }); } catch (Exception e) { logger.debug("Failure in replacing a collection. due to [{}]", e.getMessage(), e); return Flux.error(e); } } @Override public Flux<ResourceResponse<DocumentCollection>> deleteCollection(String collectionLink, RequestOptions options) { IDocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> deleteCollectionInternal(collectionLink, options, retryPolicyInstance), retryPolicyInstance); } private Flux<ResourceResponse<DocumentCollection>> deleteCollectionInternal(String collectionLink, RequestOptions options, IDocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(collectionLink)) { throw new IllegalArgumentException("collectionLink"); } logger.debug("Deleting a Collection. collectionLink: [{}]", collectionLink); String path = Utils.joinPath(collectionLink, null); Map<String, String> requestHeaders = this.getRequestHeaders(options); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(OperationType.Delete, ResourceType.DocumentCollection, path, requestHeaders, options); if (retryPolicyInstance != null){ retryPolicyInstance.onBeforeSendRequest(request); } return this.delete(request).map(response -> toResourceResponse(response, DocumentCollection.class)); } catch (Exception e) { logger.debug("Failure in deleting a collection, due to [{}]", e.getMessage(), e); return Flux.error(e); } } private Flux<RxDocumentServiceResponse> delete(RxDocumentServiceRequest request) { populateHeaders(request, HttpConstants.HttpMethods.DELETE); return getStoreProxy(request).processMessage(request); } private Flux<RxDocumentServiceResponse> read(RxDocumentServiceRequest request) { populateHeaders(request, HttpConstants.HttpMethods.GET); return getStoreProxy(request).processMessage(request); } Flux<RxDocumentServiceResponse> readFeed(RxDocumentServiceRequest request) { populateHeaders(request, HttpConstants.HttpMethods.GET); return gatewayProxy.processMessage(request); } private Flux<RxDocumentServiceResponse> query(RxDocumentServiceRequest request) { populateHeaders(request, HttpConstants.HttpMethods.POST); return this.getStoreProxy(request).processMessage(request) .map(response -> { this.captureSessionToken(request, response); return response; } ); } @Override public Flux<ResourceResponse<DocumentCollection>> readCollection(String collectionLink, RequestOptions options) { IDocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> readCollectionInternal(collectionLink, options, retryPolicyInstance), retryPolicyInstance); } private Flux<ResourceResponse<DocumentCollection>> readCollectionInternal(String collectionLink, RequestOptions options, IDocumentClientRetryPolicy retryPolicyInstance) { // we are using an observable factory here // observable will be created fresh upon subscription // this is to ensure we capture most up to date information (e.g., // session) try { if (StringUtils.isEmpty(collectionLink)) { throw new IllegalArgumentException("collectionLink"); } logger.debug("Reading a Collection. collectionLink: [{}]", collectionLink); String path = Utils.joinPath(collectionLink, null); Map<String, String> requestHeaders = this.getRequestHeaders(options); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(OperationType.Read, ResourceType.DocumentCollection, path, requestHeaders, options); if (retryPolicyInstance != null){ retryPolicyInstance.onBeforeSendRequest(request); } return this.read(request).map(response -> toResourceResponse(response, DocumentCollection.class)); } catch (Exception e) { // this is only in trace level to capture what's going on logger.debug("Failure in reading a collection, due to [{}]", e.getMessage(), e); return Flux.error(e); } } @Override public Flux<FeedResponse<DocumentCollection>> readCollections(String databaseLink, FeedOptions options) { if (StringUtils.isEmpty(databaseLink)) { throw new IllegalArgumentException("databaseLink"); } return readFeed(options, ResourceType.DocumentCollection, DocumentCollection.class, Utils.joinPath(databaseLink, Paths.COLLECTIONS_PATH_SEGMENT)); } @Override public Flux<FeedResponse<DocumentCollection>> queryCollections(String databaseLink, String query, FeedOptions options) { return createQuery(databaseLink, new SqlQuerySpec(query), options, DocumentCollection.class, ResourceType.DocumentCollection); } @Override public Flux<FeedResponse<DocumentCollection>> queryCollections(String databaseLink, SqlQuerySpec querySpec, FeedOptions options) { return createQuery(databaseLink, querySpec, options, DocumentCollection.class, ResourceType.DocumentCollection); } private static String serializeProcedureParams(Object[] objectArray) { String[] stringArray = new String[objectArray.length]; for (int i = 0; i < objectArray.length; ++i) { Object object = objectArray[i]; if (object instanceof JsonSerializable) { stringArray[i] = ((JsonSerializable) object).toJson(); } else { // POJO, ObjectNode, number, STRING or Boolean try { stringArray[i] = mapper.writeValueAsString(object); } catch (IOException e) { throw new IllegalArgumentException("Can't serialize the object into the json string", e); } } } return String.format("[%s]", StringUtils.join(stringArray, ",")); } private static void validateResource(Resource resource) { if (!StringUtils.isEmpty(resource.id())) { if (resource.id().indexOf('/') != -1 || resource.id().indexOf('\\') != -1 || resource.id().indexOf('?') != -1 || resource.id().indexOf('#') != -1) { throw new IllegalArgumentException("Id contains illegal chars."); } if (resource.id().endsWith(" ")) { throw new IllegalArgumentException("Id ends with a space."); } } } private Map<String, String> getRequestHeaders(RequestOptions options) { Map<String, String> headers = new HashMap<>(); if (this.useMultipleWriteLocations) { headers.put(HttpConstants.HttpHeaders.ALLOW_TENTATIVE_WRITES, Boolean.TRUE.toString()); } if (consistencyLevel != null) { headers.put(HttpConstants.HttpHeaders.CONSISTENCY_LEVEL, consistencyLevel.toString()); } if (options == null) { return headers; } Map<String, String> customOptions = options.getHeaders(); if (customOptions != null) { headers.putAll(customOptions); } if (options.getAccessCondition() != null) { if (options.getAccessCondition().type() == AccessConditionType.IF_MATCH) { headers.put(HttpConstants.HttpHeaders.IF_MATCH, options.getAccessCondition().condition()); } else { headers.put(HttpConstants.HttpHeaders.IF_NONE_MATCH, options.getAccessCondition().condition()); } } if (options.getConsistencyLevel() != null) { headers.put(HttpConstants.HttpHeaders.CONSISTENCY_LEVEL, options.getConsistencyLevel().toString()); } if (options.getIndexingDirective() != null) { headers.put(HttpConstants.HttpHeaders.INDEXING_DIRECTIVE, options.getIndexingDirective().toString()); } if (options.getPostTriggerInclude() != null && options.getPostTriggerInclude().size() > 0) { String postTriggerInclude = StringUtils.join(options.getPostTriggerInclude(), ","); headers.put(HttpConstants.HttpHeaders.POST_TRIGGER_INCLUDE, postTriggerInclude); } if (options.getPreTriggerInclude() != null && options.getPreTriggerInclude().size() > 0) { String preTriggerInclude = StringUtils.join(options.getPreTriggerInclude(), ","); headers.put(HttpConstants.HttpHeaders.PRE_TRIGGER_INCLUDE, preTriggerInclude); } if (!Strings.isNullOrEmpty(options.getSessionToken())) { headers.put(HttpConstants.HttpHeaders.SESSION_TOKEN, options.getSessionToken()); } if (options.getResourceTokenExpirySeconds() != null) { headers.put(HttpConstants.HttpHeaders.RESOURCE_TOKEN_EXPIRY, String.valueOf(options.getResourceTokenExpirySeconds())); } if (options.getOfferThroughput() != null && options.getOfferThroughput() >= 0) { headers.put(HttpConstants.HttpHeaders.OFFER_THROUGHPUT, options.getOfferThroughput().toString()); } else if (options.getOfferType() != null) { headers.put(HttpConstants.HttpHeaders.OFFER_TYPE, options.getOfferType()); } if (options.isPopulateQuotaInfo()) { headers.put(HttpConstants.HttpHeaders.POPULATE_QUOTA_INFO, String.valueOf(true)); } if (options.isScriptLoggingEnabled()) { headers.put(HttpConstants.HttpHeaders.SCRIPT_ENABLE_LOGGING, String.valueOf(true)); } return headers; } private Mono<RxDocumentServiceRequest> addPartitionKeyInformation(RxDocumentServiceRequest request, Document document, RequestOptions options) { Mono<DocumentCollection> collectionObs = this.collectionCache.resolveCollectionAsync(request); return collectionObs .map(collection -> { addPartitionKeyInformation(request, document, options, collection); return request; }); } private Mono<RxDocumentServiceRequest> addPartitionKeyInformation(RxDocumentServiceRequest request, Document document, RequestOptions options, Mono<DocumentCollection> collectionObs) { return collectionObs.map(collection -> { addPartitionKeyInformation(request, document, options, collection); return request; }); } private void addPartitionKeyInformation(RxDocumentServiceRequest request, Document document, RequestOptions options, DocumentCollection collection) { PartitionKeyDefinition partitionKeyDefinition = collection.getPartitionKey(); PartitionKeyInternal partitionKeyInternal = null; if (options != null && options.getPartitionKey() != null && options.getPartitionKey().equals(PartitionKey.None)){ partitionKeyInternal = BridgeInternal.getNonePartitionKey(partitionKeyDefinition); } else if (options != null && options.getPartitionKey() != null) { partitionKeyInternal = options.getPartitionKey().getInternalPartitionKey(); } else if (partitionKeyDefinition == null || partitionKeyDefinition.paths().size() == 0) { // For backward compatibility, if collection doesn't have partition key defined, we assume all documents // have empty value for it and user doesn't need to specify it explicitly. partitionKeyInternal = PartitionKeyInternal.getEmpty(); } else if (document != null) { partitionKeyInternal = extractPartitionKeyValueFromDocument(document, partitionKeyDefinition); } else { throw new UnsupportedOperationException("PartitionKey value must be supplied for this operation."); } request.getHeaders().put(HttpConstants.HttpHeaders.PARTITION_KEY, escapeNonAscii(partitionKeyInternal.toJson())); } private static String escapeNonAscii(String partitionKeyJson) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < partitionKeyJson.length(); i++) { int val = partitionKeyJson.charAt(i); if (val > 127) { sb.append("\\u").append(String.format("%04X", val)); } else { sb.append(partitionKeyJson.charAt(i)); } } return sb.toString(); } private static PartitionKeyInternal extractPartitionKeyValueFromDocument( Document document, PartitionKeyDefinition partitionKeyDefinition) { if (partitionKeyDefinition != null) { String path = partitionKeyDefinition.paths().iterator().next(); List<String> parts = PathParser.getPathParts(path); if (parts.size() >= 1) { Object value = document.getObjectByPath(parts); if (value == null || value.getClass() == ObjectNode.class) { value = BridgeInternal.getNonePartitionKey(partitionKeyDefinition); } if (value instanceof PartitionKeyInternal) { return (PartitionKeyInternal) value; } else { return PartitionKeyInternal.fromObjectArray(Collections.singletonList(value), false); } } } return null; } private Mono<RxDocumentServiceRequest> getCreateDocumentRequest(String documentCollectionLink, Object document, RequestOptions options, boolean disableAutomaticIdGeneration, OperationType operationType) { if (StringUtils.isEmpty(documentCollectionLink)) { throw new IllegalArgumentException("documentCollectionLink"); } if (document == null) { throw new IllegalArgumentException("document"); } Document typedDocument = documentFromObject(document, mapper); RxDocumentClientImpl.validateResource(typedDocument); if (typedDocument.id() == null && !disableAutomaticIdGeneration) { // We are supposed to use GUID. Basically UUID is the same as GUID // when represented as a string. typedDocument.id(UUID.randomUUID().toString()); } String path = Utils.joinPath(documentCollectionLink, Paths.DOCUMENTS_PATH_SEGMENT); Map<String, String> requestHeaders = this.getRequestHeaders(options); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(operationType, ResourceType.Document, path, typedDocument, requestHeaders, options); Mono<DocumentCollection> collectionObs = this.collectionCache.resolveCollectionAsync(request); return addPartitionKeyInformation(request, typedDocument, options, collectionObs); } private void populateHeaders(RxDocumentServiceRequest request, String httpMethod) { request.getHeaders().put(HttpConstants.HttpHeaders.X_DATE, Utils.nowAsRFC1123()); if (this.masterKeyOrResourceToken != null || this.resourceTokensMap != null || this.tokenResolver != null || this.cosmosKeyCredential != null) { String resourceName = request.getResourceAddress(); String authorization = this.getUserAuthorizationToken( resourceName, request.getResourceType(), httpMethod, request.getHeaders(), AuthorizationTokenType.PrimaryMasterKey, request.properties); try { authorization = URLEncoder.encode(authorization, "UTF-8"); } catch (UnsupportedEncodingException e) { throw new IllegalStateException("Failed to encode authtoken.", e); } request.getHeaders().put(HttpConstants.HttpHeaders.AUTHORIZATION, authorization); } if ((HttpConstants.HttpMethods.POST.equals(httpMethod) || HttpConstants.HttpMethods.PUT.equals(httpMethod)) && !request.getHeaders().containsKey(HttpConstants.HttpHeaders.CONTENT_TYPE)) { request.getHeaders().put(HttpConstants.HttpHeaders.CONTENT_TYPE, RuntimeConstants.MediaTypes.JSON); } if (!request.getHeaders().containsKey(HttpConstants.HttpHeaders.ACCEPT)) { request.getHeaders().put(HttpConstants.HttpHeaders.ACCEPT, RuntimeConstants.MediaTypes.JSON); } } @Override public String getUserAuthorizationToken(String resourceName, ResourceType resourceType, String requestVerb, Map<String, String> headers, AuthorizationTokenType tokenType, Map<String, Object> properties) { if (this.tokenResolver != null) { return this.tokenResolver.getAuthorizationToken(requestVerb, resourceName, this.resolveCosmosResourceType(resourceType), properties != null ? Collections.unmodifiableMap(properties) : null); } else if (cosmosKeyCredential != null) { return this.authorizationTokenProvider.generateKeyAuthorizationSignature(requestVerb, resourceName, resourceType, headers); } else if (masterKeyOrResourceToken != null && hasAuthKeyResourceToken && resourceTokensMap == null) { return masterKeyOrResourceToken; } else { assert resourceTokensMap != null; if(resourceType.equals(ResourceType.DatabaseAccount)) { return this.firstResourceTokenFromPermissionFeed; } return ResourceTokenAuthorizationHelper.getAuthorizationTokenUsingResourceTokens(resourceTokensMap, requestVerb, resourceName, headers); } } private CosmosResourceType resolveCosmosResourceType(ResourceType resourceType) { try { return CosmosResourceType.valueOf(resourceType.toString()); } catch (IllegalArgumentException e) { return CosmosResourceType.System; } } void captureSessionToken(RxDocumentServiceRequest request, RxDocumentServiceResponse response) { this.sessionContainer.setSessionToken(request, response.getResponseHeaders()); } private Flux<RxDocumentServiceResponse> create(RxDocumentServiceRequest request) { populateHeaders(request, HttpConstants.HttpMethods.POST); RxStoreModel storeProxy = this.getStoreProxy(request); return storeProxy.processMessage(request); } private Flux<RxDocumentServiceResponse> upsert(RxDocumentServiceRequest request) { populateHeaders(request, HttpConstants.HttpMethods.POST); Map<String, String> headers = request.getHeaders(); // headers can never be null, since it will be initialized even when no // request options are specified, // hence using assertion here instead of exception, being in the private // method assert (headers != null); headers.put(HttpConstants.HttpHeaders.IS_UPSERT, "true"); return getStoreProxy(request).processMessage(request) .map(response -> { this.captureSessionToken(request, response); return response; } ); } private Flux<RxDocumentServiceResponse> replace(RxDocumentServiceRequest request) { populateHeaders(request, HttpConstants.HttpMethods.PUT); return getStoreProxy(request).processMessage(request); } @Override public Flux<ResourceResponse<Document>> createDocument(String collectionLink, Object document, RequestOptions options, boolean disableAutomaticIdGeneration) { IDocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy(); if (options == null || options.getPartitionKey() == null) { requestRetryPolicy = new PartitionKeyMismatchRetryPolicy(collectionCache, requestRetryPolicy, collectionLink, options); } IDocumentClientRetryPolicy finalRetryPolicyInstance = requestRetryPolicy; return ObservableHelper.inlineIfPossibleAsObs(() -> createDocumentInternal(collectionLink, document, options, disableAutomaticIdGeneration, finalRetryPolicyInstance), requestRetryPolicy); } private Flux<ResourceResponse<Document>> createDocumentInternal(String collectionLink, Object document, RequestOptions options, final boolean disableAutomaticIdGeneration, IDocumentClientRetryPolicy requestRetryPolicy) { try { logger.debug("Creating a Document. collectionLink: [{}]", collectionLink); Mono<RxDocumentServiceRequest> requestObs = getCreateDocumentRequest(collectionLink, document, options, disableAutomaticIdGeneration, OperationType.Create); Flux<RxDocumentServiceResponse> responseObservable = requestObs .flux() .flatMap(req -> { if (requestRetryPolicy != null) { requestRetryPolicy.onBeforeSendRequest(req); } return create(req); }); return responseObservable .map(serviceResponse -> toResourceResponse(serviceResponse, Document.class)); } catch (Exception e) { logger.debug("Failure in creating a document due to [{}]", e.getMessage(), e); return Flux.error(e); } } @Override public Flux<ResourceResponse<Document>> upsertDocument(String collectionLink, Object document, RequestOptions options, boolean disableAutomaticIdGeneration) { IDocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy(); if (options == null || options.getPartitionKey() == null) { requestRetryPolicy = new PartitionKeyMismatchRetryPolicy(collectionCache, requestRetryPolicy, collectionLink, options); } IDocumentClientRetryPolicy finalRetryPolicyInstance = requestRetryPolicy; return ObservableHelper.inlineIfPossibleAsObs(() -> upsertDocumentInternal(collectionLink, document, options, disableAutomaticIdGeneration, finalRetryPolicyInstance), requestRetryPolicy); } private Flux<ResourceResponse<Document>> upsertDocumentInternal(String collectionLink, Object document, RequestOptions options, boolean disableAutomaticIdGeneration, IDocumentClientRetryPolicy retryPolicyInstance) { try { logger.debug("Upserting a Document. collectionLink: [{}]", collectionLink); Flux<RxDocumentServiceRequest> reqObs = getCreateDocumentRequest(collectionLink, document, options, disableAutomaticIdGeneration, OperationType.Upsert).flux(); Flux<RxDocumentServiceResponse> responseObservable = reqObs.flatMap(req -> { if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(req); } return upsert(req);}); return responseObservable .map(serviceResponse -> toResourceResponse(serviceResponse, Document.class)); } catch (Exception e) { logger.debug("Failure in upserting a document due to [{}]", e.getMessage(), e); return Flux.error(e); } } @Override public Flux<ResourceResponse<Document>> replaceDocument(String documentLink, Object document, RequestOptions options) { IDocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy(); if (options == null || options.getPartitionKey() == null) { String collectionLink = Utils.getCollectionName(documentLink); requestRetryPolicy = new PartitionKeyMismatchRetryPolicy(collectionCache, requestRetryPolicy, collectionLink, options); } IDocumentClientRetryPolicy finalRequestRetryPolicy = requestRetryPolicy; return ObservableHelper.inlineIfPossibleAsObs(() -> replaceDocumentInternal(documentLink, document, options, finalRequestRetryPolicy), requestRetryPolicy); } private Flux<ResourceResponse<Document>> replaceDocumentInternal(String documentLink, Object document, RequestOptions options, IDocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(documentLink)) { throw new IllegalArgumentException("documentLink"); } if (document == null) { throw new IllegalArgumentException("document"); } Document typedDocument = documentFromObject(document, mapper); return this.replaceDocumentInternal(documentLink, typedDocument, options, retryPolicyInstance); } catch (Exception e) { logger.debug("Failure in replacing a document due to [{}]", e.getMessage()); return Flux.error(e); } } @Override public Flux<ResourceResponse<Document>> replaceDocument(Document document, RequestOptions options) { IDocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy(); if (options == null || options.getPartitionKey() == null) { String collectionLink = document.selfLink(); requestRetryPolicy = new PartitionKeyMismatchRetryPolicy(collectionCache, requestRetryPolicy, collectionLink, options); } IDocumentClientRetryPolicy finalRequestRetryPolicy = requestRetryPolicy; return ObservableHelper.inlineIfPossibleAsObs(() -> replaceDocumentInternal(document, options, finalRequestRetryPolicy), requestRetryPolicy); } private Flux<ResourceResponse<Document>> replaceDocumentInternal(Document document, RequestOptions options, IDocumentClientRetryPolicy retryPolicyInstance) { try { if (document == null) { throw new IllegalArgumentException("document"); } return this.replaceDocumentInternal(document.selfLink(), document, options, retryPolicyInstance); } catch (Exception e) { logger.debug("Failure in replacing a database due to [{}]", e.getMessage()); return Flux.error(e); } } private Flux<ResourceResponse<Document>> replaceDocumentInternal(String documentLink, Document document, RequestOptions options, IDocumentClientRetryPolicy retryPolicyInstance) { if (document == null) { throw new IllegalArgumentException("document"); } logger.debug("Replacing a Document. documentLink: [{}]", documentLink); final String path = Utils.joinPath(documentLink, null); final Map<String, String> requestHeaders = getRequestHeaders(options); final RxDocumentServiceRequest request = RxDocumentServiceRequest.create(OperationType.Replace, ResourceType.Document, path, document, requestHeaders, options); validateResource(document); Mono<DocumentCollection> collectionObs = collectionCache.resolveCollectionAsync(request); Mono<RxDocumentServiceRequest> requestObs = addPartitionKeyInformation(request, document, options, collectionObs); return requestObs.flux().flatMap(req -> { if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } return replace(request) .map(resp -> toResourceResponse(resp, Document.class));} ); } @Override public Flux<ResourceResponse<Document>> deleteDocument(String documentLink, RequestOptions options) { IDocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> deleteDocumentInternal(documentLink, options, requestRetryPolicy), requestRetryPolicy); } private Flux<ResourceResponse<Document>> deleteDocumentInternal(String documentLink, RequestOptions options, IDocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(documentLink)) { throw new IllegalArgumentException("documentLink"); } logger.debug("Deleting a Document. documentLink: [{}]", documentLink); String path = Utils.joinPath(documentLink, null); Map<String, String> requestHeaders = this.getRequestHeaders(options); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(OperationType.Delete, ResourceType.Document, path, requestHeaders, options); Mono<DocumentCollection> collectionObs = collectionCache.resolveCollectionAsync(request); Mono<RxDocumentServiceRequest> requestObs = addPartitionKeyInformation(request, null, options, collectionObs); return requestObs.flux().flatMap(req -> { if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(req); } return this.delete(req) .map(serviceResponse -> toResourceResponse(serviceResponse, Document.class));}); } catch (Exception e) { logger.debug("Failure in deleting a document due to [{}]", e.getMessage()); return Flux.error(e); } } @Override public Flux<ResourceResponse<Document>> readDocument(String documentLink, RequestOptions options) { IDocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> readDocumentInternal(documentLink, options, retryPolicyInstance), retryPolicyInstance); } private Flux<ResourceResponse<Document>> readDocumentInternal(String documentLink, RequestOptions options, IDocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(documentLink)) { throw new IllegalArgumentException("documentLink"); } logger.debug("Reading a Document. documentLink: [{}]", documentLink); String path = Utils.joinPath(documentLink, null); Map<String, String> requestHeaders = this.getRequestHeaders(options); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(OperationType.Read, ResourceType.Document, path, requestHeaders, options); Mono<DocumentCollection> collectionObs = this.collectionCache.resolveCollectionAsync(request); Mono<RxDocumentServiceRequest> requestObs = addPartitionKeyInformation(request, null, options, collectionObs); return requestObs.flux().flatMap(req -> { if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } return this.read(request).map(serviceResponse -> toResourceResponse(serviceResponse, Document.class)); }); } catch (Exception e) { logger.debug("Failure in reading a document due to [{}]", e.getMessage()); return Flux.error(e); } } @Override public Flux<FeedResponse<Document>> readDocuments(String collectionLink, FeedOptions options) { if (StringUtils.isEmpty(collectionLink)) { throw new IllegalArgumentException("collectionLink"); } return queryDocuments(collectionLink, "SELECT * FROM r", options); } @Override public Flux<FeedResponse<Document>> queryDocuments(String collectionLink, String query, FeedOptions options) { return queryDocuments(collectionLink, new SqlQuerySpec(query), options); } private IDocumentQueryClient DocumentQueryClientImpl(RxDocumentClientImpl rxDocumentClientImpl) { return new IDocumentQueryClient () { @Override public RxCollectionCache getCollectionCache() { return RxDocumentClientImpl.this.collectionCache; } @Override public RxPartitionKeyRangeCache getPartitionKeyRangeCache() { return RxDocumentClientImpl.this.partitionKeyRangeCache; } @Override public IRetryPolicyFactory getResetSessionTokenRetryPolicy() { return RxDocumentClientImpl.this.resetSessionTokenRetryPolicy; } @Override public ConsistencyLevel getDefaultConsistencyLevelAsync() { return RxDocumentClientImpl.this.gatewayConfigurationReader.getDefaultConsistencyLevel(); } @Override public ConsistencyLevel getDesiredConsistencyLevelAsync() { // TODO Auto-generated method stub return RxDocumentClientImpl.this.consistencyLevel; } @Override public Mono<RxDocumentServiceResponse> executeQueryAsync(RxDocumentServiceRequest request) { return RxDocumentClientImpl.this.query(request).single(); } @Override public QueryCompatibilityMode getQueryCompatibilityMode() { // TODO Auto-generated method stub return QueryCompatibilityMode.Default; } @Override public Mono<RxDocumentServiceResponse> readFeedAsync(RxDocumentServiceRequest request) { // TODO Auto-generated method stub return null; } }; } @Override public Flux<FeedResponse<Document>> queryDocuments(String collectionLink, SqlQuerySpec querySpec, FeedOptions options) { return createQuery(collectionLink, querySpec, options, Document.class, ResourceType.Document); } @Override public Flux<FeedResponse<Document>> queryDocumentChangeFeed(final String collectionLink, final ChangeFeedOptions changeFeedOptions) { if (StringUtils.isEmpty(collectionLink)) { throw new IllegalArgumentException("collectionLink"); } ChangeFeedQueryImpl<Document> changeFeedQueryImpl = new ChangeFeedQueryImpl<Document>(this, ResourceType.Document, Document.class, collectionLink, changeFeedOptions); return changeFeedQueryImpl.executeAsync(); } @Override public Flux<FeedResponse<PartitionKeyRange>> readPartitionKeyRanges(final String collectionLink, FeedOptions options) { if (StringUtils.isEmpty(collectionLink)) { throw new IllegalArgumentException("collectionLink"); } return readFeed(options, ResourceType.PartitionKeyRange, PartitionKeyRange.class, Utils.joinPath(collectionLink, Paths.PARTITION_KEY_RANGES_PATH_SEGMENT)); } private RxDocumentServiceRequest getStoredProcedureRequest(String collectionLink, StoredProcedure storedProcedure, RequestOptions options, OperationType operationType) { if (StringUtils.isEmpty(collectionLink)) { throw new IllegalArgumentException("collectionLink"); } if (storedProcedure == null) { throw new IllegalArgumentException("storedProcedure"); } validateResource(storedProcedure); String path = Utils.joinPath(collectionLink, Paths.STORED_PROCEDURES_PATH_SEGMENT); Map<String, String> requestHeaders = this.getRequestHeaders(options); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(operationType, ResourceType.StoredProcedure, path, storedProcedure, requestHeaders, options); return request; } private RxDocumentServiceRequest getUserDefinedFunctionRequest(String collectionLink, UserDefinedFunction udf, RequestOptions options, OperationType operationType) { if (StringUtils.isEmpty(collectionLink)) { throw new IllegalArgumentException("collectionLink"); } if (udf == null) { throw new IllegalArgumentException("udf"); } validateResource(udf); String path = Utils.joinPath(collectionLink, Paths.USER_DEFINED_FUNCTIONS_PATH_SEGMENT); Map<String, String> requestHeaders = this.getRequestHeaders(options); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(operationType, ResourceType.UserDefinedFunction, path, udf, requestHeaders, options); return request; } @Override public Flux<ResourceResponse<StoredProcedure>> createStoredProcedure(String collectionLink, StoredProcedure storedProcedure, RequestOptions options) { IDocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> createStoredProcedureInternal(collectionLink, storedProcedure, options, requestRetryPolicy), requestRetryPolicy); } private Flux<ResourceResponse<StoredProcedure>> createStoredProcedureInternal(String collectionLink, StoredProcedure storedProcedure, RequestOptions options, IDocumentClientRetryPolicy retryPolicyInstance) { // we are using an observable factory here // observable will be created fresh upon subscription // this is to ensure we capture most up to date information (e.g., // session) try { logger.debug("Creating a StoredProcedure. collectionLink: [{}], storedProcedure id [{}]", collectionLink, storedProcedure.id()); RxDocumentServiceRequest request = getStoredProcedureRequest(collectionLink, storedProcedure, options, OperationType.Create); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } return this.create(request).map(response -> toResourceResponse(response, StoredProcedure.class)); } catch (Exception e) { // this is only in trace level to capture what's going on logger.debug("Failure in creating a StoredProcedure due to [{}]", e.getMessage(), e); return Flux.error(e); } } @Override public Flux<ResourceResponse<StoredProcedure>> upsertStoredProcedure(String collectionLink, StoredProcedure storedProcedure, RequestOptions options) { IDocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> upsertStoredProcedureInternal(collectionLink, storedProcedure, options, requestRetryPolicy), requestRetryPolicy); } private Flux<ResourceResponse<StoredProcedure>> upsertStoredProcedureInternal(String collectionLink, StoredProcedure storedProcedure, RequestOptions options, IDocumentClientRetryPolicy retryPolicyInstance) { // we are using an observable factory here // observable will be created fresh upon subscription // this is to ensure we capture most up to date information (e.g., // session) try { logger.debug("Upserting a StoredProcedure. collectionLink: [{}], storedProcedure id [{}]", collectionLink, storedProcedure.id()); RxDocumentServiceRequest request = getStoredProcedureRequest(collectionLink, storedProcedure, options, OperationType.Upsert); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } return this.upsert(request).map(response -> toResourceResponse(response, StoredProcedure.class)); } catch (Exception e) { // this is only in trace level to capture what's going on logger.debug("Failure in upserting a StoredProcedure due to [{}]", e.getMessage(), e); return Flux.error(e); } } @Override public Flux<ResourceResponse<StoredProcedure>> replaceStoredProcedure(StoredProcedure storedProcedure, RequestOptions options) { IDocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> replaceStoredProcedureInternal(storedProcedure, options, requestRetryPolicy), requestRetryPolicy); } private Flux<ResourceResponse<StoredProcedure>> replaceStoredProcedureInternal(StoredProcedure storedProcedure, RequestOptions options, IDocumentClientRetryPolicy retryPolicyInstance) { try { if (storedProcedure == null) { throw new IllegalArgumentException("storedProcedure"); } logger.debug("Replacing a StoredProcedure. storedProcedure id [{}]", storedProcedure.id()); RxDocumentClientImpl.validateResource(storedProcedure); String path = Utils.joinPath(storedProcedure.selfLink(), null); Map<String, String> requestHeaders = getRequestHeaders(options); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(OperationType.Replace, ResourceType.StoredProcedure, path, storedProcedure, requestHeaders, options); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } return this.replace(request).map(response -> toResourceResponse(response, StoredProcedure.class)); } catch (Exception e) { logger.debug("Failure in replacing a StoredProcedure due to [{}]", e.getMessage(), e); return Flux.error(e); } } @Override public Flux<ResourceResponse<StoredProcedure>> deleteStoredProcedure(String storedProcedureLink, RequestOptions options) { IDocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> deleteStoredProcedureInternal(storedProcedureLink, options, requestRetryPolicy), requestRetryPolicy); } private Flux<ResourceResponse<StoredProcedure>> deleteStoredProcedureInternal(String storedProcedureLink, RequestOptions options, IDocumentClientRetryPolicy retryPolicyInstance) { // we are using an observable factory here // observable will be created fresh upon subscription // this is to ensure we capture most up to date information (e.g., // session) try { if (StringUtils.isEmpty(storedProcedureLink)) { throw new IllegalArgumentException("storedProcedureLink"); } logger.debug("Deleting a StoredProcedure. storedProcedureLink [{}]", storedProcedureLink); String path = Utils.joinPath(storedProcedureLink, null); Map<String, String> requestHeaders = this.getRequestHeaders(options); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(OperationType.Delete, ResourceType.StoredProcedure, path, requestHeaders, options); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } return this.delete(request).map(response -> toResourceResponse(response, StoredProcedure.class)); } catch (Exception e) { // this is only in trace level to capture what's going on logger.debug("Failure in deleting a StoredProcedure due to [{}]", e.getMessage(), e); return Flux.error(e); } } @Override public Flux<ResourceResponse<StoredProcedure>> readStoredProcedure(String storedProcedureLink, RequestOptions options) { IDocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> readStoredProcedureInternal(storedProcedureLink, options, retryPolicyInstance), retryPolicyInstance); } private Flux<ResourceResponse<StoredProcedure>> readStoredProcedureInternal(String storedProcedureLink, RequestOptions options, IDocumentClientRetryPolicy retryPolicyInstance) { // we are using an observable factory here // observable will be created fresh upon subscription // this is to ensure we capture most up to date information (e.g., // session) try { if (StringUtils.isEmpty(storedProcedureLink)) { throw new IllegalArgumentException("storedProcedureLink"); } logger.debug("Reading a StoredProcedure. storedProcedureLink [{}]", storedProcedureLink); String path = Utils.joinPath(storedProcedureLink, null); Map<String, String> requestHeaders = this.getRequestHeaders(options); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(OperationType.Read, ResourceType.StoredProcedure, path, requestHeaders, options); if (retryPolicyInstance != null){ retryPolicyInstance.onBeforeSendRequest(request); } return this.read(request).map(response -> toResourceResponse(response, StoredProcedure.class)); } catch (Exception e) { // this is only in trace level to capture what's going on logger.debug("Failure in reading a StoredProcedure due to [{}]", e.getMessage(), e); return Flux.error(e); } } @Override public Flux<FeedResponse<StoredProcedure>> readStoredProcedures(String collectionLink, FeedOptions options) { if (StringUtils.isEmpty(collectionLink)) { throw new IllegalArgumentException("collectionLink"); } return readFeed(options, ResourceType.StoredProcedure, StoredProcedure.class, Utils.joinPath(collectionLink, Paths.STORED_PROCEDURES_PATH_SEGMENT)); } @Override public Flux<FeedResponse<StoredProcedure>> queryStoredProcedures(String collectionLink, String query, FeedOptions options) { return queryStoredProcedures(collectionLink, new SqlQuerySpec(query), options); } @Override public Flux<FeedResponse<StoredProcedure>> queryStoredProcedures(String collectionLink, SqlQuerySpec querySpec, FeedOptions options) { return createQuery(collectionLink, querySpec, options, StoredProcedure.class, ResourceType.StoredProcedure); } @Override public Flux<StoredProcedureResponse> executeStoredProcedure(String storedProcedureLink, Object[] procedureParams) { return this.executeStoredProcedure(storedProcedureLink, null, procedureParams); } @Override public Flux<StoredProcedureResponse> executeStoredProcedure(String storedProcedureLink, RequestOptions options, Object[] procedureParams) { return ObservableHelper.inlineIfPossibleAsObs(() -> executeStoredProcedureInternal(storedProcedureLink, options, procedureParams), this.resetSessionTokenRetryPolicy.getRequestPolicy()); } private Flux<StoredProcedureResponse> executeStoredProcedureInternal(String storedProcedureLink, RequestOptions options, Object[] procedureParams) { try { logger.debug("Executing a StoredProcedure. storedProcedureLink [{}]", storedProcedureLink); String path = Utils.joinPath(storedProcedureLink, null); Map<String, String> requestHeaders = getRequestHeaders(options); requestHeaders.put(HttpConstants.HttpHeaders.ACCEPT, RuntimeConstants.MediaTypes.JSON); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(OperationType.ExecuteJavaScript, ResourceType.StoredProcedure, path, procedureParams != null ? RxDocumentClientImpl.serializeProcedureParams(procedureParams) : "", requestHeaders, options); Flux<RxDocumentServiceRequest> reqObs = addPartitionKeyInformation(request, null, options).flux(); return reqObs.flatMap(req -> create(request) .map(response -> { this.captureSessionToken(request, response); return toStoredProcedureResponse(response); })); } catch (Exception e) { logger.debug("Failure in executing a StoredProcedure due to [{}]", e.getMessage(), e); return Flux.error(e); } } @Override public Flux<ResourceResponse<Trigger>> createTrigger(String collectionLink, Trigger trigger, RequestOptions options) { IDocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> createTriggerInternal(collectionLink, trigger, options, retryPolicyInstance), retryPolicyInstance); } private Flux<ResourceResponse<Trigger>> createTriggerInternal(String collectionLink, Trigger trigger, RequestOptions options, IDocumentClientRetryPolicy retryPolicyInstance) { try { logger.debug("Creating a Trigger. collectionLink [{}], trigger id [{}]", collectionLink, trigger.id()); RxDocumentServiceRequest request = getTriggerRequest(collectionLink, trigger, options, OperationType.Create); if (retryPolicyInstance != null){ retryPolicyInstance.onBeforeSendRequest(request); } return this.create(request).map(response -> toResourceResponse(response, Trigger.class)); } catch (Exception e) { logger.debug("Failure in creating a Trigger due to [{}]", e.getMessage(), e); return Flux.error(e); } } @Override public Flux<ResourceResponse<Trigger>> upsertTrigger(String collectionLink, Trigger trigger, RequestOptions options) { IDocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> upsertTriggerInternal(collectionLink, trigger, options, retryPolicyInstance), retryPolicyInstance); } private Flux<ResourceResponse<Trigger>> upsertTriggerInternal(String collectionLink, Trigger trigger, RequestOptions options, IDocumentClientRetryPolicy retryPolicyInstance) { try { logger.debug("Upserting a Trigger. collectionLink [{}], trigger id [{}]", collectionLink, trigger.id()); RxDocumentServiceRequest request = getTriggerRequest(collectionLink, trigger, options, OperationType.Upsert); if (retryPolicyInstance != null){ retryPolicyInstance.onBeforeSendRequest(request); } return this.upsert(request).map(response -> toResourceResponse(response, Trigger.class)); } catch (Exception e) { logger.debug("Failure in upserting a Trigger due to [{}]", e.getMessage(), e); return Flux.error(e); } } private RxDocumentServiceRequest getTriggerRequest(String collectionLink, Trigger trigger, RequestOptions options, OperationType operationType) { if (StringUtils.isEmpty(collectionLink)) { throw new IllegalArgumentException("collectionLink"); } if (trigger == null) { throw new IllegalArgumentException("trigger"); } RxDocumentClientImpl.validateResource(trigger); String path = Utils.joinPath(collectionLink, Paths.TRIGGERS_PATH_SEGMENT); Map<String, String> requestHeaders = getRequestHeaders(options); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(operationType, ResourceType.Trigger, path, trigger, requestHeaders, options); return request; } @Override public Flux<ResourceResponse<Trigger>> replaceTrigger(Trigger trigger, RequestOptions options) { IDocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> replaceTriggerInternal(trigger, options, retryPolicyInstance), retryPolicyInstance); } private Flux<ResourceResponse<Trigger>> replaceTriggerInternal(Trigger trigger, RequestOptions options, IDocumentClientRetryPolicy retryPolicyInstance) { try { if (trigger == null) { throw new IllegalArgumentException("trigger"); } logger.debug("Replacing a Trigger. trigger id [{}]", trigger.id()); RxDocumentClientImpl.validateResource(trigger); String path = Utils.joinPath(trigger.selfLink(), null); Map<String, String> requestHeaders = getRequestHeaders(options); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(OperationType.Replace, ResourceType.Trigger, path, trigger, requestHeaders, options); if (retryPolicyInstance != null){ retryPolicyInstance.onBeforeSendRequest(request); } return this.replace(request).map(response -> toResourceResponse(response, Trigger.class)); } catch (Exception e) { logger.debug("Failure in replacing a Trigger due to [{}]", e.getMessage(), e); return Flux.error(e); } } @Override public Flux<ResourceResponse<Trigger>> deleteTrigger(String triggerLink, RequestOptions options) { IDocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> deleteTriggerInternal(triggerLink, options, retryPolicyInstance), retryPolicyInstance); } private Flux<ResourceResponse<Trigger>> deleteTriggerInternal(String triggerLink, RequestOptions options, IDocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(triggerLink)) { throw new IllegalArgumentException("triggerLink"); } logger.debug("Deleting a Trigger. triggerLink [{}]", triggerLink); String path = Utils.joinPath(triggerLink, null); Map<String, String> requestHeaders = getRequestHeaders(options); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(OperationType.Delete, ResourceType.Trigger, path, requestHeaders, options); if (retryPolicyInstance != null){ retryPolicyInstance.onBeforeSendRequest(request); } return this.delete(request).map(response -> toResourceResponse(response, Trigger.class)); } catch (Exception e) { logger.debug("Failure in deleting a Trigger due to [{}]", e.getMessage(), e); return Flux.error(e); } } @Override public Flux<ResourceResponse<Trigger>> readTrigger(String triggerLink, RequestOptions options) { IDocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> readTriggerInternal(triggerLink, options, retryPolicyInstance), retryPolicyInstance); } private Flux<ResourceResponse<Trigger>> readTriggerInternal(String triggerLink, RequestOptions options, IDocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(triggerLink)) { throw new IllegalArgumentException("triggerLink"); } logger.debug("Reading a Trigger. triggerLink [{}]", triggerLink); String path = Utils.joinPath(triggerLink, null); Map<String, String> requestHeaders = getRequestHeaders(options); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(OperationType.Read, ResourceType.Trigger, path, requestHeaders, options); if (retryPolicyInstance != null){ retryPolicyInstance.onBeforeSendRequest(request); } return this.read(request).map(response -> toResourceResponse(response, Trigger.class)); } catch (Exception e) { logger.debug("Failure in reading a Trigger due to [{}]", e.getMessage(), e); return Flux.error(e); } } @Override public Flux<FeedResponse<Trigger>> readTriggers(String collectionLink, FeedOptions options) { if (StringUtils.isEmpty(collectionLink)) { throw new IllegalArgumentException("collectionLink"); } return readFeed(options, ResourceType.Trigger, Trigger.class, Utils.joinPath(collectionLink, Paths.TRIGGERS_PATH_SEGMENT)); } @Override public Flux<FeedResponse<Trigger>> queryTriggers(String collectionLink, String query, FeedOptions options) { return queryTriggers(collectionLink, new SqlQuerySpec(query), options); } @Override public Flux<FeedResponse<Trigger>> queryTriggers(String collectionLink, SqlQuerySpec querySpec, FeedOptions options) { return createQuery(collectionLink, querySpec, options, Trigger.class, ResourceType.Trigger); } @Override public Flux<ResourceResponse<UserDefinedFunction>> createUserDefinedFunction(String collectionLink, UserDefinedFunction udf, RequestOptions options) { IDocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> createUserDefinedFunctionInternal(collectionLink, udf, options, retryPolicyInstance), retryPolicyInstance); } private Flux<ResourceResponse<UserDefinedFunction>> createUserDefinedFunctionInternal(String collectionLink, UserDefinedFunction udf, RequestOptions options, IDocumentClientRetryPolicy retryPolicyInstance) { // we are using an observable factory here // observable will be created fresh upon subscription // this is to ensure we capture most up to date information (e.g., // session) try { logger.debug("Creating a UserDefinedFunction. collectionLink [{}], udf id [{}]", collectionLink, udf.id()); RxDocumentServiceRequest request = getUserDefinedFunctionRequest(collectionLink, udf, options, OperationType.Create); if (retryPolicyInstance != null){ retryPolicyInstance.onBeforeSendRequest(request); } return this.create(request).map(response -> toResourceResponse(response, UserDefinedFunction.class)); } catch (Exception e) { // this is only in trace level to capture what's going on logger.debug("Failure in creating a UserDefinedFunction due to [{}]", e.getMessage(), e); return Flux.error(e); } } @Override public Flux<ResourceResponse<UserDefinedFunction>> upsertUserDefinedFunction(String collectionLink, UserDefinedFunction udf, RequestOptions options) { IDocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> upsertUserDefinedFunctionInternal(collectionLink, udf, options, retryPolicyInstance), retryPolicyInstance); } private Flux<ResourceResponse<UserDefinedFunction>> upsertUserDefinedFunctionInternal(String collectionLink, UserDefinedFunction udf, RequestOptions options, IDocumentClientRetryPolicy retryPolicyInstance) { // we are using an observable factory here // observable will be created fresh upon subscription // this is to ensure we capture most up to date information (e.g., // session) try { logger.debug("Upserting a UserDefinedFunction. collectionLink [{}], udf id [{}]", collectionLink, udf.id()); RxDocumentServiceRequest request = getUserDefinedFunctionRequest(collectionLink, udf, options, OperationType.Upsert); if (retryPolicyInstance != null){ retryPolicyInstance.onBeforeSendRequest(request); } return this.upsert(request).map(response -> toResourceResponse(response, UserDefinedFunction.class)); } catch (Exception e) { // this is only in trace level to capture what's going on logger.debug("Failure in upserting a UserDefinedFunction due to [{}]", e.getMessage(), e); return Flux.error(e); } } @Override public Flux<ResourceResponse<UserDefinedFunction>> replaceUserDefinedFunction(UserDefinedFunction udf, RequestOptions options) { IDocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> replaceUserDefinedFunctionInternal(udf, options, retryPolicyInstance), retryPolicyInstance); } private Flux<ResourceResponse<UserDefinedFunction>> replaceUserDefinedFunctionInternal(UserDefinedFunction udf, RequestOptions options, IDocumentClientRetryPolicy retryPolicyInstance) { // we are using an observable factory here // observable will be created fresh upon subscription // this is to ensure we capture most up to date information (e.g., // session) try { if (udf == null) { throw new IllegalArgumentException("udf"); } logger.debug("Replacing a UserDefinedFunction. udf id [{}]", udf.id()); validateResource(udf); String path = Utils.joinPath(udf.selfLink(), null); Map<String, String> requestHeaders = this.getRequestHeaders(options); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(OperationType.Replace, ResourceType.UserDefinedFunction, path, udf, requestHeaders, options); if (retryPolicyInstance != null){ retryPolicyInstance.onBeforeSendRequest(request); } return this.replace(request).map(response -> toResourceResponse(response, UserDefinedFunction.class)); } catch (Exception e) { // this is only in trace level to capture what's going on logger.debug("Failure in replacing a UserDefinedFunction due to [{}]", e.getMessage(), e); return Flux.error(e); } } @Override public Flux<ResourceResponse<UserDefinedFunction>> deleteUserDefinedFunction(String udfLink, RequestOptions options) { IDocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> deleteUserDefinedFunctionInternal(udfLink, options, retryPolicyInstance), retryPolicyInstance); } private Flux<ResourceResponse<UserDefinedFunction>> deleteUserDefinedFunctionInternal(String udfLink, RequestOptions options, IDocumentClientRetryPolicy retryPolicyInstance) { // we are using an observable factory here // observable will be created fresh upon subscription // this is to ensure we capture most up to date information (e.g., // session) try { if (StringUtils.isEmpty(udfLink)) { throw new IllegalArgumentException("udfLink"); } logger.debug("Deleting a UserDefinedFunction. udfLink [{}]", udfLink); String path = Utils.joinPath(udfLink, null); Map<String, String> requestHeaders = this.getRequestHeaders(options); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(OperationType.Delete, ResourceType.UserDefinedFunction, path, requestHeaders, options); if (retryPolicyInstance != null){ retryPolicyInstance.onBeforeSendRequest(request); } return this.delete(request).map(response -> toResourceResponse(response, UserDefinedFunction.class)); } catch (Exception e) { // this is only in trace level to capture what's going on logger.debug("Failure in deleting a UserDefinedFunction due to [{}]", e.getMessage(), e); return Flux.error(e); } } @Override public Flux<ResourceResponse<UserDefinedFunction>> readUserDefinedFunction(String udfLink, RequestOptions options) { IDocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> readUserDefinedFunctionInternal(udfLink, options, retryPolicyInstance), retryPolicyInstance); } private Flux<ResourceResponse<UserDefinedFunction>> readUserDefinedFunctionInternal(String udfLink, RequestOptions options, IDocumentClientRetryPolicy retryPolicyInstance) { // we are using an observable factory here // observable will be created fresh upon subscription // this is to ensure we capture most up to date information (e.g., // session) try { if (StringUtils.isEmpty(udfLink)) { throw new IllegalArgumentException("udfLink"); } logger.debug("Reading a UserDefinedFunction. udfLink [{}]", udfLink); String path = Utils.joinPath(udfLink, null); Map<String, String> requestHeaders = this.getRequestHeaders(options); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(OperationType.Read, ResourceType.UserDefinedFunction, path, requestHeaders, options); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } return this.read(request).map(response -> toResourceResponse(response, UserDefinedFunction.class)); } catch (Exception e) { // this is only in trace level to capture what's going on logger.debug("Failure in reading a UserDefinedFunction due to [{}]", e.getMessage(), e); return Flux.error(e); } } @Override public Flux<FeedResponse<UserDefinedFunction>> readUserDefinedFunctions(String collectionLink, FeedOptions options) { if (StringUtils.isEmpty(collectionLink)) { throw new IllegalArgumentException("collectionLink"); } return readFeed(options, ResourceType.UserDefinedFunction, UserDefinedFunction.class, Utils.joinPath(collectionLink, Paths.USER_DEFINED_FUNCTIONS_PATH_SEGMENT)); } @Override public Flux<FeedResponse<UserDefinedFunction>> queryUserDefinedFunctions(String collectionLink, String query, FeedOptions options) { return queryUserDefinedFunctions(collectionLink, new SqlQuerySpec(query), options); } @Override public Flux<FeedResponse<UserDefinedFunction>> queryUserDefinedFunctions(String collectionLink, SqlQuerySpec querySpec, FeedOptions options) { return createQuery(collectionLink, querySpec, options, UserDefinedFunction.class, ResourceType.UserDefinedFunction); } @Override public Flux<ResourceResponse<Conflict>> readConflict(String conflictLink, RequestOptions options) { IDocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> readConflictInternal(conflictLink, options, retryPolicyInstance), retryPolicyInstance); } private Flux<ResourceResponse<Conflict>> readConflictInternal(String conflictLink, RequestOptions options, IDocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(conflictLink)) { throw new IllegalArgumentException("conflictLink"); } logger.debug("Reading a Conflict. conflictLink [{}]", conflictLink); String path = Utils.joinPath(conflictLink, null); Map<String, String> requestHeaders = getRequestHeaders(options); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(OperationType.Read, ResourceType.Conflict, path, requestHeaders, options); Flux<RxDocumentServiceRequest> reqObs = addPartitionKeyInformation(request, null, options).flux(); return reqObs.flatMap(req -> { if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } return this.read(request).map(response -> toResourceResponse(response, Conflict.class)); }); } catch (Exception e) { logger.debug("Failure in reading a Conflict due to [{}]", e.getMessage(), e); return Flux.error(e); } } @Override public Flux<FeedResponse<Conflict>> readConflicts(String collectionLink, FeedOptions options) { if (StringUtils.isEmpty(collectionLink)) { throw new IllegalArgumentException("collectionLink"); } return readFeed(options, ResourceType.Conflict, Conflict.class, Utils.joinPath(collectionLink, Paths.CONFLICTS_PATH_SEGMENT)); } @Override public Flux<FeedResponse<Conflict>> queryConflicts(String collectionLink, String query, FeedOptions options) { return queryConflicts(collectionLink, new SqlQuerySpec(query), options); } @Override public Flux<FeedResponse<Conflict>> queryConflicts(String collectionLink, SqlQuerySpec querySpec, FeedOptions options) { return createQuery(collectionLink, querySpec, options, Conflict.class, ResourceType.Conflict); } @Override public Flux<ResourceResponse<Conflict>> deleteConflict(String conflictLink, RequestOptions options) { IDocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> deleteConflictInternal(conflictLink, options, retryPolicyInstance), retryPolicyInstance); } private Flux<ResourceResponse<Conflict>> deleteConflictInternal(String conflictLink, RequestOptions options, IDocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(conflictLink)) { throw new IllegalArgumentException("conflictLink"); } logger.debug("Deleting a Conflict. conflictLink [{}]", conflictLink); String path = Utils.joinPath(conflictLink, null); Map<String, String> requestHeaders = getRequestHeaders(options); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(OperationType.Delete, ResourceType.Conflict, path, requestHeaders, options); Flux<RxDocumentServiceRequest> reqObs = addPartitionKeyInformation(request, null, options).flux(); return reqObs.flatMap(req -> { if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } return this.delete(request).map(response -> toResourceResponse(response, Conflict.class)); }); } catch (Exception e) { logger.debug("Failure in deleting a Conflict due to [{}]", e.getMessage(), e); return Flux.error(e); } } @Override public Flux<ResourceResponse<User>> createUser(String databaseLink, User user, RequestOptions options) { return ObservableHelper.inlineIfPossibleAsObs(() -> createUserInternal(databaseLink, user, options), this.resetSessionTokenRetryPolicy.getRequestPolicy()); } private Flux<ResourceResponse<User>> createUserInternal(String databaseLink, User user, RequestOptions options) { try { logger.debug("Creating a User. databaseLink [{}], user id [{}]", databaseLink, user.id()); RxDocumentServiceRequest request = getUserRequest(databaseLink, user, options, OperationType.Create); return this.create(request).map(response -> toResourceResponse(response, User.class)); } catch (Exception e) { logger.debug("Failure in creating a User due to [{}]", e.getMessage(), e); return Flux.error(e); } } @Override public Flux<ResourceResponse<User>> upsertUser(String databaseLink, User user, RequestOptions options) { IDocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> upsertUserInternal(databaseLink, user, options, retryPolicyInstance), retryPolicyInstance); } private Flux<ResourceResponse<User>> upsertUserInternal(String databaseLink, User user, RequestOptions options, IDocumentClientRetryPolicy retryPolicyInstance) { try { logger.debug("Upserting a User. databaseLink [{}], user id [{}]", databaseLink, user.id()); RxDocumentServiceRequest request = getUserRequest(databaseLink, user, options, OperationType.Upsert); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } return this.upsert(request).map(response -> toResourceResponse(response, User.class)); } catch (Exception e) { logger.debug("Failure in upserting a User due to [{}]", e.getMessage(), e); return Flux.error(e); } } private RxDocumentServiceRequest getUserRequest(String databaseLink, User user, RequestOptions options, OperationType operationType) { if (StringUtils.isEmpty(databaseLink)) { throw new IllegalArgumentException("databaseLink"); } if (user == null) { throw new IllegalArgumentException("user"); } RxDocumentClientImpl.validateResource(user); String path = Utils.joinPath(databaseLink, Paths.USERS_PATH_SEGMENT); Map<String, String> requestHeaders = getRequestHeaders(options); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(operationType, ResourceType.User, path, user, requestHeaders, options); return request; } @Override public Flux<ResourceResponse<User>> replaceUser(User user, RequestOptions options) { IDocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> replaceUserInternal(user, options, retryPolicyInstance), retryPolicyInstance); } private Flux<ResourceResponse<User>> replaceUserInternal(User user, RequestOptions options, IDocumentClientRetryPolicy retryPolicyInstance) { try { if (user == null) { throw new IllegalArgumentException("user"); } logger.debug("Replacing a User. user id [{}]", user.id()); RxDocumentClientImpl.validateResource(user); String path = Utils.joinPath(user.selfLink(), null); Map<String, String> requestHeaders = getRequestHeaders(options); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(OperationType.Replace, ResourceType.User, path, user, requestHeaders, options); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } return this.replace(request).map(response -> toResourceResponse(response, User.class)); } catch (Exception e) { logger.debug("Failure in replacing a User due to [{}]", e.getMessage(), e); return Flux.error(e); } } public Flux<ResourceResponse<User>> deleteUser(String userLink, RequestOptions options) { IDocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> deleteUserInternal(userLink, options, retryPolicyInstance), retryPolicyInstance); } private Flux<ResourceResponse<User>> deleteUserInternal(String userLink, RequestOptions options, IDocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(userLink)) { throw new IllegalArgumentException("userLink"); } logger.debug("Deleting a User. userLink [{}]", userLink); String path = Utils.joinPath(userLink, null); Map<String, String> requestHeaders = getRequestHeaders(options); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(OperationType.Delete, ResourceType.User, path, requestHeaders, options); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } return this.delete(request).map(response -> toResourceResponse(response, User.class)); } catch (Exception e) { logger.debug("Failure in deleting a User due to [{}]", e.getMessage(), e); return Flux.error(e); } } @Override public Flux<ResourceResponse<User>> readUser(String userLink, RequestOptions options) { IDocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> readUserInternal(userLink, options, retryPolicyInstance), retryPolicyInstance); } private Flux<ResourceResponse<User>> readUserInternal(String userLink, RequestOptions options, IDocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(userLink)) { throw new IllegalArgumentException("userLink"); } logger.debug("Reading a User. userLink [{}]", userLink); String path = Utils.joinPath(userLink, null); Map<String, String> requestHeaders = getRequestHeaders(options); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(OperationType.Read, ResourceType.User, path, requestHeaders, options); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } return this.read(request).map(response -> toResourceResponse(response, User.class)); } catch (Exception e) { logger.debug("Failure in reading a User due to [{}]", e.getMessage(), e); return Flux.error(e); } } @Override public Flux<FeedResponse<User>> readUsers(String databaseLink, FeedOptions options) { if (StringUtils.isEmpty(databaseLink)) { throw new IllegalArgumentException("databaseLink"); } return readFeed(options, ResourceType.User, User.class, Utils.joinPath(databaseLink, Paths.USERS_PATH_SEGMENT)); } @Override public Flux<FeedResponse<User>> queryUsers(String databaseLink, String query, FeedOptions options) { return queryUsers(databaseLink, new SqlQuerySpec(query), options); } @Override public Flux<FeedResponse<User>> queryUsers(String databaseLink, SqlQuerySpec querySpec, FeedOptions options) { return createQuery(databaseLink, querySpec, options, User.class, ResourceType.User); } @Override public Flux<ResourceResponse<Permission>> createPermission(String userLink, Permission permission, RequestOptions options) { return ObservableHelper.inlineIfPossibleAsObs(() -> createPermissionInternal(userLink, permission, options), this.resetSessionTokenRetryPolicy.getRequestPolicy()); } private Flux<ResourceResponse<Permission>> createPermissionInternal(String userLink, Permission permission, RequestOptions options) { try { logger.debug("Creating a Permission. userLink [{}], permission id [{}]", userLink, permission.id()); RxDocumentServiceRequest request = getPermissionRequest(userLink, permission, options, OperationType.Create); return this.create(request).map(response -> toResourceResponse(response, Permission.class)); } catch (Exception e) { logger.debug("Failure in creating a Permission due to [{}]", e.getMessage(), e); return Flux.error(e); } } @Override public Flux<ResourceResponse<Permission>> upsertPermission(String userLink, Permission permission, RequestOptions options) { IDocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> upsertPermissionInternal(userLink, permission, options, retryPolicyInstance), retryPolicyInstance); } private Flux<ResourceResponse<Permission>> upsertPermissionInternal(String userLink, Permission permission, RequestOptions options, IDocumentClientRetryPolicy retryPolicyInstance) { try { logger.debug("Upserting a Permission. userLink [{}], permission id [{}]", userLink, permission.id()); RxDocumentServiceRequest request = getPermissionRequest(userLink, permission, options, OperationType.Upsert); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } return this.upsert(request).map(response -> toResourceResponse(response, Permission.class)); } catch (Exception e) { logger.debug("Failure in upserting a Permission due to [{}]", e.getMessage(), e); return Flux.error(e); } } private RxDocumentServiceRequest getPermissionRequest(String userLink, Permission permission, RequestOptions options, OperationType operationType) { if (StringUtils.isEmpty(userLink)) { throw new IllegalArgumentException("userLink"); } if (permission == null) { throw new IllegalArgumentException("permission"); } RxDocumentClientImpl.validateResource(permission); String path = Utils.joinPath(userLink, Paths.PERMISSIONS_PATH_SEGMENT); Map<String, String> requestHeaders = getRequestHeaders(options); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(operationType, ResourceType.Permission, path, permission, requestHeaders, options); return request; } @Override public Flux<ResourceResponse<Permission>> replacePermission(Permission permission, RequestOptions options) { IDocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> replacePermissionInternal(permission, options, retryPolicyInstance), retryPolicyInstance); } private Flux<ResourceResponse<Permission>> replacePermissionInternal(Permission permission, RequestOptions options, IDocumentClientRetryPolicy retryPolicyInstance) { try { if (permission == null) { throw new IllegalArgumentException("permission"); } logger.debug("Replacing a Permission. permission id [{}]", permission.id()); RxDocumentClientImpl.validateResource(permission); String path = Utils.joinPath(permission.selfLink(), null); Map<String, String> requestHeaders = getRequestHeaders(options); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(OperationType.Replace, ResourceType.Permission, path, permission, requestHeaders, options); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } return this.replace(request).map(response -> toResourceResponse(response, Permission.class)); } catch (Exception e) { logger.debug("Failure in replacing a Permission due to [{}]", e.getMessage(), e); return Flux.error(e); } } @Override public Flux<ResourceResponse<Permission>> deletePermission(String permissionLink, RequestOptions options) { IDocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> deletePermissionInternal(permissionLink, options, retryPolicyInstance), retryPolicyInstance); } private Flux<ResourceResponse<Permission>> deletePermissionInternal(String permissionLink, RequestOptions options, IDocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(permissionLink)) { throw new IllegalArgumentException("permissionLink"); } logger.debug("Deleting a Permission. permissionLink [{}]", permissionLink); String path = Utils.joinPath(permissionLink, null); Map<String, String> requestHeaders = getRequestHeaders(options); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(OperationType.Delete, ResourceType.Permission, path, requestHeaders, options); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } return this.delete(request).map(response -> toResourceResponse(response, Permission.class)); } catch (Exception e) { logger.debug("Failure in deleting a Permission due to [{}]", e.getMessage(), e); return Flux.error(e); } } @Override public Flux<ResourceResponse<Permission>> readPermission(String permissionLink, RequestOptions options) { IDocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> readPermissionInternal(permissionLink, options, retryPolicyInstance), retryPolicyInstance); } private Flux<ResourceResponse<Permission>> readPermissionInternal(String permissionLink, RequestOptions options, IDocumentClientRetryPolicy retryPolicyInstance ) { try { if (StringUtils.isEmpty(permissionLink)) { throw new IllegalArgumentException("permissionLink"); } logger.debug("Reading a Permission. permissionLink [{}]", permissionLink); String path = Utils.joinPath(permissionLink, null); Map<String, String> requestHeaders = getRequestHeaders(options); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(OperationType.Read, ResourceType.Permission, path, requestHeaders, options); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } return this.read(request).map(response -> toResourceResponse(response, Permission.class)); } catch (Exception e) { logger.debug("Failure in reading a Permission due to [{}]", e.getMessage(), e); return Flux.error(e); } } @Override public Flux<FeedResponse<Permission>> readPermissions(String userLink, FeedOptions options) { if (StringUtils.isEmpty(userLink)) { throw new IllegalArgumentException("userLink"); } return readFeed(options, ResourceType.Permission, Permission.class, Utils.joinPath(userLink, Paths.PERMISSIONS_PATH_SEGMENT)); } @Override public Flux<FeedResponse<Permission>> queryPermissions(String userLink, String query, FeedOptions options) { return queryPermissions(userLink, new SqlQuerySpec(query), options); } @Override public Flux<FeedResponse<Permission>> queryPermissions(String userLink, SqlQuerySpec querySpec, FeedOptions options) { return createQuery(userLink, querySpec, options, Permission.class, ResourceType.Permission); } @Override public Flux<ResourceResponse<Offer>> replaceOffer(Offer offer) { return ObservableHelper.inlineIfPossibleAsObs(() -> replaceOfferInternal(offer), this.resetSessionTokenRetryPolicy.getRequestPolicy()); } private Flux<ResourceResponse<Offer>> replaceOfferInternal(Offer offer) { try { if (offer == null) { throw new IllegalArgumentException("offer"); } logger.debug("Replacing an Offer. offer id [{}]", offer.id()); RxDocumentClientImpl.validateResource(offer); String path = Utils.joinPath(offer.selfLink(), null); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(OperationType.Replace, ResourceType.Offer, path, offer, null, null); return this.replace(request).map(response -> toResourceResponse(response, Offer.class)); } catch (Exception e) { logger.debug("Failure in replacing an Offer due to [{}]", e.getMessage(), e); return Flux.error(e); } } @Override public Flux<ResourceResponse<Offer>> readOffer(String offerLink) { IDocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> readOfferInternal(offerLink, retryPolicyInstance), retryPolicyInstance); } private Flux<ResourceResponse<Offer>> readOfferInternal(String offerLink, IDocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(offerLink)) { throw new IllegalArgumentException("offerLink"); } logger.debug("Reading an Offer. offerLink [{}]", offerLink); String path = Utils.joinPath(offerLink, null); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(OperationType.Read, ResourceType.Offer, path, (HashMap<String, String>)null, null); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } return this.read(request).map(response -> toResourceResponse(response, Offer.class)); } catch (Exception e) { logger.debug("Failure in reading an Offer due to [{}]", e.getMessage(), e); return Flux.error(e); } } @Override public Flux<FeedResponse<Offer>> readOffers(FeedOptions options) { return readFeed(options, ResourceType.Offer, Offer.class, Utils.joinPath(Paths.OFFERS_PATH_SEGMENT, null)); } private <T extends Resource> Flux<FeedResponse<T>> readFeedCollectionChild(FeedOptions options, ResourceType resourceType, Class<T> klass, String resourceLink) { if (options == null) { options = new FeedOptions(); } int maxPageSize = options.maxItemCount() != null ? options.maxItemCount() : -1; final FeedOptions finalFeedOptions = options; RequestOptions requestOptions = new RequestOptions(); requestOptions.setPartitionKey(options.partitionKey()); BiFunction<String, Integer, RxDocumentServiceRequest> createRequestFunc = (continuationToken, pageSize) -> { Map<String, String> requestHeaders = new HashMap<>(); if (continuationToken != null) { requestHeaders.put(HttpConstants.HttpHeaders.CONTINUATION, continuationToken); } requestHeaders.put(HttpConstants.HttpHeaders.PAGE_SIZE, Integer.toString(pageSize)); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(OperationType.ReadFeed, resourceType, resourceLink, requestHeaders, finalFeedOptions); return request; }; Function<RxDocumentServiceRequest, Flux<FeedResponse<T>>> executeFunc = request -> { return ObservableHelper.inlineIfPossibleAsObs(() -> { Mono<DocumentCollection> collectionObs = this.collectionCache.resolveCollectionAsync(request); Mono<RxDocumentServiceRequest> requestObs = this.addPartitionKeyInformation(request, null, requestOptions, collectionObs); return requestObs.flux().flatMap(req -> this.readFeed(req) .map(response -> toFeedResponsePage(response, klass))); }, this.resetSessionTokenRetryPolicy.getRequestPolicy()); }; return Paginator.getPaginatedQueryResultAsObservable(options, createRequestFunc, executeFunc, klass, maxPageSize); } private <T extends Resource> Flux<FeedResponse<T>> readFeed(FeedOptions options, ResourceType resourceType, Class<T> klass, String resourceLink) { if (options == null) { options = new FeedOptions(); } int maxPageSize = options.maxItemCount() != null ? options.maxItemCount() : -1; final FeedOptions finalFeedOptions = options; BiFunction<String, Integer, RxDocumentServiceRequest> createRequestFunc = (continuationToken, pageSize) -> { Map<String, String> requestHeaders = new HashMap<>(); if (continuationToken != null) { requestHeaders.put(HttpConstants.HttpHeaders.CONTINUATION, continuationToken); } requestHeaders.put(HttpConstants.HttpHeaders.PAGE_SIZE, Integer.toString(pageSize)); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(OperationType.ReadFeed, resourceType, resourceLink, requestHeaders, finalFeedOptions); return request; }; Function<RxDocumentServiceRequest, Flux<FeedResponse<T>>> executeFunc = request -> { return ObservableHelper.inlineIfPossibleAsObs(() -> readFeed(request).map(response -> toFeedResponsePage(response, klass)), this.resetSessionTokenRetryPolicy.getRequestPolicy()); }; return Paginator.getPaginatedQueryResultAsObservable(options, createRequestFunc, executeFunc, klass, maxPageSize); } @Override public Flux<FeedResponse<Offer>> queryOffers(String query, FeedOptions options) { return queryOffers(new SqlQuerySpec(query), options); } @Override public Flux<FeedResponse<Offer>> queryOffers(SqlQuerySpec querySpec, FeedOptions options) { return createQuery(null, querySpec, options, Offer.class, ResourceType.Offer); } @Override public Flux<DatabaseAccount> getDatabaseAccount() { return ObservableHelper.inlineIfPossibleAsObs(() -> getDatabaseAccountInternal(), this.resetSessionTokenRetryPolicy.getRequestPolicy()); } private Flux<DatabaseAccount> getDatabaseAccountInternal() { try { logger.debug("Getting Database Account"); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(OperationType.Read, ResourceType.DatabaseAccount, "", // path (HashMap<String, String>) null, null); return this.read(request).map(response -> toDatabaseAccount(response)); } catch (Exception e) { logger.debug("Failure in getting Database Account due to [{}]", e.getMessage(), e); return Flux.error(e); } } public Object getSession() { return this.sessionContainer; } public void setSession(Object sessionContainer) { this.sessionContainer = (SessionContainer) sessionContainer; } public RxPartitionKeyRangeCache getPartitionKeyRangeCache() { return partitionKeyRangeCache; } public Flux<DatabaseAccount> getDatabaseAccountFromEndpoint(URI endpoint) { return Flux.defer(() -> { RxDocumentServiceRequest request = RxDocumentServiceRequest.create(OperationType.Read, ResourceType.DatabaseAccount, "", null, (Object) null); this.populateHeaders(request, HttpConstants.HttpMethods.GET); request.setEndpointOverride(endpoint); return this.gatewayProxy.processMessage(request).doOnError(e -> { String message = String.format("Failed to retrieve database account information. %s", e.getCause() != null ? e.getCause().toString() : e.toString()); logger.warn(message); }).map(rsp -> rsp.getResource(DatabaseAccount.class)) .doOnNext(databaseAccount -> { this.useMultipleWriteLocations = this.connectionPolicy.usingMultipleWriteLocations() && BridgeInternal.isEnableMultipleWriteLocations(databaseAccount); }); }); } /** * Certain requests must be routed through gateway even when the client connectivity mode is direct. * * @param request * @return RxStoreModel */ private RxStoreModel getStoreProxy(RxDocumentServiceRequest request) { // If a request is configured to always use GATEWAY mode(in some cases when targeting .NET Core) // we return the GATEWAY store model if (request.UseGatewayMode) { return this.gatewayProxy; } ResourceType resourceType = request.getResourceType(); OperationType operationType = request.getOperationType(); if (resourceType == ResourceType.Offer || resourceType.isScript() && operationType != OperationType.ExecuteJavaScript || resourceType == ResourceType.PartitionKeyRange) { return this.gatewayProxy; } if (operationType == OperationType.Create || operationType == OperationType.Upsert) { if (resourceType == ResourceType.Database || resourceType == ResourceType.User || resourceType == ResourceType.DocumentCollection || resourceType == ResourceType.Permission) { return this.gatewayProxy; } else { return this.storeModel; } } else if (operationType == OperationType.Delete) { if (resourceType == ResourceType.Database || resourceType == ResourceType.User || resourceType == ResourceType.DocumentCollection) { return this.gatewayProxy; } else { return this.storeModel; } } else if (operationType == OperationType.Replace) { if (resourceType == ResourceType.DocumentCollection) { return this.gatewayProxy; } else { return this.storeModel; } } else if (operationType == OperationType.Read) { if (resourceType == ResourceType.DocumentCollection) { return this.gatewayProxy; } else { return this.storeModel; } } else { if ((request.getOperationType() == OperationType.Query || request.getOperationType() == OperationType.SqlQuery) && Utils.isCollectionChild(request.getResourceType())) { if (request.getPartitionKeyRangeIdentity() == null) { return this.gatewayProxy; } } return this.storeModel; } } @Override public void close() { logger.info("Shutting down ..."); LifeCycleUtils.closeQuietly(this.globalEndpointManager); LifeCycleUtils.closeQuietly(this.storeClientFactory); try { this.reactorHttpClient.shutdown(); } catch (Exception e) { logger.warn("Failure in shutting down reactorHttpClient", e); } } }
3e0bccac64c858b8ea93da1bd5a6b78f71032984
13,364
java
Java
compiler/frontend/src/org/jetbrains/kotlin/cfg/WhenChecker.java
kotlin-playground/kotlin
3ca7925138e48e065cf698418ae389dd1fd3c11b
[ "Apache-2.0" ]
null
null
null
compiler/frontend/src/org/jetbrains/kotlin/cfg/WhenChecker.java
kotlin-playground/kotlin
3ca7925138e48e065cf698418ae389dd1fd3c11b
[ "Apache-2.0" ]
null
null
null
compiler/frontend/src/org/jetbrains/kotlin/cfg/WhenChecker.java
kotlin-playground/kotlin
3ca7925138e48e065cf698418ae389dd1fd3c11b
[ "Apache-2.0" ]
null
null
null
49.313653
141
0.662002
4,984
/* * Copyright 2010-2015 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.kotlin.cfg; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.kotlin.builtins.KotlinBuiltIns; import org.jetbrains.kotlin.descriptors.*; import org.jetbrains.kotlin.psi.*; import org.jetbrains.kotlin.resolve.BindingContext; import org.jetbrains.kotlin.resolve.BindingTrace; import org.jetbrains.kotlin.resolve.CompileTimeConstantUtils; import org.jetbrains.kotlin.resolve.DescriptorUtils; import org.jetbrains.kotlin.resolve.bindingContextUtil.BindingContextUtilsKt; import org.jetbrains.kotlin.types.FlexibleTypesKt; import org.jetbrains.kotlin.types.KotlinType; import org.jetbrains.kotlin.types.TypeUtils; import java.util.HashSet; import java.util.Set; import static org.jetbrains.kotlin.resolve.DescriptorUtils.isEnumEntry; import static org.jetbrains.kotlin.resolve.DescriptorUtils.isEnumClass; public final class WhenChecker { private WhenChecker() { } public static boolean mustHaveElse(@NotNull KtWhenExpression expression, @NotNull BindingTrace trace) { KotlinType expectedType = trace.get(BindingContext.EXPECTED_EXPRESSION_TYPE, expression); boolean isUnit = expectedType != null && KotlinBuiltIns.isUnit(expectedType); // Some "statements" are actually expressions returned from lambdas, their expected types are non-null boolean isStatement = BindingContextUtilsKt.isUsedAsStatement(expression, trace.getBindingContext()) && expectedType == null; return !isUnit && !isStatement && !isWhenExhaustive(expression, trace); } public static boolean isWhenByEnum(@NotNull KtWhenExpression expression, @NotNull BindingContext context) { return getClassDescriptorOfTypeIfEnum(whenSubjectType(expression, context)) != null; } @Nullable public static ClassDescriptor getClassDescriptorOfTypeIfEnum(@Nullable KotlinType type) { if (type == null) return null; ClassDescriptor classDescriptor = TypeUtils.getClassDescriptor(type); if (classDescriptor == null) return null; if (classDescriptor.getKind() != ClassKind.ENUM_CLASS || classDescriptor.getModality().isOverridable()) return null; return classDescriptor; } @Nullable private static KotlinType whenSubjectType(@NotNull KtWhenExpression expression, @NotNull BindingContext context) { KtExpression subjectExpression = expression.getSubjectExpression(); return subjectExpression == null ? null : context.getType(subjectExpression); } private static boolean isWhenOnBooleanExhaustive(@NotNull KtWhenExpression expression, @NotNull BindingTrace trace) { // It's assumed (and not checked) that expression is of the boolean type boolean containsFalse = false; boolean containsTrue = false; for (KtWhenEntry whenEntry: expression.getEntries()) { for (KtWhenCondition whenCondition : whenEntry.getConditions()) { if (whenCondition instanceof KtWhenConditionWithExpression) { KtExpression whenExpression = ((KtWhenConditionWithExpression) whenCondition).getExpression(); if (CompileTimeConstantUtils.canBeReducedToBooleanConstant(whenExpression, trace, true)) containsTrue = true; if (CompileTimeConstantUtils.canBeReducedToBooleanConstant(whenExpression, trace, false)) containsFalse = true; } } } return containsFalse && containsTrue; } public static boolean isWhenOnEnumExhaustive( @NotNull KtWhenExpression expression, @NotNull BindingTrace trace, @NotNull ClassDescriptor enumClassDescriptor ) { assert isEnumClass(enumClassDescriptor) : "isWhenOnEnumExhaustive should be called with an enum class descriptor"; Set<ClassDescriptor> entryDescriptors = new HashSet<ClassDescriptor>(); for (DeclarationDescriptor descriptor : DescriptorUtils.getAllDescriptors(enumClassDescriptor.getUnsubstitutedInnerClassesScope())) { if (isEnumEntry(descriptor)) { entryDescriptors.add((ClassDescriptor) descriptor); } } return !entryDescriptors.isEmpty() && containsAllClassCases(expression, entryDescriptors, trace); } private static void collectNestedSubclasses( @NotNull ClassDescriptor baseDescriptor, @NotNull ClassDescriptor currentDescriptor, @NotNull Set<ClassDescriptor> subclasses ) { for (DeclarationDescriptor descriptor : DescriptorUtils.getAllDescriptors(currentDescriptor.getUnsubstitutedInnerClassesScope())) { if (descriptor instanceof ClassDescriptor) { ClassDescriptor memberClassDescriptor = (ClassDescriptor) descriptor; if (DescriptorUtils.isDirectSubclass(memberClassDescriptor, baseDescriptor)) { subclasses.add(memberClassDescriptor); } collectNestedSubclasses(baseDescriptor, memberClassDescriptor, subclasses); } } } private static boolean isWhenOnSealedClassExhaustive( @NotNull KtWhenExpression expression, @NotNull BindingTrace trace, @NotNull ClassDescriptor classDescriptor ) { assert classDescriptor.getModality() == Modality.SEALED : "isWhenOnSealedClassExhaustive should be called with a sealed class descriptor"; Set<ClassDescriptor> memberClassDescriptors = new HashSet<ClassDescriptor>(); collectNestedSubclasses(classDescriptor, classDescriptor, memberClassDescriptors); // When on a sealed class without derived members is considered non-exhaustive (see test WhenOnEmptySealed) return !memberClassDescriptors.isEmpty() && containsAllClassCases(expression, memberClassDescriptors, trace); } /** * It's assumed that function is called for a final type. In this case the only possible smart cast is to not nullable type. * @return true if type is nullable, and cannot be smart casted */ private static boolean isNullableTypeWithoutPossibleSmartCast( @Nullable KtExpression expression, @NotNull KotlinType type, @NotNull BindingContext context ) { if (expression == null) return false; // Normally should not happen if (!TypeUtils.isNullableType(type)) return false; // We cannot read data flow information here due to lack of inputs (module descriptor is necessary) if (context.get(BindingContext.SMARTCAST, expression) != null) { // We have smart cast from enum or boolean to something // Not very nice but we *can* decide it was smart cast to not-null // because both enum and boolean are final return false; } return true; } public static boolean isWhenExhaustive(@NotNull KtWhenExpression expression, @NotNull BindingTrace trace) { KotlinType type = whenSubjectType(expression, trace.getBindingContext()); if (type == null) return false; ClassDescriptor enumClassDescriptor = getClassDescriptorOfTypeIfEnum(type); boolean exhaustive; if (enumClassDescriptor == null) { if (KotlinBuiltIns.isBoolean(TypeUtils.makeNotNullable(type))) { exhaustive = isWhenOnBooleanExhaustive(expression, trace); } else { ClassDescriptor classDescriptor = TypeUtils.getClassDescriptor(type); exhaustive = (classDescriptor != null && classDescriptor.getModality() == Modality.SEALED && isWhenOnSealedClassExhaustive(expression, trace, classDescriptor)); } } else { exhaustive = isWhenOnEnumExhaustive(expression, trace, enumClassDescriptor); } if (exhaustive) { if (// Flexible (nullable) enum types are also counted as exhaustive (enumClassDescriptor != null && FlexibleTypesKt.isFlexible(type)) || containsNullCase(expression, trace) || !isNullableTypeWithoutPossibleSmartCast(expression.getSubjectExpression(), type, trace.getBindingContext())) { trace.record(BindingContext.EXHAUSTIVE_WHEN, expression); return true; } } return false; } private static boolean containsAllClassCases( @NotNull KtWhenExpression whenExpression, @NotNull Set<ClassDescriptor> memberDescriptors, @NotNull BindingTrace trace ) { Set<ClassDescriptor> checkedDescriptors = new HashSet<ClassDescriptor>(); for (KtWhenEntry whenEntry : whenExpression.getEntries()) { for (KtWhenCondition condition : whenEntry.getConditions()) { boolean negated = false; ClassDescriptor checkedDescriptor = null; if (condition instanceof KtWhenConditionIsPattern) { KtWhenConditionIsPattern conditionIsPattern = (KtWhenConditionIsPattern) condition; KotlinType checkedType = trace.get(BindingContext.TYPE, conditionIsPattern.getTypeReference()); if (checkedType != null) { checkedDescriptor = TypeUtils.getClassDescriptor(checkedType); } negated = conditionIsPattern.isNegated(); } else if (condition instanceof KtWhenConditionWithExpression) { KtWhenConditionWithExpression conditionWithExpression = (KtWhenConditionWithExpression) condition; if (conditionWithExpression.getExpression() != null) { KtSimpleNameExpression reference = getReference(conditionWithExpression.getExpression()); if (reference != null) { DeclarationDescriptor target = trace.get(BindingContext.REFERENCE_TARGET, reference); if (target instanceof ClassDescriptor) { checkedDescriptor = (ClassDescriptor) target; } } } } // Checks are important only for nested subclasses of the sealed class // In additional, check without "is" is important only for objects if (checkedDescriptor == null || !memberDescriptors.contains(checkedDescriptor) || (condition instanceof KtWhenConditionWithExpression && !DescriptorUtils.isObject(checkedDescriptor) && !DescriptorUtils.isEnumEntry(checkedDescriptor))) { continue; } if (negated) { if (checkedDescriptors.contains(checkedDescriptor)) return true; // all members are already there checkedDescriptors.addAll(memberDescriptors); checkedDescriptors.remove(checkedDescriptor); } else { checkedDescriptors.add(checkedDescriptor); } } } return checkedDescriptors.containsAll(memberDescriptors); } public static boolean containsNullCase(@NotNull KtWhenExpression expression, @NotNull BindingTrace trace) { for (KtWhenEntry entry : expression.getEntries()) { for (KtWhenCondition condition : entry.getConditions()) { if (condition instanceof KtWhenConditionWithExpression) { KtWhenConditionWithExpression conditionWithExpression = (KtWhenConditionWithExpression) condition; if (conditionWithExpression.getExpression() != null) { KotlinType type = trace.getBindingContext().getType(conditionWithExpression.getExpression()); if (type != null && KotlinBuiltIns.isNothingOrNullableNothing(type)) { return true; } } } } } return false; } @Nullable private static KtSimpleNameExpression getReference(@Nullable KtExpression expression) { if (expression == null) { return null; } if (expression instanceof KtSimpleNameExpression) { return (KtSimpleNameExpression) expression; } if (expression instanceof KtQualifiedExpression) { return getReference(((KtQualifiedExpression) expression).getSelectorExpression()); } return null; } }
3e0bcdb8211b8f32ecc979de7c316fe28c6ba4ce
721
java
Java
freeman-app/src/main/java/com.freeman/common/base/controller/BaseController.java
lzxorz/freeman
223b959313958003415904a2192e55535e372632
[ "Apache-2.0" ]
4
2019-11-11T12:54:25.000Z
2021-01-13T15:48:57.000Z
freeman-app/src/main/java/com.freeman/common/base/controller/BaseController.java
lzxorz/freeman
223b959313958003415904a2192e55535e372632
[ "Apache-2.0" ]
6
2021-08-02T17:03:42.000Z
2022-02-27T06:22:22.000Z
freeman-app/src/main/java/com.freeman/common/base/controller/BaseController.java
lzxorz/freeman
223b959313958003415904a2192e55535e372632
[ "Apache-2.0" ]
3
2021-08-19T06:40:09.000Z
2021-12-04T10:25:10.000Z
21.757576
82
0.644847
4,985
package com.freeman.common.base.controller; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * * @description BaseController 貌似没啥用 * @author 刘志新 * @email dycjh@example.com * @date 19-6-10 上午10:15 * @Param * @return **/ public class BaseController { protected final Logger logger = LoggerFactory.getLogger(BaseController.class); /** 将前台传递过来的日期格式的字符串,自动转化为Date类型 */ /*@InitBinder public void initBinder(WebDataBinder binder){ // Date 类型转换 binder.registerCustomEditor(Date.class, new PropertyEditorSupport(){ @Override public void setAsText(String text){ setValue(DateUtil.parse(text)); } }); }*/ }
3e0bcf562a98b2ee404fdfe4ef4a6ab114e5c788
655
java
Java
src/main/java/org/ga4gh/starterkit/passport/broker/exception/PassportBrokerCustomExceptionResponse.java
ga4gh/ga4gh-starter-kit-passport
a793e2d41db6d6089a881c9c2b7ed45a4a7a4284
[ "Apache-2.0" ]
null
null
null
src/main/java/org/ga4gh/starterkit/passport/broker/exception/PassportBrokerCustomExceptionResponse.java
ga4gh/ga4gh-starter-kit-passport
a793e2d41db6d6089a881c9c2b7ed45a4a7a4284
[ "Apache-2.0" ]
1
2021-11-24T18:10:20.000Z
2021-11-24T18:10:20.000Z
src/main/java/org/ga4gh/starterkit/passport/broker/exception/PassportBrokerCustomExceptionResponse.java
ga4gh/ga4gh-starter-kit-passport
a793e2d41db6d6089a881c9c2b7ed45a4a7a4284
[ "Apache-2.0" ]
null
null
null
29.772727
84
0.798473
4,986
package org.ga4gh.starterkit.passport.broker.exception; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.databind.PropertyNamingStrategies; import com.fasterxml.jackson.databind.annotation.JsonNaming; import org.ga4gh.starterkit.common.exception.CustomExceptionResponse; @JsonInclude(JsonInclude.Include.NON_EMPTY) @JsonNaming(PropertyNamingStrategies.SnakeCaseStrategy.class) public class PassportBrokerCustomExceptionResponse extends CustomExceptionResponse { private String path; public void setPath(String path) { this.path = path; } public String getPath() { return path; } }
3e0bcf7ec445318d39bbb02f6e64907f2ab278e1
464
java
Java
src/main/java/io/turbine/core/web/handlers/ResponseTypeEnum.java
fabien33700/turbine-framework
86d787a47ac75f34cc6396590652cfc8372d5da3
[ "MIT" ]
null
null
null
src/main/java/io/turbine/core/web/handlers/ResponseTypeEnum.java
fabien33700/turbine-framework
86d787a47ac75f34cc6396590652cfc8372d5da3
[ "MIT" ]
6
2018-11-03T00:35:37.000Z
2018-12-23T01:18:51.000Z
src/main/java/io/turbine/core/web/handlers/ResponseTypeEnum.java
fabien33700/turbine-framework
86d787a47ac75f34cc6396590652cfc8372d5da3
[ "MIT" ]
null
null
null
21.090909
61
0.721983
4,987
package io.turbine.core.web.handlers; import static io.turbine.core.web.handlers.ResponseAdapter.*; public enum ResponseTypeEnum { JSON(jsonAdapter()), TEXT(plainTextAdapter()), XML(xmlAdapter()); private final ResponseAdapter responseAdapter; ResponseTypeEnum(ResponseAdapter responseAdapter) { this.responseAdapter = responseAdapter; } public ResponseAdapter responseAdapter() { return responseAdapter; } }
3e0bd03b3929cd32ddd857186b08125b832dc77f
2,905
java
Java
python/experiments/projects/seedstack-business/real_error_dataset/1/51/BaseFactory.java
andre15silva/styler
f3d752d2785c2ab76bacbe5793bd8306ac7961a1
[ "MIT" ]
null
null
null
python/experiments/projects/seedstack-business/real_error_dataset/1/51/BaseFactory.java
andre15silva/styler
f3d752d2785c2ab76bacbe5793bd8306ac7961a1
[ "MIT" ]
null
null
null
python/experiments/projects/seedstack-business/real_error_dataset/1/51/BaseFactory.java
andre15silva/styler
f3d752d2785c2ab76bacbe5793bd8306ac7961a1
[ "MIT" ]
null
null
null
37.727273
107
0.692255
4,988
/* * Copyright © 2013-2019, The SeedStack authors <http://seedstack.org> * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package org.seedstack.business.domain; import static org.seedstack.shed.reflect.ReflectUtils.makeAccessible; import java.lang.reflect.Constructor; import java.util.Arrays; import org.seedstack.business.internal.BusinessErrorCode; import org.seedstack.business.internal.BusinessException; import org.seedstack.business.internal.utils.BusinessUtils; import org.seedstack.business.internal.utils.MethodMatcher; /** * An helper base class that can be extended to create an <strong>implementation</strong> of a * factory interface which, in turn, must extend {@link Factory}. * * <p> This base implementation provides generic object creation through the {@link * #create(Object...)} method that will resolve a constructor with the same argument types as its * own and invoke it. </p> * * @param <P> Type of the produced object. * @see Factory */ public abstract class BaseFactory<P extends Producible> implements Factory<P> { private final Class<P> producedClass; /** * Creates a base domain factory. Actual class produced by the factory is determined by * reflection. */ @SuppressWarnings("unchecked") protected BaseFactory() { this.producedClass = (Class<P>) BusinessUtils.resolveGenerics(Factory.class, getClass())[0]; } /** * Creates a base domain factory. Actual class produced by the factory is specified explicitly. * This can be used to create a dynamic implementation of a factory. * * @param producedClass the produced class. */ protected BaseFactory(Class<P> producedClass) { this.producedClass = producedClass; } @Override public Class<P> getProducedClass() { return producedClass; } @Override public P create(Object... args) { Class<P> effectivelyProducedClass = getProducedClass(); Constructor<P> constructor = MethodMatcher.findMatchingConstructor(effectivelyProducedClass, args); if (constructor == null) { throw BusinessException.createNew(BusinessErrorCode.DOMAIN_OBJECT_CONSTRUCTOR_NOT_FOUND) .put("domainObject", effectivelyProducedClass) .put("parameters", Arrays.toString(args)); } try { return makeAccessible(constructor).newInstance(args); } catch (Exception e) { throw BusinessException.wrap(e, BusinessErrorCode.UNABLE_TO_INVOKE_CONSTRUCTOR) .put("constructor", constructor) .put("domainObject", effectivelyProducedClass) .put("parameters", Arrays.toString(args)); } } }
3e0bd10cec0c92ed5018baed52f5706a78817ab9
302
java
Java
gulimall-common/src/main/java/com/atguigu/common/constant/AuthServerConstant.java
gzqnb/springcloud
b7f1ef3e78155230502a3058195deb088904b547
[ "Apache-2.0" ]
null
null
null
gulimall-common/src/main/java/com/atguigu/common/constant/AuthServerConstant.java
gzqnb/springcloud
b7f1ef3e78155230502a3058195deb088904b547
[ "Apache-2.0" ]
null
null
null
gulimall-common/src/main/java/com/atguigu/common/constant/AuthServerConstant.java
gzqnb/springcloud
b7f1ef3e78155230502a3058195deb088904b547
[ "Apache-2.0" ]
null
null
null
25.166667
65
0.715232
4,989
package com.atguigu.common.constant; /** * @Auther: gzq * @Date: 2021/3/28 - 03 - 28 - 22:26 * @Description: com.atguigu.common.constant */ public class AuthServerConstant { public static final String SMS_CODE_CACHE_PREFIX="sms:code:"; public static final String LOGIN_USER="loginUser"; }
3e0bd25a2cc9a5ef60da5fe43ce81baaa8c62fc9
1,791
java
Java
src/test/java/no/nav/foreldrepenger/common/domain/validation/LukketPeriodeMedVedleggValidatorTest.java
navikt/fpsoknad-felles
12fafaebab275266c7aa9e225d3cdaca22b6d8f2
[ "MIT" ]
null
null
null
src/test/java/no/nav/foreldrepenger/common/domain/validation/LukketPeriodeMedVedleggValidatorTest.java
navikt/fpsoknad-felles
12fafaebab275266c7aa9e225d3cdaca22b6d8f2
[ "MIT" ]
36
2021-09-14T09:13:56.000Z
2022-03-31T08:07:08.000Z
src/test/java/no/nav/foreldrepenger/common/domain/validation/LukketPeriodeMedVedleggValidatorTest.java
navikt/fpsoknad-felles
12fafaebab275266c7aa9e225d3cdaca22b6d8f2
[ "MIT" ]
null
null
null
31.421053
104
0.701284
4,990
package no.nav.foreldrepenger.common.domain.validation; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; import java.time.LocalDate; import java.time.Month; import java.util.List; import javax.validation.Validation; import javax.validation.Validator; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import no.nav.foreldrepenger.common.domain.foreldrepenger.fordeling.OppholdsPeriode; import no.nav.foreldrepenger.common.domain.foreldrepenger.fordeling.Oppholdsårsak; class LukketPeriodeMedVedleggValidatorTest { private static Validator validator; @BeforeAll static void setUp() { validator = Validation.buildDefaultValidatorFactory().getValidator(); } @Test void testOKEnDag() { var periode = new OppholdsPeriode(LocalDate.of(2019, Month.MARCH, 1), LocalDate.of(2019, Month.MARCH, 1), Oppholdsårsak.INGEN, List.of()); assertTrue(validator.validate(periode).isEmpty()); } @Test void testTomBeforeFom() { var periode = new OppholdsPeriode(LocalDate.of(2019, Month.MARCH, 1), LocalDate.of(2018, Month.MARCH, 1), Oppholdsårsak.INGEN, List.of()); assertFalse(validator.validate(periode).isEmpty()); } @Test void testNullStart() { var periode = new OppholdsPeriode(null, LocalDate.of(2019, Month.MARCH, 3), Oppholdsårsak.INGEN, List.of()); assertFalse(validator.validate(periode).isEmpty()); } @Test void testNullEnd() { var periode = new OppholdsPeriode(LocalDate.of(2019, Month.MARCH, 3), null, Oppholdsårsak.INGEN, List.of()); assertFalse(validator.validate(periode).isEmpty()); } }
3e0bd3108c2caedf18bd6f359535260f01bb941e
333
java
Java
springcloud-demo/services/api-gateway/src/test/java/com/xue/demo/ApiGatewayApplicationTests.java
mingwayXue/Learning
3425bc7e2c7fb67406daa7aa76df4e695b6c8e8c
[ "Apache-2.0" ]
null
null
null
springcloud-demo/services/api-gateway/src/test/java/com/xue/demo/ApiGatewayApplicationTests.java
mingwayXue/Learning
3425bc7e2c7fb67406daa7aa76df4e695b6c8e8c
[ "Apache-2.0" ]
null
null
null
springcloud-demo/services/api-gateway/src/test/java/com/xue/demo/ApiGatewayApplicationTests.java
mingwayXue/Learning
3425bc7e2c7fb67406daa7aa76df4e695b6c8e8c
[ "Apache-2.0" ]
null
null
null
19.588235
60
0.807808
4,991
package com.xue.demo; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) @SpringBootTest public class ApiGatewayApplicationTests { @Test public void contextLoads() { } }
3e0bd43725a33777c78c72a2d31853802c9470a5
5,181
java
Java
generator.client.jaxrs/src/main/java/com/bbva/kltt/apirest/generator/client/jaxrs/velocity/example/ExampleListenerClientJaxrsGenerator.java
BBVA-CIB/APIRestGenerator
f3b28638b1d9ed98145bdd47c425cf5ac970941f
[ "Apache-2.0" ]
5
2017-01-09T20:44:24.000Z
2020-12-09T17:44:21.000Z
generator.client.jaxrs/src/main/java/com/bbva/kltt/apirest/generator/client/jaxrs/velocity/example/ExampleListenerClientJaxrsGenerator.java
BBVA-CIB/APIRestGenerator
f3b28638b1d9ed98145bdd47c425cf5ac970941f
[ "Apache-2.0" ]
null
null
null
generator.client.jaxrs/src/main/java/com/bbva/kltt/apirest/generator/client/jaxrs/velocity/example/ExampleListenerClientJaxrsGenerator.java
BBVA-CIB/APIRestGenerator
f3b28638b1d9ed98145bdd47c425cf5ac970941f
[ "Apache-2.0" ]
null
null
null
43.90678
150
0.715113
4,992
/* * 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.bbva.kltt.apirest.generator.client.jaxrs.velocity.example; import java.io.File; import java.util.List; import com.bbva.kltt.apirest.generator.client.jaxrs.velocity.GeneratorBaseClientJaxrs; import org.apache.velocity.VelocityContext; import com.bbva.kltt.apirest.core.launcher.GenerationParameters; import com.bbva.kltt.apirest.core.parsed_info.ParsedInfoHandler; import com.bbva.kltt.apirest.core.util.ConstantsOutput; import com.bbva.kltt.apirest.generator.java.util.ConstantsOutputJava; /** * ------------------------------------------------ * @author Francisco Manuel Benitez Chico * ------------------------------------------------ */ public class ExampleListenerClientJaxrsGenerator extends GeneratorBaseClientJaxrs { /** * Build the launcher examples generator * * @param baseDestDir with the base destination directory for the generated file * @param generationParams with the parameters for the generation * @param parsedInfoHandler with the parsed information */ public ExampleListenerClientJaxrsGenerator(final File baseDestDir, final GenerationParameters generationParams, final ParsedInfoHandler parsedInfoHandler) { super(baseDestDir, generationParams, parsedInfoHandler); } @Override protected VelocityContext createVelocityContext() { final VelocityContext context = new VelocityContext(); // Parameters context.put(ConstantsOutput.VP_PACKAGE_NAME, this.getOutputPackage()); context.put(ConstantsOutput.VP_ADDITIONAL_IMPORTS, this.generateAdditionalImports()); context.put(ConstantsOutput.VP_CLASS_NAME, this.getOutputFileName()); context.put(ConstantsOutput.VP_R_LISTE_INTERFACE_NAME, ConstantsOutputJava.INTERFACE_NAME_REST_LISTENER + this.getTitleCamelCase()); context.put(ConstantsOutputJava.VP_RANDOM_UTILS_CL_NAME, ConstantsOutputJava.CLASSNAME_RANDOM_UTILS + this.getTitleCamelCase()); // Java Templates context.put(ConstantsOutputJava.VP_JAVA_TEMPL_METH_COMMENTS, this.getCommonJavaResourcePath(ConstantsOutputJava.COMMON_JAVA_DIR_TEMPLATES, ConstantsOutputJava.VP_JAVA_TEMPL_METH_COMMENTS)) ; context.put(ConstantsOutputJava.VP_COMMON_J_T_LISTE_EXA_CL, this.getCommonJavaResourcePath(ConstantsOutputJava.COMMON_JAVA_DIR_LISTENER_EXA, ConstantsOutputJava.VP_COMMON_J_T_LISTE_EXA_CL)) ; context.put(ConstantsOutputJava.VP_COMM_J_T_LISTE_EXA_CL_ME, this.getCommonJavaResourcePath(ConstantsOutputJava.COMMON_JAVA_DIR_LISTENER_EXA, ConstantsOutputJava.VP_COMM_J_T_LISTE_EXA_CL_ME)) ; // Java Macros context.put(ConstantsOutputJava.VP_JAVA_MACRO_COMMON, this.getCommonJavaResourcePath(ConstantsOutputJava.COMMON_JAVA_DIR_MACROS, ConstantsOutputJava.VP_JAVA_MACRO_COMMON)) ; context.put(ConstantsOutputJava.VP_JAVA_RANDOM_GENERAT_METH, this.getCommonJavaResourcePath(ConstantsOutputJava.COMMON_JAVA_DIR_MACROS, ConstantsOutputJava.VP_JAVA_RANDOM_GENERAT_METH)) ; context.put(ConstantsOutputJava.VP_COMM_J_M_LISTE_EXA_CL_ME, this.getCommonJavaResourcePath(ConstantsOutputJava.COMMON_JAVA_DIR_LISTENER_EXA, ConstantsOutputJava.VP_COMM_J_M_LISTE_EXA_CL_ME)) ; return context; } @Override protected String getOutputPackage() { return this.getPackageUtilsJava().getExamplesPackage(this.getTranslatorType()); } @Override protected String getOutputFileName() { return ConstantsOutputJava.CLASSNAME_EXAMPLE_LISTENER + this.getTitleCamelCase(); } /** * @return the additional imports */ private List<String> generateAdditionalImports() { // Model imports final List<String> additionalImports = this.generateImportsModel(); // Add the common exception class additionalImports.add(this.generateImportExceptionCommonException()) ; // Listener interface - import additionalImports.add(this.generateImportListenerInterface(this.getTranslatorType())); return additionalImports; } }
3e0bd511fead9c88b865e755c9ac87c60bda495c
9,196
java
Java
everyboo-cms/src/main/java/com/jeff/everyboo/cms/dao/ShopUserDaoImpl.java
dingjinqing/everyboo
48ea455aeac8071f484496a10dfa3828bc8cd38b
[ "Apache-2.0" ]
null
null
null
everyboo-cms/src/main/java/com/jeff/everyboo/cms/dao/ShopUserDaoImpl.java
dingjinqing/everyboo
48ea455aeac8071f484496a10dfa3828bc8cd38b
[ "Apache-2.0" ]
5
2020-05-15T21:09:43.000Z
2021-12-09T20:46:09.000Z
everyboo-cms/src/main/java/com/jeff/everyboo/cms/dao/ShopUserDaoImpl.java
dingjinqing/everyboo
48ea455aeac8071f484496a10dfa3828bc8cd38b
[ "Apache-2.0" ]
null
null
null
54.738095
881
0.664311
4,993
package com.jeff.everyboo.cms.dao; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.commons.lang3.StringUtils; import com.jeff.everyboo.cms.dto.ShopUserQueryDTO; import com.jeff.everyboo.cms.entity.ShopUser; import com.jeff.everyboo.common.dao.CustomBaseSqlDaoImpl; import com.jeff.everyboo.common.entity.PageModel; /** * @author dingjinqing * @desc ShopUserDaoImpl类 * @date 2018-11-06 */ public class ShopUserDaoImpl extends CustomBaseSqlDaoImpl implements ShopUserDaoCustom { public PageModel<ShopUser> queryShopUserPage(ShopUserQueryDTO shopUserQueryDTO){ Map<String,Object> map = new HashMap<String,Object>(); StringBuilder hql = new StringBuilder(); hql.append("select t from ShopUser t where 1=1 "); if(shopUserQueryDTO != null){ if(StringUtils.isNotBlank(shopUserQueryDTO.getPhone())){ hql.append(" and t.phone = :phone "); map.put("phone", shopUserQueryDTO.getPhone()); } if(StringUtils.isNotBlank(shopUserQueryDTO.getVipLevel())){ hql.append(" and t.vipLevel = :vipLevel "); map.put("vipLevel", shopUserQueryDTO.getVipLevel()); } if(StringUtils.isNotBlank(shopUserQueryDTO.getLevel())){ hql.append(" and t.level = :level "); map.put("level", shopUserQueryDTO.getLevel()); } if(shopUserQueryDTO.getStatus()!=0){ hql.append(" and t.status = :status "); map.put("status", shopUserQueryDTO.getStatus()); } if(StringUtils.isNotBlank(shopUserQueryDTO.getAccount())){ hql.append(" and t.account = :account "); map.put("account", shopUserQueryDTO.getAccount()); } } hql.append(" order by t.id desc"); return this.queryForPageWithParams(hql.toString(),map,shopUserQueryDTO.getCurrentPage(),shopUserQueryDTO.getPageSize()); } public List<ShopUser> queryShopUserList(ShopUserQueryDTO shopUserQueryDTO){ Map<String,Object> map = new HashMap<String,Object>(); StringBuilder hql = new StringBuilder(); /*if(shopUserQueryDTO.getIsFront() != null && shopUserQueryDTO.getIsFront()){ hql.append("select new ShopUser(id,account,phone,password,refPhone,vipLevel,address,createDate,createBy,updateDate,updateBy,nickName,jiaoyimima,status) from ShopUser t where 1=1 "); }else { */ hql.append("select t from ShopUser t where 1=1 "); // } if(shopUserQueryDTO != null){ if(StringUtils.isNotBlank(shopUserQueryDTO.getPhone())){ hql.append(" and t.phone = :phone "); map.put("phone", shopUserQueryDTO.getPhone()); } if(StringUtils.isNotBlank(shopUserQueryDTO.getVipLevel())){ hql.append(" and t.vipLevel = :vipLevel "); map.put("vipLevel", shopUserQueryDTO.getVipLevel()); } if(StringUtils.isNotBlank(shopUserQueryDTO.getLevel())){ hql.append(" and t.level = :level "); map.put("level", shopUserQueryDTO.getLevel()); } if(shopUserQueryDTO.getStatus()!=0){ hql.append(" and t.status = :status "); map.put("status", shopUserQueryDTO.getStatus()); } if(StringUtils.isNotBlank(shopUserQueryDTO.getAccount())){ hql.append(" and t.account = :account "); map.put("account", shopUserQueryDTO.getAccount()); } if(StringUtils.isNotBlank(shopUserQueryDTO.getPassword())){ hql.append(" and t.password = :password "); map.put("password", shopUserQueryDTO.getPassword()); } } hql.append(" order by t.id desc"); return this.queryByMapParams(hql.toString(),map); } public List<Map<String, Object>> queryUser2List(String phone){ StringBuilder sql = new StringBuilder(); sql.append("select t.id,account,nick_name as nickNmae,phone,level,vip_level as viplevel,uext.active_bill as activeBill,(SELECT IFNULL(SUM(ABS(price)+ABS(duihuan)+ABS(credits)),0) from shop_trade where user_id=t.id and type=1) as selfyeji,(SELECT IFNULL(SUM(ABS(t2.price)+ABS(t2.duihuan)+ABS(t2.credits)),0) from shop_trade t2 where t2.user_id in (SELECT t3.id from shop_user t3 where t3.ref_phone=t.phone) and t2.type=1) as zituiyeji ,(SELECT IFNULL(SUM(ABS(t5.price)+ABS(t5.duihuan)+ABS(t5.credits)),0) from shop_trade t5 LEFT JOIN shop_user t6 on t5.user_id =t6.id and t5.type=1 where t6.ref_phone in (SELECT t4.phone from shop_user t4 where t4.ref_phone=t.phone)) as jiantuiyeji from shop_user t LEFT JOIN shop_user_ext uext on t.id= uext.user_id where ref_phone=? " ); List<Object> params = new ArrayList<>(); params.add(phone); return this.querySqlObjects(sql.toString(), params); } public List<Map<String, Object>> queryUser3List(String phone){ StringBuilder sql = new StringBuilder(); sql.append("SELECT id,account,nick_name as nickName,phone,level,vip_level as viplevel,t.ref_phone as refPhone,(SELECT IFNULL(SUM(ABS(price)+ABS(duihuan)+ABS(credits)),0) from shop_trade where user_id=t.id and type=1) as selfyeji from shop_user t where t.ref_phone in (select phone from shop_user where ref_phone=? ) ORDER BY t.ref_phone "); List<Object> params = new ArrayList<>(); params.add(phone); return this.querySqlObjects(sql.toString(), params); } /**后台查询直接团队购买明细 * @param phone * @return */ public List<Map<String, Object>> queryUser4List(String phone){ StringBuilder sql = new StringBuilder(); sql.append("select t.id,account,nick_name as nickNmae,phone,level,vip_level as viplevel,uext.active_bill as activeBill,(SELECT IFNULL(SUM(ABS(price)+ABS(duihuan)+ABS(credits)),0) from shop_trade where user_id=t.id and type=1) as selfyeji,(SELECT IFNULL(SUM(ABS(t2.price)+ABS(t2.duihuan)+ABS(t2.credits)),0) from shop_trade t2 where t2.user_id in (SELECT t3.id from shop_user t3 where t3.ref_phone=t.phone) and t2.type=1) as zituiyeji ,(SELECT IFNULL(SUM(ABS(t5.price)+ABS(t5.duihuan)+ABS(t5.credits)),0) from shop_trade t5 LEFT JOIN shop_user t6 on t5.user_id =t6.id and t5.type=1 where t6.ref_phone in (SELECT t4.phone from shop_user t4 where t4.ref_phone=t.phone)) as jiantuiyeji from shop_user t LEFT JOIN shop_user_ext uext on t.id= uext.user_id where ref_phone=? "); List<Object> params = new ArrayList<>(); params.add(phone); return this.querySqlObjects(sql.toString(), params); } /**后台查询间推团队购买明细 * @param phone * @return */ public List<Map<String, Object>> queryUser5List(String phone){ StringBuilder sql = new StringBuilder(); sql.append("SELECT t.id,account,nick_name as nickName,phone,level,vip_level as viplevel ,t.ref_phone as refPhone ,uext.active_bill as activeBill,(SELECT IFNULL(SUM(ABS(price)+ABS(duihuan)+ABS(credits)),0) from shop_trade where user_id=t.id and type=1) as selfyeji ,(SELECT IFNULL(SUM(ABS(t2.price)+ABS(t2.duihuan)+ABS(t2.credits)),0) from shop_trade t2 where t2.user_id in (SELECT t3.id from shop_user t3 where t3.ref_phone=t.phone) and t2.type=1) as zituiyeji ,(SELECT IFNULL(SUM(ABS(t5.price)+ABS(t5.duihuan)+ABS(t5.credits)),0) from shop_trade t5 LEFT JOIN shop_user t6 on t5.user_id =t6.id and t5.type=1 where t6.ref_phone in (SELECT t4.phone from shop_user t4 where t4.ref_phone=t.phone)) as jiantuiyeji from shop_user t LEFT JOIN shop_user_ext uext on t.id= uext.user_id where t.ref_phone in (select phone from shop_user where ref_phone=? ) ORDER BY t.ref_phone "); List<Object> params = new ArrayList<>(); params.add(phone); return this.querySqlObjects(sql.toString(), params); } public List<Map<String, Object>> queryIncomeList(String userId){ StringBuilder sql = new StringBuilder(); sql.append("SELECT sum(price) as income,type from shop_trade where user_id=? GROUP BY type "); List<Object> params = new ArrayList<>(); params.add(userId); return this.querySqlObjects(sql.toString(), params); } @Override public List<Map<String, Object>> queryIncomeList(ShopUserQueryDTO shopUserQueryDTO) { // TODO Auto-generated method stub StringBuilder sql = new StringBuilder(); sql.append("SELECT ifnull(ABS(sum(price)),0) as income,type from shop_trade where 1=1 "); List<Object> params = new ArrayList<>(); if (shopUserQueryDTO.getUserId()!=0) { sql.append("and user_id=?"); params.add(shopUserQueryDTO.getUserId()); } if (shopUserQueryDTO.getStartTime()!=null ) { sql.append("and create_date>?"); params.add(shopUserQueryDTO.getStartTime()); } if (shopUserQueryDTO.getEndTime()!=null ) { sql.append("and create_date<?"); params.add(shopUserQueryDTO.getEndTime()); } sql.append(" GROUP BY type "); return this.querySqlObjects(sql.toString(), params); } }
3e0bd5aa73b1761e783b24df347584b77da7297b
909
java
Java
chapter_001/src/main/java/ru/job4j/MapForBank/User.java
AnnaYatsun1/YatsunAn
366880853600c994ee97039c430b6e7476f7792b
[ "Apache-2.0" ]
null
null
null
chapter_001/src/main/java/ru/job4j/MapForBank/User.java
AnnaYatsun1/YatsunAn
366880853600c994ee97039c430b6e7476f7792b
[ "Apache-2.0" ]
null
null
null
chapter_001/src/main/java/ru/job4j/MapForBank/User.java
AnnaYatsun1/YatsunAn
366880853600c994ee97039c430b6e7476f7792b
[ "Apache-2.0" ]
null
null
null
19.340426
66
0.579758
4,994
package ru.job4j.MapForBank; import java.util.Objects; public class User { public void setName(String name) { this.name = name; } public void setPassport(String passport) { this.passport = passport; } public String name, passport; public String getName() { return name; } public String getPassport() { return passport; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; User user = (User) o; return Objects.equals(name, user.name) && Objects.equals(passport, user.passport); } @Override public int hashCode() { return Objects.hash(name, passport); } public User(String name, String passport) { this.name = name; this.passport = passport; } }
3e0bd61dd5352a617d2075f4a60fa70b401fae1d
1,646
java
Java
flower.center/flower.center.impl/src/test/java/flower/center/ExtensionLoaderTest.java
yuandajn578/myflower
ebebe8f62db480202985a1558b70a0478cab6a18
[ "Apache-2.0" ]
531
2018-12-27T06:37:04.000Z
2022-03-30T06:00:37.000Z
flower.center/flower.center.impl/src/test/java/flower/center/ExtensionLoaderTest.java
yuandajn578/myflower
ebebe8f62db480202985a1558b70a0478cab6a18
[ "Apache-2.0" ]
73
2019-01-29T06:32:37.000Z
2021-07-07T00:53:27.000Z
flower.center/flower.center.impl/src/test/java/flower/center/ExtensionLoaderTest.java
yuandajn578/myflower
ebebe8f62db480202985a1558b70a0478cab6a18
[ "Apache-2.0" ]
163
2019-01-29T04:21:46.000Z
2022-03-22T10:05:06.000Z
35
105
0.758663
4,995
/** * Copyright © 2019 同程艺龙 (anpch@example.com) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package flower.center; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import java.io.IOException; import java.net.URL; import java.util.Enumeration; import org.junit.Test; import com.ly.train.flower.center.core.store.ServiceInfoStore; import com.ly.train.flower.center.core.store.memory.ServiceInfoMemoryStore; import com.ly.train.flower.common.util.ExtensionLoader; /** * @author leeyazhou */ public class ExtensionLoaderTest { @Test public void testLoadServiceConfig() throws ClassNotFoundException, IOException { Enumeration<URL> it = Thread.currentThread().getContextClassLoader() .getResources("META-INF/services/flower/com.ly.train.flower.center.core.store.ServiceInfoStore"); while (it.hasMoreElements()) { System.out.println(it.nextElement()); } ServiceInfoStore infoStore = ExtensionLoader.load(ServiceInfoStore.class).load("memory"); assertNotNull(infoStore); assertEquals(infoStore.getClass(), ServiceInfoMemoryStore.class); } }
3e0bd781621fab3425720e3289ab41ecf10745ae
1,590
java
Java
src/main/java/org/attoparser/HtmlBodyElement.java
LucasJC/attoparser
f30ae80cd1eedfb317b113a0c9c138f2d0f15e6c
[ "Apache-2.0" ]
41
2015-01-16T05:58:04.000Z
2021-08-25T02:30:40.000Z
src/main/java/org/attoparser/HtmlBodyElement.java
LucasJC/attoparser
f30ae80cd1eedfb317b113a0c9c138f2d0f15e6c
[ "Apache-2.0" ]
18
2015-01-22T18:32:53.000Z
2019-11-22T14:45:17.000Z
src/main/java/org/attoparser/HtmlBodyElement.java
LucasJC/attoparser
f30ae80cd1eedfb317b113a0c9c138f2d0f15e6c
[ "Apache-2.0" ]
6
2015-02-08T11:26:31.000Z
2021-03-23T05:34:31.000Z
39.75
136
0.634591
4,996
/* * ============================================================================= * * Copyright (c) 2012-2014, The ATTOPARSER team (http://www.attoparser.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.attoparser; /* * Specialization of HtmlElement for HTML elements that will normally live inside a <body> element * and therefore will ask for its creation when it is not present when auto-open is enabled. * * @author Daniel Fernandez * @since 2.0.0 */ final class HtmlBodyElement extends HtmlAutoOpenCloseElement { private static final String[] ARRAY_HTML_BODY = new String[] { "html", "body" }; private static final String[] ARRAY_HEAD = new String[] { "head" }; private static final String[] AUTO_CLOSE_LIMITS = new String[] { "script", "template", "element", "decorator", "content", "shadow"}; HtmlBodyElement(final String name) { super(name, ARRAY_HTML_BODY, null, ARRAY_HEAD, AUTO_CLOSE_LIMITS); } }
3e0bd7cb17f50ff115dd6f30568ce5320b6cfdd8
1,568
java
Java
modules/core/src/main/java/org/apache/tuscany/sca/core/invocation/ProxyFactoryExtensionPoint.java
apache/tuscany-sca-2.x
89f2d366d4b0869a4e42ff265ccf4503dda4dc8b
[ "Apache-2.0" ]
18
2015-01-17T17:09:47.000Z
2021-11-10T16:04:56.000Z
modules/core/src/main/java/org/apache/tuscany/sca/core/invocation/ProxyFactoryExtensionPoint.java
apache/tuscany-sca-2.x
89f2d366d4b0869a4e42ff265ccf4503dda4dc8b
[ "Apache-2.0" ]
null
null
null
modules/core/src/main/java/org/apache/tuscany/sca/core/invocation/ProxyFactoryExtensionPoint.java
apache/tuscany-sca-2.x
89f2d366d4b0869a4e42ff265ccf4503dda4dc8b
[ "Apache-2.0" ]
18
2015-08-26T15:18:06.000Z
2021-11-10T16:04:45.000Z
28.509091
63
0.69898
4,997
/* * 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.tuscany.sca.core.invocation; /** * The extension point to plug in proxy factories * @version $Rev$ $Date$ * @tuscany.spi.extension.asclient */ public interface ProxyFactoryExtensionPoint { /** * Get the proxy factory for java interfaces * @return */ ProxyFactory getInterfaceProxyFactory(); /** * Get the proxy factory for java classes * @return */ ProxyFactory getClassProxyFactory(); /** * Set the proxy factory for java interfaces * @param factory */ void setInterfaceProxyFactory(ProxyFactory factory); /** * Set the proxy factory for java classes * @param factory */ void setClassProxyFactory(ProxyFactory factory); }
3e0bd7ed20cfffffefd5dba00e0bdfe9f24b1d18
3,856
java
Java
src/test/org/civilian/application/ApplicationTest.java
jdlib/civilian
ae97260ca3c1a00585361cfd932438b08ce2318a
[ "Apache-2.0" ]
3
2015-05-30T12:06:34.000Z
2021-07-27T18:06:22.000Z
src/test/org/civilian/application/ApplicationTest.java
jdlib/civilian
ae97260ca3c1a00585361cfd932438b08ce2318a
[ "Apache-2.0" ]
null
null
null
src/test/org/civilian/application/ApplicationTest.java
jdlib/civilian
ae97260ca3c1a00585361cfd932438b08ce2318a
[ "Apache-2.0" ]
5
2015-01-15T11:59:45.000Z
2015-11-20T01:15:07.000Z
27.542857
76
0.745851
4,998
/* * Copyright (C) 2014 Civilian Framework. * * Licensed under the Civilian 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.civilian-framework.org/license.txt * * 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.civilian.application; import java.io.IOException; import javax.servlet.Servlet; import org.junit.Test; import org.civilian.Application; import org.civilian.CivTest; import org.civilian.content.ContentType; import org.civilian.resource.PathParamMap; import org.civilian.server.test.TestApp; import org.civilian.server.test.TestRequest; import org.civilian.server.test.TestServer; import org.civilian.util.ClassUtil; import org.civilian.util.Settings; public class ApplicationTest extends CivTest { private static class NoArgsApp extends Application { @Override protected void init(AppConfig config) throws Exception { } @Override protected void close() throws Exception { } } private static class RelPackageApp extends Application { public RelPackageApp() { super(null, ".root"); } @Override protected void init(AppConfig config) throws Exception { } @Override protected void close() throws Exception { } } private static class ErrorApp extends Application { @Override protected void init(AppConfig config) throws Exception { throw new IOException("io"); } @Override protected void close() throws Exception { } } @Test public void testCreate() { String pname = ClassUtil.getPackageName(getClass()); Application app = new NoArgsApp(); assertEquals(pname, app.getControllerConfig().getRootPackage()); assertSame(PathParamMap.EMPTY, app.getResourceConfig().getPathParams()); app = new RelPackageApp(); assertEquals(pname + ".root", app.getControllerConfig().getRootPackage()); assertSame(PathParamMap.EMPTY, app.getResourceConfig().getPathParams()); } @Test public void testAccessors() { Application app = new NoArgsApp(); assertNull(app.getConnector()); assertNull(app.getConnector(Servlet.class)); assertSame(app, app.getApplication()); assertNull(app.getVersion()); assertFalse(app.ignoreError(null)); assertEquals("app '?'", app.toString()); assertNull(app.getAttribute("x")); app.setAttribute("x", "y"); assertEquals("y", app.getAttribute("x")); assertEquals("x", app.getAttributeNames().next()); assertNull(app.getContentSerializer(ContentType.APPLICATION_JSON)); } @Test public void testInit() throws Exception { TestServer server = new TestServer(); server.setDevelop(true); ErrorApp errorApp = new ErrorApp(); server.addApp(errorApp, "err", "err", null); assertEquals(Application.Status.ERROR, errorApp.getStatus()); TestApp testApp = new TestApp(); Settings settings = new Settings(); settings.set(ConfigKeys.DEV_CLASSRELOAD, true); server.addApp(testApp, "test", "test", settings); assertEquals(Application.Status.RUNNING, testApp.getStatus()); assertTrue(testApp.getControllerService().isReloading()); assertNotNull(testApp.getProcessors()); assertNotNull(testApp.getRootResource()); assertNull(testApp.getContentSerializer(ContentType.APPLICATION_EXCEL)); assertNotNull(testApp.getContentSerializer(ContentType.APPLICATION_JSON)); assertNotNull(testApp.getContentSerializer(ContentType.TEXT_PLAIN)); } @Test public void testProcess() throws Exception { TestApp app = new TestApp(); TestRequest request = new TestRequest(app); app.process(request); } }
3e0bd95757727472a7370781c10a5cba3de6dd4f
513
java
Java
java_backup/my java/bishwarup_!/SECONDTERM/detectmax_matrix.java
SayanGhoshBDA/code-backup
8b6135facc0e598e9686b2e8eb2d69dd68198b80
[ "MIT" ]
16
2018-11-26T08:39:42.000Z
2019-05-08T10:09:52.000Z
java_backup/my java/bishwarup_!/SECONDTERM/detectmax_matrix.java
SayanGhoshBDA/code-backup
8b6135facc0e598e9686b2e8eb2d69dd68198b80
[ "MIT" ]
8
2020-05-04T06:29:26.000Z
2022-02-12T05:33:16.000Z
java_backup/my java/bishwarup_!/SECONDTERM/detectmax_matrix.java
SayanGhoshBDA/code-backup
8b6135facc0e598e9686b2e8eb2d69dd68198b80
[ "MIT" ]
5
2020-02-11T16:02:21.000Z
2021-02-05T07:48:30.000Z
21.375
72
0.651072
4,999
package SECONDTERM; import java.io.*; class detectmax_matrix { public static void main(String args[])throws IOException { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); int a[][]=new int [50][50]; System.out.println("ENTER VALUE"); int i=0,j=0,max,n; n=Integer.parseInt(br.readLine()); for(i=0;i<n;i++) for(j=0;j<n;j++) a[i][j]=Integer.parseInt(br.readLine()); max=a[0][0]; for(i=0;i<n;i++) for(j=0;j<n;j++) if(a[i][j]>max) max=a[i][j]; System.out.println(max); } }
3e0bd998f13e5a89b8dce2c3ecc4b86aee3c5058
2,285
java
Java
java/src/main/java/org/schors/vertx/telegram/bot/api/methods/GetUserProfilePhotos.java
ledniov/vertx-telegram-bot-api
a1155482100239a7198a99c0bf1e8122d7dc3bef
[ "MIT" ]
15
2017-03-21T10:07:32.000Z
2020-03-28T12:54:07.000Z
java/src/main/java/org/schors/vertx/telegram/bot/api/methods/GetUserProfilePhotos.java
ledniov/vertx-telegram-bot-api
a1155482100239a7198a99c0bf1e8122d7dc3bef
[ "MIT" ]
3
2017-10-04T13:33:28.000Z
2019-03-26T14:57:58.000Z
java/src/main/java/org/schors/vertx/telegram/bot/api/methods/GetUserProfilePhotos.java
ledniov/vertx-telegram-bot-api
a1155482100239a7198a99c0bf1e8122d7dc3bef
[ "MIT" ]
5
2017-05-01T05:31:37.000Z
2019-03-18T01:31:02.000Z
30.065789
83
0.695842
5,000
/* * The MIT License (MIT) * * Copyright (c) 2017 schors * 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.schors.vertx.telegram.bot.api.methods; import com.fasterxml.jackson.annotation.JsonProperty; public class GetUserProfilePhotos extends TelegramMethod { @JsonProperty("user_id") private Integer userId; private Integer offset; private Integer limit; public GetUserProfilePhotos() { } public GetUserProfilePhotos(Integer userId, Integer offset, Integer limit) { this.userId = userId; this.offset = offset; this.limit = limit; } public Integer getUserId() { return userId; } public GetUserProfilePhotos setUserId(Integer userId) { this.userId = userId; return this; } public Integer getOffset() { return offset; } public GetUserProfilePhotos setOffset(Integer offset) { this.offset = offset; return this; } public Integer getLimit() { return limit; } public GetUserProfilePhotos setLimit(Integer limit) { this.limit = limit; return this; } @Override public String getMethod() { return "getUserProfilePhotos"; } }
3e0bda14a72da746c419cea398e011d39c32e110
1,276
java
Java
worldstream-server/src/main/java/com/worldstream/api/server/builder/CommandBuilder.java
drem-darios/worldstream
d653c6e8e77cb7a3f7d8f67faf77627349f4e011
[ "MIT" ]
null
null
null
worldstream-server/src/main/java/com/worldstream/api/server/builder/CommandBuilder.java
drem-darios/worldstream
d653c6e8e77cb7a3f7d8f67faf77627349f4e011
[ "MIT" ]
18
2015-02-25T23:53:56.000Z
2015-03-13T17:04:39.000Z
worldstream-server/src/main/java/com/worldstream/api/server/builder/CommandBuilder.java
drem-darios/worldstream
d653c6e8e77cb7a3f7d8f67faf77627349f4e011
[ "MIT" ]
null
null
null
31.121951
96
0.573668
5,001
package com.worldstream.api.server.builder; import com.worldstream.api.server.command.Command; import com.worldstream.api.server.command.Command.Commands; import com.worldstream.api.server.command.ErrorCommand; /** * * @author Drem Darios * */ public class CommandBuilder extends Builder<Command> { @Override public Command build(String objects) { String[] elements = getObjectElements(objects); // gets elements String[] params = new String[(elements.length - 1)]; // -1 for elements without command String command = getElement(0, elements); // command is first element for(int i = 1; i < elements.length; i++) // start at 1 to skip command { String element = getElement(i, elements); // error if element is null if(element == null) { command = ErrorCommand.COMMAND; params[0] = "Text cannot be blank."; break; } else { params[i-1] = element; // i-1 to start at zero since i starts at 1 } } // get the command found from the enumeration return Commands.getCommand(command, params); } }
3e0bdaaf739ff0cfe0418519c8e591a5499814f9
1,044
java
Java
src/main/java/lc/N474OnesAndZeroes.java
hawdies/my-leetcode-record
58b48f574d2984540de2d6f9e22e54793cd069f1
[ "MIT" ]
1
2021-04-24T15:02:07.000Z
2021-04-24T15:02:07.000Z
src/main/java/lc/N474OnesAndZeroes.java
hawdies/mylc
58b48f574d2984540de2d6f9e22e54793cd069f1
[ "MIT" ]
null
null
null
src/main/java/lc/N474OnesAndZeroes.java
hawdies/mylc
58b48f574d2984540de2d6f9e22e54793cd069f1
[ "MIT" ]
null
null
null
28.216216
99
0.356322
5,002
package lc; /** * @author hawdies * @date 2021/6/6 **/ public class N474OnesAndZeroes { public int findMaxForm(String[] strs, int m, int n) { int len = strs.length; // 0-1背包 int[][][] dp = new int[len + 1][m + 1][n + 1]; // 统计每个字符串中'0', '1'的个数 int[][] cnt = new int[len][2]; for (int i = 0; i < strs.length; i++) { for (int j = 0; j <strs[i].length(); j++) { if (strs[i].charAt(j) == '0') cnt[i][0]++; else cnt[i][1]++; } } for (int i = 1; i <= len; i++) { int cur0 = cnt[i - 1][0]; int cur1 = cnt[i - 1][1]; for (int j = 0; j <= m; j++){ for (int k = 0; k <= n; k++) { if (j - cur0 >= 0 && k - cur1 >= 0) dp[i][j][k] = Math.max(dp[i - 1][j][k], dp[i - 1][j - cur0][k - cur1] + 1); else dp[i][j][k] = dp[i-1][j][k]; } } } return dp[len][m][n]; } }
3e0bdb0c69f0525af572788c8b26753f682e0d72
1,372
java
Java
src/controlsconversion/TutorialFrame.java
ggranum/graphing-script-generator
08abd2d314cd94080a917cca4981b619fa598ea0
[ "MIT" ]
null
null
null
src/controlsconversion/TutorialFrame.java
ggranum/graphing-script-generator
08abd2d314cd94080a917cca4981b619fa598ea0
[ "MIT" ]
null
null
null
src/controlsconversion/TutorialFrame.java
ggranum/graphing-script-generator
08abd2d314cd94080a917cca4981b619fa598ea0
[ "MIT" ]
null
null
null
28
108
0.687318
5,003
package controlsconversion; import javax.swing.*; import java.awt.*; import java.io.File; import java.net.URL; /** * <p>Title: </p> * <p>Description: </p> * <p>Copyright: Copyright (c) 2003</p> * <p>Company: </p> * @author Geoff Granum * @version 1.0 */ public class TutorialFrame extends JFrame { JPanel jPanel1 = new JPanel(); BorderLayout borderLayout1 = new BorderLayout(); JEditorPane jepTutorial = new JEditorPane(); private static final String filePath = System.getProperty("user.dir") + File.separatorChar + "resources" + File.separatorChar + "help"; JScrollPane jspTutorial = new JScrollPane(); public TutorialFrame() { try { jbInit(); } catch(Exception e) { e.printStackTrace(); } } private void jbInit() throws Exception { this.setTitle("Tutorial"); File file = new File(filePath, "tutorial.html"); URL url = file.toURL(); //jPanel1.setPreferredSize(new Dimension(800, 600)); jPanel1.setToolTipText(""); jPanel1.setLayout(borderLayout1); jepTutorial.setEditable(false); jepTutorial.setContentType("text/html"); jepTutorial.setPage(url); jspTutorial.setPreferredSize(new Dimension(790, 595)); this.getContentPane().add(jPanel1, BorderLayout.CENTER); jPanel1.add(jspTutorial, BorderLayout.CENTER); jspTutorial.getViewport().add(jepTutorial, null); } }
3e0bdb6174c2e4120e96044d2158b227abf54c44
2,327
java
Java
platform-web-ui/src/main/java/ua/com/fielden/platform/web/centre/api/crit/impl/DateCriterionWidget.java
fieldenms/
4efd3b2475877d434a57cbba638b711df95748e7
[ "MIT" ]
16
2017-03-22T05:42:26.000Z
2022-01-17T22:38:38.000Z
platform-web-ui/src/main/java/ua/com/fielden/platform/web/centre/api/crit/impl/DateCriterionWidget.java
fieldenms/
4efd3b2475877d434a57cbba638b711df95748e7
[ "MIT" ]
647
2017-03-21T07:47:44.000Z
2022-03-31T13:03:47.000Z
platform-web-ui/src/main/java/ua/com/fielden/platform/web/centre/api/crit/impl/DateCriterionWidget.java
fieldenms/
4efd3b2475877d434a57cbba638b711df95748e7
[ "MIT" ]
8
2017-03-21T08:26:56.000Z
2020-06-27T01:55:09.000Z
46.54
134
0.661796
5,004
package ua.com.fielden.platform.web.centre.api.crit.impl; import java.util.Map; import ua.com.fielden.platform.entity.AbstractEntity; import ua.com.fielden.platform.serialisation.jackson.DefaultValueContract; import ua.com.fielden.platform.web.view.master.api.widgets.datetimepicker.impl.DateTimePickerWidget; /** * An implementation for date double-editor criterion. * * @author TG Team * */ public class DateCriterionWidget extends AbstractRangeCriterionWidget { /** * Creates an instance of {@link DateCriterionWidget} for specified entity type and property name. * * @param criteriaType * @param propertyName */ public DateCriterionWidget(final Class<? extends AbstractEntity<?>> root, final Class<?> managedType, final String propertyName) { super(root, "centre/criterion/multi/range/tg-date-range-criterion", propertyName, new DateTimePickerWidget( AbstractCriterionWidget.generateTitleDesc(root, managedType, propertyName).getKey(), AbstractCriterionWidget.generateNames(root, managedType, propertyName).getKey(), false, DefaultValueContract.getTimeZone(managedType, propertyName), DefaultValueContract.getTimePortionToDisplay(managedType, propertyName) ), new DateTimePickerWidget( AbstractCriterionWidget.generateTitleDesc(root, managedType, propertyName).getValue(), AbstractCriterionWidget.generateNames(root, managedType, propertyName).getValue(), true, DefaultValueContract.getTimeZone(managedType, propertyName), DefaultValueContract.getTimePortionToDisplay(managedType, propertyName) )); } @Override protected Map<String, Object> createCustomAttributes() { final Map<String, Object> attrs = super.createCustomAttributes(); attrs.put("date-prefix", "{{propertyModel." + this.propertyName() + ".datePrefix}}"); attrs.put("date-mnemonic", "{{propertyModel." + this.propertyName() + ".dateMnemonic}}"); attrs.put("and-before", "{{propertyModel." + this.propertyName() + ".andBefore}}"); return attrs; } }
3e0bdc2d83a207f1ffbc87c625428e6ec44e959c
3,096
java
Java
DungeonDiver4/src/com/puttysoftware/dungeondiver4/creatures/characterfiles/CharacterLoader.java
wrldwzrd89/older-java-games
786b0c165d800c49ab9977a34ec17286797c4589
[ "Unlicense" ]
null
null
null
DungeonDiver4/src/com/puttysoftware/dungeondiver4/creatures/characterfiles/CharacterLoader.java
wrldwzrd89/older-java-games
786b0c165d800c49ab9977a34ec17286797c4589
[ "Unlicense" ]
null
null
null
DungeonDiver4/src/com/puttysoftware/dungeondiver4/creatures/characterfiles/CharacterLoader.java
wrldwzrd89/older-java-games
786b0c165d800c49ab9977a34ec17286797c4589
[ "Unlicense" ]
null
null
null
38.8125
87
0.621578
5,005
/* DungeonDiver4: An RPG Copyright (C) 2011-2012 Eric Ahnell Any questions should be directed to the author via email at: lyhxr@example.com */ package com.puttysoftware.dungeondiver4.creatures.characterfiles; import java.io.File; import com.puttysoftware.commondialogs.CommonDialogs; import com.puttysoftware.dungeondiver4.creatures.party.PartyMember; import com.puttysoftware.dungeondiver4.dungeon.Extension; import com.puttysoftware.xio.XDataReader; import com.puttysoftware.xio.XDataWriter; public class CharacterLoader { private static PartyMember loadCharacter(final String name) { final String basePath = CharacterRegistration.getBasePath(); final String loadPath = basePath + File.separator + name + Extension.getCharacterExtensionWithPeriod(); try (XDataReader loader = new XDataReader(loadPath, "character")) { return PartyMember.read(loader); } catch (final Exception e) { return null; } } public static PartyMember[] loadAllRegisteredCharacters() { final String[] registeredNames = CharacterRegistration .getCharacterNameList(); if (registeredNames != null) { final PartyMember[] res = new PartyMember[registeredNames.length]; // Load characters for (int x = 0; x < registeredNames.length; x++) { final String name = registeredNames[x]; final PartyMember characterWithName = CharacterLoader .loadCharacter(name); if (characterWithName != null) { res[x] = characterWithName; } else { // Bad data return null; } } return res; } return null; } public static void saveCharacter(final PartyMember character) { final String basePath = CharacterRegistration.getBasePath(); final String name = character.getName(); final String characterFile = basePath + File.separator + name + Extension.getCharacterExtensionWithPeriod(); try (XDataWriter saver = new XDataWriter(characterFile, "character")) { character.write(saver); } catch (final Exception e) { // Ignore } } static void deleteCharacter(final String name) { final String basePath = CharacterRegistration.getBasePath(); final String characterFile = basePath + File.separator + name + Extension.getCharacterExtensionWithPeriod(); final File toDelete = new File(characterFile); if (toDelete.exists()) { final boolean success = toDelete.delete(); if (success) { CommonDialogs.showDialog("Character removed."); } else { CommonDialogs.showDialog("Character removal failed!"); } } else { CommonDialogs.showDialog( "The character to be removed does not have a corresponding file."); } } }
3e0bdc546d750078b361fc899c4962ec86e72edc
1,261
java
Java
src/main/java/au/org/noojee/contact/api/NoojeeContactApiResponse.java
bhorvath/noojeecontact.api
59266556e973ab5b93f4648415cefeb7a1978a0a
[ "Apache-2.0" ]
null
null
null
src/main/java/au/org/noojee/contact/api/NoojeeContactApiResponse.java
bhorvath/noojeecontact.api
59266556e973ab5b93f4648415cefeb7a1978a0a
[ "Apache-2.0" ]
null
null
null
src/main/java/au/org/noojee/contact/api/NoojeeContactApiResponse.java
bhorvath/noojeecontact.api
59266556e973ab5b93f4648415cefeb7a1978a0a
[ "Apache-2.0" ]
1
2020-03-30T03:11:41.000Z
2020-03-30T03:11:41.000Z
18.544118
100
0.75337
5,006
package au.org.noojee.contact.api; import java.io.Serializable; public class NoojeeContactApiResponse implements Serializable { private static final long serialVersionUID = 1L; private int responseCode; private String responseText; private boolean successful = false; private String httpResponseBody; // When the response is for a payment transaction then this will hold the resulting transaction id. private String transactionID; public NoojeeContactApiResponse(int responseCode, String responseText, String httpResponseBody) { this.responseCode = responseCode; this.responseText = responseText; this.httpResponseBody = httpResponseBody; } public void setSuccessful() { this.successful = true; } public String getTransactionID() { return transactionID; } public int getResponseCode() { return responseCode; } public String getResponseText() { return responseText; } public boolean isSuccessful() { return successful; } public String getHTTPResponseBody() { return httpResponseBody; } @Override public String toString() { return "Code: " + responseCode + " Message: " + responseText; } public void setTransactionID(String transactionID) { this.transactionID = transactionID; } }
3e0bdc5dc90a8a9153ce3c9b1b3307bb021c1f78
1,462
java
Java
concursus-game-demo/src/main/java/com/opencredo/concursus/demos/game/domain/TurnState.java
opencredo/concursus
31a45b13d72b39905a01485ae2cf6e38f97d7d12
[ "MIT" ]
94
2016-03-31T12:06:19.000Z
2021-06-11T12:19:43.000Z
concursus-game-demo/src/main/java/com/opencredo/concursus/demos/game/domain/TurnState.java
opencredo/concursus
31a45b13d72b39905a01485ae2cf6e38f97d7d12
[ "MIT" ]
6
2016-04-21T19:48:22.000Z
2017-02-16T00:20:24.000Z
concursus-game-demo/src/main/java/com/opencredo/concursus/demos/game/domain/TurnState.java
opencredo/concourse
31a45b13d72b39905a01485ae2cf6e38f97d7d12
[ "MIT" ]
14
2016-04-20T20:11:24.000Z
2022-02-11T16:47:00.000Z
27.584906
99
0.662791
5,007
package com.opencredo.concursus.demos.game.domain; public final class TurnState { public static TurnState of(String playerOneId, String playerTwoId, PlayerIndex currentPlayer) { return new TurnState(playerOneId, playerTwoId, currentPlayer); } private final String playerOneId; private final String playerTwoId; private PlayerIndex currentPlayer; private TurnState(String playerOneId, String playerTwoId, PlayerIndex currentPlayer) { this.playerOneId = playerOneId; this.playerTwoId = playerTwoId; this.currentPlayer = currentPlayer; } public boolean isCurrentPlayer(String playerId) { return getCurrentPlayerId().equals(playerId); } public String getCurrentPlayerId() { return currentPlayer.equals(PlayerIndex.PLAYER_1) ? playerOneId : playerTwoId; } public void switchPlayers() { currentPlayer = currentPlayer.equals(PlayerIndex.PLAYER_1) ? PlayerIndex.PLAYER_2 : PlayerIndex.PLAYER_1; } public String getPlayerOneId() { return playerOneId; } public String getPlayerTwoId() { return playerTwoId; } public PlayerIndex getCurrentPlayerIndex() { return currentPlayer; } public String getOpponentId() { return currentPlayer.equals(PlayerIndex.PLAYER_1) ? playerTwoId : playerOneId; } }
3e0bdc6aa639e7f622c485df567616a158c9053d
3,124
java
Java
src/main/java/com/jackylaucf/jpaentitymapper/processor/writer/EntityWriter.java
jackylaucf/JPAEntityBuilder
a8116e369cf392cbcafa070463a585514a37d3b0
[ "Apache-2.0" ]
4
2019-02-19T03:51:45.000Z
2019-05-09T03:25:01.000Z
src/main/java/com/jackylaucf/jpaentitymapper/processor/writer/EntityWriter.java
jackylaucf/JPAEntityBuilder
a8116e369cf392cbcafa070463a585514a37d3b0
[ "Apache-2.0" ]
null
null
null
src/main/java/com/jackylaucf/jpaentitymapper/processor/writer/EntityWriter.java
jackylaucf/JPAEntityBuilder
a8116e369cf392cbcafa070463a585514a37d3b0
[ "Apache-2.0" ]
null
null
null
40.571429
175
0.595711
5,008
package com.jackylaucf.jpaentitymapper.processor.writer; import com.jackylaucf.jpaentitymapper.config.ApplicationConfig; import com.jackylaucf.jpaentitymapper.config.BeanConfig; import java.io.IOException; import java.util.List; public class EntityWriter extends Writer{ private static final String JPA_DEPENDENCY = "javax.persistence.*"; private enum JPAEntity{ Entity, Table, Id, Column } @Override public void write(String outputPath, String tableName, String beanName, List<String> rawColumnNames, List<Integer> columnTypes, BeanConfig beanConfig) throws IOException { initBufferedWriter(outputPath, beanName, beanConfig.getNamePrefix(), beanConfig.getNameSuffix()); if(bufferedWriter!=null){ final List<String> camelizedFieldNames = camelizeFields(rawColumnNames); final String id = ApplicationConfig.getConfig().getDatabaseIdMap().get(tableName); writePackageStatement(beanConfig.getPackageName()); writeJpaDependencyImportStatement(); writeTypeImportStatements(columnTypes); writeEntityAnnotation(JPAEntity.Entity, null); writeEntityAnnotation(JPAEntity.Table, tableName); writeClassOpening(beanConfig.getNamePrefix(), beanName, beanConfig.getNameSuffix()); for(int i=0; i<camelizedFieldNames.size(); i++){ if(id!=null && id.equalsIgnoreCase(rawColumnNames.get(i))){ writeEntityAnnotation(JPAEntity.Id, null); } writeEntityAnnotation(JPAEntity.Column, rawColumnNames.get(i)); writeFieldDeclaration(false, columnTypes.get(i), camelizedFieldNames.get(i)); writeNewLines(1, 1); } writeGetterSetters(false, columnTypes, camelizedFieldNames); writeClassClosing(); bufferedWriter.flush(); bufferedWriter.close(); } } private void writeJpaDependencyImportStatement() throws IOException{ bufferedWriter.write("import " + JPA_DEPENDENCY + ";"); writeNewLines(1, 0); } private void writeEntityAnnotation(JPAEntity annotation, String value) throws IOException{ if(annotation!=null){ switch(annotation){ case Entity: bufferedWriter.write("@" + annotation.name()); writeNewLines(1, 0); break; case Table: bufferedWriter.write("@" + annotation.name()); bufferedWriter.write("(name=\"" + value + "\")"); writeNewLines(1,0); break; case Id: bufferedWriter.write("@" + annotation.name()); writeNewLines(1, 1); break; case Column: bufferedWriter.write("@" + annotation.name()); bufferedWriter.write("(name=\"" + value + "\")"); writeNewLines(1,1); break; } } } }
3e0bdcaa98691710fd907eb1b267d0e8b91ced59
3,048
java
Java
spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/main/java/org/springframework/boot/maven/BuildInfoMojo.java
youfeng243/spring-boot
69a973effa5c414307e5e842adc8b577b42cd586
[ "Apache-2.0" ]
172
2020-04-04T04:53:30.000Z
2022-03-30T03:15:52.000Z
spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/main/java/org/springframework/boot/maven/BuildInfoMojo.java
youfeng243/spring-boot
69a973effa5c414307e5e842adc8b577b42cd586
[ "Apache-2.0" ]
62
2019-07-31T05:22:05.000Z
2021-08-02T16:57:45.000Z
spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/main/java/org/springframework/boot/maven/BuildInfoMojo.java
youfeng243/spring-boot
69a973effa5c414307e5e842adc8b577b42cd586
[ "Apache-2.0" ]
130
2018-10-17T05:57:18.000Z
2022-03-30T08:11:45.000Z
34.247191
104
0.766076
5,009
/* * Copyright 2012-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.boot.maven; import java.io.File; import java.time.Instant; import java.util.Map; import org.apache.maven.plugin.AbstractMojo; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.MojoFailureException; import org.apache.maven.plugins.annotations.Component; import org.apache.maven.plugins.annotations.LifecyclePhase; import org.apache.maven.plugins.annotations.Mojo; import org.apache.maven.plugins.annotations.Parameter; import org.apache.maven.project.MavenProject; import org.sonatype.plexus.build.incremental.BuildContext; import org.springframework.boot.loader.tools.BuildPropertiesWriter; import org.springframework.boot.loader.tools.BuildPropertiesWriter.NullAdditionalPropertyValueException; import org.springframework.boot.loader.tools.BuildPropertiesWriter.ProjectDetails; /** * Generate a {@code build-info.properties} file based the content of the current * {@link MavenProject}. * * @author Stephane Nicoll * @since 1.4.0 */ @Mojo(name = "build-info", defaultPhase = LifecyclePhase.GENERATE_RESOURCES, threadSafe = true) public class BuildInfoMojo extends AbstractMojo { @Component private BuildContext buildContext; /** * The Maven project. */ @Parameter(defaultValue = "${project}", readonly = true, required = true) private MavenProject project; /** * The location of the generated build-info.properties. */ @Parameter(defaultValue = "${project.build.outputDirectory}/META-INF/build-info.properties") private File outputFile; /** * Additional properties to store in the build-info.properties. Each entry is prefixed * by {@code build.} in the generated build-info.properties. */ @Parameter private Map<String, String> additionalProperties; @Override public void execute() throws MojoExecutionException, MojoFailureException { try { new BuildPropertiesWriter(this.outputFile) .writeBuildProperties(new ProjectDetails(this.project.getGroupId(), this.project.getArtifactId(), this.project.getVersion(), this.project.getName(), Instant.now(), this.additionalProperties)); this.buildContext.refresh(this.outputFile); } catch (NullAdditionalPropertyValueException ex) { throw new MojoFailureException( "Failed to generate build-info.properties. " + ex.getMessage(), ex); } catch (Exception ex) { throw new MojoExecutionException(ex.getMessage(), ex); } } }
3e0bdcbc559eec6858b5b02ed87c5708b0eac205
861
java
Java
spring-tuling-webmvc/src/main/java/com/shihy/xml/controller/HttpRequestController.java
shihy1992/spring-framework-5.3.10
069d840654cc89bfec1b077e9d58ad3ee3217eca
[ "Apache-2.0" ]
1
2022-02-14T02:21:46.000Z
2022-02-14T02:21:46.000Z
spring-tuling-webmvc/src/main/java/com/shihy/xml/controller/HttpRequestController.java
shihy1992/spring-framework-5.3.10
069d840654cc89bfec1b077e9d58ad3ee3217eca
[ "Apache-2.0" ]
null
null
null
spring-tuling-webmvc/src/main/java/com/shihy/xml/controller/HttpRequestController.java
shihy1992/spring-framework-5.3.10
069d840654cc89bfec1b077e9d58ad3ee3217eca
[ "Apache-2.0" ]
1
2022-03-23T15:34:37.000Z
2022-03-23T15:34:37.000Z
31.888889
126
0.75842
5,010
package com.shihy.xml.controller; import org.springframework.stereotype.Component; import org.springframework.web.HttpRequestHandler; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; /*** * @Author 徐庶 QQ:1092002729 * @Slogan 致敬大师,致敬未来的你 */ @Component("/httpRequestHandler") public class HttpRequestController implements HttpRequestHandler { @Override public void handleRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { System.out.println("HttpRequestController........."); //为返回页面设置数据 request.setAttribute("source", "HttpRequestController"); //设置返回页面 request.getRequestDispatcher("/WEB-INF/jsp/a.jsp").forward(request, response); } }
3e0bdd134fb36281dd3b2d9417dfc39a154ee51f
2,029
java
Java
edexOsgi/com.raytheon.uf.common.monitor/src/com/raytheon/uf/common/monitor/scan/xml/SCANMonitorConfigXML.java
drjoeycadieux/awips2
3b467b15915cba23d9216eefd97a21758e66c748
[ "Apache-2.0" ]
null
null
null
edexOsgi/com.raytheon.uf.common.monitor/src/com/raytheon/uf/common/monitor/scan/xml/SCANMonitorConfigXML.java
drjoeycadieux/awips2
3b467b15915cba23d9216eefd97a21758e66c748
[ "Apache-2.0" ]
null
null
null
edexOsgi/com.raytheon.uf.common.monitor/src/com/raytheon/uf/common/monitor/scan/xml/SCANMonitorConfigXML.java
drjoeycadieux/awips2
3b467b15915cba23d9216eefd97a21758e66c748
[ "Apache-2.0" ]
1
2021-10-30T00:03:05.000Z
2021-10-30T00:03:05.000Z
26.350649
70
0.667324
5,011
/** * This software was developed and / or modified by Raytheon Company, * pursuant to Contract DG133W-05-CQ-1067 with the US Government. * * U.S. EXPORT CONTROLLED TECHNICAL DATA * This software product contains export-restricted data whose * export/transfer/disclosure is restricted by U.S. law. Dissemination * to non-U.S. persons whether in the United States or abroad requires * an export license or other authorization. * * Contractor Name: Raytheon Company * Contractor Address: 6825 Pine Street, Suite 340 * Mail Stop B8 * Omaha, NE 68106 * 402.291.0100 * * See the AWIPS II Master Rights File ("Master Rights File.pdf") for * further licensing information. **/ package com.raytheon.uf.common.monitor.scan.xml; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; @XmlRootElement(name = "ScanMonitorConfig") @XmlAccessorType(XmlAccessType.NONE) public class SCANMonitorConfigXML { @XmlElement(name = "CellTilt") private double cellTilt; @XmlElement(name = "DmdTilt") private double dmdTilt; @XmlElement(name = "Interval") private int interval; @XmlElement(name = "Plugins") private String plugins; public SCANMonitorConfigXML() { } public double getCellTilt() { return cellTilt; } public void setCellTilt(double cellTilt) { this.cellTilt = cellTilt; } public double getDmdTilt() { return dmdTilt; } public void setDmdTilt(double dmdTilt) { this.dmdTilt = dmdTilt; } public int getInterval() { return interval; } public void setInterval(int interval) { this.interval = interval; } public String getPlugins() { return plugins; } public void setPlugins(String plugins) { this.plugins = plugins; } }
3e0bdd57e0c3e3f8a0e852e0be515e611131021c
3,286
java
Java
com.nokia.as.jaxrs.jersey.sless.stest/src/com/nokia/as/jaxrs/jersey/sless/stest/MyResourceTest.java
nokia/osgi-microfeatures
50120f20cf929a966364550ca5829ef348d82670
[ "Apache-2.0" ]
null
null
null
com.nokia.as.jaxrs.jersey.sless.stest/src/com/nokia/as/jaxrs/jersey/sless/stest/MyResourceTest.java
nokia/osgi-microfeatures
50120f20cf929a966364550ca5829ef348d82670
[ "Apache-2.0" ]
null
null
null
com.nokia.as.jaxrs.jersey.sless.stest/src/com/nokia/as/jaxrs/jersey/sless/stest/MyResourceTest.java
nokia/osgi-microfeatures
50120f20cf929a966364550ca5829ef348d82670
[ "Apache-2.0" ]
null
null
null
28.573913
94
0.699026
5,012
// Copyright 2000-2021 Nokia // // Licensed under the Apache License 2.0 // SPDX-License-Identifier: Apache-2.0 // package com.nokia.as.jaxrs.jersey.sless.stest; import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; import javax.ws.rs.client.Client; import javax.ws.rs.client.ClientBuilder; import javax.ws.rs.client.WebTarget; import javax.ws.rs.core.Response; import org.apache.felix.dm.annotation.api.Component; import org.apache.felix.dm.annotation.api.Property; import org.apache.felix.dm.annotation.api.ServiceDependency; import org.apache.log4j.Logger; import org.glassfish.jersey.client.JerseyClient; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import com.nokia.as.k8s.sless.Function; import com.nokia.as.util.junit4osgi.OsgiJunitRunner; @Component(provides = Object.class) @Property(name = OsgiJunitRunner.JUNIT, value = "true") @RunWith(OsgiJunitRunner.class) public class MyResourceTest { private static final int RETRY = 100; Logger _log = Logger.getLogger(MyResourceTest.class); Client client = ClientBuilder.newClient(); // Make sure the resource is registered @ServiceDependency Function _myFunction; volatile static boolean _doWait = true; @Before public void before() { if (_doWait) { try { Thread.sleep(10000); } catch (InterruptedException e) { } _doWait = false; } } @Test public void secure_route_answer_403() throws Exception { String url = "http://localhost:8665/services/secure"; _log.warn("secure_route_answer_403"); int status = 0; Response response = null; for (int i = 0; i < RETRY; i++) { try { response = doRequest(url).request().get(); status = response.getStatus(); if (status == Response.Status.FORBIDDEN.getStatusCode()) { assertEquals(status, 403); return; } _log.warn("secure_route_answer_403: current status = " + status); } catch (Exception e) { // connect exception _log.warn("secure_route_answer_403: exception=" + e.toString()); } Thread.sleep(100); } fail("Status code: " + status); } @Test public void unsecure_route_answer_200() throws Exception { String url = "http://localhost:8665/services/unsecure"; _log.warn("unsecure_route_answer_200"); int status = 0; Response response = null; for (int i = 0; i < RETRY; i++) { try { response = doRequest(url).request().get(); status = response.getStatus(); if (status == Response.Status.OK.getStatusCode()) { assertEquals(status, 200); return; } _log.warn("unsecure_route_answer_200: current status = " + status); } catch (Exception e) { // connect exception _log.warn("unsecure_route_answer_200: exception=" + e.toString()); } Thread.sleep(100); } fail("Status code: " + status); } public WebTarget doRequest(String url) { ClassLoader currentThread = Thread.currentThread().getContextClassLoader(); try { Thread.currentThread().setContextClassLoader(JerseyClient.class.getClassLoader()); return client.target(url); } catch (Throwable e) { _log.error("client request failed", e); } finally { Thread.currentThread().setContextClassLoader(currentThread); } return null; } }
3e0bde1b64db85e82754fcf7fdf8fa56557346ec
273
java
Java
whois-query/src/main/java/net/ripe/db/whois/query/planner/GroupFunction.java
acidburn0zzz/whois-1
7e32ae63294e74274e825a7e54a5446893abc260
[ "BSD-3-Clause" ]
1
2016-04-19T16:56:20.000Z
2016-04-19T16:56:20.000Z
whois-query/src/main/java/net/ripe/db/whois/query/planner/GroupFunction.java
acidburn0zzz/whois-1
7e32ae63294e74274e825a7e54a5446893abc260
[ "BSD-3-Clause" ]
1
2022-03-08T21:12:44.000Z
2022-03-08T21:12:44.000Z
whois-query/src/main/java/net/ripe/db/whois/query/planner/GroupFunction.java
Acidburn0zzz/whois-1
7e32ae63294e74274e825a7e54a5446893abc260
[ "BSD-3-Clause" ]
null
null
null
30.333333
84
0.813187
5,013
package net.ripe.db.whois.query.planner; import com.google.common.base.Function; import net.ripe.db.whois.common.domain.ResponseObject; interface GroupFunction extends Function<ResponseObject, Iterable<ResponseObject>> { Iterable<ResponseObject> getGroupedAfter(); }
3e0bde1c9481c0bee03b7d000324d7f9ad47e3d1
1,881
java
Java
common/data/src/main/java/org/thingsboard/server/common/data/rule/RuleChainOutputLabelsUsage.java
andre-aktivconsultancy/thingsboard
7d5153f52ee4033c8a7ffab0a678950122b982eb
[ "ECL-2.0", "Apache-2.0" ]
11,616
2016-12-06T11:19:33.000Z
2022-03-31T16:15:40.000Z
common/data/src/main/java/org/thingsboard/server/common/data/rule/RuleChainOutputLabelsUsage.java
andre-aktivconsultancy/thingsboard
7d5153f52ee4033c8a7ffab0a678950122b982eb
[ "ECL-2.0", "Apache-2.0" ]
4,143
2016-12-06T16:58:55.000Z
2022-03-31T19:26:39.000Z
common/data/src/main/java/org/thingsboard/server/common/data/rule/RuleChainOutputLabelsUsage.java
andre-aktivconsultancy/thingsboard
7d5153f52ee4033c8a7ffab0a678950122b982eb
[ "ECL-2.0", "Apache-2.0" ]
4,144
2016-12-06T13:02:55.000Z
2022-03-31T12:22:41.000Z
40.891304
131
0.766082
5,014
/** * Copyright © 2016-2021 The Thingsboard Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.thingsboard.server.common.data.rule; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import lombok.Data; import lombok.extern.slf4j.Slf4j; import org.jetbrains.annotations.NotNull; import org.thingsboard.server.common.data.id.RuleChainId; import org.thingsboard.server.common.data.id.RuleNodeId; import java.util.Set; @ApiModel @Data @Slf4j public class RuleChainOutputLabelsUsage { @ApiModelProperty(position = 1, required = true, value = "Rule Chain Id", accessMode = ApiModelProperty.AccessMode.READ_ONLY) private RuleChainId ruleChainId; @ApiModelProperty(position = 2, required = true, value = "Rule Node Id", accessMode = ApiModelProperty.AccessMode.READ_ONLY) private RuleNodeId ruleNodeId; @ApiModelProperty(position = 3, required = true, value = "Rule Chain Name", accessMode = ApiModelProperty.AccessMode.READ_ONLY) private String ruleChainName; @ApiModelProperty(position = 4, required = true, value = "Rule Node Name", accessMode = ApiModelProperty.AccessMode.READ_ONLY) private String ruleNodeName; @ApiModelProperty(position = 5, required = true, value = "Output labels", accessMode = ApiModelProperty.AccessMode.READ_ONLY) private Set<String> labels; }
3e0bde3ab58e095b76f830450ac0412ede98e933
6,851
java
Java
java/src/main/java/com/decisionlens/client/model/ProjectTagRemovedEvent.java
dlens/dlxapi
189a6519240ce625d7a9cdb89e305a335d2aa045
[ "MIT" ]
null
null
null
java/src/main/java/com/decisionlens/client/model/ProjectTagRemovedEvent.java
dlens/dlxapi
189a6519240ce625d7a9cdb89e305a335d2aa045
[ "MIT" ]
1
2020-08-20T17:31:43.000Z
2020-08-20T17:31:43.000Z
java/src/main/java/com/decisionlens/client/model/ProjectTagRemovedEvent.java
dlens/dlxapi
189a6519240ce625d7a9cdb89e305a335d2aa045
[ "MIT" ]
null
null
null
24.467857
116
0.684134
5,015
/* * Decision Lens API * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) * * OpenAPI spec version: 1.0 * * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. */ package com.decisionlens.client.model; import java.util.Objects; import java.util.Arrays; import com.decisionlens.client.model.PortfolioPlan; import com.google.gson.TypeAdapter; import com.google.gson.annotations.JsonAdapter; import com.google.gson.annotations.SerializedName; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.io.IOException; /** * ProjectTagRemovedEvent */ public class ProjectTagRemovedEvent { @SerializedName("portfolioId") private String portfolioId = null; @SerializedName("tagParentName") private String tagParentName = null; @SerializedName("tagId") private String tagId = null; @SerializedName("tagColor") private String tagColor = null; @SerializedName("name") private String name = null; @SerializedName("id") private String id = null; @SerializedName("tagName") private String tagName = null; @SerializedName("tagParentId") private String tagParentId = null; @SerializedName("portfolioPlan") private PortfolioPlan portfolioPlan = null; public ProjectTagRemovedEvent portfolioId(String portfolioId) { this.portfolioId = portfolioId; return this; } /** * Get portfolioId * @return portfolioId **/ @ApiModelProperty(value = "") public String getPortfolioId() { return portfolioId; } public void setPortfolioId(String portfolioId) { this.portfolioId = portfolioId; } public ProjectTagRemovedEvent tagParentName(String tagParentName) { this.tagParentName = tagParentName; return this; } /** * Get tagParentName * @return tagParentName **/ @ApiModelProperty(value = "") public String getTagParentName() { return tagParentName; } public void setTagParentName(String tagParentName) { this.tagParentName = tagParentName; } public ProjectTagRemovedEvent tagId(String tagId) { this.tagId = tagId; return this; } /** * Get tagId * @return tagId **/ @ApiModelProperty(value = "") public String getTagId() { return tagId; } public void setTagId(String tagId) { this.tagId = tagId; } public ProjectTagRemovedEvent tagColor(String tagColor) { this.tagColor = tagColor; return this; } /** * Get tagColor * @return tagColor **/ @ApiModelProperty(value = "") public String getTagColor() { return tagColor; } public void setTagColor(String tagColor) { this.tagColor = tagColor; } public ProjectTagRemovedEvent name(String name) { this.name = name; return this; } /** * Get name * @return name **/ @ApiModelProperty(value = "") public String getName() { return name; } public void setName(String name) { this.name = name; } public ProjectTagRemovedEvent id(String id) { this.id = id; return this; } /** * Get id * @return id **/ @ApiModelProperty(value = "") public String getId() { return id; } public void setId(String id) { this.id = id; } public ProjectTagRemovedEvent tagName(String tagName) { this.tagName = tagName; return this; } /** * Get tagName * @return tagName **/ @ApiModelProperty(value = "") public String getTagName() { return tagName; } public void setTagName(String tagName) { this.tagName = tagName; } public ProjectTagRemovedEvent tagParentId(String tagParentId) { this.tagParentId = tagParentId; return this; } /** * Get tagParentId * @return tagParentId **/ @ApiModelProperty(value = "") public String getTagParentId() { return tagParentId; } public void setTagParentId(String tagParentId) { this.tagParentId = tagParentId; } public ProjectTagRemovedEvent portfolioPlan(PortfolioPlan portfolioPlan) { this.portfolioPlan = portfolioPlan; return this; } /** * Get portfolioPlan * @return portfolioPlan **/ @ApiModelProperty(value = "") public PortfolioPlan getPortfolioPlan() { return portfolioPlan; } public void setPortfolioPlan(PortfolioPlan portfolioPlan) { this.portfolioPlan = portfolioPlan; } @Override public boolean equals(java.lang.Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } ProjectTagRemovedEvent projectTagRemovedEvent = (ProjectTagRemovedEvent) o; return Objects.equals(this.portfolioId, projectTagRemovedEvent.portfolioId) && Objects.equals(this.tagParentName, projectTagRemovedEvent.tagParentName) && Objects.equals(this.tagId, projectTagRemovedEvent.tagId) && Objects.equals(this.tagColor, projectTagRemovedEvent.tagColor) && Objects.equals(this.name, projectTagRemovedEvent.name) && Objects.equals(this.id, projectTagRemovedEvent.id) && Objects.equals(this.tagName, projectTagRemovedEvent.tagName) && Objects.equals(this.tagParentId, projectTagRemovedEvent.tagParentId) && Objects.equals(this.portfolioPlan, projectTagRemovedEvent.portfolioPlan); } @Override public int hashCode() { return Objects.hash(portfolioId, tagParentName, tagId, tagColor, name, id, tagName, tagParentId, portfolioPlan); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class ProjectTagRemovedEvent {\n"); sb.append(" portfolioId: ").append(toIndentedString(portfolioId)).append("\n"); sb.append(" tagParentName: ").append(toIndentedString(tagParentName)).append("\n"); sb.append(" tagId: ").append(toIndentedString(tagId)).append("\n"); sb.append(" tagColor: ").append(toIndentedString(tagColor)).append("\n"); sb.append(" name: ").append(toIndentedString(name)).append("\n"); sb.append(" id: ").append(toIndentedString(id)).append("\n"); sb.append(" tagName: ").append(toIndentedString(tagName)).append("\n"); sb.append(" tagParentId: ").append(toIndentedString(tagParentId)).append("\n"); sb.append(" portfolioPlan: ").append(toIndentedString(portfolioPlan)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
3e0bde706467530455431b03f07f464af1f83d5d
514
java
Java
jeorg-jee-apps/jeorg-jee-apps-triad-1/jeorg-jee-app-3-wildfly/src/main/java/org/jesperancinha/jtd/jee/teeth/domain2/Upper.java
jesperancinha/jeorg-java-ee-7-test-drives
566d2afbd76ed6d205fbb222b52ec30ac77df827
[ "Apache-2.0" ]
1
2021-12-03T20:06:26.000Z
2021-12-03T20:06:26.000Z
jeorg-jee-apps/jeorg-jee-apps-triad-1/jeorg-jee-app-3-wildfly/src/main/java/org/jesperancinha/jtd/jee/teeth/domain2/Upper.java
jesperancinha/jeorg-java-ee-7-test-drives
566d2afbd76ed6d205fbb222b52ec30ac77df827
[ "Apache-2.0" ]
40
2021-12-22T17:27:25.000Z
2022-03-17T19:40:51.000Z
jeorg-jee-apps/jeorg-jee-apps-triad-1/jeorg-jee-app-3-wildfly/src/main/java/org/jesperancinha/jtd/jee/teeth/domain2/Upper.java
jesperancinha/jeorg-java-ee-7-test-drives
566d2afbd76ed6d205fbb222b52ec30ac77df827
[ "Apache-2.0" ]
1
2022-01-04T01:59:09.000Z
2022-01-04T01:59:09.000Z
22.347826
55
0.774319
5,016
package org.jesperancinha.jtd.jee.teeth.domain2; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; import javax.validation.constraints.NotNull; import java.util.UUID; @Entity(name = "upper2") @Table(name = "upper2") public class Upper { @Id @Column @GeneratedValue(strategy = GenerationType.IDENTITY) @NotNull private UUID uuid; }
3e0bde9af4d5bfb4cc6f40d3e97313a092e37639
439
java
Java
src/main/java/net/axelandre42/mct/common/init/Blocks.java
Axelandre42/MoreCompuThings
2e2f83731640b60d68d2a6eff202f2f3a5f7733a
[ "MIT" ]
null
null
null
src/main/java/net/axelandre42/mct/common/init/Blocks.java
Axelandre42/MoreCompuThings
2e2f83731640b60d68d2a6eff202f2f3a5f7733a
[ "MIT" ]
null
null
null
src/main/java/net/axelandre42/mct/common/init/Blocks.java
Axelandre42/MoreCompuThings
2e2f83731640b60d68d2a6eff202f2f3a5f7733a
[ "MIT" ]
null
null
null
21.95
107
0.756264
5,017
package net.axelandre42.mct.common.init; import net.axelandre42.mct.MoreCompuThings; import net.minecraft.block.Block; import cpw.mods.fml.common.registry.GameRegistry; public class Blocks { public static void construct() { } private static void simpleRegister(Block block) { GameRegistry.registerBlock(block, MoreCompuThings.MODID + ":" + block.getUnlocalizedName().substring(5)); } public static void register() { } }
3e0bdeb8866934985af308ea6fe4f56291d89873
1,577
java
Java
app/src/main/java/com/ghstudios/android/features/decorations/list/DecorationListActivity.java
CarlosFdez/MHGenDatabase
a6e6c5d1ea7edd96d711704722ae7553ddafa0a8
[ "MIT" ]
83
2016-06-11T02:22:50.000Z
2022-02-23T01:26:35.000Z
app/src/main/java/com/ghstudios/android/features/decorations/list/DecorationListActivity.java
CarlosFdez/MHGenDatabase
a6e6c5d1ea7edd96d711704722ae7553ddafa0a8
[ "MIT" ]
23
2016-07-18T13:46:19.000Z
2021-09-17T12:41:20.000Z
app/src/main/java/com/ghstudios/android/features/decorations/list/DecorationListActivity.java
CarlosFdez/MHGenDatabase
a6e6c5d1ea7edd96d711704722ae7553ddafa0a8
[ "MIT" ]
47
2016-06-14T14:53:42.000Z
2022-03-18T05:37:45.000Z
30.921569
107
0.700698
5,018
package com.ghstudios.android.features.decorations.list; import android.content.Intent; import android.os.Bundle; import androidx.fragment.app.Fragment; import com.ghstudios.android.mhgendatabase.R; import com.ghstudios.android.features.armorsetbuilder.detail.ASBDetailPagerActivity; import com.ghstudios.android.GenericActivity; import com.ghstudios.android.MenuSection; public class DecorationListActivity extends GenericActivity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setTitle(R.string.title_decorations); // Enable back button if we're coming from the set builder if (getIntent().getBooleanExtra(ASBDetailPagerActivity.EXTRA_FROM_SET_BUILDER, false)) { super.disableDrawerIndicator(); } else { // Enable drawer button instead of back button super.enableDrawerIndicator(); // Tag as top level activity super.setAsTopLevel(); } } @Override protected int getSelectedSection() { return MenuSection.DECORATION; } @Override protected Fragment createFragment() { return new DecorationListFragment(); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == ASBDetailPagerActivity.REQUEST_CODE_ADD_DECORATION && resultCode == RESULT_OK) { setResult(RESULT_OK, data); finish(); } } }
3e0be0b867a3780c710e4f9eb984d8bf0d53fbc2
6,249
java
Java
infinispan/cachestore/jdbc/src/main/java/org/infinispan/loaders/jdbc/connectionfactory/PooledConnectionFactory.java
nmldiegues/stibt
1ee662b7d4ed1f80e6092c22e235a3c994d1d393
[ "Apache-2.0" ]
4
2015-01-28T20:46:14.000Z
2021-11-16T06:45:27.000Z
infinispan/cachestore/jdbc/src/main/java/org/infinispan/loaders/jdbc/connectionfactory/PooledConnectionFactory.java
cloudtm/sti-bt
ef80d454627cc376d35d434a48088c311bdf3408
[ "FTL" ]
5
2022-01-21T23:13:01.000Z
2022-02-09T23:01:28.000Z
infinispan/cachestore/jdbc/src/main/java/org/infinispan/loaders/jdbc/connectionfactory/PooledConnectionFactory.java
cloudtm/sti-bt
ef80d454627cc376d35d434a48088c311bdf3408
[ "FTL" ]
2
2015-05-29T00:07:29.000Z
2019-05-22T17:52:45.000Z
41.7
130
0.701359
5,019
/* * JBoss, Home of Professional Open Source * Copyright 2009 Red Hat Inc. and/or its affiliates and other * contributors as indicated by the @author tags. All rights reserved. * See the copyright.txt in the distribution for a full listing of * individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.infinispan.loaders.jdbc.connectionfactory; import com.mchange.v2.c3p0.ComboPooledDataSource; import com.mchange.v2.c3p0.DataSources; import org.infinispan.loaders.CacheLoaderException; import org.infinispan.loaders.jdbc.JdbcUtil; import org.infinispan.loaders.jdbc.logging.Log; import org.infinispan.util.FileLookupFactory; import org.infinispan.util.logging.LogFactory; import java.beans.PropertyVetoException; import java.net.URL; import java.sql.Connection; import java.sql.SQLException; import java.util.Properties; /** * Pooled connection factory based on C3P0. For a complete configuration reference, look <a * href="http://www.mchange.com/projects/c3p0/index.html#configuration">here</a>. The connection pool can be configured * in various ways, as described <a href="http://www.mchange.com/projects/c3p0/index.html#configuration_files">here</a>. * The simplest way is by having an <tt>c3p0.properties</tt> file in the classpath. If no such file is found, default, * hardcoded values will be used. * * @author kenaa@example.com * @author Tristan Tarrant */ public class PooledConnectionFactory extends ConnectionFactory { private static final Log log = LogFactory.getLog(PooledConnectionFactory.class, Log.class); private ComboPooledDataSource pooledDataSource; @Override public void start(ConnectionFactoryConfig config, ClassLoader classLoader) throws CacheLoaderException { logFileOverride(classLoader); pooledDataSource = new ComboPooledDataSource(); pooledDataSource.setProperties(new Properties()); try { /* Since c3p0 does not throw an exception when it fails to load a driver we attempt to do so here * Also, c3p0 does not allow specifying a custom classloader, so use c3p0's */ Class.forName(config.getDriverClass(), true, ComboPooledDataSource.class.getClassLoader()); pooledDataSource.setDriverClass(config.getDriverClass()); //loads the jdbc driver } catch (Exception e) { log.errorInstantiatingJdbcDriver(config.getDriverClass(), e); throw new CacheLoaderException(String.format( "Error while instatianting JDBC driver: '%s'", config.getDriverClass()), e); } pooledDataSource.setJdbcUrl(config.getConnectionUrl()); pooledDataSource.setUser(config.getUserName()); pooledDataSource.setPassword(config.getPassword()); if (log.isTraceEnabled()) { log.tracef("Started connection factory with config: %s", config); } } private void logFileOverride(ClassLoader classLoader) { URL propsUrl = FileLookupFactory.newInstance().lookupFileLocation("c3p0.properties", classLoader); URL xmlUrl = FileLookupFactory.newInstance().lookupFileLocation("c3p0-config.xml", classLoader); if (log.isDebugEnabled() && propsUrl != null) { log.debugf("Found 'c3p0.properties' in classpath: %s", propsUrl); } if (log.isDebugEnabled() && xmlUrl != null) { log.debugf("Found 'c3p0-config.xml' in classpath: %s", xmlUrl); } } @Override public void stop() { try { DataSources.destroy(pooledDataSource); if (log.isDebugEnabled()) { log.debug("Successfully stopped PooledConnectionFactory."); } } catch (SQLException sqle) { log.couldNotDestroyC3p0ConnectionPool(pooledDataSource!=null?pooledDataSource.toString():null, sqle); } } @Override public Connection getConnection() throws CacheLoaderException { try { logBefore(true); Connection connection = pooledDataSource.getConnection(); logAfter(connection, true); return connection; } catch (SQLException e) { throw new CacheLoaderException("Failed obtaining connection from PooledDataSource", e); } } @Override public void releaseConnection(Connection conn) { logBefore(false); JdbcUtil.safeClose(conn); logAfter(conn, false); } public ComboPooledDataSource getPooledDataSource() { return pooledDataSource; } private void logBefore(boolean checkout) { if (log.isTraceEnabled()) { String operation = checkout ? "checkout" : "release"; try { log.tracef("DataSource before %s (NumBusyConnectionsAllUsers) : %d, (NumConnectionsAllUsers) : %d", operation, pooledDataSource.getNumBusyConnectionsAllUsers(), pooledDataSource.getNumConnectionsAllUsers()); } catch (SQLException e) { log.sqlFailureUnexpected(e); } } } private void logAfter(Connection connection, boolean checkout) { if (log.isTraceEnabled()) { String operation = checkout ? "checkout" : "release"; try { log.tracef("DataSource after %s (NumBusyConnectionsAllUsers) : %d, (NumConnectionsAllUsers) : %d", operation, pooledDataSource.getNumBusyConnectionsAllUsers(), pooledDataSource.getNumConnectionsAllUsers()); } catch (SQLException e) { log.sqlFailureUnexpected(e); } log.tracef("Connection %s : %s", operation, connection); } } }
3e0be127a8a618e4515c5e9da77065d3a867ed82
2,934
java
Java
src/main/java/com/cym/service/RemoteService.java
harryczqp/nginxWebUI
203c511699c2ba0176b88d48dad9af5e3e66a113
[ "MulanPSL-1.0" ]
null
null
null
src/main/java/com/cym/service/RemoteService.java
harryczqp/nginxWebUI
203c511699c2ba0176b88d48dad9af5e3e66a113
[ "MulanPSL-1.0" ]
null
null
null
src/main/java/com/cym/service/RemoteService.java
harryczqp/nginxWebUI
203c511699c2ba0176b88d48dad9af5e3e66a113
[ "MulanPSL-1.0" ]
null
null
null
29.34
100
0.720177
5,020
package com.cym.service; import java.util.HashMap; import java.util.List; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.cym.model.Admin; import com.cym.model.AdminGroup; import com.cym.model.Group; import com.cym.model.Remote; import cn.craccd.sqlHelper.utils.ConditionAndWrapper; import cn.craccd.sqlHelper.utils.ConditionOrWrapper; import cn.craccd.sqlHelper.utils.SqlHelper; import cn.hutool.core.util.StrUtil; import cn.hutool.http.HttpUtil; import cn.hutool.json.JSONObject; @Service public class RemoteService { @Autowired SqlHelper sqlHelper; @Autowired AdminService adminService; public void getCreditKey(Remote remote, String code, String auth) { Map<String, Object> paramMap = new HashMap<String, Object>(); paramMap.put("name", remote.getName()); paramMap.put("pass", remote.getPass()); paramMap.put("code", code); paramMap.put("auth", auth); try { String rs = HttpUtil.post(remote.getProtocol() + "://" + remote.getIp() + ":" + remote.getPort() + "/adminPage/login/getCredit", paramMap, 2000); if (StrUtil.isNotEmpty(rs)) { JSONObject jsonObject = new JSONObject(rs); if (jsonObject.getBool("success")) { remote.setSystem(jsonObject.getJSONObject("obj").getStr("system")); remote.setCreditKey(jsonObject.getJSONObject("obj").getStr("creditKey")); } } } catch (Exception e) { e.printStackTrace(); } } public List<Remote> getBySystem(String system) { return sqlHelper.findListByQuery(new ConditionAndWrapper().eq("system", system), Remote.class); } public List<Remote> getListByParent(String parentId) { ConditionAndWrapper conditionAndWrapper = new ConditionAndWrapper(); if (StrUtil.isEmpty(parentId)) { conditionAndWrapper.and(new ConditionOrWrapper().eq("parentId", "").isNull("parentId")); } else { conditionAndWrapper.eq("parentId", parentId); } return sqlHelper.findListByQuery(conditionAndWrapper, Remote.class); } public List<Remote> getMonitorRemoteList() { return sqlHelper.findListByQuery(new ConditionAndWrapper().eq("monitor", 1), Remote.class); } public boolean hasSame(Remote remote) { Long count = 0l; if (StrUtil.isEmpty(remote.getId())) { count = sqlHelper.findCountByQuery( new ConditionAndWrapper().eq("ip", remote.getIp()).eq("port", remote.getPort()), Remote.class); } else { count = sqlHelper.findCountByQuery(new ConditionAndWrapper().eq("ip", remote.getIp()) .eq("port", remote.getPort()).ne("id", remote.getId()), Remote.class); } if (count > 0) { return true; } else { return false; } } public List<Group> getGroupByAdmin(Admin admin) { if (admin.getType() == 0) { return sqlHelper.findAll(Group.class); } else { List<String> groupIds = adminService.getGroupIds(admin.getId()); return sqlHelper.findListByIds(groupIds, Group.class); } } }
3e0be15ca8e72c95114477c78b9647cb68b52264
1,384
java
Java
streampipes-model-client/src/main/java/org/apache/streampipes/model/client/user/Authc.java
Samarth08/incubator-streampipes
32223d179f507180fa4a32b7d05cf6ff133632ab
[ "BSD-3-Clause" ]
228
2019-12-05T09:10:12.000Z
2022-03-30T03:43:07.000Z
streampipes-model-client/src/main/java/org/apache/streampipes/model/client/user/Authc.java
zhangjun0x01/incubator-streampipes
bd2735cf4f70ae6608bb8dcde593b79455712b4e
[ "BSD-3-Clause" ]
29
2019-12-31T07:51:48.000Z
2022-03-13T11:37:45.000Z
streampipes-model-client/src/main/java/org/apache/streampipes/model/client/user/Authc.java
zhangjun0x01/incubator-streampipes
bd2735cf4f70ae6608bb8dcde593b79455712b4e
[ "BSD-3-Clause" ]
65
2019-12-26T09:16:52.000Z
2022-03-30T13:24:16.000Z
30.755556
75
0.756503
5,021
/* * 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.streampipes.model.client.user; public class Authc { private Principal principal; private Credentials credentials; public Authc(Principal principal, Credentials credentials) { super(); this.principal = principal; this.credentials = credentials; } public Principal getPrincipal() { return principal; } public void setPrincipal(Principal principal) { this.principal = principal; } public Credentials getCredentials() { return credentials; } public void setCredentials(Credentials credentials) { this.credentials = credentials; } }
3e0be164010c6fa3237c6b4ebe5639fa673f8147
362
java
Java
ObjectOrientedProgramming/src/entities/Rectangle.java
Zeonnatios/java_estudos
c85588a47ad903eb1762f7ced2a657316f5bacb0
[ "MIT" ]
null
null
null
ObjectOrientedProgramming/src/entities/Rectangle.java
Zeonnatios/java_estudos
c85588a47ad903eb1762f7ced2a657316f5bacb0
[ "MIT" ]
null
null
null
ObjectOrientedProgramming/src/entities/Rectangle.java
Zeonnatios/java_estudos
c85588a47ad903eb1762f7ced2a657316f5bacb0
[ "MIT" ]
null
null
null
17.238095
58
0.621547
5,022
package entities; public class Rectangle { public double width; public double height; public double calculateArea(){ return width * height; } public double calculatePerimeter(){ return 2 * (width + height); } public double calculateDiagonal() { return Math.sqrt(width * width + height * height); } }