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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
3e1de0feaac0542cc5052aadf1dc6b73a87d7d85 | 681 | java | Java | org/apache/maven/classrealm/ClassRealmManager.java | CoOwner/VisualPvP | c92d1dcf40a812787e32e8a21d6462b57e755b99 | [
"MIT"
] | null | null | null | org/apache/maven/classrealm/ClassRealmManager.java | CoOwner/VisualPvP | c92d1dcf40a812787e32e8a21d6462b57e755b99 | [
"MIT"
] | null | null | null | org/apache/maven/classrealm/ClassRealmManager.java | CoOwner/VisualPvP | c92d1dcf40a812787e32e8a21d6462b57e755b99 | [
"MIT"
] | null | null | null | 35.842105 | 148 | 0.82232 | 12,652 | package org.apache.maven.classrealm;
import java.util.List;
import org.apache.maven.model.Model;
import org.apache.maven.model.Plugin;
import org.codehaus.plexus.classworlds.realm.ClassRealm;
import org.sonatype.aether.artifact.Artifact;
public abstract interface ClassRealmManager
{
public abstract ClassRealm getCoreRealm();
public abstract ClassRealm createProjectRealm(Model paramModel, List<Artifact> paramList);
public abstract ClassRealm createExtensionRealm(Plugin paramPlugin, List<Artifact> paramList);
public abstract ClassRealm createPluginRealm(Plugin paramPlugin, ClassLoader paramClassLoader, List<String> paramList, List<Artifact> paramList1);
}
|
3e1de284a2f970f436f67897eefc0c5ceef56ab8 | 4,653 | java | Java | egov/egov-adtaxweb/src/main/java/org/egov/adtax/web/controller/penaltyRates/AdvertisementPenaltyRatesController.java | spiliti/egovzm | fcc86a0209adab63b7b9d193983499310a34fcba | [
"MIT"
] | 1 | 2019-07-25T12:44:57.000Z | 2019-07-25T12:44:57.000Z | egov/egov-adtaxweb/src/main/java/org/egov/adtax/web/controller/penaltyRates/AdvertisementPenaltyRatesController.java | spiliti/egovzm | fcc86a0209adab63b7b9d193983499310a34fcba | [
"MIT"
] | 13 | 2020-03-05T00:01:16.000Z | 2022-02-09T22:58:42.000Z | egov/egov-adtaxweb/src/main/java/org/egov/adtax/web/controller/penaltyRates/AdvertisementPenaltyRatesController.java | spiliti/egovzm | fcc86a0209adab63b7b9d193983499310a34fcba | [
"MIT"
] | 1 | 2021-02-22T21:09:08.000Z | 2021-02-22T21:09:08.000Z | 46.67 | 116 | 0.728734 | 12,653 | /*
* eGov SmartCity eGovernance suite aims to improve the internal efficiency,transparency,
* accountability and the service delivery of the government organizations.
*
* Copyright (C) 2017 eGovernments Foundation
*
* The updated version of eGov suite of products as by eGovernments Foundation
* is available at http://www.egovernments.org
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see http://www.gnu.org/licenses/ or
* http://www.gnu.org/licenses/gpl.html .
*
* In addition to the terms of the GPL license to be adhered to in using this
* program, the following additional terms are to be complied with:
*
* 1) All versions of this program, verbatim or modified must carry this
* Legal Notice.
* Further, all user interfaces, including but not limited to citizen facing interfaces,
* Urban Local Bodies interfaces, dashboards, mobile applications, of the program and any
* derived works should carry eGovernments Foundation logo on the top right corner.
*
* For the logo, please refer http://egovernments.org/html/logo/egov_logo.png.
* For any further queries on attribution, including queries on brand guidelines,
* please contact hzdkv@example.com
*
* 2) Any misrepresentation of the origin of the material is prohibited. It
* is required that all modified versions of this material be marked in
* reasonable ways as different from the original version.
*
* 3) This license does not grant any rights to any user of the program
* with regards to rights under trademark law for use of the trade names
* or trademarks of eGovernments Foundation.
*
* In case of any queries, you can reach eGovernments Foundation at hzdkv@example.com.
*
*/
package org.egov.adtax.web.controller.penaltyRates;
import org.egov.adtax.entity.AdvertisementPenaltyRates;
import org.egov.adtax.search.contract.HoardingPenaltyRates;
import org.egov.adtax.service.AdvertisementPenaltyRatesService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import java.util.ArrayList;
import java.util.List;
@Controller
@RequestMapping(value = "penalty")
public class AdvertisementPenaltyRatesController {
@Autowired
private AdvertisementPenaltyRatesService penaltyRatesService;
@RequestMapping(value = "/change")
public String changePenaltyRates(@ModelAttribute HoardingPenaltyRates hoardingPenaltyRates, final Model model) {
hoardingPenaltyRates.setAdvtPenaltyRatesList(penaltyRatesService.findPenaltyRatesInAscendingOrder());
return "penaltyRates-change";
}
@RequestMapping(value = "/create", method = RequestMethod.POST)
public String createPenaltyRates(@ModelAttribute HoardingPenaltyRates hoardingPenaltyRates,
final RedirectAttributes redirectAttributes, @RequestParam final Long id) {
List<AdvertisementPenaltyRates> rateList = new ArrayList<AdvertisementPenaltyRates>();
rateList = penaltyRatesService.findPenaltyRatesInAscendingOrder();
if (hoardingPenaltyRates != null) {
for (AdvertisementPenaltyRates advtPenaltyRates : hoardingPenaltyRates.getAdvtPenaltyRatesList()) {
penaltyRatesService.createPenaltyRates(advtPenaltyRates);
}
for (AdvertisementPenaltyRates rate : rateList) {
if (!hoardingPenaltyRates.getAdvtPenaltyRatesList().contains(rate)) {
penaltyRatesService.delete(rate);
}
}
}
return "penaltyRate-success";
}
}
|
3e1de32530c91e2113637104db75b5050fbaf8f2 | 18,314 | java | Java | clients/google-api-services-oauth2/v2/1.30.1/com/google/api/services/oauth2/Oauth2.java | yoshi-code-bot/google-api-java-client-services | 9f5e3b6073c822db4078d638c980b11a0effc686 | [
"Apache-2.0"
] | 372 | 2018-09-05T21:06:51.000Z | 2022-03-31T09:22:03.000Z | clients/google-api-services-oauth2/v2/1.30.1/com/google/api/services/oauth2/Oauth2.java | yoshi-code-bot/google-api-java-client-services | 9f5e3b6073c822db4078d638c980b11a0effc686 | [
"Apache-2.0"
] | 1,351 | 2018-10-12T23:07:12.000Z | 2022-03-05T09:25:29.000Z | clients/google-api-services-oauth2/v2/1.30.1/com/google/api/services/oauth2/Oauth2.java | yoshi-code-bot/google-api-java-client-services | 9f5e3b6073c822db4078d638c980b11a0effc686 | [
"Apache-2.0"
] | 307 | 2018-09-04T20:15:31.000Z | 2022-03-31T09:42:39.000Z | 32.299824 | 148 | 0.649612 | 12,654 | /*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
/*
* This code was generated by https://github.com/googleapis/google-api-java-client-services/
* Modify at your own risk.
*/
package com.google.api.services.oauth2;
/**
* Service definition for Oauth2 (v2).
*
* <p>
* Obtains end-user authorization grants for use with other Google APIs.
* </p>
*
* <p>
* For more information about this service, see the
* <a href="https://developers.google.com/identity/protocols/oauth2/" target="_blank">API Documentation</a>
* </p>
*
* <p>
* This service uses {@link Oauth2RequestInitializer} to initialize global parameters via its
* {@link Builder}.
* </p>
*
* @since 1.3
* @author Google, Inc.
*/
@SuppressWarnings("javadoc")
public class Oauth2 extends com.google.api.client.googleapis.services.json.AbstractGoogleJsonClient {
// Note: Leave this static initializer at the top of the file.
static {
com.google.api.client.util.Preconditions.checkState(
com.google.api.client.googleapis.GoogleUtils.MAJOR_VERSION == 1 &&
com.google.api.client.googleapis.GoogleUtils.MINOR_VERSION >= 15,
"You are currently running with version %s of google-api-client. " +
"You need at least version 1.15 of google-api-client to run version " +
"1.30.10 of the Google OAuth2 API library.", com.google.api.client.googleapis.GoogleUtils.VERSION);
}
/**
* The default encoded root URL of the service. This is determined when the library is generated
* and normally should not be changed.
*
* @since 1.7
*/
public static final String DEFAULT_ROOT_URL = "https://www.googleapis.com/";
/**
* The default encoded service path of the service. This is determined when the library is
* generated and normally should not be changed.
*
* @since 1.7
*/
public static final String DEFAULT_SERVICE_PATH = "";
/**
* The default encoded batch path of the service. This is determined when the library is
* generated and normally should not be changed.
*
* @since 1.23
*/
public static final String DEFAULT_BATCH_PATH = "batch/oauth2/v2";
/**
* The default encoded base URL of the service. This is determined when the library is generated
* and normally should not be changed.
*/
public static final String DEFAULT_BASE_URL = DEFAULT_ROOT_URL + DEFAULT_SERVICE_PATH;
/**
* Constructor.
*
* <p>
* Use {@link Builder} if you need to specify any of the optional parameters.
* </p>
*
* @param transport HTTP transport, which should normally be:
* <ul>
* <li>Google App Engine:
* {@code com.google.api.client.extensions.appengine.http.UrlFetchTransport}</li>
* <li>Android: {@code newCompatibleTransport} from
* {@code com.google.api.client.extensions.android.http.AndroidHttp}</li>
* <li>Java: {@link com.google.api.client.googleapis.javanet.GoogleNetHttpTransport#newTrustedTransport()}
* </li>
* </ul>
* @param jsonFactory JSON factory, which may be:
* <ul>
* <li>Jackson: {@code com.google.api.client.json.jackson2.JacksonFactory}</li>
* <li>Google GSON: {@code com.google.api.client.json.gson.GsonFactory}</li>
* <li>Android Honeycomb or higher:
* {@code com.google.api.client.extensions.android.json.AndroidJsonFactory}</li>
* </ul>
* @param httpRequestInitializer HTTP request initializer or {@code null} for none
* @since 1.7
*/
public Oauth2(com.google.api.client.http.HttpTransport transport, com.google.api.client.json.JsonFactory jsonFactory,
com.google.api.client.http.HttpRequestInitializer httpRequestInitializer) {
this(new Builder(transport, jsonFactory, httpRequestInitializer));
}
/**
* @param builder builder
*/
Oauth2(Builder builder) {
super(builder);
}
@Override
protected void initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest<?> httpClientRequest) throws java.io.IOException {
super.initialize(httpClientRequest);
}
/**
* An accessor for creating requests from the Userinfo collection.
*
* <p>The typical use is:</p>
* <pre>
* {@code Oauth2 oauth2 = new Oauth2(...);}
* {@code Oauth2.Userinfo.List request = oauth2.userinfo().list(parameters ...)}
* </pre>
*
* @return the resource collection
*/
public Userinfo userinfo() {
return new Userinfo();
}
/**
* The "userinfo" collection of methods.
*/
public class Userinfo {
/**
* Create a request for the method "userinfo.get".
*
* This request holds the parameters needed by the oauth2 server. After setting any optional
* parameters, call the {@link Get#execute()} method to invoke the remote operation.
*
* @return the request
*/
public Get get() throws java.io.IOException {
Get result = new Get();
initialize(result);
return result;
}
public class Get extends Oauth2Request<com.google.api.services.oauth2.model.Userinfo> {
private static final String REST_PATH = "oauth2/v2/userinfo";
/**
* Create a request for the method "userinfo.get".
*
* This request holds the parameters needed by the the oauth2 server. After setting any optional
* parameters, call the {@link Get#execute()} method to invoke the remote operation. <p> {@link
* Get#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} must be
* called to initialize this instance immediately after invoking the constructor. </p>
*
* @since 1.13
*/
protected Get() {
super(Oauth2.this, "GET", REST_PATH, null, com.google.api.services.oauth2.model.Userinfo.class);
}
@Override
public com.google.api.client.http.HttpResponse executeUsingHead() throws java.io.IOException {
return super.executeUsingHead();
}
@Override
public com.google.api.client.http.HttpRequest buildHttpRequestUsingHead() throws java.io.IOException {
return super.buildHttpRequestUsingHead();
}
@Override
public Get setAlt(java.lang.String alt) {
return (Get) super.setAlt(alt);
}
@Override
public Get setFields(java.lang.String fields) {
return (Get) super.setFields(fields);
}
@Override
public Get setKey(java.lang.String key) {
return (Get) super.setKey(key);
}
@Override
public Get setOauthToken(java.lang.String oauthToken) {
return (Get) super.setOauthToken(oauthToken);
}
@Override
public Get setPrettyPrint(java.lang.Boolean prettyPrint) {
return (Get) super.setPrettyPrint(prettyPrint);
}
@Override
public Get setQuotaUser(java.lang.String quotaUser) {
return (Get) super.setQuotaUser(quotaUser);
}
@Override
public Get setUserIp(java.lang.String userIp) {
return (Get) super.setUserIp(userIp);
}
@Override
public Get set(String parameterName, Object value) {
return (Get) super.set(parameterName, value);
}
}
/**
* An accessor for creating requests from the V2 collection.
*
* <p>The typical use is:</p>
* <pre>
* {@code Oauth2 oauth2 = new Oauth2(...);}
* {@code Oauth2.V2.List request = oauth2.v2().list(parameters ...)}
* </pre>
*
* @return the resource collection
*/
public V2 v2() {
return new V2();
}
/**
* The "v2" collection of methods.
*/
public class V2 {
/**
* An accessor for creating requests from the Me collection.
*
* <p>The typical use is:</p>
* <pre>
* {@code Oauth2 oauth2 = new Oauth2(...);}
* {@code Oauth2.Me.List request = oauth2.me().list(parameters ...)}
* </pre>
*
* @return the resource collection
*/
public Me me() {
return new Me();
}
/**
* The "me" collection of methods.
*/
public class Me {
/**
* Create a request for the method "me.get".
*
* This request holds the parameters needed by the oauth2 server. After setting any optional
* parameters, call the {@link Get#execute()} method to invoke the remote operation.
*
* @return the request
*/
public Get get() throws java.io.IOException {
Get result = new Get();
initialize(result);
return result;
}
public class Get extends Oauth2Request<com.google.api.services.oauth2.model.Userinfo> {
private static final String REST_PATH = "userinfo/v2/me";
/**
* Create a request for the method "me.get".
*
* This request holds the parameters needed by the the oauth2 server. After setting any optional
* parameters, call the {@link Get#execute()} method to invoke the remote operation. <p> {@link
* Get#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} must be
* called to initialize this instance immediately after invoking the constructor. </p>
*
* @since 1.13
*/
protected Get() {
super(Oauth2.this, "GET", REST_PATH, null, com.google.api.services.oauth2.model.Userinfo.class);
}
@Override
public com.google.api.client.http.HttpResponse executeUsingHead() throws java.io.IOException {
return super.executeUsingHead();
}
@Override
public com.google.api.client.http.HttpRequest buildHttpRequestUsingHead() throws java.io.IOException {
return super.buildHttpRequestUsingHead();
}
@Override
public Get setAlt(java.lang.String alt) {
return (Get) super.setAlt(alt);
}
@Override
public Get setFields(java.lang.String fields) {
return (Get) super.setFields(fields);
}
@Override
public Get setKey(java.lang.String key) {
return (Get) super.setKey(key);
}
@Override
public Get setOauthToken(java.lang.String oauthToken) {
return (Get) super.setOauthToken(oauthToken);
}
@Override
public Get setPrettyPrint(java.lang.Boolean prettyPrint) {
return (Get) super.setPrettyPrint(prettyPrint);
}
@Override
public Get setQuotaUser(java.lang.String quotaUser) {
return (Get) super.setQuotaUser(quotaUser);
}
@Override
public Get setUserIp(java.lang.String userIp) {
return (Get) super.setUserIp(userIp);
}
@Override
public Get set(String parameterName, Object value) {
return (Get) super.set(parameterName, value);
}
}
}
}
}
/**
* Create a request for the method "tokeninfo".
*
* This request holds the parameters needed by the oauth2 server. After setting any optional
* parameters, call the {@link Tokeninfo#execute()} method to invoke the remote operation.
*
* @return the request
*/
public Tokeninfo tokeninfo() throws java.io.IOException {
Tokeninfo result = new Tokeninfo();
initialize(result);
return result;
}
public class Tokeninfo extends Oauth2Request<com.google.api.services.oauth2.model.Tokeninfo> {
private static final String REST_PATH = "oauth2/v2/tokeninfo";
/**
* Create a request for the method "tokeninfo".
*
* This request holds the parameters needed by the the oauth2 server. After setting any optional
* parameters, call the {@link Tokeninfo#execute()} method to invoke the remote operation. <p>
* {@link
* Tokeninfo#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)}
* must be called to initialize this instance immediately after invoking the constructor. </p>
*
* @since 1.13
*/
protected Tokeninfo() {
super(Oauth2.this, "POST", REST_PATH, null, com.google.api.services.oauth2.model.Tokeninfo.class);
}
@Override
public Tokeninfo setAlt(java.lang.String alt) {
return (Tokeninfo) super.setAlt(alt);
}
@Override
public Tokeninfo setFields(java.lang.String fields) {
return (Tokeninfo) super.setFields(fields);
}
@Override
public Tokeninfo setKey(java.lang.String key) {
return (Tokeninfo) super.setKey(key);
}
@Override
public Tokeninfo setOauthToken(java.lang.String oauthToken) {
return (Tokeninfo) super.setOauthToken(oauthToken);
}
@Override
public Tokeninfo setPrettyPrint(java.lang.Boolean prettyPrint) {
return (Tokeninfo) super.setPrettyPrint(prettyPrint);
}
@Override
public Tokeninfo setQuotaUser(java.lang.String quotaUser) {
return (Tokeninfo) super.setQuotaUser(quotaUser);
}
@Override
public Tokeninfo setUserIp(java.lang.String userIp) {
return (Tokeninfo) super.setUserIp(userIp);
}
@com.google.api.client.util.Key("access_token")
private java.lang.String accessToken;
/**
*/
public java.lang.String getAccessToken() {
return accessToken;
}
public Tokeninfo setAccessToken(java.lang.String accessToken) {
this.accessToken = accessToken;
return this;
}
@com.google.api.client.util.Key("id_token")
private java.lang.String idToken;
/**
*/
public java.lang.String getIdToken() {
return idToken;
}
public Tokeninfo setIdToken(java.lang.String idToken) {
this.idToken = idToken;
return this;
}
@Override
public Tokeninfo set(String parameterName, Object value) {
return (Tokeninfo) super.set(parameterName, value);
}
}
/**
* Builder for {@link Oauth2}.
*
* <p>
* Implementation is not thread-safe.
* </p>
*
* @since 1.3.0
*/
public static final class Builder extends com.google.api.client.googleapis.services.json.AbstractGoogleJsonClient.Builder {
/**
* Returns an instance of a new builder.
*
* @param transport HTTP transport, which should normally be:
* <ul>
* <li>Google App Engine:
* {@code com.google.api.client.extensions.appengine.http.UrlFetchTransport}</li>
* <li>Android: {@code newCompatibleTransport} from
* {@code com.google.api.client.extensions.android.http.AndroidHttp}</li>
* <li>Java: {@link com.google.api.client.googleapis.javanet.GoogleNetHttpTransport#newTrustedTransport()}
* </li>
* </ul>
* @param jsonFactory JSON factory, which may be:
* <ul>
* <li>Jackson: {@code com.google.api.client.json.jackson2.JacksonFactory}</li>
* <li>Google GSON: {@code com.google.api.client.json.gson.GsonFactory}</li>
* <li>Android Honeycomb or higher:
* {@code com.google.api.client.extensions.android.json.AndroidJsonFactory}</li>
* </ul>
* @param httpRequestInitializer HTTP request initializer or {@code null} for none
* @since 1.7
*/
public Builder(com.google.api.client.http.HttpTransport transport, com.google.api.client.json.JsonFactory jsonFactory,
com.google.api.client.http.HttpRequestInitializer httpRequestInitializer) {
super(
transport,
jsonFactory,
DEFAULT_ROOT_URL,
DEFAULT_SERVICE_PATH,
httpRequestInitializer,
false);
setBatchPath(DEFAULT_BATCH_PATH);
}
/** Builds a new instance of {@link Oauth2}. */
@Override
public Oauth2 build() {
return new Oauth2(this);
}
@Override
public Builder setRootUrl(String rootUrl) {
return (Builder) super.setRootUrl(rootUrl);
}
@Override
public Builder setServicePath(String servicePath) {
return (Builder) super.setServicePath(servicePath);
}
@Override
public Builder setBatchPath(String batchPath) {
return (Builder) super.setBatchPath(batchPath);
}
@Override
public Builder setHttpRequestInitializer(com.google.api.client.http.HttpRequestInitializer httpRequestInitializer) {
return (Builder) super.setHttpRequestInitializer(httpRequestInitializer);
}
@Override
public Builder setApplicationName(String applicationName) {
return (Builder) super.setApplicationName(applicationName);
}
@Override
public Builder setSuppressPatternChecks(boolean suppressPatternChecks) {
return (Builder) super.setSuppressPatternChecks(suppressPatternChecks);
}
@Override
public Builder setSuppressRequiredParameterChecks(boolean suppressRequiredParameterChecks) {
return (Builder) super.setSuppressRequiredParameterChecks(suppressRequiredParameterChecks);
}
@Override
public Builder setSuppressAllChecks(boolean suppressAllChecks) {
return (Builder) super.setSuppressAllChecks(suppressAllChecks);
}
/**
* Set the {@link Oauth2RequestInitializer}.
*
* @since 1.12
*/
public Builder setOauth2RequestInitializer(
Oauth2RequestInitializer oauth2RequestInitializer) {
return (Builder) super.setGoogleClientRequestInitializer(oauth2RequestInitializer);
}
@Override
public Builder setGoogleClientRequestInitializer(
com.google.api.client.googleapis.services.GoogleClientRequestInitializer googleClientRequestInitializer) {
return (Builder) super.setGoogleClientRequestInitializer(googleClientRequestInitializer);
}
}
}
|
3e1de3bb4cf78c69b13776cd718cad0f870a8616 | 3,337 | java | Java | changgou-parent/changgou-service/changgou-service-goods/src/main/java/com/changgou/goods/controller/SkuController.java | xiekecheng/changgouMall | 80cca7d1127f32966ae38bc6fc414c8b4ca19230 | [
"Apache-2.0"
] | null | null | null | changgou-parent/changgou-service/changgou-service-goods/src/main/java/com/changgou/goods/controller/SkuController.java | xiekecheng/changgouMall | 80cca7d1127f32966ae38bc6fc414c8b4ca19230 | [
"Apache-2.0"
] | null | null | null | changgou-parent/changgou-service/changgou-service-goods/src/main/java/com/changgou/goods/controller/SkuController.java | xiekecheng/changgouMall | 80cca7d1127f32966ae38bc6fc414c8b4ca19230 | [
"Apache-2.0"
] | null | null | null | 26.070313 | 129 | 0.585556 | 12,655 | package com.changgou.goods.controller;
import com.changgou.goods.pojo.Sku;
import com.changgou.goods.service.SkuService;
import com.github.pagehelper.PageInfo;
import entity.Result;
import entity.StatusCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
/****
* @Author:admin
* @Description:
* @Date 2019/6/14 0:18
*****/
@RestController
@RequestMapping("/sku")
@CrossOrigin
public class SkuController {
@Autowired
private SkuService skuService;
/***
* Sku分页条件搜索实现
* @param sku
* @param page
* @param size
* @return
*/
@PostMapping(value = "/search/{page}/{size}" )
public Result<PageInfo> findPage(@RequestBody(required = false) Sku sku, @PathVariable int page, @PathVariable int size){
//调用SkuService实现分页条件查询Sku
PageInfo<Sku> pageInfo = skuService.findPage(sku, page, size);
return new Result(true,StatusCode.OK,"查询成功",pageInfo);
}
/***
* Sku分页搜索实现
* @param page:当前页
* @param size:每页显示多少条
* @return
*/
@GetMapping(value = "/search/{page}/{size}" )
public Result<PageInfo> findPage(@PathVariable int page, @PathVariable int size){
//调用SkuService实现分页查询Sku
PageInfo<Sku> pageInfo = skuService.findPage(page, size);
return new Result<PageInfo>(true,StatusCode.OK,"查询成功",pageInfo);
}
/***
* 多条件搜索品牌数据
* @param sku
* @return
*/
@PostMapping(value = "/search" )
public Result<List<Sku>> findList(@RequestBody(required = false) Sku sku){
//调用SkuService实现条件查询Sku
List<Sku> list = skuService.findList(sku);
return new Result<List<Sku>>(true,StatusCode.OK,"查询成功",list);
}
/***
* 根据ID删除品牌数据
* @param id
* @return
*/
@DeleteMapping(value = "/{id}" )
public Result delete(@PathVariable String id){
//调用SkuService实现根据主键删除
skuService.delete(id);
return new Result(true,StatusCode.OK,"删除成功");
}
/***
* 修改Sku数据
* @param sku
* @param id
* @return
*/
@PutMapping(value="/{id}")
public Result update(@RequestBody Sku sku,@PathVariable Long id){
//设置主键值
sku.setId(id);
//调用SkuService实现修改Sku
skuService.update(sku);
return new Result(true,StatusCode.OK,"修改成功");
}
/***
* 新增Sku数据
* @param sku
* @return
*/
@PostMapping
public Result add(@RequestBody Sku sku){
//调用SkuService实现添加Sku
skuService.add(sku);
return new Result(true,StatusCode.OK,"添加成功");
}
/***
* 根据ID查询Sku数据
* @param id
* @return
*/
@GetMapping("/{id}")
public Result<Sku> findById(@PathVariable String id){
//调用SkuService实现根据主键查询Sku
Sku sku = skuService.findById(id);
return new Result<Sku>(true,StatusCode.OK,"查询成功",sku);
}
/***
* 查询Sku全部数据
* @return
*/
@GetMapping
public Result<List<Sku>> findAll(){
//调用SkuService实现查询所有Sku
List<Sku> list = skuService.findAll();
return new Result<List<Sku>>(true, StatusCode.OK,"查询成功",list) ;
}
}
|
3e1de3f236241bda461343bf70fb9d9455471a91 | 595 | java | Java | src/main/java/com/hpe/apppulse/openapi/v1/bl/beans/TokenBean.java | MicroFocus/openapiclientdemo | 2662ab9554a4f11493960ca6f8dd87e5e1f9598c | [
"Apache-2.0"
] | 2 | 2016-06-28T16:56:39.000Z | 2016-08-25T20:41:24.000Z | src/main/java/com/hpe/apppulse/openapi/v1/bl/beans/TokenBean.java | MicroFocus/openapiclientdemo | 2662ab9554a4f11493960ca6f8dd87e5e1f9598c | [
"Apache-2.0"
] | 1 | 2016-06-28T00:19:06.000Z | 2016-06-28T13:55:55.000Z | src/main/java/com/hpe/apppulse/openapi/v1/bl/beans/TokenBean.java | hpe-apppulse/openapiclientdemo | 2662ab9554a4f11493960ca6f8dd87e5e1f9598c | [
"Apache-2.0"
] | null | null | null | 19.193548 | 59 | 0.645378 | 12,656 | package com.hpe.apppulse.openapi.v1.bl.beans;
/**
* Created by Meir Ron on 7/22/2015.
*
* This is the bean that contains the return Token details.
*/
public class TokenBean {
private Long expirationTime;
private String token;
public TokenBean() {
}
public Long getExpirationTime() {
return expirationTime;
}
public void setExpirationTime(Long expirationTime) {
this.expirationTime = expirationTime;
}
public String getToken() {
return token;
}
public void setToken(String token) {
this.token = token;
}
}
|
3e1de4a50ec584f6e318242012baeeaacc95cfee | 2,601 | java | Java | model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/mapping/TestMappingChaining.java | mythoss/midpoint | 834b78d89fc7e423fdf52f0fece19a24ec4e5f27 | [
"Apache-2.0"
] | null | null | null | model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/mapping/TestMappingChaining.java | mythoss/midpoint | 834b78d89fc7e423fdf52f0fece19a24ec4e5f27 | [
"Apache-2.0"
] | null | null | null | model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/mapping/TestMappingChaining.java | mythoss/midpoint | 834b78d89fc7e423fdf52f0fece19a24ec4e5f27 | [
"Apache-2.0"
] | null | null | null | 36.125 | 147 | 0.731257 | 12,657 | /*
* Copyright (C) 2010-2021 Evolveum and contributors
*
* This work is dual-licensed under the Apache License 2.0
* and European Union Public License. See LICENSE file for details.
*/
package com.evolveum.midpoint.model.intest.mapping;
import java.io.File;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.annotation.DirtiesContext.ClassMode;
import org.springframework.test.context.ContextConfiguration;
import org.testng.annotations.Test;
import com.evolveum.midpoint.schema.result.OperationResult;
import com.evolveum.midpoint.task.api.Task;
import com.evolveum.midpoint.test.TestResource;
/**
* Testing mapping chaining (eventually in all contexts - in template, in assignments, etc).
*/
@SuppressWarnings("SameParameterValue")
@ContextConfiguration(locations = { "classpath:ctx-model-intest-test-main.xml" })
@DirtiesContext(classMode = ClassMode.AFTER_CLASS)
public class TestMappingChaining extends AbstractMappingTest {
public static final File TEST_DIR = new File("src/test/resources/mapping/chaining");
private static final File SYSTEM_CONFIGURATION_FILE = new File(TEST_DIR, "system-configuration.xml");
private static final TestResource<?> USER_TEMPLATE = new TestResource<>(TEST_DIR, "user-template.xml", "c983791f-10c7-410c-83bd-71ef85174505");
private static final TestResource<?> ROLE_MASTER = new TestResource<>(TEST_DIR, "role-master.xml", "c7968dad-0711-4e45-8846-b6c28fc8c71a");
private static final TestResource<?> USER_LEGALL = new TestResource<>(TEST_DIR, "user-legall.xml", "db3875df-5f5e-4379-bca5-d1349eee5033");
@Override
public void initSystem(Task initTask, OperationResult initResult) throws Exception {
super.initSystem(initTask, initResult);
repoAdd(USER_TEMPLATE, initResult);
repoAdd(ROLE_MASTER, initResult);
repoAdd(USER_LEGALL, initResult);
}
@Override
protected File getSystemConfigurationFile() {
return SYSTEM_CONFIGURATION_FILE;
}
/**
* MID-6135. (Computation of delta from upstream mapping was not correct, misleading the downstream one.)
*/
@Test
public void test100RecomputeUser() throws Exception {
given();
Task task = getTestTask();
OperationResult result = getTestOperationResult();
when();
recomputeUser(USER_LEGALL.oid, task, result);
then();
assertSuccess(result);
assertUser(USER_LEGALL.oid, "user after")
.assertAssignments(0)
.assertExtensionValue("booleanFlag", false);
}
}
|
3e1de53d8be112dc7dcf1814c1fd23812d2df51b | 1,123 | java | Java | quepo-translator/src/main/java/com/silicornio/quepotranslator/QPCustomTranslation.java | SilicorniO/quepo-translator | d9b06dd1920fec4c4c0afae206851e1c5f00a0c9 | [
"Apache-2.0"
] | null | null | null | quepo-translator/src/main/java/com/silicornio/quepotranslator/QPCustomTranslation.java | SilicorniO/quepo-translator | d9b06dd1920fec4c4c0afae206851e1c5f00a0c9 | [
"Apache-2.0"
] | null | null | null | quepo-translator/src/main/java/com/silicornio/quepotranslator/QPCustomTranslation.java | SilicorniO/quepo-translator | d9b06dd1920fec4c4c0afae206851e1c5f00a0c9 | [
"Apache-2.0"
] | null | null | null | 35.09375 | 139 | 0.658949 | 12,658 | package com.silicornio.quepotranslator;
import java.lang.reflect.ParameterizedType;
/**
* Created by SilicorniO
*/
public abstract class QPCustomTranslation<T, U> {
public abstract U onTranslation(T t);
public abstract T onTranslationInverse(U u);
/**
* Check if the classes received are the same
* @param klass1 Class first
* @param klass2 Class second
* @return int 1 same type, -1 inverse, 0 no equal
*/
public int sameTypes(Class klass1, Class klass2){
Class<T> klassT = (Class<T>)(((ParameterizedType)getClass().getGenericSuperclass()).getActualTypeArguments()[0]);
Class<U> klassU = (Class<U>)(((ParameterizedType)getClass().getGenericSuperclass()).getActualTypeArguments()[1]);
if((klass1.equals(klassT) || klassT.isAssignableFrom(klass1)) && (klass2.equals(klassU) || klassU.isAssignableFrom(klass2))){
return 1;
}else if((klass1.equals(klassU) || klassU.isAssignableFrom(klass1)) && (klass2.equals(klassT) || klassT.isAssignableFrom(klass2))){
return -1;
}else{
return 0;
}
}
}
|
3e1de647509b817ed6abd275afeee803adbcee2b | 3,852 | java | Java | Project/AmbicableHappy.java | Shiv-Learning-Cente/Computer-Applications-X | d361e4a18326f520722476051114c1bf90d870fd | [
"MIT"
] | null | null | null | Project/AmbicableHappy.java | Shiv-Learning-Cente/Computer-Applications-X | d361e4a18326f520722476051114c1bf90d870fd | [
"MIT"
] | null | null | null | Project/AmbicableHappy.java | Shiv-Learning-Cente/Computer-Applications-X | d361e4a18326f520722476051114c1bf90d870fd | [
"MIT"
] | null | null | null | 41.869565 | 118 | 0.392783 | 12,659 | import java.util.Scanner;
import java.util.*;
public class AmbicableHappy {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("\n***** Copyright Sushil 2021 *****\n\n");
System.out.println("::Welcome to Amicable-Happy Game::\n");
while(true) {
System.out.println("\n --> To check Amicable Number, Enter \'A\'");
System.out.println(" --> To check Happy Number, Enter \'H\'");
System.out.println(" --> To Exit, Enter \'E\'");
System.out.println("\nEnter your choice::");
String choice = scan.next();//accept user input
switch(choice){
case "a":
case "A": System.out.println("\n********* AMBICABLE NUMBER *********\n");
System.out.print("Enter 1st number = ");
int a = scan.nextInt(); // input first number
System.out.print("Enter 2nd number = ");
int b = scan.nextInt(); // input second number
int sumA = 0, sumB = 0; // storing the sum of factors of both the number
for(int i = 1; i <= a; i++)
{
if (a%i == 0) sumA += i; // sum of factor of first number
}
for(int i = 1; i<=b; i++)
{
if(b%i == 0) sumB += i; // sum of factor of second number
}
if (sumA == sumB) {
System.out.print("\n----------------------------------------------------\n");
System.out.print("Result:- The numbers are AMICABLE Number.");
System.out.println("\n----------------------------------------------------");
System.out.println("\n\n------> PLAY ONCE AGAIN !! <--------\n");
} else
{
System.out.println("\n----------------------------------------------------\n");
System.out.println("Result:- The numbers are not AMICABLE Number.");
System.out.println("\n----------------------------------------------------");
System.out.println("\n\n ------> PLAY ONCE AGAIN !! <--------\n");
}
break;
case "h":
case "H": System.out.println("\n********* HAPPY NUMBER *********\n");
System.out.print("Enter a number = ");
int num = scan.nextInt(); // input the number
Set<Integer> unique_num = new HashSet<Integer>();
while (unique_num.add(num))
{
int value = 0;
while (num > 0)
{
value += Math.pow(num % 10, 2);
num /= 10;
}
num = value;
}
if (num == 1) {
System.out.print("\n----------------------------------------------------\n");
System.out.print("Result:- The number is HAPPY Number.");
System.out.println("\n----------------------------------------------------");
System.out.println("\n\n------> PLAY ONCE AGAIN !! <--------\n");
} else {
System.out.print("\n----------------------------------------------------\n");
System.out.print("Result:- The number is not HAPPY Number.");
System.out.println("\n----------------------------------------------------");
System.out.println("\n\n------> PLAY ONCE AGAIN !! <--------\n");
}
break;
case "e":
case "E": System.out.println("Exiting the application");
System.exit(0);
default: System.out.println("Incorrect input!!! Please re-enter choice from our menu");
}
}
}
}
|
3e1de7b9fbcd14193ab246ef6234848e7d758005 | 99 | java | Java | corpus/class/eclipse.jdt.ui/10085.java | masud-technope/ACER-Replication-Package-ASE2017 | cb7318a729eb1403004d451a164c851af2d81f7a | [
"MIT"
] | 15 | 2018-07-10T09:38:31.000Z | 2021-11-29T08:28:07.000Z | corpus/class/eclipse.jdt.ui/10085.java | masud-technope/ACER-Replication-Package-ASE2017 | cb7318a729eb1403004d451a164c851af2d81f7a | [
"MIT"
] | 3 | 2018-11-16T02:58:59.000Z | 2021-01-20T16:03:51.000Z | corpus/class/eclipse.jdt.ui/10085.java | masud-technope/ACER-Replication-Package-ASE2017 | cb7318a729eb1403004d451a164c851af2d81f7a | [
"MIT"
] | 6 | 2018-06-27T20:19:00.000Z | 2022-02-19T02:29:53.000Z | 9.9 | 30 | 0.383838 | 12,660 | //5, 20, 5, 29
package p;
class A {
public void m() {
int a = 1 - ((2 + 3));
}
}
|
3e1de7cbc15653ec6fb6ecd011be81a517c2045b | 2,025 | java | Java | name.martingeisse.gui-server/src/main/java/name/martingeisse/guiserver/configuration/element/xml/PanelParser.java | MartinGeisse/public | 57b905485322222447187ae78a5a56bf3ce67900 | [
"MIT"
] | 1 | 2015-06-16T13:18:45.000Z | 2015-06-16T13:18:45.000Z | name.martingeisse.gui-server/src/main/java/name/martingeisse/guiserver/configuration/element/xml/PanelParser.java | MartinGeisse/public | 57b905485322222447187ae78a5a56bf3ce67900 | [
"MIT"
] | 3 | 2022-03-08T21:11:04.000Z | 2022-03-08T21:11:15.000Z | name.martingeisse.gui-server/src/main/java/name/martingeisse/guiserver/configuration/element/xml/PanelParser.java | MartinGeisse/public | 57b905485322222447187ae78a5a56bf3ce67900 | [
"MIT"
] | null | null | null | 33.75 | 181 | 0.809383 | 12,661 | /**
* Copyright (c) 2013 Martin Geisse
*
* This file is distributed under the terms of the MIT license.
*/
package name.martingeisse.guiserver.configuration.element.xml;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamWriter;
import name.martingeisse.guiserver.configuration.element.Element;
import name.martingeisse.guiserver.template.ComponentGroupConfiguration;
import name.martingeisse.guiserver.template.MarkupContent;
import name.martingeisse.guiserver.template.Template;
import name.martingeisse.guiserver.xml.content.ContentParser;
/**
* Parses a panel template.
*/
public class PanelParser extends TemplateBasedElementParser {
/**
* Constructor.
* @param templateParser the template parser
*/
public PanelParser(ContentParser<MarkupContent<ComponentGroupConfiguration>> templateParser) {
super(templateParser);
}
/* (non-Javadoc)
* @see name.martingeisse.guiserver.configuration.element.xml.TemplateBasedElementParser#writeWicketMarkupIntro(javax.xml.stream.XMLStreamWriter)
*/
@Override
protected void writeWicketMarkupIntro(XMLStreamWriter markupWriter) throws XMLStreamException {
markupWriter.writeStartElement("html");
markupWriter.writeStartElement("body");
markupWriter.writeStartElement("wicket:panel");
}
/* (non-Javadoc)
* @see name.martingeisse.guiserver.configuration.element.xml.TemplateBasedElementParser#writeWicketMarkupOutro(javax.xml.stream.XMLStreamWriter)
*/
@Override
protected void writeWicketMarkupOutro(XMLStreamWriter markupWriter) throws XMLStreamException {
markupWriter.writeEndElement();
markupWriter.writeEndElement();
markupWriter.writeEndElement();
}
/* (non-Javadoc)
* @see name.martingeisse.guiserver.configuration.element.xml.TemplateBasedElementParser#createConfigurationElement(java.lang.String, name.martingeisse.guiserver.template.Template)
*/
@Override
protected Element createConfigurationElement(String path, Template template) {
return new PanelConfiguration(path, template);
}
}
|
3e1de8eaaec300bff548690e7b8e7de561046016 | 6,286 | java | Java | web-client/src/test/java/eu/cityopt/service/ScenarioServiceTest.java | Cityopt/cityopt | 41a47edd08145c3d2c249626a26221b48f85e7cb | [
"CNRI-Jython"
] | null | null | null | web-client/src/test/java/eu/cityopt/service/ScenarioServiceTest.java | Cityopt/cityopt | 41a47edd08145c3d2c249626a26221b48f85e7cb | [
"CNRI-Jython"
] | 1 | 2016-10-31T10:54:19.000Z | 2019-09-30T07:36:51.000Z | web-client/src/test/java/eu/cityopt/service/ScenarioServiceTest.java | Cityopt/cityopt | 41a47edd08145c3d2c249626a26221b48f85e7cb | [
"CNRI-Jython"
] | null | null | null | 37.86747 | 138 | 0.765511 | 12,662 | package eu.cityopt.service;
import static org.junit.Assert.*;
import java.util.Iterator;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.TestExecutionListeners;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.support.DependencyInjectionTestExecutionListener;
import org.springframework.test.context.support.DirtiesContextTestExecutionListener;
import org.springframework.test.context.transaction.TransactionalTestExecutionListener;
import org.springframework.transaction.annotation.Transactional;
import com.github.springtestdbunit.DbUnitTestExecutionListener;
import com.github.springtestdbunit.annotation.DatabaseSetup;
import eu.cityopt.DTO.ComponentDTO;
import eu.cityopt.DTO.InputParamValDTO;
import eu.cityopt.DTO.InputParameterDTO;
import eu.cityopt.DTO.MetricValDTO;
import eu.cityopt.DTO.ScenarioDTO;
import eu.cityopt.DTO.ScenarioMetricsDTO;
import eu.cityopt.DTO.SimulationResultDTO;
import eu.cityopt.model.ObjectiveFunction;
import eu.cityopt.model.OptimizationSet;
@Transactional
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={"classpath:/jpaContext.xml", "classpath:/test-context.xml"})
@TestExecutionListeners({ DependencyInjectionTestExecutionListener.class,
DirtiesContextTestExecutionListener.class,
TransactionalTestExecutionListener.class,
DbUnitTestExecutionListener.class })
public class ScenarioServiceTest {
@Autowired
ProjectService projectService;
@Autowired
ScenarioService scenarioService;
@Autowired
InputParameterService inputParameterService;
@Autowired
ComponentService componentService;
@Autowired
InputParamValService inputParamValService;
@PersistenceContext
EntityManager em;
@Test(expected=EntityNotFoundException.class)
@DatabaseSetup({"classpath:/testData/globalTestData.xml", "classpath:/testData/project1TestData.xml",
"classpath:/testData/Sample Test case - SC1.xml"})
public void deleteScenario() throws EntityNotFoundException {
try{
scenarioService.delete(1);
}catch(Exception ex){
fail("id 1 not found, check testdata");
}
em.flush();
ScenarioDTO scen = scenarioService.findByID(1);
}
@Test
@DatabaseSetup({"classpath:/testData/globalTestData.xml", "classpath:/testData/project1TestData.xml",
"classpath:/testData/SampleTestCaseNoResults/Sample Test case - SC1.xml"})
public void getScenarioMetrics() throws EntityNotFoundException {
Set<ScenarioMetricsDTO> scenmetL = scenarioService.getScenarioMetrics(1);
assertNotNull(scenmetL);
assertEquals(1,scenmetL.size());
ScenarioMetricsDTO scenmet = scenmetL.iterator().next();
ScenarioDTO scen = scenmet.getScenario();
assertNotNull(scen);
assertEquals(1,scen.getScenid());
assertEquals("Sample Test case - SC1",scen.getName());
}
@Test
@DatabaseSetup({"classpath:/testData/globalTestData.xml", "classpath:/testData/project1TestData.xml",
"classpath:/testData/SampleTestCaseNoResults/Sample Test case - SC1.xml",
"classpath:/testData/SampleTestCaseNoResults/Sample Test case - SC2.xml",
"classpath:/testData/SampleTestCaseNoResults/Sample Test case - SC3.xml"})
public void findByName() throws EntityNotFoundException {
List<ScenarioDTO> scen = scenarioService.findByNameContaining("sam");
assertNotNull(scen);
assertEquals(3, scen.size());
scen = scenarioService.findByNameContaining("sc1");
assertNotNull(scen);
assertEquals(1, scen.size());
scen = scenarioService.findByNameContaining("scen sc1");
assertNotNull(scen);
assertEquals(0, scen.size());
}
@Test
@DatabaseSetup({"classpath:/testData/globalTestData.xml", "classpath:/testData/project1TestData.xml",
"classpath:/testData/SampleTestCaseNoResults/Sample Test case - SC1.xml",
"classpath:/testData/SampleTestCaseNoResults/Sample Test case - SC2.xml"})
public void getMetricsValues() throws EntityNotFoundException {
Set<MetricValDTO> mvL = scenarioService.getMetricsValues(1);
assertEquals(5, mvL.size());
Optional<MetricValDTO> mvOpt = mvL.stream().filter(m -> m.getValue().equals("569399.35")).findFirst();
assertTrue(mvOpt.isPresent());
MetricValDTO mv = mvOpt.get();
ScenarioMetricsDTO metScenMet = mv.getScenariometrics();
assertEquals(1,metScenMet.getScenario().getScenid());
}
@Test
@DatabaseSetup({"classpath:/testData/globalTestData.xml", "classpath:/testData/project1TestData.xml"})
public void saveWithDefaultInputs() throws EntityNotFoundException {
long start = System.nanoTime();
ScenarioDTO scenario = new ScenarioDTO();
scenario.setName("test with default inputs");
scenario.getScenid();
scenario = scenarioService.save(scenario, 1);
em.flush();
em.clear();
List<ComponentDTO> components = projectService.getComponents(1);
// Create input param vals for all input params
for (int i = 0; i < components.size(); i++)
{
ComponentDTO component = components.get(i);
//List<ComponentInputParamDTO> listComponentInputParams = componentInputParamService.findAllByComponentId(component.getComponentid());
List<InputParameterDTO> setInputParams = componentService.getInputParameters(component.getComponentid());
Iterator<InputParameterDTO> iter = setInputParams.iterator();
while(iter.hasNext())
{
InputParameterDTO inputParam = iter.next();
//InputParameterDTO inputParam = inputParamService.findByID(setInputParams.get(j).getInputid());
InputParamValDTO inputParamVal = new InputParamValDTO();
inputParamVal.setInputparameter(inputParam);
inputParamVal.setValue(inputParam.getDefaultvalue());
inputParamVal.setScenario(scenario);
inputParamVal = inputParamValService.save(inputParamVal, null);
}
}
System.out.printf("time in millis: " + (System.nanoTime()- start)/1000000);
}
}
|
3e1de8f199e01b51b7c8eca48bb0a964be9ef8c0 | 13,713 | java | Java | services/roma/src/main/java/com/huaweicloud/sdk/roma/v2/model/SignApiBindingInfo.java | huaweicloud/huaweicloud-sdk-java-v3 | a01cd21a3d03f6dffc807bea7c522e34adfa368d | [
"Apache-2.0"
] | 50 | 2020-05-18T11:35:20.000Z | 2022-03-15T02:07:05.000Z | services/roma/src/main/java/com/huaweicloud/sdk/roma/v2/model/SignApiBindingInfo.java | huaweicloud/huaweicloud-sdk-java-v3 | a01cd21a3d03f6dffc807bea7c522e34adfa368d | [
"Apache-2.0"
] | 45 | 2020-07-06T03:34:12.000Z | 2022-03-31T09:41:54.000Z | services/roma/src/main/java/com/huaweicloud/sdk/roma/v2/model/SignApiBindingInfo.java | huaweicloud/huaweicloud-sdk-java-v3 | a01cd21a3d03f6dffc807bea7c522e34adfa368d | [
"Apache-2.0"
] | 27 | 2020-05-28T11:08:44.000Z | 2022-03-30T03:30:37.000Z | 27.985714 | 106 | 0.612849 | 12,663 | package com.huaweicloud.sdk.roma.v2.model;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonValue;
import java.time.OffsetDateTime;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
/** SignApiBindingInfo */
public class SignApiBindingInfo {
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonProperty(value = "publish_id")
private String publishId;
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonProperty(value = "api_id")
private String apiId;
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonProperty(value = "group_name")
private String groupName;
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonProperty(value = "binding_time")
private OffsetDateTime bindingTime;
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonProperty(value = "env_id")
private String envId;
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonProperty(value = "env_name")
private String envName;
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonProperty(value = "api_type")
private Integer apiType;
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonProperty(value = "api_name")
private String apiName;
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonProperty(value = "id")
private String id;
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonProperty(value = "api_remark")
private String apiRemark;
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonProperty(value = "sign_id")
private String signId;
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonProperty(value = "sign_name")
private String signName;
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonProperty(value = "sign_key")
private String signKey;
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonProperty(value = "sign_secret")
private String signSecret;
/** 签名密钥类型: - hmac - basic - public_key basic类型需要实例升级到对应版本,若不存在可联系技术工程师升级。
* public_key类型开启实例配置public_key才可使用,实例特性配置详情请参考“附录 > 实例支持的APIC特性”,如确认实例不存在public_key配置可联系技术工程师开启。 */
public static final class SignTypeEnum {
/** Enum HMAC for value: "hmac" */
public static final SignTypeEnum HMAC = new SignTypeEnum("hmac");
/** Enum BASIC for value: "basic" */
public static final SignTypeEnum BASIC = new SignTypeEnum("basic");
/** Enum PUBLIC_KEY for value: "public_key" */
public static final SignTypeEnum PUBLIC_KEY = new SignTypeEnum("public_key");
private static final Map<String, SignTypeEnum> STATIC_FIELDS = createStaticFields();
private static Map<String, SignTypeEnum> createStaticFields() {
Map<String, SignTypeEnum> map = new HashMap<>();
map.put("hmac", HMAC);
map.put("basic", BASIC);
map.put("public_key", PUBLIC_KEY);
return Collections.unmodifiableMap(map);
}
private String value;
SignTypeEnum(String value) {
this.value = value;
}
@JsonValue
public String getValue() {
return value;
}
@Override
public String toString() {
return String.valueOf(value);
}
@JsonCreator
public static SignTypeEnum fromValue(String value) {
if (value == null) {
return null;
}
SignTypeEnum result = STATIC_FIELDS.get(value);
if (result == null) {
result = new SignTypeEnum(value);
}
return result;
}
public static SignTypeEnum valueOf(String value) {
if (value == null) {
return null;
}
SignTypeEnum result = STATIC_FIELDS.get(value);
if (result != null) {
return result;
}
throw new IllegalArgumentException("Unexpected value '" + value + "'");
}
@Override
public boolean equals(Object obj) {
if (obj instanceof SignTypeEnum) {
return this.value.equals(((SignTypeEnum) obj).value);
}
return false;
}
@Override
public int hashCode() {
return this.value.hashCode();
}
}
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonProperty(value = "sign_type")
private SignTypeEnum signType;
public SignApiBindingInfo withPublishId(String publishId) {
this.publishId = publishId;
return this;
}
/** API的发布编号
*
* @return publishId */
public String getPublishId() {
return publishId;
}
public void setPublishId(String publishId) {
this.publishId = publishId;
}
public SignApiBindingInfo withApiId(String apiId) {
this.apiId = apiId;
return this;
}
/** API编号
*
* @return apiId */
public String getApiId() {
return apiId;
}
public void setApiId(String apiId) {
this.apiId = apiId;
}
public SignApiBindingInfo withGroupName(String groupName) {
this.groupName = groupName;
return this;
}
/** API所属分组的名称
*
* @return groupName */
public String getGroupName() {
return groupName;
}
public void setGroupName(String groupName) {
this.groupName = groupName;
}
public SignApiBindingInfo withBindingTime(OffsetDateTime bindingTime) {
this.bindingTime = bindingTime;
return this;
}
/** 绑定时间
*
* @return bindingTime */
public OffsetDateTime getBindingTime() {
return bindingTime;
}
public void setBindingTime(OffsetDateTime bindingTime) {
this.bindingTime = bindingTime;
}
public SignApiBindingInfo withEnvId(String envId) {
this.envId = envId;
return this;
}
/** API所属环境的编号
*
* @return envId */
public String getEnvId() {
return envId;
}
public void setEnvId(String envId) {
this.envId = envId;
}
public SignApiBindingInfo withEnvName(String envName) {
this.envName = envName;
return this;
}
/** API所属环境的名称
*
* @return envName */
public String getEnvName() {
return envName;
}
public void setEnvName(String envName) {
this.envName = envName;
}
public SignApiBindingInfo withApiType(Integer apiType) {
this.apiType = apiType;
return this;
}
/** API类型
*
* @return apiType */
public Integer getApiType() {
return apiType;
}
public void setApiType(Integer apiType) {
this.apiType = apiType;
}
public SignApiBindingInfo withApiName(String apiName) {
this.apiName = apiName;
return this;
}
/** API名称
*
* @return apiName */
public String getApiName() {
return apiName;
}
public void setApiName(String apiName) {
this.apiName = apiName;
}
public SignApiBindingInfo withId(String id) {
this.id = id;
return this;
}
/** 绑定关系的ID
*
* @return id */
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public SignApiBindingInfo withApiRemark(String apiRemark) {
this.apiRemark = apiRemark;
return this;
}
/** API描述
*
* @return apiRemark */
public String getApiRemark() {
return apiRemark;
}
public void setApiRemark(String apiRemark) {
this.apiRemark = apiRemark;
}
public SignApiBindingInfo withSignId(String signId) {
this.signId = signId;
return this;
}
/** 签名密钥的编号
*
* @return signId */
public String getSignId() {
return signId;
}
public void setSignId(String signId) {
this.signId = signId;
}
public SignApiBindingInfo withSignName(String signName) {
this.signName = signName;
return this;
}
/** 签名密钥的名称。支持汉字,英文,数字,下划线,且只能以英文和汉字开头,3 ~ 64字符。 > 中文字符必须为UTF-8或者unicode编码。
*
* @return signName */
public String getSignName() {
return signName;
}
public void setSignName(String signName) {
this.signName = signName;
}
public SignApiBindingInfo withSignKey(String signKey) {
this.signKey = signKey;
return this;
}
/** 签名密钥的key。 - hmac类型的签名密钥key:支持英文,数字,下划线,中划线,且只能以英文字母或数字开头,8 ~ 32字符。未填写时后台自动生成。 -
* basic类型的签名密钥key:支持英文,数字,下划线,中划线,且只能以英文字母开头,4 ~ 32字符。未填写时后台自动生成。 -
* public_key类型的签名密钥key:支持英文,数字,下划线,中划线,+,/,=,可以英文字母,数字,+,/开头,8 ~ 512字符。未填写时后台自动生成。
*
* @return signKey */
public String getSignKey() {
return signKey;
}
public void setSignKey(String signKey) {
this.signKey = signKey;
}
public SignApiBindingInfo withSignSecret(String signSecret) {
this.signSecret = signSecret;
return this;
}
/** 签名密钥的密钥。 - hmac类型的签名密钥key:支持英文,数字,下划线,中划线,!,@,#,$,%,且只能以英文字母或数字开头,16 ~ 64字符。未填写时后台自动生成。 -
* basic类型的签名密钥key:支持英文,数字,下划线,中划线,!,@,#,$,%,且只能以英文字母或数字开头,8 ~ 64字符。未填写时后台自动生成。 -
* public_key类型的签名密钥key:支持英文,数字,下划线,中划线,!,@,#,$,%,+,/,=,可以英文字母,数字,+,/开头,15 ~ 2048字符。未填写时后台自动生成。
*
* @return signSecret */
public String getSignSecret() {
return signSecret;
}
public void setSignSecret(String signSecret) {
this.signSecret = signSecret;
}
public SignApiBindingInfo withSignType(SignTypeEnum signType) {
this.signType = signType;
return this;
}
/** 签名密钥类型: - hmac - basic - public_key basic类型需要实例升级到对应版本,若不存在可联系技术工程师升级。
* public_key类型开启实例配置public_key才可使用,实例特性配置详情请参考“附录 > 实例支持的APIC特性”,如确认实例不存在public_key配置可联系技术工程师开启。
*
* @return signType */
public SignTypeEnum getSignType() {
return signType;
}
public void setSignType(SignTypeEnum signType) {
this.signType = signType;
}
@Override
public boolean equals(java.lang.Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
SignApiBindingInfo signApiBindingInfo = (SignApiBindingInfo) o;
return Objects.equals(this.publishId, signApiBindingInfo.publishId)
&& Objects.equals(this.apiId, signApiBindingInfo.apiId)
&& Objects.equals(this.groupName, signApiBindingInfo.groupName)
&& Objects.equals(this.bindingTime, signApiBindingInfo.bindingTime)
&& Objects.equals(this.envId, signApiBindingInfo.envId)
&& Objects.equals(this.envName, signApiBindingInfo.envName)
&& Objects.equals(this.apiType, signApiBindingInfo.apiType)
&& Objects.equals(this.apiName, signApiBindingInfo.apiName)
&& Objects.equals(this.id, signApiBindingInfo.id)
&& Objects.equals(this.apiRemark, signApiBindingInfo.apiRemark)
&& Objects.equals(this.signId, signApiBindingInfo.signId)
&& Objects.equals(this.signName, signApiBindingInfo.signName)
&& Objects.equals(this.signKey, signApiBindingInfo.signKey)
&& Objects.equals(this.signSecret, signApiBindingInfo.signSecret)
&& Objects.equals(this.signType, signApiBindingInfo.signType);
}
@Override
public int hashCode() {
return Objects.hash(publishId,
apiId,
groupName,
bindingTime,
envId,
envName,
apiType,
apiName,
id,
apiRemark,
signId,
signName,
signKey,
signSecret,
signType);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class SignApiBindingInfo {\n");
sb.append(" publishId: ").append(toIndentedString(publishId)).append("\n");
sb.append(" apiId: ").append(toIndentedString(apiId)).append("\n");
sb.append(" groupName: ").append(toIndentedString(groupName)).append("\n");
sb.append(" bindingTime: ").append(toIndentedString(bindingTime)).append("\n");
sb.append(" envId: ").append(toIndentedString(envId)).append("\n");
sb.append(" envName: ").append(toIndentedString(envName)).append("\n");
sb.append(" apiType: ").append(toIndentedString(apiType)).append("\n");
sb.append(" apiName: ").append(toIndentedString(apiName)).append("\n");
sb.append(" id: ").append(toIndentedString(id)).append("\n");
sb.append(" apiRemark: ").append(toIndentedString(apiRemark)).append("\n");
sb.append(" signId: ").append(toIndentedString(signId)).append("\n");
sb.append(" signName: ").append(toIndentedString(signName)).append("\n");
sb.append(" signKey: ").append(toIndentedString(signKey)).append("\n");
sb.append(" signSecret: ").append(toIndentedString(signSecret)).append("\n");
sb.append(" signType: ").append(toIndentedString(signType)).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 ");
}
}
|
3e1dea3ab612b50c844aba4a4a177e9390fda938 | 944 | java | Java | app/src/main/java/com/example/eksamensprojekt/presentation/viewmodel/BeskedViewModel.java | yokarak/EksamensProjekt | fb30145314dd569c0a5f77c9ec5468d0ddea04fd | [
"MIT"
] | null | null | null | app/src/main/java/com/example/eksamensprojekt/presentation/viewmodel/BeskedViewModel.java | yokarak/EksamensProjekt | fb30145314dd569c0a5f77c9ec5468d0ddea04fd | [
"MIT"
] | null | null | null | app/src/main/java/com/example/eksamensprojekt/presentation/viewmodel/BeskedViewModel.java | yokarak/EksamensProjekt | fb30145314dd569c0a5f77c9ec5468d0ddea04fd | [
"MIT"
] | null | null | null | 29.5 | 152 | 0.768008 | 12,664 | package com.example.eksamensprojekt.presentation.viewmodel;
import android.app.Application;
import androidx.annotation.NonNull;
import androidx.lifecycle.AndroidViewModel;
import androidx.lifecycle.LiveData;
import com.example.eksamensprojekt.data.model.Besked;
import com.example.eksamensprojekt.data.repository.BeskedRepository;
public class BeskedViewModel extends AndroidViewModel {
/**
* @author Anders, Sebastian og Marc
* @version 1.2
*/
private BeskedRepository beskedRepository;
LiveData<Besked> nyChatBeskedLiveData;
public BeskedViewModel(@NonNull Application application) {
super(application);
beskedRepository = new BeskedRepository();
}
public void nyBesked(Besked nyBesked) { //her forbindes Repositoriet og viewModel. hvor MutableLiveData bliver til LiveData, med nyBesked af Besked.
nyChatBeskedLiveData = beskedRepository.sendNyBesked(nyBesked);
}
}
|
3e1deb062352d5a3a3019c7db8797e08901c955c | 2,404 | java | Java | src/main/java/com/google/zxing/client/result/BizcardResultParser.java | JackChan1999/boohee_v5.6 | 221f7ea237f491e2153039a42941a515493ba52c | [
"Apache-2.0"
] | 7 | 2017-05-30T12:01:38.000Z | 2021-04-22T12:22:39.000Z | src/main/java/com/google/zxing/client/result/BizcardResultParser.java | JackChan1999/boohee_v5.6 | 221f7ea237f491e2153039a42941a515493ba52c | [
"Apache-2.0"
] | null | null | null | src/main/java/com/google/zxing/client/result/BizcardResultParser.java | JackChan1999/boohee_v5.6 | 221f7ea237f491e2153039a42941a515493ba52c | [
"Apache-2.0"
] | 6 | 2017-07-28T03:47:08.000Z | 2019-06-28T17:57:50.000Z | 41.448276 | 100 | 0.624792 | 12,665 | package com.google.zxing.client.result;
import com.google.zxing.Result;
import java.util.ArrayList;
import java.util.List;
public final class BizcardResultParser extends AbstractDoCoMoResultParser {
public AddressBookParsedResult parse(Result result) {
String rawText = ResultParser.getMassagedText(result);
if (!rawText.startsWith("BIZCARD:")) {
return null;
}
String fullName = buildName(AbstractDoCoMoResultParser.matchSingleDoCoMoPrefixedField
("N:", rawText, true), AbstractDoCoMoResultParser.matchSingleDoCoMoPrefixedField
("X:", rawText, true));
String title = AbstractDoCoMoResultParser.matchSingleDoCoMoPrefixedField("T:", rawText,
true);
String org = AbstractDoCoMoResultParser.matchSingleDoCoMoPrefixedField("C:", rawText, true);
return new AddressBookParsedResult(ResultParser.maybeWrap(fullName), null, null,
buildPhoneNumbers(AbstractDoCoMoResultParser.matchSingleDoCoMoPrefixedField("B:",
rawText, true), AbstractDoCoMoResultParser.matchSingleDoCoMoPrefixedField
("M:", rawText, true), AbstractDoCoMoResultParser
.matchSingleDoCoMoPrefixedField("F:", rawText, true)), null, ResultParser
.maybeWrap(AbstractDoCoMoResultParser.matchSingleDoCoMoPrefixedField("E:",
rawText, true)), null, null, null, AbstractDoCoMoResultParser
.matchDoCoMoPrefixedField("A:", rawText, true), null, org, null, title, null, null);
}
private static String[] buildPhoneNumbers(String number1, String number2, String number3) {
List<String> numbers = new ArrayList(3);
if (number1 != null) {
numbers.add(number1);
}
if (number2 != null) {
numbers.add(number2);
}
if (number3 != null) {
numbers.add(number3);
}
int size = numbers.size();
if (size == 0) {
return null;
}
return (String[]) numbers.toArray(new String[size]);
}
private static String buildName(String firstName, String lastName) {
if (firstName == null) {
return lastName;
}
if (lastName != null) {
firstName = firstName + ' ' + lastName;
}
return firstName;
}
}
|
3e1ded3abdebc5fa8caae4701f0198844026e3c3 | 904 | java | Java | src/main/java/org/monarch/golr/beans/Closure.java | yy20716/golr-loader | 35574d890bf40cca13ab3952f67eca7fd85502fe | [
"Apache-2.0"
] | 2 | 2017-06-01T17:02:30.000Z | 2019-04-13T01:53:14.000Z | src/main/java/org/monarch/golr/beans/Closure.java | yy20716/golr-loader | 35574d890bf40cca13ab3952f67eca7fd85502fe | [
"Apache-2.0"
] | 42 | 2015-05-21T23:48:22.000Z | 2021-01-08T18:16:27.000Z | src/main/java/org/monarch/golr/beans/Closure.java | yy20716/golr-loader | 35574d890bf40cca13ab3952f67eca7fd85502fe | [
"Apache-2.0"
] | 4 | 2016-12-12T22:36:42.000Z | 2021-12-22T19:54:16.000Z | 18.08 | 56 | 0.665929 | 12,666 | package org.monarch.golr.beans;
import java.util.ArrayList;
import java.util.List;
import com.google.common.base.MoreObjects;
/***
* A convenience class encapsulating a closure pair.
*/
public class Closure {
private String curie;
private String label;
private final List<String> curies = new ArrayList<>();
private final List<String> labels = new ArrayList<>();
public String getCurie() {
return curie;
}
public void setCurie(String curie) {
this.curie = curie;
}
public String getLabel() {
return label;
}
public void setLabel(String label) {
this.label = label;
}
public List<String> getCuries() {
return curies;
}
public List<String> getLabels() {
return labels;
}
@Override
public String toString() {
return MoreObjects.toStringHelper(this)
.add("curies", curies)
.add("labels", labels).toString();
}
}
|
3e1dee8804df198deb7a5149845a28cf06e1e32e | 6,242 | java | Java | JavadocSandcastle/SandcastleDoclet/src/net/izsak/sandcastle/tags/XomHtmlSerializer.java | jozefizso/sandcastle-presentation | 1abca4240ebc719e270512aaaed3934b0efda08e | [
"BSD-3-Clause"
] | 1 | 2017-02-22T22:37:53.000Z | 2017-02-22T22:37:53.000Z | JavadocSandcastle/SandcastleDoclet/src/net/izsak/sandcastle/tags/XomHtmlSerializer.java | jozefizso/sandcastle-presentation | 1abca4240ebc719e270512aaaed3934b0efda08e | [
"BSD-3-Clause"
] | 2 | 2017-03-05T22:55:59.000Z | 2017-03-05T22:56:14.000Z | JavadocSandcastle/SandcastleDoclet/src/net/izsak/sandcastle/tags/XomHtmlSerializer.java | jozefizso/sandcastle-presentation | 1abca4240ebc719e270512aaaed3934b0efda08e | [
"BSD-3-Clause"
] | null | null | null | 25.900415 | 138 | 0.669978 | 12,667 | /**
* Copyright (c) 2009 Jozef Izso. All Rights Reserved.
*/
package net.izsak.sandcastle.tags;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import nu.xom.Attribute;
import nu.xom.Element;
import nu.xom.ParentNode;
import nu.xom.Text;
import org.xml.sax.Attributes;
import org.xml.sax.ContentHandler;
import org.xml.sax.Locator;
import org.xml.sax.SAXException;
import org.xml.sax.ext.LexicalHandler;
/**
* @author Jozef Izso
*
*/
public class XomHtmlSerializer implements ContentHandler, LexicalHandler {
private static final Set<String> ALLOWED_TAGS = new HashSet<String>( Arrays.asList(
"b", "i", "strong", "em", "p", "table", "br"//, "html", "head", "body"
));
private static final Set<String> VOID_ELEMENTS = new HashSet<String>( Arrays.asList(
"area", "base", "basefont",
"bgsound", "br", "col", "command", "embed", "event-source",
"frame", "hr", "img", "input", "keygen", "link", "meta", "param",
"source", "spacer", "wbr"
));
private HtmlParserInfrastructureTags infrastructure;
private Element root;
private ParentNode current;
private int ignoreLevel = 0;
protected XomHtmlSerializer() {
this.infrastructure = new HtmlParserInfrastructureTags();
}
private void pushCurrentElement(ParentNode elm) {
this.current = elm;
}
private void popCurrentElement() {
this.current = this.current.getParent();
}
public Element getRootElement() {
return this.root;
}
/* (non-Javadoc)
* @see org.xml.sax.ContentHandler#startElement(java.lang.String, java.lang.String, java.lang.String, org.xml.sax.Attributes)
*/
@Override
public void startElement(String uri, String localName, String qName, Attributes atts) throws SAXException {
boolean isInfr = this.infrastructure.isInfrastrucuteTag(localName);
if (isInfr) {
this.infrastructure.markTagAsUsed(localName);
ignoreLevel++;
return;
}
boolean shouldEscape = false; // */ (isInfr && this.infrastructure.allTagsWritten()) || (!isInfr && !ALLOWED_TAGS.contains(localName));
shouldEscape = !ALLOWED_TAGS.contains(localName);
Element elm = new Element(localName);
for (int i = 0; i < atts.getLength(); i++) {
String n = atts.getLocalName(i);
String v = atts.getValue(i);
elm.addAttribute(new Attribute(n, v));
}
if (shouldEscape) {
this.current.appendChild(new Text(elm.toXML()));
ignoreLevel++;
}
else {
this.current.appendChild(elm);
if (VOID_ELEMENTS.contains(localName)) {
ignoreLevel++;
} else {
pushCurrentElement(elm);
}
}
}
/* (non-Javadoc)
* @see org.xml.sax.ContentHandler#endElement(java.lang.String, java.lang.String, java.lang.String)
*/
@Override
public void endElement(String uri, String localName, String qName) throws SAXException {
if (ignoreLevel > 0) {
ignoreLevel--;
} else {
this.popCurrentElement();
}
}
/* (non-Javadoc)
* @see org.xml.sax.ext.LexicalHandler#comment(char[], int, int)
*/
@Override
public void comment(char[] ch, int start, int length) throws SAXException {
if (ignoreLevel > 0) {
return;
}
String text = new String(ch, start, length);
this.current.appendChild(new Text(text));
}
/* (non-Javadoc)
* @see org.xml.sax.ContentHandler#startDocument()
*/
@Override
public void startDocument() throws SAXException {
this.root = new Element("body");
this.pushCurrentElement(this.root);
}
/* (non-Javadoc)
* @see org.xml.sax.ContentHandler#endDocument()
*/
@Override
public void endDocument() throws SAXException {
}
/* (non-Javadoc)
* @see org.xml.sax.ContentHandler#characters(char[], int, int)
*/
@Override
public void characters(char[] ch, int start, int length)
throws SAXException {
String text = new String(ch, start, length);
this.current.appendChild(new Text(text));
}
/* (non-Javadoc)
* @see org.xml.sax.ContentHandler#ignorableWhitespace(char[], int, int)
*/
@Override
public void ignorableWhitespace(char[] ch, int start, int length)
throws SAXException {
this.characters(ch, start, length);
}
/* (non-Javadoc)
* @see org.xml.sax.ContentHandler#endPrefixMapping(java.lang.String)
*/
@Override
public void endPrefixMapping(String prefix) throws SAXException {
}
/* (non-Javadoc)
* @see org.xml.sax.ContentHandler#processingInstruction(java.lang.String, java.lang.String)
*/
@Override
public void processingInstruction(String target, String data)
throws SAXException {
}
/* (non-Javadoc)
* @see org.xml.sax.ContentHandler#setDocumentLocator(org.xml.sax.Locator)
*/
@Override
public void setDocumentLocator(Locator locator) {
}
/* (non-Javadoc)
* @see org.xml.sax.ContentHandler#skippedEntity(java.lang.String)
*/
@Override
public void skippedEntity(String name) throws SAXException {
}
/* (non-Javadoc)
* @see org.xml.sax.ContentHandler#startPrefixMapping(java.lang.String, java.lang.String)
*/
@Override
public void startPrefixMapping(String prefix, String uri)
throws SAXException {
}
/* (non-Javadoc)
* @see org.xml.sax.ext.LexicalHandler#endCDATA()
*/
@Override
public void endCDATA() throws SAXException {
}
/* (non-Javadoc)
* @see org.xml.sax.ext.LexicalHandler#endDTD()
*/
@Override
public void endDTD() throws SAXException {
}
/* (non-Javadoc)
* @see org.xml.sax.ext.LexicalHandler#endEntity(java.lang.String)
*/
@Override
public void endEntity(String name) throws SAXException {
}
/* (non-Javadoc)
* @see org.xml.sax.ext.LexicalHandler#startCDATA()
*/
@Override
public void startCDATA() throws SAXException {
}
/* (non-Javadoc)
* @see org.xml.sax.ext.LexicalHandler#startDTD(java.lang.String, java.lang.String, java.lang.String)
*/
@Override
public void startDTD(String name, String publicId, String systemId)
throws SAXException {
}
/* (non-Javadoc)
* @see org.xml.sax.ext.LexicalHandler#startEntity(java.lang.String)
*/
@Override
public void startEntity(String name) throws SAXException {
}
}
|
3e1dee9bb4cdf6fe2806c050057ac1986a383b44 | 32,928 | java | Java | gateleen-routing/src/main/java/org/swisspush/gateleen/routing/DeferCloseHttpClient.java | Kusig/gateleen | cb27a0d6035f56caae8c553bbeaf1eee39cac9ec | [
"Apache-2.0"
] | 79 | 2016-02-25T12:20:40.000Z | 2022-03-09T17:25:58.000Z | gateleen-routing/src/main/java/org/swisspush/gateleen/routing/DeferCloseHttpClient.java | Kusig/gateleen | cb27a0d6035f56caae8c553bbeaf1eee39cac9ec | [
"Apache-2.0"
] | 314 | 2016-02-29T08:58:01.000Z | 2022-03-31T05:34:51.000Z | gateleen-routing/src/main/java/org/swisspush/gateleen/routing/DeferCloseHttpClient.java | Kusig/gateleen | cb27a0d6035f56caae8c553bbeaf1eee39cac9ec | [
"Apache-2.0"
] | 47 | 2016-02-25T13:13:03.000Z | 2022-03-02T13:20:00.000Z | 39.624549 | 205 | 0.710277 | 12,668 | package org.swisspush.gateleen.routing;
import io.vertx.core.Future;
import io.vertx.core.Handler;
import io.vertx.core.MultiMap;
import io.vertx.core.Vertx;
import io.vertx.core.http.*;
import io.vertx.core.streams.ReadStream;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.lang.reflect.Field;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.function.Function;
/**
* Decorates an {@link HttpClient} to only effectively close the client
* if there are no more requests in progress.
*
* HINT: We for now only fix the issue in the exact call we know to misbehave
* in our concrete scenario. Feel free to implement the (few...) remaining
* methods.
*/
public class DeferCloseHttpClient implements HttpClient {
private final int CLOSE_ANYWAY_AFTER_MS = 86_400_000; // <- TODO: Find a good value.
private static final Logger logger = LoggerFactory.getLogger(DeferCloseHttpClient.class);
private final Vertx vertx;
private final HttpClient delegate;
private int countOfRequestsInProgress = 0;
private boolean doCloseWhenDone = false;
/**
* See {@link DeferCloseHttpClient}.
*/
public DeferCloseHttpClient(Vertx vertx, HttpClient delegate) {
this.vertx = vertx;
this.delegate = delegate;
}
@Override
public HttpClientRequest request(HttpMethod method, int port, String host, String requestURI, Handler<HttpClientResponse> responseHandler) {
logger.debug("({}:{}).request({}, \"{}\")", host, port, method, requestURI);
countOfRequestsInProgress += 1;
logger.debug("Pending request count: {}", countOfRequestsInProgress);
// Delegate to the same method on the delegate. But install our own handler which
// allows us to intercept the response.
HttpClientRequest request = delegate.request(method, port, host, requestURI, upstreamRsp -> {
logger.debug("onUpstreamRsp(code={})", upstreamRsp.statusCode());
// 1st we have to pass-through the response so our caller is able to install its handlers.
try {
callHandlerIfExists(responseHandler, upstreamRsp);
} catch (Exception e) {
// Does not make sense to install any handlers. Just make sure we decrement
// our counter then pass-through the exception.
onEndOfRequestResponseCycle();
throw e;
}
// We also need to ensure that our reference counter stays accurate. Badly vertx
// may call BOTH of our handlers. And in this scenario we MUST NOT decrement
// twice. So we additionally track this too.
final AtomicBoolean needToDecrementCounter = new AtomicBoolean(true);
// Then (after client installed its handlers), we now can intercept those by
// replacing them with our own handlers.
// To do this, we 1st backup the original handler (so we can delegate to it later).
Handler<Void> originalEndHandler = getEndHandler(upstreamRsp);
upstreamRsp.endHandler(event -> {
logger.debug("upstreamRsp.endHandler()");
if (needToDecrementCounter.getAndSet(false)) {
onEndOfRequestResponseCycle();
}
// Call the original handler independent of the above condition to not change
// behaviour of the impl we are decorating.
callHandlerIfExists(originalEndHandler, event);
});
// We also need to intercept exception handler to decrement our counter in case
// of erroneous-end scenario. Basically same idea as above.
Handler<Throwable> originalExceptionHandler = getExceptionHandler(upstreamRsp);
upstreamRsp.exceptionHandler(event -> {
logger.debug("upstreamRsp.exceptionHandler({})", event.toString());
if (needToDecrementCounter.getAndSet(false)) {
onEndOfRequestResponseCycle();
}
callHandlerIfExists(originalExceptionHandler, event);
});
});
return request;
}
private void onEndOfRequestResponseCycle() {
countOfRequestsInProgress -= 1;
logger.debug("Pending request count: {}", countOfRequestsInProgress);
if (countOfRequestsInProgress == 0 && doCloseWhenDone) {
logger.debug("No pending request right now. And someone called 'close()' earlier. So close now.");
doCloseWhenDone = false;
try {
delegate.close();
} catch (Exception e) {
logger.warn("delegate.close() failed", e);
}
}
}
@Override
public void close() {
if (countOfRequestsInProgress > 0) {
logger.debug("Do NOT close right now. But close as soon there are no more pending requests (pending={})", countOfRequestsInProgress);
doCloseWhenDone = true;
// Still use a timer. Because who knows.
vertx.setTimer(CLOSE_ANYWAY_AFTER_MS, timerId -> {
if (doCloseWhenDone) {
logger.warn("RequestResponse cycle still running after {} ms. Will close now to prevent resource leaks.", CLOSE_ANYWAY_AFTER_MS);
doCloseWhenDone = false;
delegate.close();
}
});
return;
}
logger.debug("Client idle. Close right now");
delegate.close();
}
///////////////////////////////////////////////////////////////////////////////
// Some helpers so we are able to do our work.
///////////////////////////////////////////////////////////////////////////////
private <T> void callHandlerIfExists(Handler<T> maybeNull, T event){
if(maybeNull == null){
return; // No handler? Nothing we could call.
}
maybeNull.handle(event);
}
private Handler<Void> getEndHandler(HttpClientResponse rsp) {
return getPrivateField(rsp, "endHandler", Handler.class);
}
private Handler<Throwable> getExceptionHandler(HttpClientResponse rsp) {
return getPrivateField(rsp, "exceptionHandler", Handler.class);
}
private <T> T getPrivateField(HttpClientResponse rsp, String name, Class<T> type) {
try {
Field field = rsp.getClass().getDeclaredField(name);
field.setAccessible(true);
return (T) field.get(rsp);
} catch (NoSuchFieldException | IllegalAccessException e) {
throw new RuntimeException(e);
}
}
///////////////////////////////////////////////////////////////////////////////
// Below are only the remaining methods which all just delegate.
///////////////////////////////////////////////////////////////////////////////
@Override
public HttpClientRequest request(HttpMethod method, RequestOptions options) {
return delegate.request(method, options);
}
@Override
public HttpClientRequest request(HttpMethod method, int port, String host, String requestURI) {
return delegate.request(method, port, host, requestURI);
}
@Override
public HttpClientRequest request(HttpMethod method, String host, String requestURI) {
return delegate.request(method, host, requestURI);
}
@Override
public HttpClientRequest request(HttpMethod method, RequestOptions options, Handler<HttpClientResponse> responseHandler) {
return delegate.request(method, options, responseHandler);
}
@Override
public HttpClientRequest request(HttpMethod method, String host, String requestURI, Handler<HttpClientResponse> responseHandler) {
return delegate.request(method, host, requestURI, responseHandler);
}
@Override
public HttpClientRequest request(HttpMethod method, String requestURI) {
return delegate.request(method, requestURI);
}
@Override
public HttpClientRequest request(HttpMethod method, String requestURI, Handler<HttpClientResponse> responseHandler) {
return delegate.request(method, requestURI, responseHandler);
}
@Override
public HttpClientRequest requestAbs(HttpMethod method, String absoluteURI) {
return delegate.requestAbs(method, absoluteURI);
}
@Override
public HttpClientRequest requestAbs(HttpMethod method, String absoluteURI, Handler<HttpClientResponse> responseHandler) {
return delegate.requestAbs(method, absoluteURI, responseHandler);
}
@Override
public HttpClientRequest get(RequestOptions options) {
return delegate.get(options);
}
@Override
public HttpClientRequest get(int port, String host, String requestURI) {
return delegate.get(port, host, requestURI);
}
@Override
public HttpClientRequest get(String host, String requestURI) {
return delegate.get(host, requestURI);
}
@Override
public HttpClientRequest get(RequestOptions options, Handler<HttpClientResponse> responseHandler) {
return delegate.get(options, responseHandler);
}
@Override
public HttpClientRequest get(int port, String host, String requestURI, Handler<HttpClientResponse> responseHandler) {
return delegate.get(port, host, requestURI, responseHandler);
}
@Override
public HttpClientRequest get(String host, String requestURI, Handler<HttpClientResponse> responseHandler) {
return delegate.get(host, requestURI, responseHandler);
}
@Override
public HttpClientRequest get(String requestURI) {
return delegate.get(requestURI);
}
@Override
public HttpClientRequest get(String requestURI, Handler<HttpClientResponse> responseHandler) {
return delegate.get(requestURI, responseHandler);
}
@Override
public HttpClientRequest getAbs(String absoluteURI) {
return delegate.getAbs(absoluteURI);
}
@Override
public HttpClientRequest getAbs(String absoluteURI, Handler<HttpClientResponse> responseHandler) {
return delegate.getAbs(absoluteURI, responseHandler);
}
@Override
public HttpClient getNow(RequestOptions options, Handler<HttpClientResponse> responseHandler) {
return delegate.getNow(options, responseHandler);
}
@Override
public HttpClient getNow(int port, String host, String requestURI, Handler<HttpClientResponse> responseHandler) {
return delegate.getNow(port, host, requestURI, responseHandler);
}
@Override
public HttpClient getNow(String host, String requestURI, Handler<HttpClientResponse> responseHandler) {
return delegate.getNow(host, requestURI, responseHandler);
}
@Override
public HttpClient getNow(String requestURI, Handler<HttpClientResponse> responseHandler) {
return delegate.getNow(requestURI, responseHandler);
}
@Override
public HttpClientRequest post(RequestOptions options) {
return delegate.post(options);
}
@Override
public HttpClientRequest post(int port, String host, String requestURI) {
return delegate.post(port, host, requestURI);
}
@Override
public HttpClientRequest post(String host, String requestURI) {
return delegate.post(host, requestURI);
}
@Override
public HttpClientRequest post(RequestOptions options, Handler<HttpClientResponse> responseHandler) {
return delegate.post(options, responseHandler);
}
@Override
public HttpClientRequest post(int port, String host, String requestURI, Handler<HttpClientResponse> responseHandler) {
return delegate.post(port, host, requestURI, responseHandler);
}
@Override
public HttpClientRequest post(String host, String requestURI, Handler<HttpClientResponse> responseHandler) {
return delegate.post(host, requestURI, responseHandler);
}
@Override
public HttpClientRequest post(String requestURI) {
return delegate.post(requestURI);
}
@Override
public HttpClientRequest post(String requestURI, Handler<HttpClientResponse> responseHandler) {
return delegate.post(requestURI, responseHandler);
}
@Override
public HttpClientRequest postAbs(String absoluteURI) {
return delegate.postAbs(absoluteURI);
}
@Override
public HttpClientRequest postAbs(String absoluteURI, Handler<HttpClientResponse> responseHandler) {
return delegate.postAbs(absoluteURI, responseHandler);
}
@Override
public HttpClientRequest head(RequestOptions options) {
return delegate.head(options);
}
@Override
public HttpClientRequest head(int port, String host, String requestURI) {
return delegate.head(port, host, requestURI);
}
@Override
public HttpClientRequest head(String host, String requestURI) {
return delegate.head(host, requestURI);
}
@Override
public HttpClientRequest head(RequestOptions options, Handler<HttpClientResponse> responseHandler) {
return delegate.head(options, responseHandler);
}
@Override
public HttpClientRequest head(int port, String host, String requestURI, Handler<HttpClientResponse> responseHandler) {
return delegate.head(port, host, requestURI, responseHandler);
}
@Override
public HttpClientRequest head(String host, String requestURI, Handler<HttpClientResponse> responseHandler) {
return delegate.head(host, requestURI, responseHandler);
}
@Override
public HttpClientRequest head(String requestURI) {
return delegate.head(requestURI);
}
@Override
public HttpClientRequest head(String requestURI, Handler<HttpClientResponse> responseHandler) {
return delegate.head(requestURI, responseHandler);
}
@Override
public HttpClientRequest headAbs(String absoluteURI) {
return delegate.headAbs(absoluteURI);
}
@Override
public HttpClientRequest headAbs(String absoluteURI, Handler<HttpClientResponse> responseHandler) {
return delegate.headAbs(absoluteURI, responseHandler);
}
@Override
public HttpClient headNow(RequestOptions options, Handler<HttpClientResponse> responseHandler) {
return delegate.headNow(options, responseHandler);
}
@Override
public HttpClient headNow(int port, String host, String requestURI, Handler<HttpClientResponse> responseHandler) {
return delegate.headNow(port, host, requestURI, responseHandler);
}
@Override
public HttpClient headNow(String host, String requestURI, Handler<HttpClientResponse> responseHandler) {
return delegate.headNow(host, requestURI, responseHandler);
}
@Override
public HttpClient headNow(String requestURI, Handler<HttpClientResponse> responseHandler) {
return delegate.headNow(requestURI, responseHandler);
}
@Override
public HttpClientRequest options(RequestOptions options) {
return delegate.options(options);
}
@Override
public HttpClientRequest options(int port, String host, String requestURI) {
return delegate.options(port, host, requestURI);
}
@Override
public HttpClientRequest options(String host, String requestURI) {
return delegate.options(host, requestURI);
}
@Override
public HttpClientRequest options(RequestOptions options, Handler<HttpClientResponse> responseHandler) {
return delegate.options(options, responseHandler);
}
@Override
public HttpClientRequest options(int port, String host, String requestURI, Handler<HttpClientResponse> responseHandler) {
return delegate.options(port, host, requestURI, responseHandler);
}
@Override
public HttpClientRequest options(String host, String requestURI, Handler<HttpClientResponse> responseHandler) {
return delegate.options(host, requestURI, responseHandler);
}
@Override
public HttpClientRequest options(String requestURI) {
return delegate.options(requestURI);
}
@Override
public HttpClientRequest options(String requestURI, Handler<HttpClientResponse> responseHandler) {
return delegate.options(requestURI, responseHandler);
}
@Override
public HttpClientRequest optionsAbs(String absoluteURI) {
return delegate.optionsAbs(absoluteURI);
}
@Override
public HttpClientRequest optionsAbs(String absoluteURI, Handler<HttpClientResponse> responseHandler) {
return delegate.optionsAbs(absoluteURI, responseHandler);
}
@Override
public HttpClient optionsNow(RequestOptions options, Handler<HttpClientResponse> responseHandler) {
return delegate.optionsNow(options, responseHandler);
}
@Override
public HttpClient optionsNow(int port, String host, String requestURI, Handler<HttpClientResponse> responseHandler) {
return delegate.optionsNow(port, host, requestURI, responseHandler);
}
@Override
public HttpClient optionsNow(String host, String requestURI, Handler<HttpClientResponse> responseHandler) {
return delegate.optionsNow(host, requestURI, responseHandler);
}
@Override
public HttpClient optionsNow(String requestURI, Handler<HttpClientResponse> responseHandler) {
return delegate.optionsNow(requestURI, responseHandler);
}
@Override
public HttpClientRequest put(RequestOptions options) {
return delegate.put(options);
}
@Override
public HttpClientRequest put(int port, String host, String requestURI) {
return delegate.put(port, host, requestURI);
}
@Override
public HttpClientRequest put(String host, String requestURI) {
return delegate.put(host, requestURI);
}
@Override
public HttpClientRequest put(RequestOptions options, Handler<HttpClientResponse> responseHandler) {
return delegate.put(options, responseHandler);
}
@Override
public HttpClientRequest put(int port, String host, String requestURI, Handler<HttpClientResponse> responseHandler) {
return delegate.put(port, host, requestURI, responseHandler);
}
@Override
public HttpClientRequest put(String host, String requestURI, Handler<HttpClientResponse> responseHandler) {
return delegate.put(host, requestURI, responseHandler);
}
@Override
public HttpClientRequest put(String requestURI) {
return delegate.put(requestURI);
}
@Override
public HttpClientRequest put(String requestURI, Handler<HttpClientResponse> responseHandler) {
return delegate.put(requestURI, responseHandler);
}
@Override
public HttpClientRequest putAbs(String absoluteURI) {
return delegate.putAbs(absoluteURI);
}
@Override
public HttpClientRequest putAbs(String absoluteURI, Handler<HttpClientResponse> responseHandler) {
return delegate.putAbs(absoluteURI, responseHandler);
}
@Override
public HttpClientRequest delete(RequestOptions options) {
return delegate.delete(options);
}
@Override
public HttpClientRequest delete(int port, String host, String requestURI) {
return delegate.delete(port, host, requestURI);
}
@Override
public HttpClientRequest delete(String host, String requestURI) {
return delegate.delete(host, requestURI);
}
@Override
public HttpClientRequest delete(RequestOptions options, Handler<HttpClientResponse> responseHandler) {
return delegate.delete(options, responseHandler);
}
@Override
public HttpClientRequest delete(int port, String host, String requestURI, Handler<HttpClientResponse> responseHandler) {
return delegate.delete(port, host, requestURI, responseHandler);
}
@Override
public HttpClientRequest delete(String host, String requestURI, Handler<HttpClientResponse> responseHandler) {
return delegate.delete(host, requestURI, responseHandler);
}
@Override
public HttpClientRequest delete(String requestURI) {
return delegate.delete(requestURI);
}
@Override
public HttpClientRequest delete(String requestURI, Handler<HttpClientResponse> responseHandler) {
return delegate.delete(requestURI, responseHandler);
}
@Override
public HttpClientRequest deleteAbs(String absoluteURI) {
return delegate.deleteAbs(absoluteURI);
}
@Override
public HttpClientRequest deleteAbs(String absoluteURI, Handler<HttpClientResponse> responseHandler) {
return delegate.deleteAbs(absoluteURI, responseHandler);
}
@Override
public HttpClient websocket(RequestOptions options, Handler<WebSocket> wsConnect) {
return delegate.websocket(options, wsConnect);
}
@Override
public HttpClient websocket(int port, String host, String requestURI, Handler<WebSocket> wsConnect) {
return delegate.websocket(port, host, requestURI, wsConnect);
}
@Override
public HttpClient websocket(RequestOptions options, Handler<WebSocket> wsConnect, Handler<Throwable> failureHandler) {
return delegate.websocket(options, wsConnect, failureHandler);
}
@Override
public HttpClient websocket(int port, String host, String requestURI, Handler<WebSocket> wsConnect, Handler<Throwable> failureHandler) {
return delegate.websocket(port, host, requestURI, wsConnect, failureHandler);
}
@Override
public HttpClient websocket(String host, String requestURI, Handler<WebSocket> wsConnect) {
return delegate.websocket(host, requestURI, wsConnect);
}
@Override
public HttpClient websocket(String host, String requestURI, Handler<WebSocket> wsConnect, Handler<Throwable> failureHandler) {
return delegate.websocket(host, requestURI, wsConnect, failureHandler);
}
@Override
public HttpClient websocket(RequestOptions options, MultiMap headers, Handler<WebSocket> wsConnect) {
return delegate.websocket(options, headers, wsConnect);
}
@Override
public HttpClient websocket(int port, String host, String requestURI, MultiMap headers, Handler<WebSocket> wsConnect) {
return delegate.websocket(port, host, requestURI, headers, wsConnect);
}
@Override
public HttpClient websocket(RequestOptions options, MultiMap headers, Handler<WebSocket> wsConnect, Handler<Throwable> failureHandler) {
return delegate.websocket(options, headers, wsConnect, failureHandler);
}
@Override
public HttpClient websocket(int port, String host, String requestURI, MultiMap headers, Handler<WebSocket> wsConnect, Handler<Throwable> failureHandler) {
return delegate.websocket(port, host, requestURI, headers, wsConnect, failureHandler);
}
@Override
public HttpClient websocket(String host, String requestURI, MultiMap headers, Handler<WebSocket> wsConnect) {
return delegate.websocket(host, requestURI, headers, wsConnect);
}
@Override
public HttpClient websocket(String host, String requestURI, MultiMap headers, Handler<WebSocket> wsConnect, Handler<Throwable> failureHandler) {
return delegate.websocket(host, requestURI, headers, wsConnect, failureHandler);
}
@Override
public HttpClient websocket(RequestOptions options, MultiMap headers, WebsocketVersion version, Handler<WebSocket> wsConnect) {
return delegate.websocket(options, headers, version, wsConnect);
}
@Override
public HttpClient websocket(int port, String host, String requestURI, MultiMap headers, WebsocketVersion version, Handler<WebSocket> wsConnect) {
return delegate.websocket(port, host, requestURI, headers, version, wsConnect);
}
@Override
public HttpClient websocket(RequestOptions options, MultiMap headers, WebsocketVersion version, Handler<WebSocket> wsConnect, Handler<Throwable> failureHandler) {
return delegate.websocket(options, headers, version, wsConnect, failureHandler);
}
@Override
public HttpClient websocket(int port, String host, String requestURI, MultiMap headers, WebsocketVersion version, Handler<WebSocket> wsConnect, Handler<Throwable> failureHandler) {
return delegate.websocket(port, host, requestURI, headers, version, wsConnect, failureHandler);
}
@Override
public HttpClient websocket(String host, String requestURI, MultiMap headers, WebsocketVersion version, Handler<WebSocket> wsConnect) {
return delegate.websocket(host, requestURI, headers, version, wsConnect);
}
@Override
public HttpClient websocket(String host, String requestURI, MultiMap headers, WebsocketVersion version, Handler<WebSocket> wsConnect, Handler<Throwable> failureHandler) {
return delegate.websocket(host, requestURI, headers, version, wsConnect, failureHandler);
}
@Override
public HttpClient websocket(RequestOptions options, MultiMap headers, WebsocketVersion version, String subProtocols, Handler<WebSocket> wsConnect) {
return delegate.websocket(options, headers, version, subProtocols, wsConnect);
}
@Override
public HttpClient websocket(int port, String host, String requestURI, MultiMap headers, WebsocketVersion version, String subProtocols, Handler<WebSocket> wsConnect) {
return delegate.websocket(port, host, requestURI, headers, version, subProtocols, wsConnect);
}
@Override
public HttpClient websocketAbs(String url, MultiMap headers, WebsocketVersion version, String subProtocols, Handler<WebSocket> wsConnect, Handler<Throwable> failureHandler) {
return delegate.websocketAbs(url, headers, version, subProtocols, wsConnect, failureHandler);
}
@Override
public HttpClient websocket(RequestOptions options, MultiMap headers, WebsocketVersion version, String subProtocols, Handler<WebSocket> wsConnect, Handler<Throwable> failureHandler) {
return delegate.websocket(options, headers, version, subProtocols, wsConnect, failureHandler);
}
@Override
public HttpClient websocket(int port, String host, String requestURI, MultiMap headers, WebsocketVersion version, String subProtocols, Handler<WebSocket> wsConnect, Handler<Throwable> failureHandler) {
return delegate.websocket(port, host, requestURI, headers, version, subProtocols, wsConnect, failureHandler);
}
@Override
public HttpClient websocket(String host, String requestURI, MultiMap headers, WebsocketVersion version, String subProtocols, Handler<WebSocket> wsConnect) {
return delegate.websocket(host, requestURI, headers, version, subProtocols, wsConnect);
}
@Override
public HttpClient websocket(String host, String requestURI, MultiMap headers, WebsocketVersion version, String subProtocols, Handler<WebSocket> wsConnect, Handler<Throwable> failureHandler) {
return delegate.websocket(host, requestURI, headers, version, subProtocols, wsConnect, failureHandler);
}
@Override
public HttpClient websocket(String requestURI, Handler<WebSocket> wsConnect) {
return delegate.websocket(requestURI, wsConnect);
}
@Override
public HttpClient websocket(String requestURI, Handler<WebSocket> wsConnect, Handler<Throwable> failureHandler) {
return delegate.websocket(requestURI, wsConnect, failureHandler);
}
@Override
public HttpClient websocket(String requestURI, MultiMap headers, Handler<WebSocket> wsConnect) {
return delegate.websocket(requestURI, headers, wsConnect);
}
@Override
public HttpClient websocket(String requestURI, MultiMap headers, Handler<WebSocket> wsConnect, Handler<Throwable> failureHandler) {
return delegate.websocket(requestURI, headers, wsConnect, failureHandler);
}
@Override
public HttpClient websocket(String requestURI, MultiMap headers, WebsocketVersion version, Handler<WebSocket> wsConnect) {
return delegate.websocket(requestURI, headers, version, wsConnect);
}
@Override
public HttpClient websocket(String requestURI, MultiMap headers, WebsocketVersion version, Handler<WebSocket> wsConnect, Handler<Throwable> failureHandler) {
return delegate.websocket(requestURI, headers, version, wsConnect, failureHandler);
}
@Override
public HttpClient websocket(String requestURI, MultiMap headers, WebsocketVersion version, String subProtocols, Handler<WebSocket> wsConnect) {
return delegate.websocket(requestURI, headers, version, subProtocols, wsConnect);
}
@Override
public HttpClient websocket(String requestURI, MultiMap headers, WebsocketVersion version, String subProtocols, Handler<WebSocket> wsConnect, Handler<Throwable> failureHandler) {
return delegate.websocket(requestURI, headers, version, subProtocols, wsConnect, failureHandler);
}
@Override
public ReadStream<WebSocket> websocketStream(RequestOptions options) {
return delegate.websocketStream(options);
}
@Override
public ReadStream<WebSocket> websocketStream(int port, String host, String requestURI) {
return delegate.websocketStream(port, host, requestURI);
}
@Override
public ReadStream<WebSocket> websocketStream(String host, String requestURI) {
return delegate.websocketStream(host, requestURI);
}
@Override
public ReadStream<WebSocket> websocketStream(RequestOptions options, MultiMap headers) {
return delegate.websocketStream(options, headers);
}
@Override
public ReadStream<WebSocket> websocketStream(int port, String host, String requestURI, MultiMap headers) {
return delegate.websocketStream(port, host, requestURI, headers);
}
@Override
public ReadStream<WebSocket> websocketStream(String host, String requestURI, MultiMap headers) {
return delegate.websocketStream(host, requestURI, headers);
}
@Override
public ReadStream<WebSocket> websocketStream(RequestOptions options, MultiMap headers, WebsocketVersion version) {
return delegate.websocketStream(options, headers, version);
}
@Override
public ReadStream<WebSocket> websocketStream(int port, String host, String requestURI, MultiMap headers, WebsocketVersion version) {
return delegate.websocketStream(port, host, requestURI, headers, version);
}
@Override
public ReadStream<WebSocket> websocketStream(String host, String requestURI, MultiMap headers, WebsocketVersion version) {
return delegate.websocketStream(host, requestURI, headers, version);
}
@Override
public ReadStream<WebSocket> websocketStreamAbs(String url, MultiMap headers, WebsocketVersion version, String subProtocols) {
return delegate.websocketStreamAbs(url, headers, version, subProtocols);
}
@Override
public ReadStream<WebSocket> websocketStream(RequestOptions options, MultiMap headers, WebsocketVersion version, String subProtocols) {
return delegate.websocketStream(options, headers, version, subProtocols);
}
@Override
public ReadStream<WebSocket> websocketStream(int port, String host, String requestURI, MultiMap headers, WebsocketVersion version, String subProtocols) {
return delegate.websocketStream(port, host, requestURI, headers, version, subProtocols);
}
@Override
public ReadStream<WebSocket> websocketStream(String host, String requestURI, MultiMap headers, WebsocketVersion version, String subProtocols) {
return delegate.websocketStream(host, requestURI, headers, version, subProtocols);
}
@Override
public ReadStream<WebSocket> websocketStream(String requestURI) {
return delegate.websocketStream(requestURI);
}
@Override
public ReadStream<WebSocket> websocketStream(String requestURI, MultiMap headers) {
return delegate.websocketStream(requestURI, headers);
}
@Override
public ReadStream<WebSocket> websocketStream(String requestURI, MultiMap headers, WebsocketVersion version) {
return delegate.websocketStream(requestURI, headers, version);
}
@Override
public ReadStream<WebSocket> websocketStream(String requestURI, MultiMap headers, WebsocketVersion version, String subProtocols) {
return delegate.websocketStream(requestURI, headers, version, subProtocols);
}
@Override
public HttpClient connectionHandler(Handler<HttpConnection> handler) {
return delegate.connectionHandler(handler);
}
@Override
public HttpClient redirectHandler(Function<HttpClientResponse, Future<HttpClientRequest>> handler) {
return delegate.redirectHandler(handler);
}
@Override
public Function<HttpClientResponse, Future<HttpClientRequest>> redirectHandler() {
return delegate.redirectHandler();
}
}
|
3e1def8f770fd4dda4ed25aec12a24da583e7282 | 2,074 | java | Java | WEB-INF/src/com/skymiracle/gameUnion/models/team/TeamRolePower.java | neorayer/eg-website | b7250392103e6aee15980a3388df884ec253e1a3 | [
"MIT"
] | 1 | 2019-09-16T01:45:14.000Z | 2019-09-16T01:45:14.000Z | WEB-INF/src/com/skymiracle/gameUnion/models/team/TeamRolePower.java | neorayer/eg-website | b7250392103e6aee15980a3388df884ec253e1a3 | [
"MIT"
] | null | null | null | WEB-INF/src/com/skymiracle/gameUnion/models/team/TeamRolePower.java | neorayer/eg-website | b7250392103e6aee15980a3388df884ec253e1a3 | [
"MIT"
] | null | null | null | 21.381443 | 88 | 0.722276 | 12,669 | package com.skymiracle.gameUnion.models.team;
import static com.skymiracle.gameUnion.Singletons.*;
import com.skymiracle.gameUnion.models.AbsMdo;
import com.skymiracle.gameUnion.models.Authority;
import com.skymiracle.mdo5.MList;
import com.skymiracle.mdo5.Mdo_X;
import com.skymiracle.sor.exception.AppException;
public class TeamRolePower extends AbsMdo<TeamRolePower> {
public static class X extends Mdo_X<TeamRolePower> {
public void add4TeamLeader(TeamRole role) throws AppException, Exception {
for (Authority au : AuthorityX.getItemsMap().values())
new TeamRolePower(role, au).create();
}
public void add4Newer(TeamRole role) throws AppException, Exception {
Authority au = AuthorityX.getItemsMap().get("vi_member");
new TeamRolePower(role, au).create();
}
public MList<TeamRolePower> findByRole(TeamRole role) throws AppException, Exception {
return this.find("teamId, roleId", role.getTeamId(), role.getId());
}
}
@Length(32)
private String teamId;
@Length(64)
private String roleId;
@Length(64)
private String powerId;
public String getTeamId() {
return teamId;
}
public void setTeamId(String teamId) {
this.teamId = teamId;
}
public String getRoleId() {
return roleId;
}
public void setRoleId(String roleId) {
this.roleId = roleId;
}
public String getPowerId() {
return powerId;
}
public void setPowerId(String powerId) {
this.powerId = powerId;
}
public TeamRolePower() {
super(TeamRolePowerX);
}
public TeamRolePower(String teamId, String roleId, String powerId) {
this();
this.teamId = teamId;
this.roleId = roleId;
this.powerId = powerId;
}
public TeamRolePower(TeamRole role, Authority au) {
this();
this.teamId = role.getTeamId();
this.roleId = role.getId();
this.powerId = au.getCode();
}
@Override
public String[] keyNames() {
return new String[] { "teamid", "roleid", "powerid" };
}
@Override
public String table() {
return "tb_teamrolepower";
}
public Authority getAuthority() {
return AuthorityX.getItemsMap().get(powerId);
}
}
|
3e1defea76735e2deb9c6f90ab71a980bb8f08c8 | 15,232 | java | Java | saiku-core/saiku-service/src/main/java/org/saiku/olap/query/OlapQuery.java | ZENGJINHUAI/saiku | 709ca1267a12e2d8bb582f68668b96080e8d97d6 | [
"Apache-2.0"
] | 1,073 | 2015-01-14T22:12:04.000Z | 2022-03-24T07:54:24.000Z | saiku-core/saiku-service/src/main/java/org/saiku/olap/query/OlapQuery.java | ZENGJINHUAI/saiku | 709ca1267a12e2d8bb582f68668b96080e8d97d6 | [
"Apache-2.0"
] | 422 | 2015-03-03T08:57:05.000Z | 2021-05-01T13:19:11.000Z | saiku-core/saiku-service/src/main/java/org/saiku/olap/query/OlapQuery.java | ZENGJINHUAI/saiku | 709ca1267a12e2d8bb582f68668b96080e8d97d6 | [
"Apache-2.0"
] | 649 | 2015-01-06T16:58:34.000Z | 2022-03-31T23:11:31.000Z | 31.341564 | 157 | 0.607668 | 12,670 | /*
* Copyright 2012 OSBI Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.saiku.olap.query;
import org.saiku.olap.dto.SaikuCube;
import org.saiku.olap.dto.SaikuTag;
import org.saiku.olap.dto.filter.SaikuFilter;
import org.saiku.olap.query.QueryProperties.QueryProperty;
import org.saiku.olap.query.QueryProperties.QueryPropertyFactory;
import org.saiku.olap.util.QueryConverter;
import org.saiku.olap.util.SaikuProperties;
import org.saiku.olap.util.exception.SaikuIncompatibleException;
import org.saiku.olap.util.exception.SaikuOlapException;
import org.saiku.olap.util.formatter.ICellSetFormatter;
import org.saiku.service.util.exception.SaikuServiceException;
import org.apache.commons.lang.StringUtils;
import org.olap4j.*;
import org.olap4j.Axis.Standard;
import org.olap4j.impl.IdentifierParser;
import org.olap4j.mdx.ParseTreeWriter;
import org.olap4j.mdx.SelectNode;
import org.olap4j.metadata.Catalog;
import org.olap4j.metadata.Cube;
import org.olap4j.query.*;
import org.olap4j.query.QueryDimension.HierarchizeMode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.Writer;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import mondrian.rolap.RolapConnection;
public class OlapQuery implements IQuery {
private static final Logger log = LoggerFactory.getLogger(OlapQuery.class);
private static final String SCENARIO = "Scenario";
private final Query query;
private final Properties properties = new Properties();
private final Map<String, String> totalsFunctions = new HashMap<>();
private final SaikuCube cube;
private Scenario scenario;
private SaikuTag tag = null;
private SaikuFilter filter;
private CellSet cellset = null;
private OlapStatement statement = null;
private final OlapConnection connection;
private ICellSetFormatter formatter;
public OlapQuery(Query query, OlapConnection connection, SaikuCube cube, boolean applyDefaultProperties) {
this.query = query;
this.cube = cube;
this.connection = connection;
if (applyDefaultProperties) {
applyDefaultProperties();
}
}
public OlapQuery(Query query, OlapConnection connection, SaikuCube cube) {
this(query,connection, cube,true);
}
public void swapAxes() {
this.query.swapAxes();
QueryAxis rows = query.getAxis(Axis.ROWS);
QueryAxis cols = query.getAxis(Axis.COLUMNS);
SortOrder colSort = cols.getSortOrder();
String colSortIdentifier = cols.getSortIdentifierNodeName();
cols.clearSort();
if (rows.getSortOrder() != null) {
cols.sort(rows.getSortOrder(), rows.getSortIdentifierNodeName());
}
rows.clearSort();
if (colSort != null) {
rows.sort(colSort, colSortIdentifier);
}
try {
// 3-way swap
String colFilter = cols.getFilterCondition();
LimitFunction colLimit = cols.getLimitFunction();
BigDecimal colN = cols.getLimitFunctionN();
String colLimitSort = cols.getLimitFunctionSortLiteral();
cols.clearFilter();
cols.clearLimitFunction();
// columns
if (rows.getLimitFunction() != null) {
cols.limit(rows.getLimitFunction(), rows.getLimitFunctionN(), rows.getLimitFunctionSortLiteral());
}
if (StringUtils.isNotBlank(rows.getFilterCondition())) {
cols.filter(rows.getFilterCondition());
}
rows.clearFilter();
rows.clearLimitFunction();
// rows
if (colLimit != null) {
rows.limit(colLimit, colN, colLimitSort);
}
if (StringUtils.isNotBlank(colFilter)) {
rows.filter(colFilter);
}
} catch (NoSuchMethodError e) {}
}
public Map<Axis, QueryAxis> getAxes() {
return this.query.getAxes();
}
public QueryAxis getAxis(Axis axis) {
return this.query.getAxis(axis);
}
public QueryAxis getAxis(String name) throws SaikuOlapException {
if ("UNUSED".equals(name)) {
return getUnusedAxis();
}
Standard standardAxis = Standard.valueOf(name);
if (standardAxis == null)
throw new SaikuOlapException("Axis ("+name+") not found for query ("+ query.getName() + ")");
Axis queryAxis = Axis.Factory.forOrdinal(standardAxis.axisOrdinal());
return query.getAxis(queryAxis);
}
public Cube getCube() {
return this.query.getCube();
}
public QueryAxis getUnusedAxis() {
return this.query.getUnusedAxis();
}
public void moveDimension(QueryDimension dimension, Axis axis) {
moveDimension(dimension, axis, -1);
}
public void moveDimension(QueryDimension dimension, Axis axis, int position) {
QueryAxis oldQueryAxis = findAxis(dimension);
QueryAxis newQueryAxis = query.getAxis(axis);
if (!Axis.FILTER.equals(axis)) {
dimension.setHierarchyConsistent(true);
dimension.setHierarchizeMode(HierarchizeMode.PRE);
} else {
dimension.setHierarchyConsistent(false);
dimension.clearHierarchizeMode();
}
if (oldQueryAxis != null && newQueryAxis != null && (oldQueryAxis.getLocation() != newQueryAxis.getLocation()) && oldQueryAxis.getLocation() != null)
{
for (QueryAxis qAxis : query.getAxes().values()) {
if (qAxis.getSortOrder() != null && qAxis.getSortIdentifierNodeName() != null) {
String sortLiteral = qAxis.getSortIdentifierNodeName();
if (sortLiteral.startsWith(dimension.getDimension().getUniqueName()) || sortLiteral.startsWith("[" + dimension.getName())) {
qAxis.clearSort();
}
}
}
}
if (oldQueryAxis != null && newQueryAxis != null && (position > -1 || (oldQueryAxis.getLocation() != newQueryAxis.getLocation()))) {
oldQueryAxis.removeDimension(dimension);
if (position > -1) {
newQueryAxis.addDimension(position, dimension);
} else {
newQueryAxis.addDimension(dimension);
}
}
}
public QueryDimension getDimension(String name) {
return this.query.getDimension(name);
}
private QueryAxis findAxis(QueryDimension dimension) {
if (query.getUnusedAxis().getDimensions().contains(dimension)) {
return query.getUnusedAxis();
}
else {
Map<Axis,QueryAxis> axes = query.getAxes();
for (Axis axis : axes.keySet()) {
if (axes.get(axis).getDimensions().contains(dimension)) {
return axes.get(axis);
}
}
}
return null;
}
public String getMdx() {
final Writer writer = new StringWriter();
if (SaikuProperties.olapConvertQuery) {
try {
SelectNode s = QueryConverter.convert(query);
s.unparse(new ParseTreeWriter(new PrintWriter(writer)));
} catch (SaikuIncompatibleException se) {
log.debug("Cannot convert to new query model mdx, falling back to old version", se);
this.query.getSelect().unparse(new ParseTreeWriter(new PrintWriter(writer)));
} catch (Exception e) {
throw new SaikuServiceException("Cannot convert to new query model", e);
}
} else {
this.query.getSelect().unparse(new ParseTreeWriter(new PrintWriter(writer)));
}
return writer.toString();
}
public SaikuCube getSaikuCube() {
return cube;
}
public String getName() {
return query.getName();
}
public CellSet execute() throws Exception {
try {
if (statement != null) {
statement.close();
statement = null;
}
if (scenario != null && query.getDimension(SCENARIO) != null) {
QueryDimension dimension = query.getDimension(SCENARIO);
moveDimension(dimension, Axis.FILTER);
Selection sel = dimension.createSelection(IdentifierParser.parseIdentifier("[Scenario].[" + getScenario().getId() + "]"));
if (!dimension.getInclusions().contains(sel)) {
dimension.getInclusions().add(sel);
}
}
String mdx = getMdx();
log.trace("Executing query (" + this.getName() + ") :\n" + mdx);
final Catalog catalog = query.getCube().getSchema().getCatalog();
this.connection.setCatalog(catalog.getName());
OlapStatement stmt = connection.createStatement();
this.statement = stmt;
CellSet cellSet = stmt.executeOlapQuery(mdx);
if (scenario != null && query.getDimension(SCENARIO) != null) {
QueryDimension dimension = query.getDimension(SCENARIO);
dimension.getInclusions().clear();
moveDimension(dimension, null);
}
return cellSet;
} finally {
if (this.statement != null) {
this.statement.close();
}
}
}
private void applyDefaultProperties() {
if (SaikuProperties.olapDefaultNonEmpty) {
query.getAxis(Axis.ROWS).setNonEmpty(true);
query.getAxis(Axis.COLUMNS).setNonEmpty(true);
}
}
public void resetAxisSelections(QueryAxis axis) {
for (QueryDimension dim : axis.getDimensions()) {
dim.clearInclusions();
dim.clearExclusions();
dim.clearSort();
}
try {
axis.clearFilter();
axis.clearLimitFunction();
axis.clearSort();
} catch (NoSuchMethodError e) {}
}
public void clearAllQuerySelections() {
resetAxisSelections(getUnusedAxis());
Map<Axis,QueryAxis> axes = getAxes();
for (Axis axis : axes.keySet()) {
resetAxisSelections(axes.get(axis));
}
}
public void resetQuery() {
clearAllQuerySelections();
Map<Axis,QueryAxis> axes = getAxes();
for (Axis axis : axes.keySet()) {
QueryAxis qAxis = axes.get(axis);
for (int i = 0; i < qAxis.getDimensions().size(); i++ ) {
QueryDimension qDim = qAxis.getDimensions().get(0);
moveDimension(qDim, null);
}
}
}
public void clearAxis(String axisName) throws SaikuOlapException {
if (StringUtils.isNotBlank(axisName)) {
QueryAxis qAxis = getAxis(axisName);
resetAxisSelections(qAxis);
for (int i = 0; i < qAxis.getDimensions().size(); i++ ) {
QueryDimension qDim = qAxis.getDimensions().get(0);
moveDimension(qDim, null);
}
}
}
public void setProperties(Properties props) {
if (props != null) {
this.properties.putAll(props);
for (Object _key : props.keySet()) {
String key = (String) _key;
String value = props.getProperty((String) key);
QueryProperty prop = QueryPropertyFactory.getProperty(key, value, this);
prop.handle();
}
}
}
public Properties getProperties() {
this.properties.putAll(QueryPropertyFactory.forQuery(this));
try {
connection.createScenario();
if (query.getDimension("Scenario") != null) {
this.properties.put("org.saiku.connection.scenario", Boolean.toString(true));
}
else {
this.properties.put("org.saiku.connection.scenario", Boolean.toString(false));
}
this.properties.put("org.saiku.query.explain", Boolean.toString(connection.isWrapperFor(RolapConnection.class)));
} catch (Exception e) {
this.properties.put("org.saiku.connection.scenario", Boolean.toString(false));
this.properties.put("org.saiku.query.explain", Boolean.toString(false));
}
return this.properties;
}
public String toXml() {
QuerySerializer qs = new QuerySerializer(this);
return qs.createXML();
}
public Boolean isDrillThroughEnabled() {
return query.getCube().isDrillThroughEnabled();
}
public QueryType getType() {
return QueryType.QM;
}
public void setMdx(String mdx) {
throw new UnsupportedOperationException();
}
public void setScenario(Scenario scenario) {
this.scenario = scenario;
}
public Scenario getScenario() {
return scenario;
}
public void setTag(SaikuTag tag) {
this.tag = tag;
}
public SaikuTag getTag() {
return this.tag;
}
public void removeTag() {
tag = null;
}
public void setFilter(SaikuFilter filter) {
this.filter = filter;
}
public SaikuFilter getFilter() {
return this.filter;
}
public void removeFilter() {
this.filter = null;
}
public void storeCellset(CellSet cs) {
this.cellset = cs;
}
public CellSet getCellset() {
return cellset;
}
public void setStatement(OlapStatement os) {
this.statement = os;
}
public OlapStatement getStatement() {
return this.statement;
}
public void cancel() throws Exception {
if (this.statement != null && !this.statement.isClosed()) {
statement.cancel();
statement.close();
}
this.statement = null;
}
public OlapConnection getConnection() {
return this.connection;
}
public void storeFormatter(ICellSetFormatter formatter) {
this.formatter = formatter;
}
public ICellSetFormatter getFormatter() {
return formatter;
}
public void setTotalFunction(String uniqueLevelName, String value) {
totalsFunctions.put(uniqueLevelName, value);
}
public String getTotalFunction(String uniqueLevelName) {
return totalsFunctions.get(uniqueLevelName);
}
public Map<String, String> getTotalFunctions() {
return totalsFunctions;
}
public Query getQuery() {
return query;
}
}
|
3e1df0ee73fb2881dd2376d2b3823699f3087f33 | 4,966 | java | Java | components/javaee/org.wso2.carbon.javaee.tomee/src/main/java/org/wso2/carbon/javaee/tomee/scan/ASTomEEJarScanner.java | Niranjan-K/carbon-deployment | 2b550bfe9e485d63819877281202789e29a1525c | [
"Apache-2.0"
] | null | null | null | components/javaee/org.wso2.carbon.javaee.tomee/src/main/java/org/wso2/carbon/javaee/tomee/scan/ASTomEEJarScanner.java | Niranjan-K/carbon-deployment | 2b550bfe9e485d63819877281202789e29a1525c | [
"Apache-2.0"
] | null | null | null | components/javaee/org.wso2.carbon.javaee.tomee/src/main/java/org/wso2/carbon/javaee/tomee/scan/ASTomEEJarScanner.java | Niranjan-K/carbon-deployment | 2b550bfe9e485d63819877281202789e29a1525c | [
"Apache-2.0"
] | null | null | null | 38.2 | 102 | 0.578937 | 12,671 | /*
* Copyright 2004,2013 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.wso2.carbon.javaee.tomee.scan;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.tomcat.JarScannerCallback;
import org.apache.tomcat.util.res.StringManager;
import org.apache.tomcat.util.scan.Constants;
import org.apache.tomee.loader.TomEEJarScanner;
import org.eclipse.osgi.framework.adaptor.BundleClassLoader;
import javax.servlet.ServletContext;
import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.net.JarURLConnection;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLConnection;
import java.util.Set;
/**
* TomEE jar scanner with Carbon bits.
* In addition to what TomEE and Tomcat does, we need to scan the jars
* under plugins
*/
public class ASTomEEJarScanner extends TomEEJarScanner {
private static final Log log = LogFactory.getLog(ASTomEEJarScanner.class);
private static final StringManager sm =
StringManager.getManager(Constants.Package);
private static final String CARBON_PLUGINS_DIR_PATH = System.getProperty("carbon.home") +
File.separator +"repository" + File.separator + "components" + File.separator + "plugins";
@Override
public void scan(ServletContext context, ClassLoader classloader,
JarScannerCallback callback, Set<String> jarsToSkip) {
ClassLoader loader =
Thread.currentThread().getContextClassLoader();
while (loader != null) {
// WSO2 Carbon specific code snippet
// Setting the plugins directory only if the parent classLoader is a bundleClassLoader.
if (loader instanceof BundleClassLoader) {
File pluginsDir = new File(CARBON_PLUGINS_DIR_PATH);
File[] jarFiles = pluginsDir.listFiles(new FileFilter(){
public boolean accept(File file) {
return file.getName().endsWith(Constants.JAR_EXT);
}
});
// processing collected jar files for tldListeners
for (File jarFile : jarFiles) {
try {
process(callback, jarFile.toURI().toURL());
} catch (IOException e) {
log.warn(sm.getString("jarScan.classloaderFail"),e);
}
}
}
}
}
/**
* Scan a URL for JARs with the optional extensions to look at all files
* and all directories.
*/
private void process(JarScannerCallback callback, URL url)
throws IOException {
if (log.isTraceEnabled()) {
log.trace(sm.getString("jarScan.jarUrlStart", url));
}
URLConnection conn = url.openConnection();
if (conn instanceof JarURLConnection) {
callback.scan((JarURLConnection) conn);
} else {
String urlStr = url.toString();
if (urlStr.startsWith("file:") || urlStr.startsWith("jndi:")) {
if (urlStr.endsWith(Constants.JAR_EXT)) {
URL jarURL = new URL("jar:" + urlStr + "!/");
callback.scan((JarURLConnection) jarURL.openConnection());
} else {
File f;
try {
f = new File(url.toURI());
if (f.isFile() && isScanAllFiles()) {
// Treat this file as a JAR
URL jarURL = new URL("jar:" + urlStr + "!/");
callback.scan((JarURLConnection) jarURL.openConnection());
} else if (f.isDirectory() && isScanAllDirectories()) {
File metainf = new File(f.getAbsoluteFile() +
File.separator + "META-INF");
if (metainf.isDirectory()) {
callback.scan(f);
}
}
} catch (URISyntaxException e) {
// Wrap the exception and re-throw
IOException ioe = new IOException();
ioe.initCause(e);
throw ioe;
}
}
}
}
}
}
|
3e1df1139f4e235cd338866245c4511bb5d76909 | 2,740 | java | Java | instrumentation/jetty-8.0/src/main/java/io/opentelemetry/auto/instrumentation/jetty/JettyDecorator.java | ksameersrk/opentelemetry-java-instrumentation | 77654a44bcb3b66421b000b72334ac148ab3ca2d | [
"Apache-2.0"
] | null | null | null | instrumentation/jetty-8.0/src/main/java/io/opentelemetry/auto/instrumentation/jetty/JettyDecorator.java | ksameersrk/opentelemetry-java-instrumentation | 77654a44bcb3b66421b000b72334ac148ab3ca2d | [
"Apache-2.0"
] | null | null | null | instrumentation/jetty-8.0/src/main/java/io/opentelemetry/auto/instrumentation/jetty/JettyDecorator.java | ksameersrk/opentelemetry-java-instrumentation | 77654a44bcb3b66421b000b72334ac148ab3ca2d | [
"Apache-2.0"
] | null | null | null | 33.012048 | 94 | 0.739781 | 12,672 | /*
* Copyright The OpenTelemetry 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 io.opentelemetry.auto.instrumentation.jetty;
import io.opentelemetry.OpenTelemetry;
import io.opentelemetry.auto.bootstrap.instrumentation.decorator.HttpServerDecorator;
import io.opentelemetry.trace.Span;
import io.opentelemetry.trace.Tracer;
import java.net.URI;
import java.net.URISyntaxException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class JettyDecorator
extends HttpServerDecorator<HttpServletRequest, HttpServletRequest, HttpServletResponse> {
public static final JettyDecorator DECORATE = new JettyDecorator();
public static final Tracer TRACER =
OpenTelemetry.getTracerProvider().get("io.opentelemetry.auto.jetty-8.0");
@Override
protected String method(final HttpServletRequest httpServletRequest) {
return httpServletRequest.getMethod();
}
@Override
protected URI url(final HttpServletRequest httpServletRequest) throws URISyntaxException {
return new URI(
httpServletRequest.getScheme(),
null,
httpServletRequest.getServerName(),
httpServletRequest.getServerPort(),
httpServletRequest.getRequestURI(),
httpServletRequest.getQueryString(),
null);
}
@Override
protected String peerHostIP(final HttpServletRequest httpServletRequest) {
return httpServletRequest.getRemoteAddr();
}
@Override
protected Integer peerPort(final HttpServletRequest httpServletRequest) {
return httpServletRequest.getRemotePort();
}
@Override
protected Integer status(final HttpServletResponse httpServletResponse) {
return httpServletResponse.getStatus();
}
@Override
public Span onRequest(final Span span, final HttpServletRequest request) {
assert span != null;
if (request != null) {
final String sc = request.getContextPath();
if (sc != null && !sc.isEmpty()) {
span.setAttribute("servlet.context", sc);
}
final String sp = request.getServletPath();
if (sp != null && !sp.isEmpty()) {
span.setAttribute("servlet.path", sp);
}
}
return super.onRequest(span, request);
}
}
|
3e1df2034199d527e620b57dc0cb7eb82d1ab2d2 | 2,559 | java | Java | algorithms/src/test/java/com/pjzhong/leetcode/CarPooling.java | pjzhong/algorithms | bf8dfdcebd84a6bc93f0895ae995253380f2b233 | [
"MIT"
] | 1 | 2018-03-28T08:09:48.000Z | 2018-03-28T08:09:48.000Z | algorithms/src/test/java/com/pjzhong/leetcode/CarPooling.java | pjzhong/algorithms | bf8dfdcebd84a6bc93f0895ae995253380f2b233 | [
"MIT"
] | 12 | 2020-06-21T14:06:32.000Z | 2022-01-04T16:47:36.000Z | algorithms/src/test/java/com/pjzhong/leetcode/CarPooling.java | pjzhong/algorithms | bf8dfdcebd84a6bc93f0895ae995253380f2b233 | [
"MIT"
] | null | null | null | 28.752809 | 100 | 0.566237 | 12,673 | package com.pjzhong.leetcode;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Map;
import java.util.PriorityQueue;
import java.util.Queue;
import java.util.TreeMap;
import org.junit.Test;
/**
* You are driving a vehicle that has capacity empty seats initially available for passengers. The
* vehicle only drives east (ie. it cannot turn around and drive west.)
*
* Given a list of trips, trip[i] = [num_passengers, start_location, end_location] contains
* information about the i-th trip: the number of passengers that must be picked up, and the
* locations to pick them up and drop them off. The locations are given as the number of kilometers
* due east from your vehicle's initial location.
*
* Return true if and only if it is possible to pick up and drop off all passengers for all the
* given trips.
*
* @link https://leetcode.com/problems/car-pooling/
**/
public class CarPooling {
@Test
public void test() {
int[][][] tests = {
{{9, 3, 6}, {8, 1, 7}, {6, 6, 8}, {8, 4, 9}, {4, 2, 9}},
{{9, 3, 4}, {9, 1, 7}, {4, 2, 4}, {7, 4, 5}},
{{7, 5, 6}, {6, 7, 8}, {10, 1, 6}},
{{2, 1, 5}, {3, 3, 7}},
{{2, 1, 5}, {3, 3, 7}},
{{2, 1, 5}, {3, 5, 7}},
{{3, 2, 7}, {3, 7, 9}, {8, 3, 9}},
};
int[] testC = {28, 23, 16, 4, 5, 3, 11};
for (int i = 0; i < testC.length; i++) {
System.out.println(carPooling(tests[i], testC[i]));
}
}
public boolean carPooling(int[][] trips, int capacity) {
Map<Integer, Integer> onAndOff = new TreeMap<>();
for (int[] trip : trips) {
onAndOff.merge(trip[1], trip[0], Integer::sum);//上车位置,加
onAndOff.merge(trip[2], -trip[0], Integer::sum);//下车位置,减
}
int count = 0;
for (Integer i : onAndOff.values()) {
count += i;
if (capacity < count) {
return false;
}
}
return true;
}
private boolean useSortAndPriorityQueue(int[][] trips, int capacity) {
Arrays.sort(trips, Comparator.comparingInt(a -> a[1]));//上车顺序
Queue<int[]> passengers = new PriorityQueue<>(Comparator.comparingInt(a -> a[2])); //下车顺序
int left = capacity;
for (int[] trip : trips) {
while (passengers.peek() != null) {
int[] p = passengers.peek();
if (p[2] <= trip[1]) {//是否到站
left += p[0];
passengers.poll();
} else {
break;
}
}
left -= trip[0];
if (left < 0) {
return false;
} else {
passengers.add(trip);
}
}
return true;
}
}
|
3e1df2b8eb51caf3c6743f671605960dc26ca3da | 3,118 | java | Java | components/identity/org.wso2.carbon.identity.relyingparty.ui/src/main/java/org/wso2/carbon/identity/relyingparty/ui/openid/OpenIDExtensionFactory.java | milindaperera/carbon-identity | 600e65d8a4b37031c6a5dff33e45f304db64f551 | [
"Apache-2.0"
] | null | null | null | components/identity/org.wso2.carbon.identity.relyingparty.ui/src/main/java/org/wso2/carbon/identity/relyingparty/ui/openid/OpenIDExtensionFactory.java | milindaperera/carbon-identity | 600e65d8a4b37031c6a5dff33e45f304db64f551 | [
"Apache-2.0"
] | null | null | null | components/identity/org.wso2.carbon.identity.relyingparty.ui/src/main/java/org/wso2/carbon/identity/relyingparty/ui/openid/OpenIDExtensionFactory.java | milindaperera/carbon-identity | 600e65d8a4b37031c6a5dff33e45f304db64f551 | [
"Apache-2.0"
] | null | null | null | 35.033708 | 91 | 0.74567 | 12,674 | /*
* Copyright 2005-2008 WSO2, Inc. (http://wso2.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.wso2.carbon.identity.relyingparty.ui.openid;
import org.openid4java.message.AuthSuccess;
import org.openid4java.message.ax.AxMessage;
import org.openid4java.message.pape.PapeMessage;
import org.openid4java.message.sreg.SRegMessage;
import org.wso2.carbon.identity.base.IdentityConstants;
import org.wso2.carbon.identity.relyingparty.ui.openid.extensions.OpenIDAttributeExchange;
import org.wso2.carbon.identity.relyingparty.ui.openid.extensions.OpenIDExtension;
import org.wso2.carbon.identity.relyingparty.ui.openid.extensions.OpenIDPape;
import org.wso2.carbon.identity.relyingparty.ui.openid.extensions.OpenIDSimpleReg;
public class OpenIDExtensionFactory {
private static OpenIDExtensionFactory factory = new OpenIDExtensionFactory();
/**
* Make the class singleton
*/
private OpenIDExtensionFactory() {
}
/**
* Returns a singleton instance of OpenIDExtensionFactory
*
* @return An instance of OpenIDExtensionFactory
*/
public static OpenIDExtensionFactory getInstance() {
return factory;
}
/**
* Create an instance of the OpenIDExtension based on the OpenID request type
*
* @param type Type of the OpenID request
* @return Appropriate OpenIDExtension instance
*/
public OpenIDExtension getExtension(String type) {
if (IdentityConstants.OpenId.ATTRIBUTE_EXCHANGE.equals(type)) {
return new OpenIDAttributeExchange();
} else if (IdentityConstants.OpenId.SIMPLE_REGISTRATION.equals(type)) {
return new OpenIDSimpleReg();
} else if (IdentityConstants.OpenId.PAPE.equals(type)) {
return new OpenIDPape();
} else {
return null;
}
}
/**
* Create an instance of the OpenIDExtension based on the OpenID extension type
*
* @param alias Extension alias
* @param auth AuthSuccess instance
* @return Appropriate OpenIDExtension instance
*/
public OpenIDExtension getExtension(String alias, AuthSuccess auth) {
if (alias.equals(AxMessage.OPENID_NS_AX)
|| alias.equals(IdentityConstants.OpenId.ExchangeAttributes.NS_AX)) {
return new OpenIDAttributeExchange(auth);
} else if (alias.equals(IdentityConstants.OpenId.SimpleRegAttributes.NS_SREG)
|| alias.equals(SRegMessage.OPENID_NS_SREG)
|| alias.equals(IdentityConstants.OpenId.SimpleRegAttributes.NS_SREG_1)) {
return new OpenIDSimpleReg(auth);
} else if (alias.equals(PapeMessage.OPENID_NS_PAPE)) {
return new OpenIDPape(auth);
}
return null;
}
} |
3e1df370285fa03c285c41ce1fa11409ffb72a93 | 544 | java | Java | reformcloud2-executor-api/src/main/java/systems/reformcloud/reformcloud2/executor/api/common/restapi/HttpOperation.java | zLvkas/reformcloud2 | 9142f6806fce926e613a8c259d5831ada74e9bde | [
"Apache-2.0"
] | null | null | null | reformcloud2-executor-api/src/main/java/systems/reformcloud/reformcloud2/executor/api/common/restapi/HttpOperation.java | zLvkas/reformcloud2 | 9142f6806fce926e613a8c259d5831ada74e9bde | [
"Apache-2.0"
] | null | null | null | reformcloud2-executor-api/src/main/java/systems/reformcloud/reformcloud2/executor/api/common/restapi/HttpOperation.java | zLvkas/reformcloud2 | 9142f6806fce926e613a8c259d5831ada74e9bde | [
"Apache-2.0"
] | null | null | null | 19.428571 | 88 | 0.681985 | 12,675 | package systems.reformcloud.reformcloud2.executor.api.common.restapi;
import systems.reformcloud.reformcloud2.executor.api.common.utility.operation.Operation;
import java.util.UUID;
public final class HttpOperation implements Operation {
private boolean done = false;
private final UUID uuid = UUID.randomUUID();
@Override
public UUID identifier() {
return uuid;
}
@Override
public boolean isDone() {
return done;
}
@Override
public void complete() {
done = true;
}
}
|
3e1df4d4a43304e11130a7772697eb611c3de224 | 4,927 | java | Java | hazelcast/src/main/java/org/apache/karaf/cellar/hazelcast/TopicConsumer.java | jbonofre/karaf-cellar | 9f266d22b4397b70b55a759a59027641be9d1d0e | [
"MIT"
] | 32 | 2015-01-07T00:48:00.000Z | 2021-11-09T22:31:18.000Z | hazelcast/src/main/java/org/apache/karaf/cellar/hazelcast/TopicConsumer.java | jbonofre/karaf-cellar | 9f266d22b4397b70b55a759a59027641be9d1d0e | [
"MIT"
] | 37 | 2015-01-15T21:15:16.000Z | 2020-07-10T05:09:58.000Z | hazelcast/src/main/java/org/apache/karaf/cellar/hazelcast/TopicConsumer.java | jbonofre/karaf-cellar | 9f266d22b4397b70b55a759a59027641be9d1d0e | [
"MIT"
] | 65 | 2015-01-14T11:34:24.000Z | 2022-03-24T14:43:37.000Z | 29.680723 | 166 | 0.657601 | 12,676 | /*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.karaf.cellar.hazelcast;
import com.hazelcast.core.HazelcastInstance;
import com.hazelcast.core.ITopic;
import com.hazelcast.core.Message;
import com.hazelcast.core.MessageListener;
import org.apache.karaf.cellar.core.Configurations;
import org.apache.karaf.cellar.core.Dispatcher;
import org.apache.karaf.cellar.core.Node;
import org.apache.karaf.cellar.core.control.BasicSwitch;
import org.apache.karaf.cellar.core.control.Switch;
import org.apache.karaf.cellar.core.control.SwitchStatus;
import org.apache.karaf.cellar.core.event.Event;
import org.apache.karaf.cellar.core.event.EventConsumer;
import org.osgi.service.cm.Configuration;
import org.osgi.service.cm.ConfigurationAdmin;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Consumes messages from the Hazelcast {@code ITopic} and calls the {@code EventDispatcher}.
*/
public class TopicConsumer<E extends Event> implements EventConsumer<E>, MessageListener<E> {
private static final transient Logger LOGGER = LoggerFactory.getLogger(TopicConsumer.class);
public static final String SWITCH_ID = "org.apache.karaf.cellar.topic.consumer";
private final Switch eventSwitch = new BasicSwitch(SWITCH_ID);
private String registrationId;
private HazelcastInstance instance;
private ITopic topic;
private Dispatcher dispatcher;
private Node node;
private ConfigurationAdmin configurationAdmin;
private boolean isConsuming;
public void init() {
if (topic == null) {
topic = instance.getTopic(Constants.TOPIC);
}
start();
}
public void destroy() {
stop();
}
@Override
public void consume(E event) {
// check if event has a specified destination.
if ((event.getDestination() == null || event.getDestination().contains(node)) && (this.getSwitch().getStatus().equals(SwitchStatus.ON) || event.getForce())) {
dispatcher.dispatch(event);
} else {
if (eventSwitch.getStatus().equals(SwitchStatus.OFF)) {
LOGGER.debug("CELLAR HAZELCAST: {} switch is OFF, cluster event is not consumed", SWITCH_ID);
}
}
}
@Override
public void start() {
isConsuming = true;
if (topic != null) {
registrationId = topic.addMessageListener(this);
} else {
topic = instance.getTopic(Constants.TOPIC);
registrationId = topic.addMessageListener(this);
}
}
@Override
public void stop() {
isConsuming = false;
if (topic != null) {
topic.removeMessageListener(registrationId);
}
}
@Override
public Boolean isConsuming() {
return isConsuming;
}
@Override
public void onMessage(Message<E> message) {
consume(message.getMessageObject());
}
public Dispatcher getDispatcher() {
return dispatcher;
}
public void setDispatcher(Dispatcher dispatcher) {
this.dispatcher = dispatcher;
}
public HazelcastInstance getInstance() {
return instance;
}
public void setInstance(HazelcastInstance instance) {
this.instance = instance;
}
public ITopic getTopic() {
return topic;
}
public void setTopic(ITopic topic) {
this.topic = topic;
}
@Override
public Switch getSwitch() {
// load the switch status from the config
try {
Configuration configuration = configurationAdmin.getConfiguration(Configurations.NODE, null);
if (configuration != null) {
Boolean status = new Boolean((String) configuration.getProperties().get(Configurations.CONSUMER));
if (status) {
eventSwitch.turnOn();
} else {
eventSwitch.turnOff();
}
}
} catch (Exception e) {
// ignore
}
return eventSwitch;
}
public Node getNode() {
return node;
}
public void setNode(Node node) {
this.node = node;
}
public ConfigurationAdmin getConfigurationAdmin() {
return configurationAdmin;
}
public void setConfigurationAdmin(ConfigurationAdmin configurationAdmin) {
this.configurationAdmin = configurationAdmin;
}
}
|
3e1df502f722de0eb9196bc469ab2ac0c424d608 | 1,063 | java | Java | optaplanner-examples/src/main/java/org/optaplanner/examples/common/domain/PersistableIdComparator.java | JimTyrrell/optaplanner | b47b870d217827751bf5d2f26e98aa28aec29b8d | [
"Apache-2.0"
] | 2 | 2018-11-21T14:31:33.000Z | 2019-01-15T10:20:28.000Z | optaplanner-examples/src/main/java/org/optaplanner/examples/common/domain/PersistableIdComparator.java | JimTyrrell/optaplanner | b47b870d217827751bf5d2f26e98aa28aec29b8d | [
"Apache-2.0"
] | 20 | 2018-09-28T07:27:13.000Z | 2018-12-13T15:08:26.000Z | optaplanner-examples/src/main/java/org/optaplanner/examples/common/domain/PersistableIdComparator.java | JimTyrrell/optaplanner | b47b870d217827751bf5d2f26e98aa28aec29b8d | [
"Apache-2.0"
] | 1 | 2018-10-15T12:17:26.000Z | 2018-10-15T12:17:26.000Z | 33.21875 | 95 | 0.751646 | 12,677 | /*
* Copyright 2010 Red Hat, Inc. and/or its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.optaplanner.examples.common.domain;
import java.io.Serializable;
import java.util.Comparator;
import org.apache.commons.lang3.builder.CompareToBuilder;
public class PersistableIdComparator implements Comparator<AbstractPersistable>, Serializable {
@Override
public int compare(AbstractPersistable a, AbstractPersistable b) {
return new CompareToBuilder().append(a.getId(), b.getId()).toComparison();
}
}
|
3e1df603bc4673f52ab81147e599dbdefeb29b4e | 10,518 | java | Java | ivr/kookoo/src/test/java/org/motechproject/ivr/kookoo/web/KookooIvrControllerTest.java | jkondrat/modules | 48ab2e098464bc734440bbb5fb9aacc05400cd28 | [
"BSD-3-Clause"
] | null | null | null | ivr/kookoo/src/test/java/org/motechproject/ivr/kookoo/web/KookooIvrControllerTest.java | jkondrat/modules | 48ab2e098464bc734440bbb5fb9aacc05400cd28 | [
"BSD-3-Clause"
] | null | null | null | ivr/kookoo/src/test/java/org/motechproject/ivr/kookoo/web/KookooIvrControllerTest.java | jkondrat/modules | 48ab2e098464bc734440bbb5fb9aacc05400cd28 | [
"BSD-3-Clause"
] | null | null | null | 42.072 | 135 | 0.703936 | 12,678 | package org.motechproject.ivr.kookoo.web;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.motechproject.callflow.domain.FlowSessionRecord;
import org.motechproject.callflow.domain.IvrEvent;
import org.motechproject.callflow.service.CallFlowServer;
import org.motechproject.callflow.service.FlowSessionService;
import org.motechproject.decisiontree.model.FlowSession;
import org.motechproject.decisiontree.model.DialStatus;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.web.servlet.ModelAndView;
import static junit.framework.Assert.assertEquals;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.mockito.MockitoAnnotations.initMocks;
public class KookooIvrControllerTest {
private KookooIvrController kookooIvrController;
@Mock
private CallFlowServer callFlowServer;
@Mock
private FlowSessionService flowSessionService;
@Before
public void setup() {
initMocks(this);
kookooIvrController = new KookooIvrController(callFlowServer, flowSessionService);
}
@Test
public void shouldRenderKookooNodeRespone() {
MockHttpServletRequest request = new MockHttpServletRequest();
request.setParameter("sid", "123a");
request.setParameter("cid", "1234567890");
request.setParameter("tree", "sometree");
request.setParameter("ln", "en");
FlowSession flowSession = new FlowSessionRecord("123a", "1234567890");
when(flowSessionService.findOrCreate("123a", "1234567890")).thenReturn(flowSession);
ModelAndView view = new ModelAndView();
when(callFlowServer.getResponse("123a", "1234567890", "kookoo", "sometree", null, "en")).thenReturn(view);
assertEquals(view, kookooIvrController.ivrCallback(request, new MockHttpServletResponse()));
}
@Test
public void shouldPopulateSessionFields() {
MockHttpServletRequest request = new MockHttpServletRequest();
request.setParameter("sid", "123a");
request.setParameter("cid", "1234567890");
request.setParameter("tree", "sometree");
request.setParameter("ln", "en");
request.setParameter("foo", "bar");
FlowSession flowSession = new FlowSessionRecord("123a", "1234567890");
when(flowSessionService.findOrCreate("123a", "1234567890")).thenReturn(flowSession);
ModelAndView view = new ModelAndView();
when(callFlowServer.getResponse("123a", "1234567890", "kookoo", "sometree", null, "en")).thenReturn(view);
kookooIvrController.ivrCallback(request, new MockHttpServletResponse());
FlowSessionRecord session = new FlowSessionRecord("123a", "1234567890");
session.setLanguage("en");
session.set("foo", "bar");
verify(flowSessionService).updateSession(session);
}
@Test
public void shouldCreateSessionWithKookooSidForIncomingCallback() {
MockHttpServletRequest request = new MockHttpServletRequest();
request.setParameter("sid", "123a");
request.setParameter("cid", "1234567890");
request.setParameter("tree", "sometree");
request.setParameter("ln", "en");
FlowSession flowSession = new FlowSessionRecord("123a", "1234567890");
when(flowSessionService.findOrCreate("123a", "1234567890")).thenReturn(flowSession);
ModelAndView view = new ModelAndView();
when(callFlowServer.getResponse("123a", "1234567890", "kookoo", "sometree", null, "en")).thenReturn(view);
kookooIvrController.ivrCallback(request, new MockHttpServletResponse());
verify(flowSessionService).findOrCreate("123a", "1234567890");
}
@Test
public void shouldUpdateSessionWithKookooSidForOutgoingCallback() {
MockHttpServletRequest request = new MockHttpServletRequest();
request.setParameter("motech_call_id", "123a");
request.setParameter("sid", "456b");
request.setParameter("cid", "1234567890");
request.setParameter("tree", "sometree");
request.setParameter("ln", "en");
FlowSession flowSession = new FlowSessionRecord("123a", "1234567890");
when(flowSessionService.getSession("123a")).thenReturn(flowSession);
FlowSession newFlowSession = new FlowSessionRecord("456b", "1234567890");
when(flowSessionService.updateSessionId("123a", "456b")).thenReturn(newFlowSession);
ModelAndView view = new ModelAndView();
when(callFlowServer.getResponse("456b", "1234567890", "kookoo", "sometree", null, "en")).thenReturn(view);
kookooIvrController.ivrCallback(request, new MockHttpServletResponse());
verify(flowSessionService).updateSession(newFlowSession);
}
@Test
public void shouldRaiseCallInitiatedEvent() {
FlowSession flowSession = new FlowSessionRecord("123a", "1234567890");
when(flowSessionService.findOrCreate("123a", "1234567890")).thenReturn(flowSession);
ModelAndView view = new ModelAndView();
when(callFlowServer.getResponse("123a", "1234567890", "kookoo", null, null, null)).thenReturn(view);
MockHttpServletRequest request = new MockHttpServletRequest();
request.setParameter("sid", "123a");
request.setParameter("cid", "1234567890");
request.setParameter("event", "NewCall");
kookooIvrController.ivrCallback(request, new MockHttpServletResponse());
verify(callFlowServer).raiseCallEvent(IvrEvent.Initiated, "123a");
}
@Test
public void shouldRaiseCallAnsweredEvent() {
MockHttpServletRequest request = new MockHttpServletRequest();
request.setParameter("sid", "123a");
request.setParameter("status", "answered");
request.setParameter("status_details", "Normal");
kookooIvrController.handleStatus(request);
verify(callFlowServer).raiseCallEvent(IvrEvent.Answered, "123a");
}
@Test
public void shouldRaiseCallUnansweredEvent() {
MockHttpServletRequest request = new MockHttpServletRequest();
request.setParameter("sid", "123a");
request.setParameter("status", "ring");
request.setParameter("status_details", "NoAnswer");
kookooIvrController.handleStatus(request);
verify(callFlowServer).raiseCallEvent(IvrEvent.Unanswered, "123a");
}
@Test
public void shouldRaiseHangupEvent() {
FlowSession flowSession = new FlowSessionRecord("123a", "1234567890");
when(flowSessionService.findOrCreate("123a", "1234567890")).thenReturn(flowSession);
ModelAndView view = new ModelAndView();
when(callFlowServer.getResponse("123a", "1234567890", "kookoo", null, "Hangup", null)).thenReturn(view);
MockHttpServletRequest request = new MockHttpServletRequest();
request.setParameter("sid", "123a");
request.setParameter("cid", "1234567890");
request.setParameter("event", "Hangup");
kookooIvrController.ivrCallback(request, new MockHttpServletResponse());
verify(callFlowServer).raiseCallEvent(IvrEvent.Hangup, "123a");
}
@Test
public void shouldRaiseDisconnectEvent() {
FlowSession flowSession = new FlowSessionRecord("123a", "1234567890");
when(flowSessionService.findOrCreate("123a", "1234567890")).thenReturn(flowSession);
ModelAndView view = new ModelAndView();
when(callFlowServer.getResponse("123a", "1234567890", "kookoo", null, "Disconnect", null)).thenReturn(view);
MockHttpServletRequest request = new MockHttpServletRequest();
request.setParameter("sid", "123a");
request.setParameter("cid", "1234567890");
request.setParameter("event", "Disconnect");
kookooIvrController.ivrCallback(request, new MockHttpServletResponse());
verify(callFlowServer).raiseCallEvent(IvrEvent.Disconnected, "123a");
}
@Test
public void shouldRaiseCallAnsweredEventForConnectCalls() {
FlowSession flowSession = new FlowSessionRecord("123a", "1234567890");
when(flowSessionService.findOrCreate("123a", "1234567890")).thenReturn(flowSession);
ModelAndView view = new ModelAndView();
when(callFlowServer.getResponse("123a", "1234567890", "kookoo", null, DialStatus.completed.toString(), null)).thenReturn(view);
MockHttpServletRequest request = new MockHttpServletRequest();
request.setParameter("sid", "123a");
request.setParameter("cid", "1234567890");
request.setParameter("event", "Dial");
request.setParameter("status", "answered");
kookooIvrController.ivrCallback(request, new MockHttpServletResponse());
verify(callFlowServer).raiseCallEvent(IvrEvent.DialAnswered, "123a");
}
@Test
public void shouldRaiseCallUnAnsweredEventForConnectCalls() {
FlowSession flowSession = new FlowSessionRecord("123a", "1234567890");
when(flowSessionService.findOrCreate("123a", "1234567890")).thenReturn(flowSession);
ModelAndView view = new ModelAndView();
when(callFlowServer.getResponse("123a", "1234567890", "kookoo", null, DialStatus.noAnswer.toString(), null)).thenReturn(view);
MockHttpServletRequest request = new MockHttpServletRequest();
request.setParameter("sid", "123a");
request.setParameter("cid", "1234567890");
request.setParameter("event", "Dial");
request.setParameter("status", "not_answered");
kookooIvrController.ivrCallback(request, new MockHttpServletResponse());
verify(callFlowServer).raiseCallEvent(IvrEvent.DialUnanswered, "123a");
}
@Test
public void shouldRaiseCallRecordEvent() {
FlowSession flowSession = new FlowSessionRecord("123a", "1234567890");
when(flowSessionService.findOrCreate("123a", "1234567890")).thenReturn(flowSession);
ModelAndView view = new ModelAndView();
when(callFlowServer.getResponse("123a", "1234567890", "kookoo", null, null, null)).thenReturn(view);
MockHttpServletRequest request = new MockHttpServletRequest();
request.setParameter("sid", "123a");
request.setParameter("cid", "1234567890");
request.setParameter("event", "Record");
kookooIvrController.ivrCallback(request, new MockHttpServletResponse());
verify(callFlowServer).raiseCallEvent(IvrEvent.DialRecord, "123a");
}
}
|
3e1df626aafda2a1964a66ba4bf85276e6047cab | 1,515 | java | Java | src/com/mauriciotogneri/betfair/models/Wallet.java | vndly/betfair | 4720f910d47ef2d4c6ab44c4b1a04c2bac8099e2 | [
"MIT"
] | 3 | 2015-08-07T04:33:52.000Z | 2019-11-06T16:02:39.000Z | src/com/mauriciotogneri/betfair/models/Wallet.java | vndly/betfair | 4720f910d47ef2d4c6ab44c4b1a04c2bac8099e2 | [
"MIT"
] | null | null | null | src/com/mauriciotogneri/betfair/models/Wallet.java | vndly/betfair | 4720f910d47ef2d4c6ab44c4b1a04c2bac8099e2 | [
"MIT"
] | null | null | null | 24.836066 | 133 | 0.630363 | 12,679 | package com.mauriciotogneri.betfair.models;
import com.mauriciotogneri.betfair.logs.WalletLog;
import java.io.IOException;
public class Wallet
{
private double balance = 0;
private static Wallet instance = null;
public enum Type
{
WITHDRAW, //
DEPOSIT, //
FAIL
}
private static final double DEFAULT_BALANCE = 50.00;
private Wallet(double balance) throws IOException
{
this.balance = balance;
}
public static synchronized Wallet getInstance() throws IOException
{
if (instance == null)
{
instance = new Wallet(DEFAULT_BALANCE);
}
return instance;
}
public synchronized boolean withdraw(Budget budget, String eventId, String marketId, String player) throws IOException
{
if (balance >= budget.getRequested())
{
balance -= budget.getRequested();
WalletLog.log(Type.WITHDRAW, budget.getId(), eventId, marketId, player, budget.getRequested(), balance);
return true;
}
else
{
WalletLog.log(Type.FAIL, budget.getId(), eventId, marketId, player, budget.getRequested(), balance);
}
return false;
}
public synchronized void deposit(Budget budget, String eventId, String marketId, String player, double profit) throws IOException
{
balance += profit;
WalletLog.log(Type.DEPOSIT, budget.getId(), eventId, marketId, player, profit, balance);
}
} |
3e1df63f67cd7efe3e2bcfafea42513ca8d12dcb | 571 | java | Java | Lecture-2/src/com/codingblocks/Reverse.java | doshirishabh26/Crux-Noida-2018-Aug-Evening | 5c84bf97875bfd8ff2b89cbd5e12c2123cee0649 | [
"Apache-2.0"
] | 12 | 2018-08-28T13:31:38.000Z | 2021-03-27T13:06:13.000Z | Lecture-2/src/com/codingblocks/Reverse.java | samikshaw4/Crux-Noida-2018-Aug-Evening | a392bb80bf59ecc2b218b4f1c00b00d40246a484 | [
"Apache-2.0"
] | null | null | null | Lecture-2/src/com/codingblocks/Reverse.java | samikshaw4/Crux-Noida-2018-Aug-Evening | a392bb80bf59ecc2b218b4f1c00b00d40246a484 | [
"Apache-2.0"
] | 14 | 2018-08-27T14:47:20.000Z | 2021-03-27T13:06:15.000Z | 18.419355 | 49 | 0.464098 | 12,680 | package com.codingblocks;
import java.util.Scanner;
public class Reverse {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int num = scanner.nextInt();
int result = 0;
int counter = 0;
while (num > 0){
int rem = num % 10;
num = num / 10;
// to count no. of 5
if (rem == 5){
counter++;
}
// to reverse
result = result * 10 + rem;
}
System.out.println(result);
}
}
|
3e1df684206ac2c736e03b363a8e0b32524a3681 | 5,867 | java | Java | delta-app/src/main/java/io/cdap/delta/store/DBReplicationStateStore.java | data-integrations/delta | ffc03a0e48e79b60ac62c46b0ac10c93a27511e9 | [
"Apache-2.0"
] | 4 | 2020-04-14T19:28:45.000Z | 2022-03-05T09:12:44.000Z | delta-app/src/main/java/io/cdap/delta/store/DBReplicationStateStore.java | data-integrations/delta | ffc03a0e48e79b60ac62c46b0ac10c93a27511e9 | [
"Apache-2.0"
] | 65 | 2020-01-23T23:45:30.000Z | 2022-02-07T19:24:00.000Z | delta-app/src/main/java/io/cdap/delta/store/DBReplicationStateStore.java | data-integrations/delta | ffc03a0e48e79b60ac62c46b0ac10c93a27511e9 | [
"Apache-2.0"
] | 2 | 2021-06-29T09:31:42.000Z | 2022-03-23T20:57:34.000Z | 41.609929 | 119 | 0.73547 | 12,681 | /*
* Copyright © 2021 Cask Data, 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 io.cdap.delta.store;
import io.cdap.cdap.api.dataset.lib.CloseableIterator;
import io.cdap.cdap.spi.data.StructuredRow;
import io.cdap.cdap.spi.data.StructuredTable;
import io.cdap.cdap.spi.data.StructuredTableContext;
import io.cdap.cdap.spi.data.TableNotFoundException;
import io.cdap.cdap.spi.data.table.StructuredTableId;
import io.cdap.cdap.spi.data.table.StructuredTableSpecification;
import io.cdap.cdap.spi.data.table.field.Field;
import io.cdap.cdap.spi.data.table.field.FieldType;
import io.cdap.cdap.spi.data.table.field.Fields;
import io.cdap.cdap.spi.data.table.field.Range;
import io.cdap.delta.app.DeltaWorkerId;
import org.apache.commons.lang.StringUtils;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Optional;
/**
* A StructuredTable based database table to store generic replicator states.
*/
public class DBReplicationStateStore {
private static final StructuredTableId TABLE_ID = new StructuredTableId("delta_state_store");
private static final String NAMESPACE_COL = "namespace";
private static final String APP_GENERATION_COL = "app_generation";
private static final String APPNAME_COL = "app_name";
private static final String INSTANCEID_COL = "instance_id";
private static final String STATE_COL = "state";
private static final String VALUE_COL = "value";
private static final String UPDATED_COL = "last_updated";
public static final StructuredTableSpecification TABLE_SPEC = new StructuredTableSpecification.Builder()
.withId(TABLE_ID)
.withFields(new FieldType(NAMESPACE_COL, FieldType.Type.STRING),
new FieldType(APP_GENERATION_COL, FieldType.Type.LONG),
new FieldType(APPNAME_COL, FieldType.Type.STRING),
new FieldType(INSTANCEID_COL, FieldType.Type.INTEGER),
new FieldType(STATE_COL, FieldType.Type.STRING),
new FieldType(VALUE_COL, FieldType.Type.BYTES),
new FieldType(UPDATED_COL, FieldType.Type.LONG))
.withPrimaryKeys(NAMESPACE_COL, APPNAME_COL, APP_GENERATION_COL, INSTANCEID_COL, STATE_COL)
.build();
private final StructuredTable table;
private DBReplicationStateStore(StructuredTable table) {
this.table = table;
}
static DBReplicationStateStore get(StructuredTableContext context) {
try {
StructuredTable table = context.getTable(TABLE_ID);
return new DBReplicationStateStore(table);
} catch (TableNotFoundException e) {
throw new IllegalStateException(String.format(
"System table '%s' does not exist. Please check your system environment.", TABLE_ID.getName()), e);
}
}
public byte[] getStateData(DeltaWorkerId id, String state)
throws IOException {
List<Field<?>> keys = getKey(id, state);
Optional<StructuredRow> row = table.read(keys);
if (!row.isPresent() || row.get().getBytes(VALUE_COL) == null) {
return new byte[0];
}
return row.get().getBytes(VALUE_COL);
}
public void writeStateData(DeltaWorkerId id, String state, byte[] data) throws IOException {
Collection<Field<?>> fields = getKey(id, state);
fields.add(Fields.bytesField(VALUE_COL, data));
fields.add(Fields.longField(UPDATED_COL, System.currentTimeMillis()));
table.upsert(fields);
}
public Long getLatestGeneration(String namespace, String appName) throws IOException {
List<Field<?>> prefix = new ArrayList<>(2);
prefix.add(Fields.stringField(NAMESPACE_COL, namespace));
prefix.add(Fields.stringField(APPNAME_COL, appName));
Range range = Range.singleton(prefix);
long maxGeneration = -1L;
try (CloseableIterator<StructuredRow> rowIter = table.scan(range, Integer.MAX_VALUE)) {
while (rowIter.hasNext()) {
long gen = rowIter.next().getLong(APP_GENERATION_COL);
maxGeneration = Math.max(gen, maxGeneration);
}
}
return maxGeneration;
}
public Collection<Integer> getWorkerInstances(String namespace, String appName, Long generation) throws IOException {
List<Field<?>> prefix = new ArrayList<>(3);
prefix.add(Fields.stringField(NAMESPACE_COL, namespace));
prefix.add(Fields.stringField(APPNAME_COL, appName));
prefix.add(Fields.longField(APP_GENERATION_COL, generation));
Range range = Range.singleton(prefix);
HashSet<Integer> instancesSet = new HashSet<>();
try (CloseableIterator<StructuredRow> rowIter = table.scan(range, Integer.MAX_VALUE)) {
while (rowIter.hasNext()) {
instancesSet.add(rowIter.next().getInteger(INSTANCEID_COL));
}
}
List<Integer> workerInstances = new ArrayList<>(instancesSet);
return workerInstances;
}
private List<Field<?>> getKey(DeltaWorkerId id, String state) {
List<Field<?>> keyFields = new ArrayList<>(5);
keyFields.add(Fields.stringField(NAMESPACE_COL, id.getPipelineId().getNamespace()));
keyFields.add(Fields.stringField(APPNAME_COL, id.getPipelineId().getApp()));
keyFields.add(Fields.longField(APP_GENERATION_COL, id.getPipelineId().getGeneration()));
keyFields.add(Fields.intField(INSTANCEID_COL, id.getInstanceId()));
keyFields.add(Fields.stringField(STATE_COL, state));
return keyFields;
}
}
|
3e1df6e4ff5013220a4de69fee5ceb6ff255927b | 1,329 | java | Java | src/main/java/ru/r2cloud/jradio/blocks/GfskModulator.java | dernasherbrezon/jradio | ec86db80ab6b36b6222bb0d3978abba89f555ac4 | [
"Apache-2.0"
] | 40 | 2017-04-11T06:25:22.000Z | 2022-03-24T17:44:20.000Z | src/main/java/ru/r2cloud/jradio/blocks/GfskModulator.java | dernasherbrezon/jradio | ec86db80ab6b36b6222bb0d3978abba89f555ac4 | [
"Apache-2.0"
] | 6 | 2019-01-24T13:53:53.000Z | 2021-04-26T16:54:33.000Z | src/main/java/ru/r2cloud/jradio/blocks/GfskModulator.java | dernasherbrezon/jradio | ec86db80ab6b36b6222bb0d3978abba89f555ac4 | [
"Apache-2.0"
] | 10 | 2017-04-11T06:25:26.000Z | 2022-02-05T16:50:44.000Z | 28.276596 | 101 | 0.739654 | 12,682 | package ru.r2cloud.jradio.blocks;
import java.io.IOException;
import java.util.Arrays;
import ru.r2cloud.jradio.ByteInput;
import ru.r2cloud.jradio.Context;
import ru.r2cloud.jradio.FloatInput;
import ru.r2cloud.jradio.util.MathUtils;
public class GfskModulator implements FloatInput {
private final FloatInput input;
public GfskModulator(ByteInput source, float samplesPerSymbol, float sensitivity, float bt) {
if (samplesPerSymbol < 2) {
throw new IllegalArgumentException("samples per symbol should be >= 2. Got: " + samplesPerSymbol);
}
int ntaps = (int) (4 * samplesPerSymbol);
ByteInput next = source;
FloatInput fnext = new ChunksToSymbols(next, new float[] { -1, 1 });
float[] gaussianTaps = Firdes.gaussian(1.0f, samplesPerSymbol, bt, ntaps);
float[] sqwave = new float[(int) samplesPerSymbol];
Arrays.fill(sqwave, 1);
float[] taps = MathUtils.convolve(gaussianTaps, sqwave);
fnext = new InterpFIRFilter(fnext, (int) samplesPerSymbol, taps);
fnext = new FrequencyModulator(fnext, sensitivity);
this.input = new MultiplyConst(fnext, 0.999f);
}
@Override
public void close() throws IOException {
input.close();
}
@Override
public float readFloat() throws IOException {
return input.readFloat();
}
@Override
public Context getContext() {
return input.getContext();
}
}
|
3e1df706cd88d7413b19fdbcc84aee20988fd093 | 1,648 | java | Java | CSipSimple/src/com/csipsimple/widgets/contactbadge/ContactBadge3.java | dmfr/CSipSimple-mirror | f2f2b8efcb739090a45b205690a0fb5b74bce343 | [
"OpenSSL",
"Unlicense"
] | 4 | 2016-09-29T00:04:31.000Z | 2021-12-02T08:39:51.000Z | CSipSimple/src/com/csipsimple/widgets/contactbadge/ContactBadge3.java | dmfr/CSipSimple-mirror | f2f2b8efcb739090a45b205690a0fb5b74bce343 | [
"OpenSSL",
"Unlicense"
] | null | null | null | CSipSimple/src/com/csipsimple/widgets/contactbadge/ContactBadge3.java | dmfr/CSipSimple-mirror | f2f2b8efcb739090a45b205690a0fb5b74bce343 | [
"OpenSSL",
"Unlicense"
] | null | null | null | 32.313725 | 79 | 0.725121 | 12,683 | /**
* Copyright (C) 2010-2012 Regis Montoya (aka r3gis - www.r3gis.fr)
* This file is part of CSipSimple.
*
* CSipSimple is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* If you own a pjsip commercial license you can also redistribute it
* and/or modify it under the terms of the GNU Lesser General Public License
* as an android library.
*
* CSipSimple is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with CSipSimple. If not, see <http://www.gnu.org/licenses/>.
*/
package com.csipsimple.widgets.contactbadge;
import android.content.Context;
import android.net.Uri;
import android.util.AttributeSet;
import android.widget.ImageView;
public class ContactBadge3 extends ContactBadgeContract {
private OverlayedImageView imageView;
public ContactBadge3(Context context, AttributeSet attrs, int defStyle,
QuickContactBadge topBadge) {
super(context, attrs, defStyle, topBadge);
imageView = new OverlayedImageView(context, attrs, defStyle, topBadge);
}
@Override
public ImageView getImageView() {
return imageView;
}
@Override
public void assignContactUri(Uri uri) {
// Nothing to do
}
}
|
3e1df7a08af71a4e36e9ae404f180c387e165c46 | 17,321 | java | Java | projects/java/cdm/src/mil/tatrc/physiology/datamodel/substance/SESubstance.java | timhoer/core | f3af359ecdb88b8b8e3b976fa11c3075e0ca7c11 | [
"Apache-2.0"
] | null | null | null | projects/java/cdm/src/mil/tatrc/physiology/datamodel/substance/SESubstance.java | timhoer/core | f3af359ecdb88b8b8e3b976fa11c3075e0ca7c11 | [
"Apache-2.0"
] | null | null | null | projects/java/cdm/src/mil/tatrc/physiology/datamodel/substance/SESubstance.java | timhoer/core | f3af359ecdb88b8b8e3b976fa11c3075e0ca7c11 | [
"Apache-2.0"
] | null | null | null | 36.697034 | 149 | 0.728884 | 12,684 | /**************************************************************************************
Copyright 2015 Applied Research Associates, 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 mil.tatrc.physiology.datamodel.substance;
import java.util.*;
import mil.tatrc.physiology.datamodel.CDMSerializer;
import mil.tatrc.physiology.datamodel.bind.*;
import mil.tatrc.physiology.datamodel.properties.*;
import mil.tatrc.physiology.utilities.StringUtils;
public class SESubstance
{
protected EnumSubstanceState state;
protected EnumSubstanceClass subClass;
protected String name;
protected SEScalarMassPerVolume density;
protected SEScalarMassPerAmount molarMass;
// Diffusion related-ish
protected SEScalarMassPerAreaTime maximumDiffusionFlux;
protected SEScalar michaelisCoefficient;
protected SEScalarElectricResistance membraneResistance;
// Liquid related-ish
protected SESubstanceAerosolization aerosolization;
protected SEScalarMassPerVolume bloodConcentration;
protected SEScalarMass massInBody;
protected SEScalarMass massInBlood;
protected SEScalarMass massInTissue;
protected SEScalarMassPerVolume plasmaConcentration;
protected SEScalarMassPerVolume effectSiteConcentration;
protected SEScalarMass systemicMassCleared;
protected SEScalarMassPerVolume tissueConcentration;
// Gas related-ish
protected SEScalarVolumePerTime alveolarTransfer;
protected SEScalarVolumePerTimePressure diffusingCapacity;
protected SEScalarFraction endTidalFraction;
protected SEScalarPressure endTidalPressure;
protected SEScalar relativeDiffusionCoefficient;
protected SEScalarInversePressure solubilityCoefficient;
protected SESubstanceClearance clearance;
protected SESubstancePharmacokinetics pk;
protected SESubstancePharmacodynamics pd;
public SESubstance()
{
}
public void reset()
{
this.name=null;
this.subClass=null;
this.state=null;
if(this.density!=null)
this.density.invalidate();
if(this.molarMass!=null)
this.molarMass.invalidate();
if(this.maximumDiffusionFlux!=null)
this.maximumDiffusionFlux.invalidate();
if(this.michaelisCoefficient!=null)
this.michaelisCoefficient.invalidate();
if(this.membraneResistance!=null)
this.membraneResistance.invalidate();
if(this.aerosolization!=null)
this.aerosolization.reset();
if(this.bloodConcentration!=null)
this.bloodConcentration.invalidate();
if(this.massInBody!=null)
this.massInBody.invalidate();
if(this.massInBlood!=null)
this.massInBlood.invalidate();
if(this.massInTissue!=null)
this.massInTissue.invalidate();
if(this.plasmaConcentration!=null)
this.plasmaConcentration.invalidate();
if(this.effectSiteConcentration!=null)
this.effectSiteConcentration.invalidate();
if(this.systemicMassCleared!=null)
this.systemicMassCleared.invalidate();
if(this.tissueConcentration!=null)
this.tissueConcentration.invalidate();
if(this.alveolarTransfer!=null)
this.alveolarTransfer.invalidate();
if(this.diffusingCapacity!=null)
this.diffusingCapacity.invalidate();
if(this.endTidalFraction!=null)
this.endTidalFraction.invalidate();
if(this.endTidalPressure!=null)
this.endTidalPressure.invalidate();
if(this.relativeDiffusionCoefficient!=null)
this.relativeDiffusionCoefficient.invalidate();
if(this.solubilityCoefficient!=null)
this.solubilityCoefficient.invalidate();
if(this.clearance!=null)
this.clearance.reset();
if(this.pk!=null)
this.pk.reset();
if(this.pd!=null)
this.pd.reset();
}
public boolean load(SubstanceData data)
{
this.reset();
if(data.getName()!=null)
this.setName(data.getName());
if(data.getState()!=null)
this.setState(data.getState());
if(data.getClassification()!=null)
this.setSubClass(data.getClassification());
if(data.getDensity()!=null)
this.getDensity().load(data.getDensity());
if(data.getMolarMass()!=null)
this.getMolarMass().load(data.getMolarMass());
if(data.getMaximumDiffusionFlux()!=null)
this.getMaximumDiffusionFlux().load(data.getMaximumDiffusionFlux());
if(data.getMichaelisCoefficient()!=null)
this.getMichaelisCoefficient().load(data.getMolarMass());
if(data.getMembraneResistance()!=null)
this.getMembraneResistance().load(data.getMembraneResistance());
if(data.getAerosolization()!=null)
this.getAerosolization().load(data.getAerosolization());
if(data.getBloodConcentration()!=null)
this.getBloodConcentration().load(data.getBloodConcentration());
if(data.getMassInBody()!=null)
this.getMassInBody().load(data.getMassInBody());
if(data.getMassInBlood()!=null)
this.getMassInBlood().load(data.getMassInBlood());
if(data.getMassInTissue()!=null)
this.getMassInTissue().load(data.getMassInTissue());
if(data.getPlasmaConcentration()!=null)
this.getPlasmaConcentration().load(data.getPlasmaConcentration());
if(data.getEffectSiteConcentration()!=null)
this.getEffectSiteConcentration().load(data.getEffectSiteConcentration());
if(data.getSystemicMassCleared()!=null)
this.getSystemicMassCleared().load(data.getSystemicMassCleared());
if(data.getTissueConcentration()!=null)
this.getTissueConcentration().load(data.getTissueConcentration());
if(data.getAlveolarTransfer()!=null)
this.getAlveolarTransfer().load(data.getAlveolarTransfer());
if(data.getDiffusingCapacity()!=null)
this.getDiffusingCapacity().load(data.getDiffusingCapacity());
if(data.getEndTidalFraction()!=null)
this.getEndTidalFraction().load(data.getEndTidalFraction());
if(data.getEndTidalPressure()!=null)
this.getEndTidalPressure().load(data.getEndTidalPressure());
if(data.getRelativeDiffusionCoefficient()!=null)
this.getRelativeDiffusionCoefficient().load(data.getRelativeDiffusionCoefficient());
if(data.getSolubilityCoefficient()!=null)
this.getSolubilityCoefficient().load(data.getSolubilityCoefficient());
if(data.getClearance()!=null)
this.getClearance().load(data.getClearance());
if(data.getPharmacokinetics()!=null)
this.getPK().load(data.getPharmacokinetics());
if(data.getPharmacodynamics()!=null)
this.getPD().load(data.getPharmacodynamics());
return true;
}
public SubstanceData unload()
{
SubstanceData to = CDMSerializer.objFactory.createSubstanceData();
unload(to);
return to;
}
protected void unload(SubstanceData to)
{
if(hasName())
to.setName(this.name);
if(hasState())
to.setState(this.state);
if(hasSubClass())
to.setClassification(this.subClass);
if(hasDensity())
to.setDensity(this.density.unload());
if(hasMolarMass())
to.setMolarMass(this.molarMass.unload());
if(hasMaximumDiffusionFlux())
to.setMaximumDiffusionFlux(this.maximumDiffusionFlux.unload());
if(hasMichaelisCoefficient())
to.setMichaelisCoefficient(this.michaelisCoefficient.unload());
if(hasMembraneResistance())
to.setMembraneResistance(this.membraneResistance.unload());
if(hasAerosolization())
to.setAerosolization(this.aerosolization.unload());
if(hasBloodConcentration())
to.setBloodConcentration(this.bloodConcentration.unload());
if(hasMassInBody())
to.setMassInBody(this.massInBody.unload());
if(hasMassInBlood())
to.setMassInBlood(this.massInBlood.unload());
if(hasMassInTissue())
to.setMassInTissue(this.massInTissue.unload());
if(hasPlasmaConcentration())
to.setPlasmaConcentration(this.plasmaConcentration.unload());
if(hasEffectSiteConcentration())
to.setEffectSiteConcentration(this.effectSiteConcentration.unload());
if(hasSystemicMassCleared())
to.setSystemicMassCleared(this.systemicMassCleared.unload());
if(hasTissueConcentration())
to.setTissueConcentration(this.tissueConcentration.unload());
if(hasAlveolarTransfer())
to.setAlveolarTransfer(this.alveolarTransfer.unload());
if(hasDiffusingCapacity())
to.setDiffusingCapacity(this.diffusingCapacity.unload());
if(hasEndTidalFraction())
to.setEndTidalFraction(this.endTidalFraction.unload());
if(hasEndTidalPressure())
to.setEndTidalPressure(this.endTidalPressure.unload());
if(hasRelativeDiffusionCoefficient())
to.setRelativeDiffusionCoefficient(this.relativeDiffusionCoefficient.unload());
if(hasSolubilityCoefficient())
to.setSolubilityCoefficient(this.solubilityCoefficient.unload());
if(hasClearance())
to.setClearance(this.clearance.unload());
if(hasPK())
to.setPharmacokinetics(this.pk.unload());
if(hasPD())
to.setPharmacodynamics(this.pd.unload());
}
public String getName() { return this.name;}
public void setName(String name){this.name=name;}
public boolean hasName(){return StringUtils.exists(this.name);}
public EnumSubstanceState getState() { return this.state;}
public void setState(EnumSubstanceState state){this.state=state;}
public boolean hasState(){return this.state==null?false:true;}
public EnumSubstanceClass getSubClass() { return this.subClass;}
public void setSubClass(EnumSubstanceClass subClass){this.subClass=subClass;}
public boolean hasSubClass() {return this.subClass==null?false:true;}
public SEScalarMassPerVolume getDensity()
{
if(this.density==null)
this.density=new SEScalarMassPerVolume();
return this.density;
}
public boolean hasDensity() {return this.density==null?false:this.density.isValid();}
public SEScalarMassPerAmount getMolarMass()
{
if(this.molarMass==null)
this.molarMass=new SEScalarMassPerAmount();
return this.molarMass;
}
public boolean hasMolarMass() {return this.molarMass==null?false:this.molarMass.isValid();}
////////////////
// Diffusion-ish //
////////////////
public SEScalarMassPerAreaTime getMaximumDiffusionFlux()
{
if(this.maximumDiffusionFlux==null)
this.maximumDiffusionFlux=new SEScalarMassPerAreaTime();
return this.maximumDiffusionFlux;
}
public boolean hasMaximumDiffusionFlux() {return this.maximumDiffusionFlux==null?false:this.maximumDiffusionFlux.isValid();}
public SEScalar getMichaelisCoefficient()
{
if(this.michaelisCoefficient==null)
this.michaelisCoefficient=new SEScalar();
return this.michaelisCoefficient;
}
public boolean hasMichaelisCoefficient() {return this.michaelisCoefficient==null?false:this.michaelisCoefficient.isValid();}
public SEScalarElectricResistance getMembraneResistance()
{
if(this.membraneResistance==null)
this.membraneResistance=new SEScalarElectricResistance();
return this.membraneResistance;
}
public boolean hasMembraneResistance() {return this.membraneResistance==null?false:this.membraneResistance.isValid();}
////////////////
// Liquid-ish //
////////////////
public SESubstanceAerosolization getAerosolization()
{
if(this.aerosolization==null)
this.aerosolization = new SESubstanceAerosolization();
return this.aerosolization;
}
public boolean hasAerosolization() { return this.aerosolization!=null; }
public void removeAerosolization() { this.aerosolization = null; }
public SEScalarMassPerVolume getBloodConcentration()
{
if(this.bloodConcentration==null)
this.bloodConcentration=new SEScalarMassPerVolume();
return this.bloodConcentration;
}
public boolean hasBloodConcentration() {return this.bloodConcentration==null?false:this.bloodConcentration.isValid();}
public SEScalarMass getMassInBody()
{
if(this.massInBody==null)
this.massInBody=new SEScalarMass();
return this.massInBody;
}
public boolean hasMassInBody() {return this.massInBody==null?false:this.massInBody.isValid();}
public SEScalarMass getMassInBlood()
{
if(this.massInBlood==null)
this.massInBlood=new SEScalarMass();
return this.massInBlood;
}
public boolean hasMassInBlood() {return this.massInBlood==null?false:this.massInBlood.isValid();}
public SEScalarMass getMassInTissue()
{
if(this.massInTissue==null)
this.massInTissue=new SEScalarMass();
return this.massInTissue;
}
public boolean hasMassInTissue() {return this.massInTissue==null?false:this.massInTissue.isValid();}
public SEScalarMassPerVolume getPlasmaConcentration()
{
if(this.plasmaConcentration==null)
this.plasmaConcentration=new SEScalarMassPerVolume();
return this.plasmaConcentration;
}
public boolean hasPlasmaConcentration() {return this.plasmaConcentration==null?false:this.plasmaConcentration.isValid();}
public SEScalarMassPerVolume getEffectSiteConcentration()
{
if(this.effectSiteConcentration==null)
this.effectSiteConcentration=new SEScalarMassPerVolume();
return this.effectSiteConcentration;
}
public boolean hasEffectSiteConcentration() {return this.effectSiteConcentration==null?false:this.effectSiteConcentration.isValid();}
public SEScalarMass getSystemicMassCleared()
{
if(this.systemicMassCleared==null)
this.systemicMassCleared=new SEScalarMass();
return this.systemicMassCleared;
}
public boolean hasSystemicMassCleared() {return this.systemicMassCleared==null?false:this.systemicMassCleared.isValid();}
public SEScalarMassPerVolume getTissueConcentration()
{
if(this.tissueConcentration==null)
this.tissueConcentration=new SEScalarMassPerVolume();
return this.tissueConcentration;
}
public boolean hasTissueConcentration() {return this.tissueConcentration==null?false:this.tissueConcentration.isValid();}
/////////////
// Gas-ish //
/////////////
public SEScalarVolumePerTime getAlveolarTransfer()
{
if(this.alveolarTransfer==null)
this.alveolarTransfer=new SEScalarVolumePerTime();
return this.alveolarTransfer;
}
public boolean hasAlveolarTransfer() {return this.alveolarTransfer==null?false:this.alveolarTransfer.isValid();}
public SEScalarVolumePerTimePressure getDiffusingCapacity()
{
if(this.diffusingCapacity==null)
this.diffusingCapacity=new SEScalarVolumePerTimePressure();
return this.diffusingCapacity;
}
public boolean hasDiffusingCapacity() {return this.diffusingCapacity==null?false:this.diffusingCapacity.isValid();}
public SEScalarFraction getEndTidalFraction()
{
if(this.endTidalFraction==null)
this.endTidalFraction=new SEScalarFraction();
return this.endTidalFraction;
}
public boolean hasEndTidalFraction() {return this.endTidalFraction==null?false:this.endTidalFraction.isValid();}
public SEScalarPressure getEndTidalPressure()
{
if(this.endTidalPressure==null)
this.endTidalPressure=new SEScalarPressure();
return this.endTidalPressure;
}
public boolean hasEndTidalPressure() {return this.endTidalPressure==null?false:this.endTidalPressure.isValid();}
public SEScalarInversePressure getSolubilityCoefficient()
{
if(this.solubilityCoefficient==null)
this.solubilityCoefficient=new SEScalarInversePressure();
return this.solubilityCoefficient;
}
public boolean hasSolubilityCoefficient() {return this.solubilityCoefficient==null?false:this.solubilityCoefficient.isValid();}
public SEScalar getRelativeDiffusionCoefficient()
{
if(this.relativeDiffusionCoefficient==null)
this.relativeDiffusionCoefficient=new SEScalar();
return this.relativeDiffusionCoefficient;
}
public boolean hasRelativeDiffusionCoefficient() {return this.relativeDiffusionCoefficient==null?false:this.relativeDiffusionCoefficient.isValid();}
///////////////
// Clearance //
///////////////
public SESubstanceClearance getClearance()
{
if(this.clearance==null)
this.clearance = new SESubstanceClearance();
return this.clearance;
}
public boolean hasClearance() { return this.clearance!=null; }
public void removeClearance() { this.clearance = null; }
///////////
// PK/PD //
///////////
public SESubstancePharmacokinetics getPK()
{
if(this.pk==null)
this.pk = new SESubstancePharmacokinetics();
return this.pk;
}
public boolean hasPK() { return this.pk!=null; }
public void removePK() { this.pk = null; }
public SESubstancePharmacodynamics getPD()
{
if(this.pd==null)
this.pd = new SESubstancePharmacodynamics();
return this.pd;
}
public boolean hasPD() { return this.pd!=null; }
public void removePD() { this.pd = null; }
}
|
3e1df91cb331f82828b425290c88eda20a88efe6 | 1,753 | java | Java | jgiven-testng/src/test/java/com/tngtech/jgiven/testng/PendingTest.java | Hatzen/JGiven | 07bfdfd15ee60466e22bb9669b0e61f7463cf391 | [
"Apache-2.0"
] | 381 | 2015-01-08T06:46:25.000Z | 2022-03-25T06:39:10.000Z | jgiven-testng/src/test/java/com/tngtech/jgiven/testng/PendingTest.java | Hatzen/JGiven | 07bfdfd15ee60466e22bb9669b0e61f7463cf391 | [
"Apache-2.0"
] | 437 | 2015-01-08T07:47:18.000Z | 2022-03-03T06:09:45.000Z | jgiven-testng/src/test/java/com/tngtech/jgiven/testng/PendingTest.java | Hatzen/JGiven | 07bfdfd15ee60466e22bb9669b0e61f7463cf391 | [
"Apache-2.0"
] | 120 | 2015-01-29T19:47:02.000Z | 2022-03-28T08:22:17.000Z | 34.372549 | 97 | 0.741586 | 12,685 | package com.tngtech.jgiven.testng;
import static org.assertj.core.api.Assertions.assertThat;
import com.tngtech.jgiven.annotation.Pending;
import com.tngtech.jgiven.report.model.ExecutionStatus;
import org.assertj.core.api.Assertions;
import org.testng.SkipException;
import org.testng.annotations.Test;
import com.tngtech.jgiven.annotation.Description;
import com.tngtech.jgiven.report.model.ScenarioCaseModel;
import com.tngtech.jgiven.report.model.StepStatus;
@Description( "Pending annotation is handled correctly" )
public class PendingTest extends SimpleScenarioTest<TestNgTest.TestSteps> {
@Test
@Pending
public void pending_annotation_should_catch_exceptions() {
given().something();
when().something_fails();
then().nothing_happens();
ScenarioCaseModel aCase = getScenario().getScenarioCaseModel();
assertThat( aCase.getExecutionStatus() ).isEqualTo( ExecutionStatus.SCENARIO_PENDING );
}
@Test
@Pending(executeSteps = true)
public void pending_annotation_should_catch_exceptions_when_executing_steps() {
given().something();
when().something_fails();
then().nothing_happens();
ScenarioCaseModel aCase = getScenario().getScenarioCaseModel();
assertThat( aCase.getExecutionStatus() ).isEqualTo( ExecutionStatus.SCENARIO_PENDING );
}
@Test
public void pending_annotation_on_failing_steps_should_catch_exceptions() {
given().something();
when().something_fails_with_pending_annotation();
then().nothing_happens();
ScenarioCaseModel aCase = getScenario().getScenarioCaseModel();
assertThat( aCase.getExecutionStatus() ).isEqualTo( ExecutionStatus.SOME_STEPS_PENDING );
}
}
|
3e1df924ef3fe46a3d38ff94c5911154bb3f0780 | 788 | java | Java | hypersistence-optimizer-spring-hibernate-example/src/main/java/io/hypersistence/optimizer/forum/dao/TagDAOImpl.java | Diffblue-benchmarks/hypersistence-optimizer | af89bf619e69e9e3ee3c854922ef0652c190ed0f | [
"Apache-2.0"
] | 203 | 2019-03-16T18:26:37.000Z | 2022-03-30T18:45:42.000Z | hypersistence-optimizer-spring-hibernate-example/src/main/java/io/hypersistence/optimizer/forum/dao/TagDAOImpl.java | Diffblue-benchmarks/hypersistence-optimizer | af89bf619e69e9e3ee3c854922ef0652c190ed0f | [
"Apache-2.0"
] | 158 | 2019-03-19T19:21:16.000Z | 2022-03-31T18:56:05.000Z | hypersistence-optimizer-spring-hibernate-example/src/main/java/io/hypersistence/optimizer/forum/dao/TagDAOImpl.java | Diffblue-benchmarks/hypersistence-optimizer | af89bf619e69e9e3ee3c854922ef0652c190ed0f | [
"Apache-2.0"
] | 27 | 2019-03-18T01:32:38.000Z | 2021-11-30T10:44:04.000Z | 24.625 | 85 | 0.634518 | 12,686 | package io.hypersistence.optimizer.forum.dao;
import io.hypersistence.optimizer.forum.domain.Tag;
import org.springframework.stereotype.Repository;
import java.util.Arrays;
import java.util.List;
/**
* @author Vlad Mihalcea
*/
@Repository
public class TagDAOImpl extends GenericDAOImpl<Tag, Long> implements TagDAO {
protected TagDAOImpl() {
super(Tag.class);
}
@Override
public List<Tag> findByName(String... tags) {
if(tags.length == 0) {
throw new IllegalArgumentException("There's no tag name to search for!");
}
return getSession().createQuery(
"select t " +
"from Tag t " +
"where t.name in :tags")
.setParameterList("tags", Arrays.asList(tags))
.list();
}
}
|
3e1df9385c26923dd1bf8c5e846ac95a6277b718 | 2,261 | java | Java | aljebra/src/test/java/com/aljebra/field/impl/doubles/DblVectTest.java | andreoss/jeometry | 89add5a14a252c86672e63fe242a994fa1eb4a07 | [
"MIT"
] | 26 | 2017-07-01T20:43:05.000Z | 2022-01-08T08:57:03.000Z | aljebra/src/test/java/com/aljebra/field/impl/doubles/DblVectTest.java | andreoss/jeometry | 89add5a14a252c86672e63fe242a994fa1eb4a07 | [
"MIT"
] | 193 | 2016-03-30T15:52:00.000Z | 2021-05-27T09:00:14.000Z | aljebra/src/test/java/com/aljebra/field/impl/doubles/DblVectTest.java | andreoss/jeometry | 89add5a14a252c86672e63fe242a994fa1eb4a07 | [
"MIT"
] | 10 | 2016-04-01T19:19:16.000Z | 2021-06-28T13:38:58.000Z | 35.888889 | 79 | 0.662096 | 12,687 | /*
* The MIT License (MIT)
*
* Copyright (c) 2016-2020, Hamdi Douss
*
* 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.aljebra.field.impl.doubles;
import com.aljebra.scalar.Scalar;
import java.util.Arrays;
import org.hamcrest.MatcherAssert;
import org.hamcrest.Matchers;
import org.junit.Test;
/**
* Tests for {@link DblVect}.
* @since 0.1
*/
public final class DblVectTest {
/**
* DblVect returns right coordinates.
*/
@Test
public void returnsCoordinates() {
final double coora = Math.random();
final double coorb = Math.random();
final double coorc = Math.random();
final double coord = Math.random();
final double coore = Math.random();
final DblVect vect = new DblVect(coora, coorb, coorc, coord, coore);
MatcherAssert.assertThat(
Arrays.asList(vect.coords()),
Matchers.equalTo(
Arrays.asList(
new Scalar.Default<>(coora),
new Scalar.Default<>(coorb),
new Scalar.Default<>(coorc),
new Scalar.Default<>(coord),
new Scalar.Default<>(coore)
)
)
);
}
}
|
3e1df957d4c26a1492088567a0b1873c5f24c985 | 1,813 | java | Java | src/main/java/datastructure/tree/TreeNode.java | nsnikhil/Thoughtworks | 8282331346bcf22fecebfc1570da62688425888e | [
"Apache-2.0"
] | null | null | null | src/main/java/datastructure/tree/TreeNode.java | nsnikhil/Thoughtworks | 8282331346bcf22fecebfc1570da62688425888e | [
"Apache-2.0"
] | null | null | null | src/main/java/datastructure/tree/TreeNode.java | nsnikhil/Thoughtworks | 8282331346bcf22fecebfc1570da62688425888e | [
"Apache-2.0"
] | null | null | null | 25.180556 | 89 | 0.617761 | 12,688 | /*
* Copyright 2017 nsnikhil
*
* 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 datastructure.tree;
import java.util.List;
/**
* Tree is a recursive data structure
* No of edge = no of node - 1
* Depth of a node = length of path from root to that node(x) = No of edge from root to x
* Height of node = no of edges in longest path from that node(x) to leaf node
* Height of tree = Height of root node
*
* @param <T>
*/
class TreeNode<T> {
private T mData;
private List<TreeNode<T>> mLinks;
/**
* @param data the data part of a node
* @param links the list of child nodes of a node
*/
TreeNode(final T data, final List<TreeNode<T>> links) {
this.mData = data;
this.mLinks = links;
}
/**
* @return the data of node
*/
public T getData() {
return mData;
}
/**
* @param data the data to be set at node
*/
public void setData(T data) {
this.mData = data;
}
/**
* @return all the child nodes of a node
*/
public List<TreeNode<T>> getLinks() {
return mLinks;
}
/**
* @param links the child list for a node
*/
public void setLinks(List<TreeNode<T>> links) {
this.mLinks = links;
}
}
|
3e1df9ae8d90999c5c4248fc9d9d440103bd6daa | 24,121 | java | Java | Platform/Apple/tools/jace/src/main/java/jace/hardware/PassportMidiInterface.java | peterferrie/lawless-legends | 55735c9be31c8d1b3d146d9e0129733efade7786 | [
"Apache-2.0"
] | 51 | 2015-03-16T20:27:53.000Z | 2022-03-17T17:08:41.000Z | Platform/Apple/tools/jace/src/main/java/jace/hardware/PassportMidiInterface.java | peterferrie/lawless-legends | 55735c9be31c8d1b3d146d9e0129733efade7786 | [
"Apache-2.0"
] | 33 | 2015-05-22T18:29:28.000Z | 2021-12-21T02:24:00.000Z | Platform/Apple/tools/jace/src/main/java/jace/hardware/PassportMidiInterface.java | peterferrie/lawless-legends | 55735c9be31c8d1b3d146d9e0129733efade7786 | [
"Apache-2.0"
] | 11 | 2016-01-09T07:28:36.000Z | 2021-04-12T15:36:59.000Z | 40.427136 | 137 | 0.537642 | 12,689 | /*
* Copyright (C) 2012 Brendan Robert (BLuRry) dycjh@example.com.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301 USA
*/
package jace.hardware;
import jace.config.ConfigurableField;
import jace.config.DynamicSelection;
import jace.config.Name;
import jace.core.Card;
import jace.core.Computer;
import jace.core.RAMEvent;
import jace.core.RAMEvent.TYPE;
import java.util.LinkedHashMap;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.sound.midi.InvalidMidiDataException;
import javax.sound.midi.MidiDevice;
import javax.sound.midi.MidiSystem;
import javax.sound.midi.MidiUnavailableException;
import javax.sound.midi.Receiver;
import javax.sound.midi.ShortMessage;
import javax.sound.midi.Synthesizer;
/**
* Partial implementation of Passport midi card, supporting midi output routed
* to the java midi synth for playback. Compatible with Ultima V. Card
* operational notes taken from the Passport MIDI interface manual
* ftp://ftp.apple.asimov.net/pub/apple_II/documentation/hardware/misc/passport_midi.pdf
*
* @author Brendan Robert (BLuRry) dycjh@example.com
*/
@Name(value = "Passport Midi Interface", description = "MIDI sound card")
public class PassportMidiInterface extends Card {
private Receiver midiOut;
public PassportMidiInterface(Computer computer) {
super(computer);
}
@Override
protected void handleC8FirmwareAccess(int register, TYPE type, int value, RAMEvent e) {
// There is no rom on this card, so nothing to do here
}
// MIDI timing: 31250 BPS, 8-N-1 (roughly 3472k per second)
public static enum TIMER_MODE {
CONTINUOUS, SINGLE_SHOT, FREQ_COMPARISON, PULSE_COMPARISON
};
@ConfigurableField(name = "Midi Output Device", description = "Midi output device")
public static DynamicSelection<String> preferredMidiDevice = new DynamicSelection<String>(null) {
@Override
public boolean allowNull() {
return false;
}
@Override
public LinkedHashMap<? extends String, String> getSelections() {
LinkedHashMap<String, String> out = new LinkedHashMap<>();
MidiDevice.Info[] devices = MidiSystem.getMidiDeviceInfo();
for (MidiDevice.Info dev : devices) {
try {
MidiDevice device = MidiSystem.getMidiDevice(dev);
if (device.getMaxReceivers() > 0 || dev instanceof Synthesizer)
System.out.println("MIDI Device found: " + dev);
out.put(dev.getName(), dev.getName());
} catch (MidiUnavailableException ex) {
Logger.getLogger(PassportMidiInterface.class.getName()).log(Level.SEVERE, null, ex);
}
}
return out;
}
};
public static class PTMTimer {
// Configuration values
public boolean prescaledTimer = false; // Only available on Timer 3
public boolean enableClock = false; // False == use CX clock input
public boolean dual8BitMode = false;
public TIMER_MODE mode = TIMER_MODE.CONTINUOUS;
public boolean irqEnabled = false;
public boolean counterOutputEnable = false;
// Set by data latches
public Long duration = 0L;
// Run values
public boolean irqRequested = true;
public Long value = 0L;
}
// I/O registers
// --- 6840 PTM
public static final int TIMER_CONTROL_1 = 0;
public static final int TIMER_CONTROL_2 = 1;
public static final int TIMER1_MSB = 2;
public static final int TIMER1_LSB = 3;
public static final int TIMER2_MSB = 4;
public static final int TIMER2_LSB = 5;
// (Most likely not used)
public static final int TIMER3_MSB = 6;
public static final int TIMER3_LSB = 7;
// --- 6850 ACIA registers (write)
public static final int ACIA_CONTROL = 8;
public static final int ACIA_SEND = 9;
// --- 6850 ACIA registers (read)
public static final int ACIA_STATUS = 8;
public static final int ACIA_RECV = 9;
// --- Drums
public static final int DRUM_SYNC_SET = 0x0e;
public static final int DRUM_SYNC_CLEAR = 0x0f;
//---------------------------------------------------------
// PTM control values (register 1,2 and 3)
public static final int PTM_START_TIMERS = 0;
public static final int PTM_STOP_TIMERS = 1;
public static final int PTM_RESET = 67;
// PTM select values (register 2 only) -- modifies what Reg 1 points to
public static final int PTM_SELECT_REG_1 = 1;
public static final int PTM_SELECT_REG_3 = 0;
// PTM select values (register 3 only)
public static final int TIMER3_PRESCALED = 1;
public static final int TIMER3_NOT_PRESCALED = 0;
// PTM bit values
public static final int PTM_CLOCK_SOURCE = 2; // Bit 1
// 0 = external, 2 = internal clock
public static final int PTM_LATCH_IS_16BIT = 4; // Bit 2
// 0 = 16-bit, 4 = dual 8-bit
// Bits 3-5
// 5 4 3
public static final int PTM_CONTINUOUS = 0; // 0 x 0
public static final int PTM_SINGLE_SHOT = 32; // 1 x 0
public static final int PTM_FREQ_COMP = 8; // x 0 1
public static final int PTM_PULSE_COMP = 24; // x 1 1
public static final int PTM_IRQ_ENABLED = 64; // Bit 6
// 64 = IRQ Enabled, 0 = IRQ Masked
public static final int PTM_OUTPUT_ENABLED = 128; // Bit 7
// 128 = Timer output enabled, 0 = disabled
// ACIA control values
// Reset == Master reset + even parity + 2 stop bits + 8 bit + No interrupts (??)
public static final int ACIA_RESET = 19;
public static final int ACIA_MASK_INTERRUPTS = 17;
public static final int ACIA_OFF = 21;
// Counter * 1 + RTS = low, transmit interrupt enabled
public static final int ACIA_INT_ON_SEND = 49;
// Counter * 1 + RTS = high, transmit interrupt disabled + Interrupt on receive
public static final int ACIA_INT_ON_RECV = 145;
// Counter * 1 + RTS = low, transmit interrupt enabled + Interrupt on receive
public static final int ACIA_INT_ON_SEND_AND_RECV = 177;
// ACIA control register values
// --- Bits 1 and 0 control counter divide select
public static final int ACIA_COUNTER_1 = 0;
public static final int ACIA_COUNTER_16 = 1;
public static final int ACIA_COUNTER_64 = 2;
public static final int ACIA_MASTER_RESET = 3;
// Midi is always transmitted 8-N-1
public static final int ACIA_ODD_PARITY = 4; // 4 = odd, 0 = even
public static final int ACIA_STOP_BITS_1 = 8; // 8 = 1 stop bit, 0 = 2 stop bits
public static final int ACIA_WORD_LENGTH_8 = 16; // 16 = 8-bit, 0 = 7-bit
// --- Bits 5 and 6 control interrupts
// 6 5
// 0 0 RTS = low, transmit interrupt disabled
// 0 1 RTS = low, transmit interrupt enabled
// 1 0 RTS = high, transmit interrupt disabled
// 1 1 RTS = low, Transmit break, trasmit interrupt disabled
public static final int ACIA_RECV_INTERRUPT = 128; // 128 = interrupt on receive, 0 = no interrupt
// PTM configuration
private boolean ptmTimer3Selected = false; // When true, reg 1 points at timer 3
private boolean ptmTimersActive = false; // When true, timers run constantly
private final PTMTimer[] ptmTimer = {
new PTMTimer(),
new PTMTimer(),
new PTMTimer()
};
private boolean ptmStatusReadSinceIRQ = false;
// ---------------------- ACIA CONFIGURATION
private final boolean aciaInterruptOnSend = false;
private final boolean aciaInterruptOnReceive = false;
// ---------------------- ACIA STATUS BITS
// True when MIDI IN receives a byte
private final boolean receivedACIAByte = false;
// True when data is not transmitting (always true because we aren't really doing wire transmission);
private final boolean transmitACIAEmpty = true;
// True if another byte is received before the previous byte was processed
private final boolean receiverACIAOverrun = false;
// True if ACIA generated interrupt request
private final boolean irqRequestedACIA = false;
@Override
public void reset() {
// TODO: Deactivate card
suspend();
}
@Override
public boolean suspend() {
// TODO: Deactivate card
suspendACIA();
return super.suspend();
}
@Override
protected void handleFirmwareAccess(int register, TYPE type, int value, RAMEvent e) {
// No firmware, so do nothing
}
@Override
protected void handleIOAccess(int register, TYPE type, int value, RAMEvent e) {
switch (type) {
case READ_DATA:
int returnValue = 0;
switch (register) {
case ACIA_STATUS:
returnValue = getACIAStatus();
break;
case ACIA_RECV:
returnValue = getACIARecieve();
break;
//TODO: Implement PTM registers
case TIMER_CONTROL_1:
// Technically it's not supposed to return anything...
returnValue = getPTMStatus();
break;
case TIMER_CONTROL_2:
returnValue = getPTMStatus();
break;
case TIMER1_LSB:
returnValue = (int) (ptmTimer[0].value & 0x0ff);
if (ptmStatusReadSinceIRQ) {
ptmTimer[0].irqRequested = false;
}
break;
case TIMER1_MSB:
returnValue = (int) (ptmTimer[0].value >> 8) & 0x0ff;
if (ptmStatusReadSinceIRQ) {
ptmTimer[0].irqRequested = false;
}
break;
case TIMER2_LSB:
returnValue = (int) (ptmTimer[1].value & 0x0ff);
if (ptmStatusReadSinceIRQ) {
ptmTimer[1].irqRequested = false;
}
break;
case TIMER2_MSB:
returnValue = (int) (ptmTimer[1].value >> 8) & 0x0ff;
if (ptmStatusReadSinceIRQ) {
ptmTimer[1].irqRequested = false;
}
break;
case TIMER3_LSB:
returnValue = (int) (ptmTimer[2].value & 0x0ff);
if (ptmStatusReadSinceIRQ) {
ptmTimer[2].irqRequested = false;
}
break;
case TIMER3_MSB:
returnValue = (int) (ptmTimer[2].value >> 8) & 0x0ff;
if (ptmStatusReadSinceIRQ) {
ptmTimer[2].irqRequested = false;
}
break;
default:
System.out.println("Passport midi read unrecognized, port " + register);
}
e.setNewValue(returnValue);
// System.out.println("Passport I/O read register " + register + " == " + returnValue);
break;
case WRITE:
int v = e.getNewValue() & 0x0ff;
// System.out.println("Passport I/O write register " + register + " == " + v);
switch (register) {
case ACIA_CONTROL:
processACIAControl(v);
break;
case ACIA_SEND:
processACIASend(v);
break;
case TIMER_CONTROL_1:
if (ptmTimer3Selected) {
// System.out.println("Configuring timer 3");
ptmTimer[2].prescaledTimer = ((v & TIMER3_PRESCALED) != 0);
processPTMConfiguration(ptmTimer[2], v);
} else {
// System.out.println("Configuring timer 1");
if ((v & PTM_STOP_TIMERS) == 0) {
startPTM();
} else {
stopPTM();
}
processPTMConfiguration(ptmTimer[0], v);
}
break;
case TIMER_CONTROL_2:
// System.out.println("Configuring timer 2");
ptmTimer3Selected = ((v & PTM_SELECT_REG_1) == 0);
processPTMConfiguration(ptmTimer[1], v);
break;
case TIMER1_LSB:
ptmTimer[0].duration = (ptmTimer[0].duration & 0x0ff00) | v;
break;
case TIMER1_MSB:
ptmTimer[0].duration = (ptmTimer[0].duration & 0x0ff) | (v << 8);
break;
case TIMER2_LSB:
ptmTimer[1].duration = (ptmTimer[1].duration & 0x0ff00) | v;
break;
case TIMER2_MSB:
ptmTimer[1].duration = (ptmTimer[1].duration & 0x0ff) | (v << 8);
break;
case TIMER3_LSB:
ptmTimer[2].duration = (ptmTimer[2].duration & 0x0ff00) | v;
break;
case TIMER3_MSB:
ptmTimer[2].duration = (ptmTimer[2].duration & 0x0ff00) | (v << 8);
break;
default:
System.out.println("Passport midi write unrecognized, port " + register);
}
break;
}
}
@Override
public void tick() {
if (ptmTimersActive) {
for (PTMTimer t : ptmTimer) {
// if (t.duration == 0) {
// continue;
// }
t.value--;
if (t.value < 0) {
// TODO: interrupt dual 8-bit mode, whatver that is!
if (t.irqEnabled) {
// System.out.println("Timer generating interrupt!");
t.irqRequested = true;
computer.getCpu().generateInterrupt();
ptmStatusReadSinceIRQ = false;
}
if (t.mode == TIMER_MODE.CONTINUOUS || t.mode == TIMER_MODE.FREQ_COMPARISON) {
t.value = t.duration;
}
}
}
}
}
@Override
public String getDeviceName() {
return "Passport MIDI Controller";
}
//------------------------------------------------------ PTM
private void processPTMConfiguration(PTMTimer timer, int val) {
timer.enableClock = (val & PTM_CLOCK_SOURCE) != 0;
timer.dual8BitMode = (val & PTM_LATCH_IS_16BIT) != 0;
switch (val & 56) {
// Evaluate bits 3, 4 and 5 to determine mode
case PTM_CONTINUOUS:
timer.mode = TIMER_MODE.CONTINUOUS;
break;
case PTM_PULSE_COMP:
timer.mode = TIMER_MODE.PULSE_COMPARISON;
break;
case PTM_FREQ_COMP:
timer.mode = TIMER_MODE.FREQ_COMPARISON;
break;
case PTM_SINGLE_SHOT:
timer.mode = TIMER_MODE.SINGLE_SHOT;
break;
default:
timer.mode = TIMER_MODE.CONTINUOUS;
break;
}
timer.irqEnabled = (val & PTM_IRQ_ENABLED) != 0;
timer.counterOutputEnable = (val & PTM_OUTPUT_ENABLED) != 0;
}
private void stopPTM() {
// System.out.println("Passport timers halted");
ptmTimersActive = false;
}
private void startPTM() {
// System.out.println("Passport timers started");
ptmTimersActive = true;
ptmTimer[0].irqRequested = false;
ptmTimer[1].irqRequested = false;
ptmTimer[2].irqRequested = false;
ptmTimer[0].value = ptmTimer[0].duration;
ptmTimer[1].value = ptmTimer[1].duration;
ptmTimer[2].value = ptmTimer[2].duration;
}
// Bits 0, 1 and 2 == IRQ requested from timer 1, 2 or 3
// Bit 7 = Any IRQ
private int getPTMStatus() {
int status = 0;
for (int i = 0; i < 3; i++) {
PTMTimer t = ptmTimer[i];
if (t.irqRequested && t.irqEnabled) {
ptmStatusReadSinceIRQ = true;
status |= (1 << i);
status |= 128;
}
}
return status;
}
//------------------------------------------------------ ACIA
/*
ACIA status register
Bit 0 = Receive data register full
Bit 1 = Transmit data register empty
Bits 2 and 3 pertain to modem (DCD and CTS, so ignore)
Bit 4 = Framing error
Bit 5 = Receiver overrun
Bit 6 = Partity error (not used by MIDI)
Bit 7 = Interrupt request
*/
private int getACIAStatus() {
int status = 0;
if (receivedACIAByte) {
status |= 1;
}
if (transmitACIAEmpty) {
status |= 2;
}
if (receiverACIAOverrun) {
status |= 32;
}
if (irqRequestedACIA) {
status |= 128;
}
return status;
}
// TODO: Implement MIDI IN... some day
private int getACIARecieve() {
return 0;
}
private void processACIAControl(int value) {
if ((value & 0x03) == ACIA_MASTER_RESET) {
resume();
}
}
ShortMessage currentMessage;
int currentMessageStatus;
int currentMessageData1;
int currentMessageData2;
int messageSize = 255;
int currentMessageReceived = 0;
private void processACIASend(int value) {
if (!isRunning()) {
// System.err.println("ACIA not active!");
return;
} else {
// System.out.println("ACIA send "+value);
}
// First off try to finish off previous command already in play
boolean sendMessage = false;
if (currentMessage != null) {
if ((value & 0x080) > 0) {
// Any command byte received means we finished receiving another command
// and valid or not, process it as-is
if (currentMessage != null) {
sendMessage = true;
}
// If there is no current message, then we'll pick this up afterwards...
} else {
// If we receive a data byte ( < 128 ) then check if we have the right size
// if so, then the command was completely received, and it's time to send it.
currentMessageReceived++;
if (currentMessageReceived >= messageSize) {
sendMessage = true;
}
if (currentMessageReceived == 1) {
currentMessageData1 = value;
} else {
// Possibly redundant, but there's no reason a message should be longer than this...
currentMessageData2 = value;
sendMessage = true;
}
}
}
// If we have a command to send, then do it
if (sendMessage == true) {
if (midiOut != null) {
// Send message
try {
// System.out.println("Sending MIDI message "+currentMessageStatus+","+currentMessageData1+","+currentMessageData2);
currentMessage.setMessage(currentMessageStatus, currentMessageData1, currentMessageData2);
midiOut.send(currentMessage, -1L);
} catch (InvalidMidiDataException ex) {
Logger.getLogger(PassportMidiInterface.class.getName()).log(Level.SEVERE, null, ex);
}
}
currentMessage = null;
}
// Do we have a new command byte?
if ((value & 0x080) > 0) {
// Start a new message
currentMessage = new ShortMessage();
currentMessageStatus = value;
currentMessageData1 = 0;
currentMessageData2 = 0;
try {
currentMessage.setMessage(currentMessageStatus, 0, 0);
messageSize = currentMessage.getLength();
} catch (InvalidMidiDataException ex) {
messageSize = 0;
}
currentMessageReceived = 0;
}
}
@Override
public void resume() {
if (isRunning() && midiOut != null) {
return;
}
try {
MidiDevice selectedDevice = MidiSystem.getSynthesizer();
MidiDevice.Info[] devices = MidiSystem.getMidiDeviceInfo();
if (devices.length == 0) {
System.out.println("No MIDI devices found");
} else {
for (MidiDevice.Info dev : devices) {
if (MidiSystem.getMidiDevice(dev).getMaxReceivers() == 0) {
continue;
}
System.out.println("MIDI Device found: " + dev);
if ((preferredMidiDevice.getValue() == null && dev.getName().contains("Java Sound") && dev instanceof Synthesizer) ||
preferredMidiDevice.getValue().equalsIgnoreCase(dev.getName())
) {
selectedDevice = MidiSystem.getMidiDevice(dev);
break;
}
}
}
if (selectedDevice != null) {
System.out.println("Selected MIDI device: " + selectedDevice.getDeviceInfo().getName());
selectedDevice.open();
midiOut = selectedDevice.getReceiver();
super.resume();
}
} catch (MidiUnavailableException ex) {
System.out.println("Could not open MIDI synthesizer");
Logger.getLogger(PassportMidiInterface.class.getName()).log(Level.SEVERE, null, ex);
}
}
private void suspendACIA() {
// TODO: Stop ACIA thread...
if (midiOut != null) {
currentMessage = new ShortMessage();
// Send a note-off on every channel
for (int channel = 0; channel < 16; channel++) {
try {
// All Notes Off
currentMessage.setMessage(0x0B0 | channel, 123, 0);
midiOut.send(currentMessage, 0);
// All Oscillators Off
currentMessage.setMessage(0x0B0 | channel, 120, 0);
midiOut.send(currentMessage, 0);
} catch (InvalidMidiDataException ex) {
Logger.getLogger(PassportMidiInterface.class.getName()).log(Level.SEVERE, null, ex);
}
}
midiOut.close();
midiOut = null;
}
}
}
|
3e1dfa8036133d9c84cf69a69ae1864e0c4be347 | 8,837 | java | Java | src/main/java/edu/drexel/cis/dragon/ir/index/BasicIRRelationIndexList.java | xc35/dragontoolkit | e7ef78a9c2ff549102b2644e52f67f0d062589aa | [
"Apache-2.0"
] | null | null | null | src/main/java/edu/drexel/cis/dragon/ir/index/BasicIRRelationIndexList.java | xc35/dragontoolkit | e7ef78a9c2ff549102b2644e52f67f0d062589aa | [
"Apache-2.0"
] | null | null | null | src/main/java/edu/drexel/cis/dragon/ir/index/BasicIRRelationIndexList.java | xc35/dragontoolkit | e7ef78a9c2ff549102b2644e52f67f0d062589aa | [
"Apache-2.0"
] | null | null | null | 41.294393 | 108 | 0.50198 | 12,690 | /* */ package edu.drexel.cis.dragon.ir.index;
/* */
/* */ import edu.drexel.cis.dragon.nlp.compare.IndexComparator;
/* */ import edu.drexel.cis.dragon.util.ByteArrayConvert;
/* */ import edu.drexel.cis.dragon.util.FastBinaryReader;
/* */ import edu.drexel.cis.dragon.util.FileUtil;
/* */ import edu.drexel.cis.dragon.util.SortedArray;
/* */ import java.io.PrintStream;
/* */ import java.io.RandomAccessFile;
/* */ import java.util.Date;
/* */
/* */ public class BasicIRRelationIndexList
/* */ implements IRRelationIndexList, IRSignatureIndexList
/* */ {
/* */ private RandomAccessFile raf;
/* */ private SortedArray indexList;
/* */ private int elementLength;
/* */ private boolean writingMode;
/* */ private String indexlistFilename;
/* */ private int relationNum;
/* */ private int maxOldIndex;
/* */ private int maxIndex;
/* */ private int maxCacheSize;
/* */ private byte[] buf;
/* */
/* */ public BasicIRRelationIndexList(String filename, boolean writingMode)
/* */ {
/* */ try
/* */ {
/* 29 */ this.elementLength = 20;
/* 30 */ this.buf = new byte[this.elementLength];
/* 31 */ this.writingMode = writingMode;
/* 32 */ this.indexlistFilename = filename;
/* 33 */ this.maxCacheSize = 200000;
/* 34 */ if (writingMode) {
/* 35 */ this.raf = new RandomAccessFile(filename, "rw");
/* 36 */ if (this.raf.length() < 4L) {
/* 37 */ this.raf.writeInt(0);
/* 38 */ this.maxOldIndex = -1;
/* */ }
/* */ else {
/* 41 */ this.maxOldIndex = (this.raf.readInt() - 1);
/* 42 */ }this.maxIndex = this.maxOldIndex;
/* 43 */ this.raf.close();
/* 44 */ this.raf = null;
/* 45 */ this.indexList = new SortedArray(new IndexComparator());
/* */ }
/* */ else {
/* 48 */ if (FileUtil.exist(filename)) {
/* 49 */ this.raf = new RandomAccessFile(filename, "r");
/* 50 */ if (this.raf.length() > 0L)
/* 51 */ this.relationNum = this.raf.readInt();
/* */ else
/* 53 */ this.relationNum = 0;
/* */ }
/* */ else {
/* 56 */ this.relationNum = 0;
/* 57 */ }this.maxIndex = (this.relationNum - 1);
/* */ }
/* */ }
/* */ catch (Exception e) {
/* 61 */ e.printStackTrace();
/* */ }
/* */ }
/* */
/* */ public void setCacheSize(int size) {
/* 66 */ this.maxCacheSize = size;
/* */ }
/* */
/* */ public int getCacheSize() {
/* 70 */ return this.maxCacheSize;
/* */ }
/* */
/* */ public IRSignature getIRSignature(int index) {
/* 74 */ return get(index);
/* */ }
/* */
/* */ public IRRelation get(int index) {
/* */ try {
/* 79 */ if ((this.writingMode) || (index >= this.relationNum)) {
/* 80 */ return null;
/* */ }
/* 82 */ this.raf.seek(index * this.elementLength + 4);
/* 83 */ this.raf.read(this.buf);
/* 84 */ return getIRRelationFromByteArray(this.buf);
/* */ }
/* */ catch (Exception e) {
/* 87 */ e.printStackTrace();
/* 88 */ }return null;
/* */ }
/* */
/* */ public boolean add(IRRelation curRelation)
/* */ {
/* 95 */ if (!this.writingMode) {
/* 96 */ return false;
/* */ }
/* 98 */ if (!this.indexList.add(curRelation.copy())) {
/* 99 */ IRRelation oldRelation = (IRRelation)this.indexList.get(this.indexList.insertedPos());
/* 100 */ oldRelation.addFrequency(curRelation.getFrequency());
/* 101 */ oldRelation.setDocFrequency(oldRelation.getDocFrequency() + curRelation.getDocFrequency());
/* */ }
/* */ else {
/* 104 */ if (curRelation.getIndex() > this.maxIndex)
/* 105 */ this.maxIndex = curRelation.getIndex();
/* 106 */ if (this.indexList.size() > this.maxCacheSize)
/* 107 */ saveRelationIndexList(this.indexlistFilename, this.indexList);
/* */ }
/* 109 */ return true;
/* */ }
/* */
/* */ public int size() {
/* 113 */ return this.maxIndex + 1;
/* */ }
/* */
/* */ public void close() {
/* */ try {
/* 118 */ if (this.writingMode) {
/* 119 */ saveRelationIndexList(this.indexlistFilename, this.indexList);
/* 120 */ this.indexList.clear();
/* */ }
/* 123 */ else if (this.raf != null) {
/* 124 */ this.raf.close();
/* */ }
/* */ }
/* */ catch (Exception e) {
/* 128 */ e.printStackTrace();
/* */ }
/* */ }
/* */
/* */ private void saveRelationIndexList(String filename, SortedArray list)
/* */ {
/* */ try
/* */ {
int i;
/* 139 */ if ((list == null) || (list.size() == 0))
/* 140 */ return;
/* 141 */ System.out.println(new Date() + " Saving Relation Index List...");
/* */
/* 144 */ FastBinaryReader fbr = new FastBinaryReader(filename);
/* 145 */ fbr.skip(4L);
/* 146 */ int lastIndex = 0;
/* 147 */ for ( i = 0; i < list.size(); i++) {
/* 148 */ IRRelation cur = (IRRelation)list.get(i);
/* 149 */ if (cur.getIndex() > this.maxOldIndex)
/* */ break;
/* 151 */ fbr.skip((cur.getIndex() - lastIndex) * this.elementLength + 12);
/* 152 */ cur.addFrequency(fbr.readInt());
/* 153 */ cur.setDocFrequency(cur.getDocFrequency() + fbr.readInt());
/* 154 */ lastIndex = cur.getIndex() + 1;
/* */ }
/* 156 */ int cutoff = i - 1;
/* 157 */ fbr.close();
/* */
/* 160 */ RandomAccessFile rafRelation = new RandomAccessFile(filename, "rw");
/* 161 */ rafRelation.writeInt(this.maxIndex + 1);
/* 162 */ for ( i = 0; i <= cutoff; i++) {
/* 163 */ IRRelation cur = (IRRelation)list.get(i);
/* 164 */ rafRelation.seek(cur.getIndex() * this.elementLength + 4);
/* 165 */ writeToByteArray(cur, this.buf);
/* 166 */ rafRelation.write(this.buf);
/* */ }
/* */
/* 170 */ lastIndex = this.maxOldIndex;
/* 171 */ rafRelation.seek((this.maxOldIndex + 1) * this.elementLength + 4);
/* 172 */ for ( i = cutoff + 1; i < list.size(); i++) {
/* 173 */ IRRelation cur = (IRRelation)list.get(i);
/* 174 */ for (int j = lastIndex + 1; j < cur.getIndex(); j++) {
/* 175 */ writeToByteArray(j, this.buf);
/* 176 */ rafRelation.write(this.buf);
/* */ }
/* 178 */ writeToByteArray(cur, this.buf);
/* 179 */ rafRelation.write(this.buf);
/* 180 */ lastIndex = cur.getIndex();
/* */ }
/* 182 */ rafRelation.close();
/* 183 */ this.maxOldIndex = this.maxIndex;
/* 184 */ list.clear();
/* */ }
/* */ catch (Exception ex) {
/* 187 */ ex.printStackTrace();
/* */ }
/* */ }
/* */
/* */ private void writeToByteArray(IRRelation cur, byte[] array) {
/* 192 */ ByteArrayConvert.toByte(cur.getIndex(), array, 0);
/* 193 */ ByteArrayConvert.toByte(cur.getFirstTerm(), array, 4);
/* 194 */ ByteArrayConvert.toByte(cur.getSecondTerm(), array, 8);
/* 195 */ ByteArrayConvert.toByte(cur.getFrequency(), array, 12);
/* 196 */ ByteArrayConvert.toByte(cur.getDocFrequency(), array, 16);
/* */ }
/* */
/* */ private void writeToByteArray(int index, byte[] array) {
/* 200 */ ByteArrayConvert.toByte(index, array, 0);
/* 201 */ ByteArrayConvert.toByte(-1, array, 4);
/* 202 */ ByteArrayConvert.toByte(-1, array, 8);
/* 203 */ ByteArrayConvert.toByte(0, array, 12);
/* 204 */ ByteArrayConvert.toByte(0, array, 16);
/* */ }
/* */
/* */ private IRRelation getIRRelationFromByteArray(byte[] array)
/* */ {
/* 210 */ int relationIndex = ByteArrayConvert.toInt(array, 0);
/* 211 */ int first = ByteArrayConvert.toInt(array, 4);
/* 212 */ int second = ByteArrayConvert.toInt(array, 8);
/* 213 */ int frequency = ByteArrayConvert.toInt(array, 12);
/* 214 */ int docFrequency = ByteArrayConvert.toInt(array, 16);
/* 215 */ return new IRRelation(relationIndex, first, second, frequency, docFrequency);
/* */ }
/* */ }
/* Location: C:\dragontoolikt\dragontool.jar
* Qualified Name: dragon.ir.index.BasicIRRelationIndexList
* JD-Core Version: 0.6.2
*/ |
3e1dfaa8a5b84ab803b8d165685bbbdad035fb88 | 1,569 | java | Java | xwder-biz-app/src/main/java/com/xwder/app/XwderApplication.java | xwder/xwder | 5cac0ab12334d749fe80dcb2b3958bcae38aca94 | [
"Apache-2.0"
] | null | null | null | xwder-biz-app/src/main/java/com/xwder/app/XwderApplication.java | xwder/xwder | 5cac0ab12334d749fe80dcb2b3958bcae38aca94 | [
"Apache-2.0"
] | null | null | null | xwder-biz-app/src/main/java/com/xwder/app/XwderApplication.java | xwder/xwder | 5cac0ab12334d749fe80dcb2b3958bcae38aca94 | [
"Apache-2.0"
] | null | null | null | 40.230769 | 156 | 0.840663 | 12,691 | package com.xwder.app;
import com.xwder.app.common.jpa.bean.BaseJpaRepositoryFactoryBean;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.web.servlet.ServletComponentScan;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.data.jpa.repository.config.EnableJpaAuditing;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import java.util.TimeZone;
/**
* @author wande
* @version 1.0
* @date 2020/07/07
*/
@EnableDiscoveryClient
@EnableAsync
@EnableJpaAuditing
@EnableCaching
@ServletComponentScan
@EnableTransactionManagement(proxyTargetClass = true)
@EnableConfigurationProperties
@SpringBootApplication(exclude={DataSourceAutoConfiguration.class})
@EnableJpaRepositories(repositoryFactoryBeanClass = BaseJpaRepositoryFactoryBean.class, basePackages = {"com.xwder.app"}, enableDefaultTransactions = false)
public class XwderApplication {
public static void main(String[] args) {
TimeZone.setDefault(TimeZone.getTimeZone("Asia/Shanghai"));
SpringApplication.run(XwderApplication.class, args);
}
}
|
3e1dfb209cae5888ab74fc7273a15ecf6ecd2682 | 1,268 | java | Java | processor/src/test/java/org/mapstruct/ap/testutil/IssueKey.java | velo/mapstruct | 4d127c3f008cc7125c0daa06ce583d0ac47c0c8a | [
"Apache-2.0"
] | 1 | 2017-08-17T07:10:35.000Z | 2017-08-17T07:10:35.000Z | processor/src/test/java/org/mapstruct/ap/testutil/IssueKey.java | velo/mapstruct | 4d127c3f008cc7125c0daa06ce583d0ac47c0c8a | [
"Apache-2.0"
] | null | null | null | processor/src/test/java/org/mapstruct/ap/testutil/IssueKey.java | velo/mapstruct | 4d127c3f008cc7125c0daa06ce583d0ac47c0c8a | [
"Apache-2.0"
] | null | null | null | 31.7 | 76 | 0.714511 | 12,692 | /**
* Copyright 2012-2015 Gunnar Morling (http://www.gunnarmorling.de/)
* and/or other contributors as indicated by the @authors tag. See the
* copyright.txt file in the distribution for a full listing of all
* contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.mapstruct.ap.testutil;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
/**
* Id of the issue addressed by a test or test method in the <a
* href="https://github.com/mapstruct/mapstruct/issues">issue tracker</a>.
*
* @author Gunnar Morling
*/
@Retention(RetentionPolicy.SOURCE)
public @interface IssueKey {
/**
* The issue number.
*
* @return the issue number
*/
String value();
}
|
3e1dfc75e7e1c5e1bfffcef8c248712bb4a34623 | 4,504 | java | Java | sharding-jdbc/sharding-jdbc-core/src/test/java/org/apache/shardingsphere/shardingjdbc/api/ShardingDataSourceFactoryTest.java | jacken-snian/shardingsphere | a39867f0310aee3382fc1c179bf9e059900502d4 | [
"Apache-2.0"
] | 1 | 2020-04-28T07:16:08.000Z | 2020-04-28T07:16:08.000Z | sharding-jdbc/sharding-jdbc-core/src/test/java/org/apache/shardingsphere/shardingjdbc/api/ShardingDataSourceFactoryTest.java | jacken-snian/shardingsphere | a39867f0310aee3382fc1c179bf9e059900502d4 | [
"Apache-2.0"
] | null | null | null | sharding-jdbc/sharding-jdbc-core/src/test/java/org/apache/shardingsphere/shardingjdbc/api/ShardingDataSourceFactoryTest.java | jacken-snian/shardingsphere | a39867f0310aee3382fc1c179bf9e059900502d4 | [
"Apache-2.0"
] | null | null | null | 48.956522 | 182 | 0.750222 | 12,693 | /*
* 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.shardingsphere.shardingjdbc.api;
import lombok.SneakyThrows;
import org.apache.shardingsphere.api.config.sharding.ShardingRuleConfiguration;
import org.apache.shardingsphere.api.config.sharding.TableRuleConfiguration;
import org.apache.shardingsphere.shardingjdbc.jdbc.core.context.RuntimeContext;
import org.junit.Test;
import org.mockito.ArgumentMatchers;
import org.mockito.Mockito;
import javax.sql.DataSource;
import java.lang.reflect.Field;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public final class ShardingDataSourceFactoryTest {
@Test
public void assertCreateDataSourceWithShardingRuleAndProperties() throws SQLException {
ShardingRuleConfiguration shardingRuleConfig = createShardingRuleConfig();
Properties props = new Properties();
DataSource dataSource = ShardingDataSourceFactory.createDataSource(getDataSourceMap(), shardingRuleConfig, props);
assertThat(getProperties(dataSource), is(props));
}
private Map<String, DataSource> getDataSourceMap() throws SQLException {
DataSource dataSource = mock(DataSource.class);
Connection connection = mock(Connection.class);
DatabaseMetaData databaseMetaData = mock(DatabaseMetaData.class);
Statement statement = mock(Statement.class);
ResultSet resultSet = mock(ResultSet.class);
when(statement.getResultSet()).thenReturn(resultSet);
when(resultSet.next()).thenReturn(false);
when(dataSource.getConnection()).thenReturn(connection);
when(connection.getMetaData()).thenReturn(databaseMetaData);
when(connection.createStatement()).thenReturn(statement);
when(statement.executeQuery(Mockito.anyString())).thenReturn(resultSet);
when(statement.getConnection()).thenReturn(connection);
when(statement.getConnection().getMetaData().getTables(ArgumentMatchers.any(), ArgumentMatchers.any(), ArgumentMatchers.any(), ArgumentMatchers.any())).thenReturn(resultSet);
when(resultSet.next()).thenReturn(false);
when(statement.getConnection().getMetaData().getURL()).thenReturn("jdbc:h2:mem:demo_ds;DB_CLOSE_DELAY=-1;DATABASE_TO_UPPER=false;MODE=MySQL");
when(statement.getConnection().getMetaData().getColumns(null, null, "table_0", "%")).thenReturn(mock(ResultSet.class));
when(statement.getConnection().getMetaData().getPrimaryKeys(null, null, "table_0")).thenReturn(mock(ResultSet.class));
when(statement.getConnection().getMetaData().getIndexInfo(null, null, "table_0", false, false)).thenReturn(mock(ResultSet.class));
Map<String, DataSource> result = new HashMap<>(1);
result.put("ds", dataSource);
return result;
}
private ShardingRuleConfiguration createShardingRuleConfig() {
ShardingRuleConfiguration result = new ShardingRuleConfiguration();
result.getTableRuleConfigs().add(new TableRuleConfiguration("logicTable", "ds.table_${0..2}"));
return result;
}
@SneakyThrows
private Properties getProperties(final DataSource dataSource) {
Field field = dataSource.getClass().getDeclaredField("runtimeContext");
field.setAccessible(true);
RuntimeContext runtimeContext = (RuntimeContext) field.get(dataSource);
return runtimeContext.getProperties().getProps();
}
}
|
3e1dfc8299a8f9be92c012cb5836e8bb9af9e931 | 1,603 | java | Java | heroic-component/src/main/java/com/spotify/heroic/aggregation/AggregationRegistry.java | dmichel1/heroic | be5f2d0752bea809b4d452469bd09e86836deafc | [
"Apache-2.0"
] | 898 | 2015-11-17T13:20:05.000Z | 2022-01-11T20:46:06.000Z | heroic-component/src/main/java/com/spotify/heroic/aggregation/AggregationRegistry.java | dmichel1/heroic | be5f2d0752bea809b4d452469bd09e86836deafc | [
"Apache-2.0"
] | 712 | 2015-11-19T12:02:17.000Z | 2021-03-26T18:37:47.000Z | heroic-component/src/main/java/com/spotify/heroic/aggregation/AggregationRegistry.java | dmichel1/heroic | be5f2d0752bea809b4d452469bd09e86836deafc | [
"Apache-2.0"
] | 133 | 2015-11-17T16:10:12.000Z | 2022-03-19T10:03:13.000Z | 35.622222 | 95 | 0.726762 | 12,694 | /*
* Copyright (c) 2015 Spotify AB.
*
* 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.spotify.heroic.aggregation;
import com.fasterxml.jackson.databind.Module;
public interface AggregationRegistry {
/**
* Register a new aggregation.
*
* @param id The id of the new aggregation, will be used in the type field, and in the DSL.
* @param type The type of the aggregation.
* @param instanceType The type of the instance.
* @param dsl DSL factory for the aggregation.
*/
<A extends Aggregation, I extends AggregationInstance> void register(
String id, Class<A> type, Class<I> instanceType, AggregationDSL dsl
);
<I extends AggregationInstance> void registerInstance(String id, Class<I> instanceType);
Module module();
AggregationFactory newAggregationFactory();
}
|
3e1dfc87cacfc540f9aeef8cb7f257119a0695c4 | 29,294 | java | Java | postgres-odbc-server/src/main/java/com/asksunny/jdbc4/InternalResult.java | devsunny/app-galleries | 98aed1b18031ded93056ad12bda5b2c62c40a85b | [
"MIT"
] | null | null | null | postgres-odbc-server/src/main/java/com/asksunny/jdbc4/InternalResult.java | devsunny/app-galleries | 98aed1b18031ded93056ad12bda5b2c62c40a85b | [
"MIT"
] | 15 | 2020-05-15T21:00:34.000Z | 2022-01-21T23:19:52.000Z | postgres-odbc-server/src/main/java/com/asksunny/jdbc4/InternalResult.java | devsunny/app-galleries | 98aed1b18031ded93056ad12bda5b2c62c40a85b | [
"MIT"
] | 1 | 2016-03-09T18:35:46.000Z | 2016-03-09T18:35:46.000Z | 22.41316 | 134 | 0.739264 | 12,695 | package com.asksunny.jdbc4;
import java.io.InputStream;
import java.io.Reader;
import java.math.BigDecimal;
import java.net.URL;
import java.sql.Array;
import java.sql.Blob;
import java.sql.Clob;
import java.sql.Date;
import java.sql.NClob;
import java.sql.Ref;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.RowId;
import java.sql.SQLException;
import java.sql.SQLWarning;
import java.sql.SQLXML;
import java.sql.Statement;
import java.sql.Time;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Map;
public class InternalResult implements ResultSet{
private List<InternalDataRow> rows = null;
private int currentPos = -1;
private ResultSetMetaData rsMetaData = null;
public InternalResult(ResultSetMetaData rsMetaData) {
rows = new ArrayList<InternalDataRow>();
this.rsMetaData = rsMetaData;
}
public void addRow(Object obj){
InternalDataRow row = new InternalDataRow();
row.add(obj);
rows.add(row);
}
public void addRow(Object obj1, Object obj2){
InternalDataRow row = new InternalDataRow();
row.add(obj1);
row.add(obj2);
rows.add(row);
}
public void addRow(Object obj1, Object obj2, Object obj3){
InternalDataRow row = new InternalDataRow();
row.add(obj1);
row.add(obj2);
row.add(obj3);
rows.add(row);
}
public void addRow(Object obj1, Object obj2, Object obj3, Object... moreColumns){
InternalDataRow row = new InternalDataRow();
row.add(obj1);
row.add(obj2);
row.add(obj3);
for(Object col:moreColumns){
row.add(col);
}
rows.add(row);
}
@Override
public <T> T unwrap(Class<T> iface) throws SQLException {
return iface.cast(this);
}
@Override
public boolean isWrapperFor(Class<?> iface) throws SQLException {
return iface.isInstance(this);
}
@Override
public boolean next() throws SQLException {
currentPos++;
return currentPos<rows.size();
}
@Override
public void close() throws SQLException {
}
@Override
public boolean wasNull() throws SQLException {
return false;
}
@Override
public String getString(int columnIndex) throws SQLException {
if(columnIndex<1 || columnIndex>rsMetaData.getColumnCount()){
throw new IndexOutOfBoundsException(String.format("Column Index %d is out of bound %d", columnIndex, rsMetaData.getColumnCount()));
}
InternalDataRow row = this.rows.get(currentPos);
Object obj = row.get(columnIndex-1);
if(obj==null) return null;
return obj.toString();
}
@Override
public boolean getBoolean(int columnIndex) throws SQLException {
return false;
}
@Override
public byte getByte(int columnIndex) throws SQLException {
return 0;
}
@Override
public short getShort(int columnIndex) throws SQLException {
if(columnIndex<1 || columnIndex>rsMetaData.getColumnCount()){
throw new IndexOutOfBoundsException(String.format("Column Index %d is out of bound %d", columnIndex, rsMetaData.getColumnCount()));
}
InternalDataRow row = this.rows.get(currentPos);
Object obj = row.get(columnIndex-1);
if(obj==null) return 0;
BigDecimal bd = new BigDecimal(obj.toString());
return bd.shortValue();
}
@Override
public int getInt(int columnIndex) throws SQLException {
if(columnIndex<1 || columnIndex>rsMetaData.getColumnCount()){
throw new IndexOutOfBoundsException(String.format("Column Index %d is out of bound %d", columnIndex, rsMetaData.getColumnCount()));
}
InternalDataRow row = this.rows.get(currentPos);
Object obj = row.get(columnIndex-1);
if(obj==null) return 0;
BigDecimal bd = new BigDecimal(obj.toString());
return bd.intValue();
}
@Override
public long getLong(int columnIndex) throws SQLException {
if(columnIndex<1 || columnIndex>rsMetaData.getColumnCount()){
throw new IndexOutOfBoundsException(String.format("Column Index %d is out of bound %d", columnIndex, rsMetaData.getColumnCount()));
}
InternalDataRow row = this.rows.get(currentPos);
Object obj = row.get(columnIndex-1);
if(obj==null) return 0;
BigDecimal bd = new BigDecimal(obj.toString());
return bd.longValue();
}
@Override
public float getFloat(int columnIndex) throws SQLException {
if(columnIndex<1 || columnIndex>rsMetaData.getColumnCount()){
throw new IndexOutOfBoundsException(String.format("Column Index %d is out of bound %d", columnIndex, rsMetaData.getColumnCount()));
}
InternalDataRow row = this.rows.get(currentPos);
Object obj = row.get(columnIndex-1);
if(obj==null) return 0;
BigDecimal bd = new BigDecimal(obj.toString());
return bd.floatValue();
}
@Override
public double getDouble(int columnIndex) throws SQLException {
if(columnIndex<1 || columnIndex>rsMetaData.getColumnCount()){
throw new IndexOutOfBoundsException(String.format("Column Index %d is out of bound %d", columnIndex, rsMetaData.getColumnCount()));
}
InternalDataRow row = this.rows.get(currentPos);
Object obj = row.get(columnIndex-1);
if(obj==null) return 0;
BigDecimal bd = new BigDecimal(obj.toString());
return bd.doubleValue();
}
@Override
public BigDecimal getBigDecimal(int columnIndex, int scale)
throws SQLException {
if(columnIndex<1 || columnIndex>rsMetaData.getColumnCount()){
throw new IndexOutOfBoundsException(String.format("Column Index %d is out of bound %d", columnIndex, rsMetaData.getColumnCount()));
}
InternalDataRow row = this.rows.get(currentPos);
Object obj = row.get(columnIndex-1);
if(obj==null) return null;
BigDecimal bd = new BigDecimal(obj.toString());
return bd;
}
@Override
public byte[] getBytes(int columnIndex) throws SQLException {
if(columnIndex<1 || columnIndex>rsMetaData.getColumnCount()){
throw new IndexOutOfBoundsException(String.format("Column Index %d is out of bound %d", columnIndex, rsMetaData.getColumnCount()));
}
InternalDataRow row = this.rows.get(currentPos);
Object obj = row.get(columnIndex-1);
if(obj==null) return null;
return obj.toString().getBytes();
}
@Override
public Date getDate(int columnIndex) throws SQLException {
return null;
}
@Override
public Time getTime(int columnIndex) throws SQLException {
return null;
}
@Override
public Timestamp getTimestamp(int columnIndex) throws SQLException {
return null;
}
@Override
public InputStream getAsciiStream(int columnIndex) throws SQLException {
return null;
}
@Override
public InputStream getUnicodeStream(int columnIndex) throws SQLException {
return null;
}
@Override
public InputStream getBinaryStream(int columnIndex) throws SQLException {
return null;
}
@Override
public String getString(String columnLabel) throws SQLException {
// TODO Auto-generated method stub
return null;
}
@Override
public boolean getBoolean(String columnLabel) throws SQLException {
// TODO Auto-generated method stub
return false;
}
@Override
public byte getByte(String columnLabel) throws SQLException {
// TODO Auto-generated method stub
return 0;
}
@Override
public short getShort(String columnLabel) throws SQLException {
// TODO Auto-generated method stub
return 0;
}
@Override
public int getInt(String columnLabel) throws SQLException {
// TODO Auto-generated method stub
return 0;
}
@Override
public long getLong(String columnLabel) throws SQLException {
// TODO Auto-generated method stub
return 0;
}
@Override
public float getFloat(String columnLabel) throws SQLException {
// TODO Auto-generated method stub
return 0;
}
@Override
public double getDouble(String columnLabel) throws SQLException {
// TODO Auto-generated method stub
return 0;
}
@Override
public BigDecimal getBigDecimal(String columnLabel, int scale)
throws SQLException {
// TODO Auto-generated method stub
return null;
}
@Override
public byte[] getBytes(String columnLabel) throws SQLException {
// TODO Auto-generated method stub
return null;
}
@Override
public Date getDate(String columnLabel) throws SQLException {
// TODO Auto-generated method stub
return null;
}
@Override
public Time getTime(String columnLabel) throws SQLException {
// TODO Auto-generated method stub
return null;
}
@Override
public Timestamp getTimestamp(String columnLabel) throws SQLException {
// TODO Auto-generated method stub
return null;
}
@Override
public InputStream getAsciiStream(String columnLabel) throws SQLException {
// TODO Auto-generated method stub
return null;
}
@Override
public InputStream getUnicodeStream(String columnLabel) throws SQLException {
// TODO Auto-generated method stub
return null;
}
@Override
public InputStream getBinaryStream(String columnLabel) throws SQLException {
// TODO Auto-generated method stub
return null;
}
@Override
public SQLWarning getWarnings() throws SQLException {
// TODO Auto-generated method stub
return null;
}
@Override
public void clearWarnings() throws SQLException {
// TODO Auto-generated method stub
}
@Override
public String getCursorName() throws SQLException {
// TODO Auto-generated method stub
return null;
}
@Override
public ResultSetMetaData getMetaData() throws SQLException {
return this.rsMetaData;
}
@Override
public Object getObject(int columnIndex) throws SQLException {
// TODO Auto-generated method stub
return null;
}
@Override
public Object getObject(String columnLabel) throws SQLException {
// TODO Auto-generated method stub
return null;
}
@Override
public int findColumn(String columnLabel) throws SQLException {
// TODO Auto-generated method stub
return 0;
}
@Override
public Reader getCharacterStream(int columnIndex) throws SQLException {
// TODO Auto-generated method stub
return null;
}
@Override
public Reader getCharacterStream(String columnLabel) throws SQLException {
// TODO Auto-generated method stub
return null;
}
@Override
public BigDecimal getBigDecimal(int columnIndex) throws SQLException {
// TODO Auto-generated method stub
return null;
}
@Override
public BigDecimal getBigDecimal(String columnLabel) throws SQLException {
// TODO Auto-generated method stub
return null;
}
@Override
public boolean isBeforeFirst() throws SQLException {
// TODO Auto-generated method stub
return false;
}
@Override
public boolean isAfterLast() throws SQLException {
// TODO Auto-generated method stub
return false;
}
@Override
public boolean isFirst() throws SQLException {
// TODO Auto-generated method stub
return false;
}
@Override
public boolean isLast() throws SQLException {
// TODO Auto-generated method stub
return false;
}
@Override
public void beforeFirst() throws SQLException {
// TODO Auto-generated method stub
}
@Override
public void afterLast() throws SQLException {
// TODO Auto-generated method stub
}
@Override
public boolean first() throws SQLException {
// TODO Auto-generated method stub
return false;
}
@Override
public boolean last() throws SQLException {
// TODO Auto-generated method stub
return false;
}
@Override
public int getRow() throws SQLException {
// TODO Auto-generated method stub
return 0;
}
@Override
public boolean absolute(int row) throws SQLException {
// TODO Auto-generated method stub
return false;
}
@Override
public boolean relative(int rows) throws SQLException {
// TODO Auto-generated method stub
return false;
}
@Override
public boolean previous() throws SQLException {
// TODO Auto-generated method stub
return false;
}
@Override
public void setFetchDirection(int direction) throws SQLException {
// TODO Auto-generated method stub
}
@Override
public int getFetchDirection() throws SQLException {
// TODO Auto-generated method stub
return 0;
}
@Override
public void setFetchSize(int rows) throws SQLException {
// TODO Auto-generated method stub
}
@Override
public int getFetchSize() throws SQLException {
// TODO Auto-generated method stub
return 0;
}
@Override
public int getType() throws SQLException {
// TODO Auto-generated method stub
return 0;
}
@Override
public int getConcurrency() throws SQLException {
// TODO Auto-generated method stub
return 0;
}
@Override
public boolean rowUpdated() throws SQLException {
// TODO Auto-generated method stub
return false;
}
@Override
public boolean rowInserted() throws SQLException {
// TODO Auto-generated method stub
return false;
}
@Override
public boolean rowDeleted() throws SQLException {
// TODO Auto-generated method stub
return false;
}
@Override
public void updateNull(int columnIndex) throws SQLException {
// TODO Auto-generated method stub
}
@Override
public void updateBoolean(int columnIndex, boolean x) throws SQLException {
// TODO Auto-generated method stub
}
@Override
public void updateByte(int columnIndex, byte x) throws SQLException {
// TODO Auto-generated method stub
}
@Override
public void updateShort(int columnIndex, short x) throws SQLException {
// TODO Auto-generated method stub
}
@Override
public void updateInt(int columnIndex, int x) throws SQLException {
// TODO Auto-generated method stub
}
@Override
public void updateLong(int columnIndex, long x) throws SQLException {
// TODO Auto-generated method stub
}
@Override
public void updateFloat(int columnIndex, float x) throws SQLException {
// TODO Auto-generated method stub
}
@Override
public void updateDouble(int columnIndex, double x) throws SQLException {
// TODO Auto-generated method stub
}
@Override
public void updateBigDecimal(int columnIndex, BigDecimal x)
throws SQLException {
// TODO Auto-generated method stub
}
@Override
public void updateString(int columnIndex, String x) throws SQLException {
// TODO Auto-generated method stub
}
@Override
public void updateBytes(int columnIndex, byte[] x) throws SQLException {
// TODO Auto-generated method stub
}
@Override
public void updateDate(int columnIndex, Date x) throws SQLException {
// TODO Auto-generated method stub
}
@Override
public void updateTime(int columnIndex, Time x) throws SQLException {
// TODO Auto-generated method stub
}
@Override
public void updateTimestamp(int columnIndex, Timestamp x)
throws SQLException {
// TODO Auto-generated method stub
}
@Override
public void updateAsciiStream(int columnIndex, InputStream x, int length)
throws SQLException {
// TODO Auto-generated method stub
}
@Override
public void updateBinaryStream(int columnIndex, InputStream x, int length)
throws SQLException {
// TODO Auto-generated method stub
}
@Override
public void updateCharacterStream(int columnIndex, Reader x, int length)
throws SQLException {
// TODO Auto-generated method stub
}
@Override
public void updateObject(int columnIndex, Object x, int scaleOrLength)
throws SQLException {
// TODO Auto-generated method stub
}
@Override
public void updateObject(int columnIndex, Object x) throws SQLException {
// TODO Auto-generated method stub
}
@Override
public void updateNull(String columnLabel) throws SQLException {
// TODO Auto-generated method stub
}
@Override
public void updateBoolean(String columnLabel, boolean x)
throws SQLException {
// TODO Auto-generated method stub
}
@Override
public void updateByte(String columnLabel, byte x) throws SQLException {
// TODO Auto-generated method stub
}
@Override
public void updateShort(String columnLabel, short x) throws SQLException {
// TODO Auto-generated method stub
}
@Override
public void updateInt(String columnLabel, int x) throws SQLException {
// TODO Auto-generated method stub
}
@Override
public void updateLong(String columnLabel, long x) throws SQLException {
// TODO Auto-generated method stub
}
@Override
public void updateFloat(String columnLabel, float x) throws SQLException {
// TODO Auto-generated method stub
}
@Override
public void updateDouble(String columnLabel, double x) throws SQLException {
// TODO Auto-generated method stub
}
@Override
public void updateBigDecimal(String columnLabel, BigDecimal x)
throws SQLException {
// TODO Auto-generated method stub
}
@Override
public void updateString(String columnLabel, String x) throws SQLException {
// TODO Auto-generated method stub
}
@Override
public void updateBytes(String columnLabel, byte[] x) throws SQLException {
// TODO Auto-generated method stub
}
@Override
public void updateDate(String columnLabel, Date x) throws SQLException {
// TODO Auto-generated method stub
}
@Override
public void updateTime(String columnLabel, Time x) throws SQLException {
// TODO Auto-generated method stub
}
@Override
public void updateTimestamp(String columnLabel, Timestamp x)
throws SQLException {
// TODO Auto-generated method stub
}
@Override
public void updateAsciiStream(String columnLabel, InputStream x, int length)
throws SQLException {
// TODO Auto-generated method stub
}
@Override
public void updateBinaryStream(String columnLabel, InputStream x, int length)
throws SQLException {
// TODO Auto-generated method stub
}
@Override
public void updateCharacterStream(String columnLabel, Reader reader,
int length) throws SQLException {
// TODO Auto-generated method stub
}
@Override
public void updateObject(String columnLabel, Object x, int scaleOrLength)
throws SQLException {
// TODO Auto-generated method stub
}
@Override
public void updateObject(String columnLabel, Object x) throws SQLException {
// TODO Auto-generated method stub
}
@Override
public void insertRow() throws SQLException {
// TODO Auto-generated method stub
}
@Override
public void updateRow() throws SQLException {
// TODO Auto-generated method stub
}
@Override
public void deleteRow() throws SQLException {
// TODO Auto-generated method stub
}
@Override
public void refreshRow() throws SQLException {
// TODO Auto-generated method stub
}
@Override
public void cancelRowUpdates() throws SQLException {
// TODO Auto-generated method stub
}
@Override
public void moveToInsertRow() throws SQLException {
// TODO Auto-generated method stub
}
@Override
public void moveToCurrentRow() throws SQLException {
// TODO Auto-generated method stub
}
@Override
public Statement getStatement() throws SQLException {
// TODO Auto-generated method stub
return null;
}
@Override
public Object getObject(int columnIndex, Map<String, Class<?>> map)
throws SQLException {
// TODO Auto-generated method stub
return null;
}
@Override
public Ref getRef(int columnIndex) throws SQLException {
// TODO Auto-generated method stub
return null;
}
@Override
public Blob getBlob(int columnIndex) throws SQLException {
// TODO Auto-generated method stub
return null;
}
@Override
public Clob getClob(int columnIndex) throws SQLException {
// TODO Auto-generated method stub
return null;
}
@Override
public Array getArray(int columnIndex) throws SQLException {
// TODO Auto-generated method stub
return null;
}
@Override
public Object getObject(String columnLabel, Map<String, Class<?>> map)
throws SQLException {
// TODO Auto-generated method stub
return null;
}
@Override
public Ref getRef(String columnLabel) throws SQLException {
// TODO Auto-generated method stub
return null;
}
@Override
public Blob getBlob(String columnLabel) throws SQLException {
// TODO Auto-generated method stub
return null;
}
@Override
public Clob getClob(String columnLabel) throws SQLException {
// TODO Auto-generated method stub
return null;
}
@Override
public Array getArray(String columnLabel) throws SQLException {
// TODO Auto-generated method stub
return null;
}
@Override
public Date getDate(int columnIndex, Calendar cal) throws SQLException {
// TODO Auto-generated method stub
return null;
}
@Override
public Date getDate(String columnLabel, Calendar cal) throws SQLException {
// TODO Auto-generated method stub
return null;
}
@Override
public Time getTime(int columnIndex, Calendar cal) throws SQLException {
// TODO Auto-generated method stub
return null;
}
@Override
public Time getTime(String columnLabel, Calendar cal) throws SQLException {
// TODO Auto-generated method stub
return null;
}
@Override
public Timestamp getTimestamp(int columnIndex, Calendar cal)
throws SQLException {
// TODO Auto-generated method stub
return null;
}
@Override
public Timestamp getTimestamp(String columnLabel, Calendar cal)
throws SQLException {
// TODO Auto-generated method stub
return null;
}
@Override
public URL getURL(int columnIndex) throws SQLException {
// TODO Auto-generated method stub
return null;
}
@Override
public URL getURL(String columnLabel) throws SQLException {
// TODO Auto-generated method stub
return null;
}
@Override
public void updateRef(int columnIndex, Ref x) throws SQLException {
// TODO Auto-generated method stub
}
@Override
public void updateRef(String columnLabel, Ref x) throws SQLException {
// TODO Auto-generated method stub
}
@Override
public void updateBlob(int columnIndex, Blob x) throws SQLException {
// TODO Auto-generated method stub
}
@Override
public void updateBlob(String columnLabel, Blob x) throws SQLException {
// TODO Auto-generated method stub
}
@Override
public void updateClob(int columnIndex, Clob x) throws SQLException {
// TODO Auto-generated method stub
}
@Override
public void updateClob(String columnLabel, Clob x) throws SQLException {
// TODO Auto-generated method stub
}
@Override
public void updateArray(int columnIndex, Array x) throws SQLException {
// TODO Auto-generated method stub
}
@Override
public void updateArray(String columnLabel, Array x) throws SQLException {
// TODO Auto-generated method stub
}
@Override
public RowId getRowId(int columnIndex) throws SQLException {
// TODO Auto-generated method stub
return null;
}
@Override
public RowId getRowId(String columnLabel) throws SQLException {
// TODO Auto-generated method stub
return null;
}
@Override
public void updateRowId(int columnIndex, RowId x) throws SQLException {
// TODO Auto-generated method stub
}
@Override
public void updateRowId(String columnLabel, RowId x) throws SQLException {
// TODO Auto-generated method stub
}
@Override
public int getHoldability() throws SQLException {
// TODO Auto-generated method stub
return 0;
}
@Override
public boolean isClosed() throws SQLException {
// TODO Auto-generated method stub
return false;
}
@Override
public void updateNString(int columnIndex, String nString)
throws SQLException {
// TODO Auto-generated method stub
}
@Override
public void updateNString(String columnLabel, String nString)
throws SQLException {
// TODO Auto-generated method stub
}
@Override
public void updateNClob(int columnIndex, NClob nClob) throws SQLException {
// TODO Auto-generated method stub
}
@Override
public void updateNClob(String columnLabel, NClob nClob)
throws SQLException {
// TODO Auto-generated method stub
}
@Override
public NClob getNClob(int columnIndex) throws SQLException {
// TODO Auto-generated method stub
return null;
}
@Override
public NClob getNClob(String columnLabel) throws SQLException {
// TODO Auto-generated method stub
return null;
}
@Override
public SQLXML getSQLXML(int columnIndex) throws SQLException {
// TODO Auto-generated method stub
return null;
}
@Override
public SQLXML getSQLXML(String columnLabel) throws SQLException {
// TODO Auto-generated method stub
return null;
}
@Override
public void updateSQLXML(int columnIndex, SQLXML xmlObject)
throws SQLException {
// TODO Auto-generated method stub
}
@Override
public void updateSQLXML(String columnLabel, SQLXML xmlObject)
throws SQLException {
// TODO Auto-generated method stub
}
@Override
public String getNString(int columnIndex) throws SQLException {
// TODO Auto-generated method stub
return null;
}
@Override
public String getNString(String columnLabel) throws SQLException {
// TODO Auto-generated method stub
return null;
}
@Override
public Reader getNCharacterStream(int columnIndex) throws SQLException {
// TODO Auto-generated method stub
return null;
}
@Override
public Reader getNCharacterStream(String columnLabel) throws SQLException {
// TODO Auto-generated method stub
return null;
}
@Override
public void updateNCharacterStream(int columnIndex, Reader x, long length)
throws SQLException {
// TODO Auto-generated method stub
}
@Override
public void updateNCharacterStream(String columnLabel, Reader reader,
long length) throws SQLException {
// TODO Auto-generated method stub
}
@Override
public void updateAsciiStream(int columnIndex, InputStream x, long length)
throws SQLException {
// TODO Auto-generated method stub
}
@Override
public void updateBinaryStream(int columnIndex, InputStream x, long length)
throws SQLException {
// TODO Auto-generated method stub
}
@Override
public void updateCharacterStream(int columnIndex, Reader x, long length)
throws SQLException {
// TODO Auto-generated method stub
}
@Override
public void updateAsciiStream(String columnLabel, InputStream x, long length)
throws SQLException {
// TODO Auto-generated method stub
}
@Override
public void updateBinaryStream(String columnLabel, InputStream x,
long length) throws SQLException {
// TODO Auto-generated method stub
}
@Override
public void updateCharacterStream(String columnLabel, Reader reader,
long length) throws SQLException {
// TODO Auto-generated method stub
}
@Override
public void updateBlob(int columnIndex, InputStream inputStream, long length)
throws SQLException {
// TODO Auto-generated method stub
}
@Override
public void updateBlob(String columnLabel, InputStream inputStream,
long length) throws SQLException {
// TODO Auto-generated method stub
}
@Override
public void updateClob(int columnIndex, Reader reader, long length)
throws SQLException {
// TODO Auto-generated method stub
}
@Override
public void updateClob(String columnLabel, Reader reader, long length)
throws SQLException {
// TODO Auto-generated method stub
}
@Override
public void updateNClob(int columnIndex, Reader reader, long length)
throws SQLException {
// TODO Auto-generated method stub
}
@Override
public void updateNClob(String columnLabel, Reader reader, long length)
throws SQLException {
// TODO Auto-generated method stub
}
@Override
public void updateNCharacterStream(int columnIndex, Reader x)
throws SQLException {
// TODO Auto-generated method stub
}
@Override
public void updateNCharacterStream(String columnLabel, Reader reader)
throws SQLException {
// TODO Auto-generated method stub
}
@Override
public void updateAsciiStream(int columnIndex, InputStream x)
throws SQLException {
// TODO Auto-generated method stub
}
@Override
public void updateBinaryStream(int columnIndex, InputStream x)
throws SQLException {
// TODO Auto-generated method stub
}
@Override
public void updateCharacterStream(int columnIndex, Reader x)
throws SQLException {
// TODO Auto-generated method stub
}
@Override
public void updateAsciiStream(String columnLabel, InputStream x)
throws SQLException {
// TODO Auto-generated method stub
}
@Override
public void updateBinaryStream(String columnLabel, InputStream x)
throws SQLException {
// TODO Auto-generated method stub
}
@Override
public void updateCharacterStream(String columnLabel, Reader reader)
throws SQLException {
// TODO Auto-generated method stub
}
@Override
public void updateBlob(int columnIndex, InputStream inputStream)
throws SQLException {
// TODO Auto-generated method stub
}
@Override
public void updateBlob(String columnLabel, InputStream inputStream)
throws SQLException {
// TODO Auto-generated method stub
}
@Override
public void updateClob(int columnIndex, Reader reader) throws SQLException {
// TODO Auto-generated method stub
}
@Override
public void updateClob(String columnLabel, Reader reader)
throws SQLException {
// TODO Auto-generated method stub
}
@Override
public void updateNClob(int columnIndex, Reader reader) throws SQLException {
// TODO Auto-generated method stub
}
@Override
public void updateNClob(String columnLabel, Reader reader)
throws SQLException {
// TODO Auto-generated method stub
}
@Override
public <T> T getObject(int columnIndex, Class<T> type) throws SQLException {
// TODO Auto-generated method stub
return null;
}
@Override
public <T> T getObject(String columnLabel, Class<T> type)
throws SQLException {
// TODO Auto-generated method stub
return null;
}
}
|
3e1dfd261677be74e7d9ae62f9ba78e1ef3c4353 | 5,440 | java | Java | sdk-fleet/src/main/kotlin/com/xee/sdk/fleet/model/Behavior.java | xee-lab/sdk-android | 817bf96dd9d92fcd8da27c124b82314ef2c7059c | [
"Apache-2.0"
] | 4 | 2017-11-18T20:43:38.000Z | 2021-04-02T10:11:43.000Z | sdk-fleet/src/main/kotlin/com/xee/sdk/fleet/model/Behavior.java | xee-lab/sdk-android | 817bf96dd9d92fcd8da27c124b82314ef2c7059c | [
"Apache-2.0"
] | null | null | null | sdk-fleet/src/main/kotlin/com/xee/sdk/fleet/model/Behavior.java | xee-lab/sdk-android | 817bf96dd9d92fcd8da27c124b82314ef2c7059c | [
"Apache-2.0"
] | 5 | 2017-11-18T20:42:39.000Z | 2018-12-13T22:59:02.000Z | 28.186528 | 83 | 0.600735 | 12,696 | package com.xee.sdk.fleet.model;
import android.os.Parcel;
import android.os.Parcelable;
import com.google.gson.annotations.SerializedName;
import java.util.Date;
import java.util.List;
public class Behavior implements Parcelable {
public static final String SPEED_LIMIT = "SPEED_LIMIT";
public static final String HARD_ACCELERATION = "HARD_ACCELERATION";
public static final String HARD_BRAKING = "HARD_BRAKING";
public static final String RPM_LIMIT = "RPM_LIMIT";
@SerializedName("behaviorId")
private long behaviorId;
@SerializedName("type")
private String type;
@SerializedName("startDate")
private Date startDate;
@SerializedName("endDate")
private Date endDate;
@SerializedName("value")
private double value;
@SerializedName("defaultValue")
private double defaultValue;
@SerializedName("reasons")
private List<String> reasons;
@SerializedName("count")
private Integer count;
public long getBehaviorId() {
return behaviorId;
}
public void setBehaviorId(long behaviorId) {
this.behaviorId = behaviorId;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public Date getStartDate() {
return startDate;
}
public void setStartDate(Date startDate) {
this.startDate = startDate;
}
public Date getEndDate() {
return endDate;
}
public void setEndDate(Date endDate) {
this.endDate = endDate;
}
public double getValue() {
return value;
}
public void setValue(double value) {
this.value = value;
}
public double getDefaultValue() {
return defaultValue;
}
public void setDefaultValue(double defaultValue) {
this.defaultValue = defaultValue;
}
public List<String> getReasons() {
return reasons;
}
public void setReasons(List<String> reason) {
this.reasons = reason;
}
public Integer getCount() {
return count;
}
public void setCount(Integer count) {
this.count = count;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Behavior behavior = (Behavior) o;
if (behaviorId != behavior.behaviorId) return false;
if (Double.compare(behavior.value, value) != 0) return false;
if (Double.compare(behavior.defaultValue, defaultValue) != 0) return false;
if (!type.equals(behavior.type)) return false;
if (!startDate.equals(behavior.startDate)) return false;
if (!endDate.equals(behavior.endDate)) return false;
if (!reasons.equals(behavior.reasons)) return false;
return count.equals(behavior.count);
}
@Override
public int hashCode() {
int result;
long temp;
result = (int) (behaviorId ^ (behaviorId >>> 32));
result = 31 * result + type.hashCode();
result = 31 * result + startDate.hashCode();
result = 31 * result + endDate.hashCode();
temp = Double.doubleToLongBits(value);
result = 31 * result + (int) (temp ^ (temp >>> 32));
temp = Double.doubleToLongBits(defaultValue);
result = 31 * result + (int) (temp ^ (temp >>> 32));
result = 31 * result + reasons.hashCode();
result = 31 * result + count.hashCode();
return result;
}
@Override
public String toString() {
return "Behavior{" +
"behaviorId=" + behaviorId +
", type='" + type + '\'' +
", startDate=" + startDate +
", endDate=" + endDate +
", value=" + value +
", defaultValue=" + defaultValue +
", reasons=" + reasons +
", count=" + count +
'}';
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeLong(this.behaviorId);
dest.writeString(this.type);
dest.writeLong(this.startDate != null ? this.startDate.getTime() : -1);
dest.writeLong(this.endDate != null ? this.endDate.getTime() : -1);
dest.writeDouble(this.value);
dest.writeDouble(this.defaultValue);
dest.writeStringList(this.reasons);
dest.writeValue(this.count);
}
public Behavior() {
}
protected Behavior(Parcel in) {
this.behaviorId = in.readLong();
this.type = in.readString();
long tmpStartDate = in.readLong();
this.startDate = tmpStartDate == -1 ? null : new Date(tmpStartDate);
long tmpEndDate = in.readLong();
this.endDate = tmpEndDate == -1 ? null : new Date(tmpEndDate);
this.value = in.readDouble();
this.defaultValue = in.readDouble();
this.reasons = in.createStringArrayList();
this.count = (Integer) in.readValue(Integer.class.getClassLoader());
}
public static final Creator<Behavior> CREATOR = new Creator<Behavior>() {
@Override
public Behavior createFromParcel(Parcel source) {
return new Behavior(source);
}
@Override
public Behavior[] newArray(int size) {
return new Behavior[size];
}
};
} |
3e1dfdef1d59fbd20a789ab59eef5b4443d9e83c | 3,773 | java | Java | MUtils/src/main/java/cn/mutils/core/io/serial/primitive/BoolItem.java | wavinsun/mUtils | 1f1117a060fbd2b1917579a41d45e4d0c3cfa554 | [
"MIT"
] | null | null | null | MUtils/src/main/java/cn/mutils/core/io/serial/primitive/BoolItem.java | wavinsun/mUtils | 1f1117a060fbd2b1917579a41d45e4d0c3cfa554 | [
"MIT"
] | null | null | null | MUtils/src/main/java/cn/mutils/core/io/serial/primitive/BoolItem.java | wavinsun/mUtils | 1f1117a060fbd2b1917579a41d45e4d0c3cfa554 | [
"MIT"
] | null | null | null | 27.34058 | 83 | 0.567453 | 12,697 | package cn.mutils.core.io.serial.primitive;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import cn.mutils.core.annotation.False;
import cn.mutils.core.annotation.Primitive;
import cn.mutils.core.annotation.PrimitiveType;
import cn.mutils.core.annotation.True;
import cn.mutils.core.beans.BeanField;
import cn.mutils.core.io.serial.Serial;
import cn.mutils.core.json.IJsonItem;
import cn.mutils.core.properties.IPropertyItem;
import cn.mutils.core.xml.IXmlItem;
import cn.mutils.core.xml.XmlUtil;
/**
* Support two data types: {"isOK":true} {"isOK":"true"}
*/
@SuppressWarnings({"serial", "UnnecessaryBoxing", "unused", "UnnecessaryUnboxing"})
public class BoolItem extends Serial<Boolean> {
protected String mTrue = "true";
protected String mFalse = "false";
public BoolItem() {
mType = PrimitiveType.STRING_BOOL;
mValue = Boolean.FALSE;
}
public BoolItem(boolean value) {
mType = PrimitiveType.STRING_BOOL;
mValue = Boolean.valueOf(value);
}
public BoolItem(String value) {
mType = PrimitiveType.STRING_BOOL;
mValue = Boolean.valueOf(value);
}
public boolean booleanValue() {
return mValue.booleanValue();
}
protected void init(BeanField itemField) {
if (itemField != null) {
Primitive type = itemField.getAnnotation(Primitive.class);
if (type != null) {
mType = type.value();
}
True t = itemField.getAnnotation(True.class);
if (t != null && !t.value().isEmpty()) {
mTrue = t.value();
}
False f = itemField.getAnnotation(False.class);
if (f != null && !f.value().isEmpty()) {
mFalse = f.value();
}
}
}
@Override
public IJsonItem fromJson(Object json, BeanField itemField) {
init(itemField);
String str = json.toString();
if (mType == PrimitiveType.STRING_BOOL) {
if (str.equals(mTrue)) {
mValue = Boolean.TRUE;
} else if (str.equals(mFalse)) {
mValue = Boolean.FALSE;
} else {
return null;
}
return this;
} else {
try {
mValue = Boolean.valueOf(str);
} catch (Exception e) {
return null;
}
return this;
}
}
@Override
public Object toJson(BeanField itemField) {
init(itemField);
if (mType == PrimitiveType.STRING_BOOL) {
return mValue ? mTrue : mFalse;
} else {
return mValue;
}
}
@Override
public IXmlItem fromXml(Node xml, BeanField itemField) {
init(itemField);
String str = xml.getTextContent();
if (str.equals(mTrue)) {
mValue = Boolean.TRUE;
} else if (str.equals(mFalse)) {
mValue = Boolean.FALSE;
} else {
return null;
}
return this;
}
@Override
public Node toXml(Document doc, BeanField itemField) {
init(itemField);
Node node = XmlUtil.newNode(doc, itemField);
node.setTextContent(mValue ? mTrue : mFalse);
return node;
}
@Override
public IPropertyItem fromProperty(String value, BeanField itemField) {
init(itemField);
if (value.equals(mTrue)) {
mValue = Boolean.TRUE;
} else if (value.equals(mFalse)) {
mValue = Boolean.FALSE;
} else {
return null;
}
return this;
}
@Override
public String toProperty(BeanField itemField) {
init(itemField);
return mValue ? mTrue : mFalse;
}
}
|
3e1dfe292fa159867265d8e3efe0b6c8a7668d1e | 557 | java | Java | common/src/main/java/com/zegelin/picocli/JMXServiceURLTypeConverter.java | Dlorite/cassandra-exporter | cb3e231f13448bdae59cee6a81703490feddca60 | [
"Apache-2.0"
] | 56 | 2018-10-11T15:33:55.000Z | 2022-03-22T05:50:30.000Z | common/src/main/java/com/zegelin/picocli/JMXServiceURLTypeConverter.java | Dlorite/cassandra-exporter | cb3e231f13448bdae59cee6a81703490feddca60 | [
"Apache-2.0"
] | 77 | 2018-10-03T22:20:39.000Z | 2022-02-02T19:10:07.000Z | common/src/main/java/com/zegelin/picocli/JMXServiceURLTypeConverter.java | edgelaboratories/cassandra-exporter | 6a7a401b4a889050d1823856dd6ee2f3cf5eb58e | [
"Apache-2.0"
] | 40 | 2018-10-13T18:53:19.000Z | 2022-03-03T07:50:43.000Z | 29.315789 | 119 | 0.719928 | 12,698 | package com.zegelin.picocli;
import picocli.CommandLine;
import javax.management.remote.JMXServiceURL;
import java.net.MalformedURLException;
public class JMXServiceURLTypeConverter implements CommandLine.ITypeConverter<JMXServiceURL> {
@Override
public JMXServiceURL convert(final String value) {
try {
return new JMXServiceURL(value);
} catch (final MalformedURLException e) {
throw new CommandLine.TypeConversionException("Invalid JMX service URL (" + e.getLocalizedMessage() + ")");
}
}
}
|
3e1dfe9a46067553f20d2a126e0fdd84f577a546 | 2,420 | java | Java | cookcc-core/src/main/java/org/yuanheng/cookcc/input/xml/TreeRuleCreator.java | coconut2015/cookcc | 8d9228a925ebb8557f067848b54341cc215c4d39 | [
"Apache-2.0"
] | 10 | 2015-06-16T22:22:05.000Z | 2021-07-02T23:01:33.000Z | cookcc-core/src/main/java/org/yuanheng/cookcc/input/xml/TreeRuleCreator.java | coconut2015/cookcc | 8d9228a925ebb8557f067848b54341cc215c4d39 | [
"Apache-2.0"
] | 7 | 2015-07-13T01:34:56.000Z | 2019-01-26T15:16:24.000Z | cookcc-core/src/main/java/org/yuanheng/cookcc/input/xml/TreeRuleCreator.java | coconut2015/cookcc | 8d9228a925ebb8557f067848b54341cc215c4d39 | [
"Apache-2.0"
] | 3 | 2017-05-30T21:30:53.000Z | 2020-11-22T19:55:28.000Z | 41.016949 | 150 | 0.758264 | 12,699 | /*
* Copyright (c) 2008-2013, Heng Yuan
* 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 Heng Yuan 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 Heng Yuan ''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 Heng Yuan BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.yuanheng.cookcc.input.xml;
import org.w3c.dom.Element;
import org.yuanheng.cookcc.doc.TreeRuleDoc;
import cookxml.core.DecodeEngine;
import cookxml.core.interfaces.Creator;
import cookxml.core.util.TextUtils;
/**
* @author Heng Yuan
* @since 0.4
*/
public class TreeRuleCreator implements Creator
{
@Override
public Object create (String parentNS, String parentTag, Element elm, Object parentObj, DecodeEngine decodeEngine) throws Exception
{
TreeRuleDoc treeRule = new TreeRuleDoc ();
Integer lineNum = (Integer)elm.getUserData ("line");
if (lineNum != null)
treeRule.setLineNumber (lineNum.intValue ());
treeRule.setGrammar (TextUtils.getText (elm));
return treeRule;
}
@Override
public Object editFinished (String parentNS, String parentTag, Element elm, Object parentObj, Object obj, DecodeEngine decodeEngine) throws Exception
{
return obj;
}
}
|
3e1dfed9b5def77f3192ce24290e8ca0c2c63703 | 6,286 | java | Java | entity-browser/src/test/java/emlkoks/entitybrowser/query/comparator/NumberComparatorTest.java | EmlKoks/EntityBrowser | bb2cfda4a310fe63fa6e9067edd834a10cf8ff4f | [
"Apache-2.0"
] | null | null | null | entity-browser/src/test/java/emlkoks/entitybrowser/query/comparator/NumberComparatorTest.java | EmlKoks/EntityBrowser | bb2cfda4a310fe63fa6e9067edd834a10cf8ff4f | [
"Apache-2.0"
] | null | null | null | entity-browser/src/test/java/emlkoks/entitybrowser/query/comparator/NumberComparatorTest.java | EmlKoks/EntityBrowser | bb2cfda4a310fe63fa6e9067edd834a10cf8ff4f | [
"Apache-2.0"
] | 1 | 2020-04-26T21:26:50.000Z | 2020-04-26T21:26:50.000Z | 44.9 | 120 | 0.751034 | 12,700 | package emlkoks.entitybrowser.query.comparator;
import emlkoks.entitybrowser.connection.provider.JpaProvider;
import emlkoks.entitybrowser.connection.provider.TestProvider;
import emlkoks.entitybrowser.query.FieldFilter;
import emlkoks.entitybrowser.session.entity.FieldProperty;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.Date;
import java.util.List;
import java.util.Set;
import javax.persistence.criteria.Path;
import org.hibernate.jpa.criteria.predicate.BetweenPredicate;
import org.hibernate.jpa.criteria.predicate.ComparisonPredicate;
import org.hibernate.jpa.criteria.predicate.NullnessPredicate;
import org.junit.BeforeClass;
import org.junit.Test;
import test.EntityWithInteger;
import static org.hamcrest.CoreMatchers.instanceOf;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.mock;
public class NumberComparatorTest {
private static Comparator comparator;
private static JpaProvider provider;
private static Path fieldPath;
private FieldProperty fieldProperty = mock(FieldProperty.class);
@BeforeClass
public static void init() {
provider = new TestProvider(EntityWithInteger.class).getProvider();
fieldPath = UtilClass.buildPath(provider.getCriteriaBuilder(), EntityWithInteger.class, "testInteger");
comparator = new NumberComparator();
}
@Test
public void canUseForClass() {
assertTrue(comparator.canUseForClass(int.class));
assertTrue(comparator.canUseForClass(float.class));
assertTrue(comparator.canUseForClass(long.class));
assertTrue(comparator.canUseForClass(double.class));
assertTrue(comparator.canUseForClass(short.class));
assertTrue(comparator.canUseForClass(Integer.class));
assertTrue(comparator.canUseForClass(Float.class));
assertTrue(comparator.canUseForClass(Long.class));
assertTrue(comparator.canUseForClass(Double.class));
assertTrue(comparator.canUseForClass(Short.class));
assertTrue(comparator.canUseForClass(BigInteger.class));
assertTrue(comparator.canUseForClass(BigDecimal.class));
}
@Test
public void canNotUseForClass() {
assertFalse(comparator.canUseForClass(Date.class));
assertFalse(comparator.canUseForClass(Boolean.class));
assertFalse(comparator.canUseForClass(String.class));
assertFalse(comparator.canUseForClass(List.class));
assertFalse(comparator.canUseForClass(Set.class));
}
@Test
public void createNullPredicate() {
var fieldFilter = new FieldFilter(ComparationType.IS_NULL, fieldProperty);
var predicate = comparator.createPredicate(provider.getCriteriaBuilder(), fieldPath, fieldFilter);
assertThat(predicate, instanceOf(NullnessPredicate.class));
}
@Test
public void createNotNullPredicate() {
var fieldFilter = new FieldFilter(ComparationType.IS_NOT_NULL, fieldProperty);
var predicate = comparator.createPredicate(provider.getCriteriaBuilder(), fieldPath, fieldFilter);
assertTrue(predicate.isNegated());
}
@Test
public void createEqualPredicate() {
var fieldFilter = new FieldFilter(ComparationType.EQUAL, fieldProperty);
var predicate =
(ComparisonPredicate) comparator.createPredicate(provider.getCriteriaBuilder(), fieldPath, fieldFilter);
assertEquals(ComparisonPredicate.ComparisonOperator.EQUAL, predicate.getComparisonOperator());
}
@Test
public void createNotEqualPredicate() {
var fieldFilter = new FieldFilter(ComparationType.NOT_EQUAL, fieldProperty);
var predicate =
(ComparisonPredicate) comparator.createPredicate(provider.getCriteriaBuilder(), fieldPath, fieldFilter);
assertEquals(ComparisonPredicate.ComparisonOperator.NOT_EQUAL, predicate.getComparisonOperator());
}
@Test
public void createGreaterPredicate() {
var fieldFilter = new FieldFilter(ComparationType.GREATER, fieldProperty);
var predicate =
(ComparisonPredicate) comparator.createPredicate(provider.getCriteriaBuilder(), fieldPath, fieldFilter);
assertEquals(ComparisonPredicate.ComparisonOperator.GREATER_THAN, predicate.getComparisonOperator());
}
@Test
public void createGreaterOrEqualPredicate() {
var fieldFilter = new FieldFilter(ComparationType.GREATER_OR_EQUAL, fieldProperty);
var predicate =
(ComparisonPredicate) comparator.createPredicate(provider.getCriteriaBuilder(), fieldPath, fieldFilter);
assertEquals(ComparisonPredicate.ComparisonOperator.GREATER_THAN_OR_EQUAL, predicate.getComparisonOperator());
}
@Test
public void createLessPredicate() {
var fieldFilter = new FieldFilter(ComparationType.LESS, fieldProperty);
var predicate =
(ComparisonPredicate) comparator.createPredicate(provider.getCriteriaBuilder(), fieldPath, fieldFilter);
assertEquals(ComparisonPredicate.ComparisonOperator.LESS_THAN, predicate.getComparisonOperator());
}
@Test
public void createLessOrEqualPredicate() {
var fieldFilter = new FieldFilter(ComparationType.LESS_OR_EQUAL, fieldProperty);
var predicate =
(ComparisonPredicate) comparator.createPredicate(provider.getCriteriaBuilder(), fieldPath, fieldFilter);
assertEquals(ComparisonPredicate.ComparisonOperator.LESS_THAN_OR_EQUAL, predicate.getComparisonOperator());
}
@Test
public void createBetweenPredicate() {
var fieldFilter = new FieldFilter(ComparationType.BETWEEN, fieldProperty, 1, 2);
var predicate = comparator.createPredicate(provider.getCriteriaBuilder(), fieldPath, fieldFilter);
assertThat(predicate, instanceOf(BetweenPredicate.class));
}
@Test(expected = ComparationTypeNotAllowedException.class)
public void createWrongPredicateForContains() {
var fieldFilter = new FieldFilter(ComparationType.CONTAINS, fieldProperty);
comparator.createPredicate(provider.getCriteriaBuilder(), fieldPath, fieldFilter);
}
} |
3e1dff08c1a99f92281a2d925411a3fd1eff765b | 877 | java | Java | src/integration-test/java/uk/gov/ida/integrationtest/helpers/AttributeFactory.java | uk-gov-mirror/alphagov.verify-matching-service-adapter | e48c03e28d908c5e0e5c3b51305b3acd334682e0 | [
"MIT"
] | 5 | 2017-11-01T10:30:23.000Z | 2018-07-17T09:18:02.000Z | src/integration-test/java/uk/gov/ida/integrationtest/helpers/AttributeFactory.java | uk-gov-mirror/alphagov.verify-matching-service-adapter | e48c03e28d908c5e0e5c3b51305b3acd334682e0 | [
"MIT"
] | 47 | 2017-11-07T12:06:21.000Z | 2022-01-11T15:44:28.000Z | src/integration-test/java/uk/gov/ida/integrationtest/helpers/AttributeFactory.java | uk-gov-mirror/alphagov.verify-matching-service-adapter | e48c03e28d908c5e0e5c3b51305b3acd334682e0 | [
"MIT"
] | 6 | 2017-10-31T22:17:36.000Z | 2021-04-10T18:07:40.000Z | 36.541667 | 103 | 0.802737 | 12,701 | package uk.gov.ida.integrationtest.helpers;
import com.google.inject.Inject;
import org.opensaml.saml.saml2.core.Attribute;
import uk.gov.ida.matchingserviceadapter.domain.UserAccountCreationAttribute;
import uk.gov.ida.saml.core.OpenSamlXmlObjectFactory;
public class AttributeFactory {
private final OpenSamlXmlObjectFactory openSamlXmlObjectFactory;
@Inject
public AttributeFactory(OpenSamlXmlObjectFactory openSamlXmlObjectFactory) {
this.openSamlXmlObjectFactory = openSamlXmlObjectFactory;
}
public Attribute createAttribute(final UserAccountCreationAttribute userAccountCreationAttribute) {
final Attribute attribute = openSamlXmlObjectFactory.createAttribute();
attribute.setName(userAccountCreationAttribute.getAttributeName());
attribute.setNameFormat(Attribute.UNSPECIFIED);
return attribute;
}
}
|
3e1dff16e1625c6950b102f1c0dd56707ab0de1c | 3,825 | java | Java | deobfuscator/src/main/java/net/runelite/deob/updater/UpdateMappings.java | SRLJustin/SanLite | 05ddd74502fbbfc2969e93f41467b40c3fa0124e | [
"BSD-2-Clause"
] | null | null | null | deobfuscator/src/main/java/net/runelite/deob/updater/UpdateMappings.java | SRLJustin/SanLite | 05ddd74502fbbfc2969e93f41467b40c3fa0124e | [
"BSD-2-Clause"
] | null | null | null | deobfuscator/src/main/java/net/runelite/deob/updater/UpdateMappings.java | SRLJustin/SanLite | 05ddd74502fbbfc2969e93f41467b40c3fa0124e | [
"BSD-2-Clause"
] | null | null | null | 34.772727 | 102 | 0.756601 | 12,702 | /*
* Copyright (c) 2016-2017, Adam <ychag@example.com>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package net.runelite.deob.updater;
import java.io.File;
import java.io.IOException;
import net.runelite.asm.ClassGroup;
import net.runelite.deob.deobfuscators.mapping.AnnotationIntegrityChecker;
import net.runelite.deob.deobfuscators.mapping.AnnotationMapper;
import net.runelite.deob.deobfuscators.mapping.Mapper;
import net.runelite.deob.deobfuscators.mapping.ParallelExecutorMapping;
import net.runelite.deob.deobfuscators.transformers.GraphicsObjectTransformer;
import net.runelite.deob.deobfuscators.transformers.ScriptOpcodesTransformer;
import net.runelite.deob.util.JarUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class UpdateMappings
{
private static final Logger logger = LoggerFactory.getLogger(UpdateMappings.class);
private final ClassGroup group1, group2;
public UpdateMappings(ClassGroup group1, ClassGroup group2)
{
this.group1 = group1;
this.group2 = group2;
}
public void update()
{
Mapper mapper = new Mapper(group1, group2);
mapper.run();
ParallelExecutorMapping mapping = mapper.getMapping();
AnnotationMapper amapper = new AnnotationMapper(group1, group2, mapping);
amapper.run();
AnnotationIntegrityChecker aic = new AnnotationIntegrityChecker(group1, group2, mapping);
aic.run();
int errors = aic.getErrors();
if (errors > 0)
{
logger.warn("Errors in annotation checker, exiting");
System.exit(-1);
}
AnnotationRenamer an = new AnnotationRenamer(group2);
an.run();
ParameterRenamer pr = new ParameterRenamer(group1, group2, mapping);
pr.run();
AnnotationAdder ad = new AnnotationAdder(group2);
ad.run();
new ScriptOpcodesTransformer().transform(group2);
new GraphicsObjectTransformer().transform(group2);
}
public void save(File out) throws IOException
{
JarUtil.save(group2, out);
}
public static void main(String[] args) throws IOException
{
if (args.length < 3 || (args[0].isEmpty() || args[1].isEmpty() || args[2].isEmpty()))
{
System.err.println("Syntax: rs_client_jar deob_jar output_jar");
System.exit(-1);
}
System.out.println("Updating mappings from: " + args[0] + " for deobfuscated gamepack: " + args[1]);
UpdateMappings updateMappings = new UpdateMappings(
JarUtil.load(new File(args[0]), true),
JarUtil.load(new File(args[1]), true)
);
updateMappings.update();
updateMappings.save(new File(args[2]));
System.out.println("Saved updated gamepack at: " + args[2]);
}
}
|
3e1dffa5585b5b39439322a49cd2a353e4560b87 | 5,865 | java | Java | accountstracker/src/com/st/accounts/LastTransactions.java | bane215/Yo_App | ebd089d4157078fcd3292e0a47978b4cc421b2c8 | [
"Apache-2.0"
] | null | null | null | accountstracker/src/com/st/accounts/LastTransactions.java | bane215/Yo_App | ebd089d4157078fcd3292e0a47978b4cc421b2c8 | [
"Apache-2.0"
] | null | null | null | accountstracker/src/com/st/accounts/LastTransactions.java | bane215/Yo_App | ebd089d4157078fcd3292e0a47978b4cc421b2c8 | [
"Apache-2.0"
] | null | null | null | 32.583333 | 96 | 0.751577 | 12,703 | package com.st.accounts;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.ViewGroup.LayoutParams;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import com.sqlite.helper.DatabaseHelper;
import com.table.Transaction;
import com.util.MySharedPref;
public class LastTransactions extends Activity {
private TableLayout tableLayout;
private ArrayList<String> arr_index;
private ArrayList<String> arr_transferAmount;
private ArrayList<String> arr_fromAccount;
private ArrayList<String> arr_toAccount;
private ArrayList<String> arr_transactionDate;
private int maxTrans;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_last_transactions);
String accntno = MySharedPref.getInstance(this).getString("account_number");
maxTrans = Integer.parseInt(MySharedPref.getInstance(this).getString("prevTrans"));
long accnt_no = Long.parseLong(accntno);
tableLayout = (TableLayout) findViewById(R.id.tbl);
DatabaseHelper db = new DatabaseHelper(this);
List<Transaction> tras_list = db.getAllTransactionByAcc(accnt_no);
arr_index = new ArrayList<String>();
arr_index.add("Transaction Id");
arr_transferAmount = new ArrayList<String>();
arr_transferAmount.add("Transfer Money");
arr_fromAccount = new ArrayList<String>();
arr_fromAccount.add("From Account");
arr_toAccount = new ArrayList<String>();
arr_toAccount.add("To Account");
arr_transactionDate = new ArrayList<String>();
arr_transactionDate.add("Transaction Date");
for(Transaction transaction1 : tras_list)
{
arr_index.add(String.valueOf(transaction1.getTransac_id()));
arr_transferAmount.add(String.valueOf(transaction1.getTransfer_amt()));
arr_fromAccount.add(String.valueOf(transaction1.getFrom_accountNo()));
arr_toAccount.add(String.valueOf(transaction1.getTo_accountNO()));
arr_transactionDate.add(transaction1.getTransict_date());
}
TableRow defrow = new TableRow(this);
TextView textview_a = new TextView(this);
textview_a.setPadding(5, 5, 5, 5);
textview_a.setBackgroundResource(R.drawable.textback);
String ss1 = String.valueOf(arr_index.get(0));
textview_a.setHeight(80);
textview_a.setTextSize(20);
textview_a.setText(ss1);
TextView textView_b = new TextView(this);
textView_b.setPadding(5, 5, 5, 5);
String ss2 = String.valueOf(arr_transferAmount.get(0));
textView_b.setBackgroundResource(R.drawable.textback);
textView_b.setHeight(80);
textView_b.setTextSize(20);
textView_b.setText(ss2);
TextView textView_c = new TextView(this);
textView_c.setPadding(5, 5, 5, 5);
String ss3 = arr_fromAccount.get(0);
textView_c.setBackgroundResource(R.drawable.textback);
textView_c.setHeight(80);
textView_c.setTextSize(20);
textView_c.setText(ss3);
TextView textView_d = new TextView(this);
textView_d.setPadding(5, 5, 5, 5);
String ss4 = arr_toAccount.get(0);
textView_d.setBackgroundResource(R.drawable.textback);
textView_d.setHeight(80);
textView_d.setTextSize(20);
textView_d.setText(ss4);
TextView textView_e = new TextView(this);
textView_e.setPadding(5, 5, 5, 5);
String ss5 = arr_transactionDate.get(0);
textView_e.setBackgroundResource(R.drawable.textback);
textView_e.setHeight(80);
textView_e.setTextSize(20);
textView_e.setText(ss5);
defrow.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));
defrow.addView(textview_a);
defrow.addView(textView_b);
defrow.addView(textView_c);
defrow.addView(textView_d);
defrow.addView(textView_e);
tableLayout.addView(defrow);
for(int i = arr_index.size()-1,j=0; i >0 && j<maxTrans;i--,j++)
{
TableRow row = new TableRow(this);
TextView textview_Index = new TextView(this);
textview_Index.setPadding(5, 5, 5, 5);
textview_Index.setBackgroundResource(R.drawable.textback);
String s1 = String.valueOf(arr_index.get(i));
if(s1==null)
{
break;
}
textview_Index.setHeight(80);
textview_Index.setTextSize(20);
textview_Index.setText(s1);
TextView textView_transAmt = new TextView(this);
textView_transAmt.setPadding(5, 5, 5, 5);
String s2 = String.valueOf(arr_transferAmount.get(i));
textView_transAmt.setBackgroundResource(R.drawable.textback);
textView_transAmt.setHeight(80);
textView_transAmt.setTextSize(20);
textView_transAmt.setText(s2);
TextView textView_fromAccn = new TextView(this);
textView_fromAccn.setPadding(5, 5, 5, 5);
String s3 = arr_fromAccount.get(i);
textView_fromAccn.setBackgroundResource(R.drawable.textback);
textView_fromAccn.setHeight(80);
textView_fromAccn.setTextSize(20);
textView_fromAccn.setText(s3);
TextView textView_toAccn = new TextView(this);
textView_toAccn.setPadding(5, 5, 5, 5);
String s4 = arr_toAccount.get(i);
textView_toAccn.setBackgroundResource(R.drawable.textback);
textView_toAccn.setHeight(80);
textView_toAccn.setTextSize(20);
textView_toAccn.setText(s4);
TextView textView_trasDate = new TextView(this);
textView_trasDate.setPadding(5, 5, 5, 5);
String s5 = arr_transactionDate.get(i);
textView_trasDate.setBackgroundResource(R.drawable.textback);
textView_trasDate.setHeight(80);
textView_trasDate.setTextSize(20);
textView_trasDate.setText(s5);
row.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));
row.addView(textview_Index);
row.addView(textView_transAmt);
row.addView(textView_fromAccn);
row.addView(textView_toAccn);
row.addView(textView_trasDate);
tableLayout.addView(row);
}
}
}
|
3e1e0040f4d1225bd26bde00851eb8e8a658c715 | 1,556 | java | Java | src/modelo/objetos/Cliente.java | work-teams/analysis-design-algorithms | 30de22a76eb45d8832d149f30a6ee65c1a903905 | [
"Unlicense"
] | null | null | null | src/modelo/objetos/Cliente.java | work-teams/analysis-design-algorithms | 30de22a76eb45d8832d149f30a6ee65c1a903905 | [
"Unlicense"
] | 15 | 2021-08-07T18:25:08.000Z | 2021-08-13T00:26:59.000Z | src/modelo/objetos/Cliente.java | work-teams/analysis-design-algorithms | 30de22a76eb45d8832d149f30a6ee65c1a903905 | [
"Unlicense"
] | null | null | null | 22.550725 | 137 | 0.630463 | 12,704 | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package modelo.objetos;
import java.io.Serializable;
/**
*
* @author krypt97
*/
public class Cliente implements Serializable {
// ATRIBUTOS DE CLASE
private String dni;
private String nombre;
private String apellido;
private int estadoPaciente; // 1=Grave, 2=Moderado, 3=Leve
// CONSTRUCTOR
public Cliente(String dni, String nombre, String apellido, int estadoPaciente) {
this.dni = dni;
this.nombre = nombre;
this.apellido = apellido;
this.estadoPaciente = estadoPaciente;
}
// SETTERS AND GETTERS
public String getDni() {
return dni;
}
public void setDni(String dni) {
this.dni = dni;
}
public String getNombre() {
return nombre;
}
public void setNombre(String nombre) {
this.nombre = nombre;
}
public String getApellido() {
return apellido;
}
public void setApellido(String apellido) {
this.apellido = apellido;
}
public int getEstadoPaciente() {
return estadoPaciente;
}
public void setEstadoPaciente(int estadoPaciente) {
this.estadoPaciente = estadoPaciente;
}
@Override
public String toString() {
return "Cliente{" + "dni=" + dni + ", nombre=" + nombre + ", apellido=" + apellido + ", estado_paciente=" + estadoPaciente + '}';
}
}
|
3e1e010e08f6e3c3af9531797b4ad03e8a5bd189 | 2,017 | java | Java | Isometric-Assignment/src/ie/gmit/sw/sprite/SpriteTile.java | Gazza1996/Advanced-Object-Oriented | f9462cbd870bb3ea4f8a40c4f97540cbea312942 | [
"MIT"
] | null | null | null | Isometric-Assignment/src/ie/gmit/sw/sprite/SpriteTile.java | Gazza1996/Advanced-Object-Oriented | f9462cbd870bb3ea4f8a40c4f97540cbea312942 | [
"MIT"
] | null | null | null | Isometric-Assignment/src/ie/gmit/sw/sprite/SpriteTile.java | Gazza1996/Advanced-Object-Oriented | f9462cbd870bb3ea4f8a40c4f97540cbea312942 | [
"MIT"
] | null | null | null | 16.808333 | 99 | 0.651958 | 12,705 | package ie.gmit.sw.sprite;
import java.awt.image.BufferedImage;
import java.util.List;
import ie.gmit.sw.Tile;
import ie.gmit.sw.player.Direction;
import ie.gmit.sw.player.Position;
public class SpriteTile extends Tile {
private Direction direction = Direction.RIGHT;
private boolean engaged;
private SpriteType type;
private List<BufferedImage> images;
private int index = 3;
private int dirIndex = 3;
private boolean canMove;
public SpriteTile() {
super();
}
public SpriteTile(Position p, int x, int y, List<BufferedImage> images, boolean e, SpriteType t) {
super(p, images.get(3), x, y);
this.engaged = e;
this.type = t;
}
public boolean isEngaged() {
return engaged;
}
public void setEngaged(boolean engaged) {
this.engaged = engaged;
}
public SpriteType getType() {
return type;
}
public void setType(SpriteType type) {
this.type = type;
}
public Direction getDirection() {
return this.direction;
}
public void setDirection(Direction d) {
direction = d;
/*
* changes our image when direction is changed
*/
switch (direction.getOrientation()) {
case 1:
if (index > 3 && index < 6) {
return;
}
changeImage(3);
break;
case 2:
if (index > 6 && index < 9) {
return;
}
changeImage(6);
break;
case 3:
if (index > 9 && index < 11) {
return;
}
changeImage(9);
break;
default:
if (index > 0 && index < 3) {
return;
}
changeImage(0);
break;
}
}
// the object steps
public BufferedImage step() {
index++;
if (index == dirIndex + 3) {
index = dirIndex;
}
BufferedImage image = type.getImg().get(index);
this.setImage(image);
return image;
}
public BufferedImage getImage(int i) {
return images.get(i);
}
public void setImage(List<BufferedImage> images) {
this.images = images;
}
private void changeImage(int i) {
index = i;
dirIndex = index;
this.setImage(type.getImg().get(index));
}
public boolean moveable() {
return canMove;
}
} |
3e1e016cef996d10b9140e9647a289828c3ef504 | 510 | java | Java | src/main/java/org/ligoj/app/plugin/prov/ProvisioningService.java | acleret69/plugin-prov | 6333636cb0bf1eadcc581f859a0851ed57b5de64 | [
"MIT"
] | 7 | 2017-04-14T07:53:21.000Z | 2022-02-08T18:00:52.000Z | src/main/java/org/ligoj/app/plugin/prov/ProvisioningService.java | acleret69/plugin-prov | 6333636cb0bf1eadcc581f859a0851ed57b5de64 | [
"MIT"
] | 165 | 2017-06-30T08:37:44.000Z | 2022-01-06T10:09:20.000Z | src/main/java/org/ligoj/app/plugin/prov/ProvisioningService.java | acleret69/plugin-prov | 6333636cb0bf1eadcc581f859a0851ed57b5de64 | [
"MIT"
] | 4 | 2017-06-14T12:29:34.000Z | 2021-02-12T07:57:03.000Z | 20.4 | 74 | 0.703922 | 12,706 | /*
* Licensed under MIT (https://github.com/ligoj/ligoj/blob/master/LICENSE)
*/
package org.ligoj.app.plugin.prov;
import java.util.Optional;
import org.ligoj.app.plugin.prov.model.VmOs;
/**
* Provisioning contract.
*/
public interface ProvisioningService {
/**
* Return the OS to lookup from the queried OS.
*
* @param os The required OS.
* @return The OS used in the lookup.
*/
default VmOs getCatalogOs(VmOs os) {
return Optional.ofNullable(os).map(VmOs::toPricingOs).orElse(os);
}
}
|
3e1e01abc6a2d1e94cdd001607296112a4fa175a | 511 | java | Java | louismall-member/src/main/java/com/louisblogs/louismall/member/service/IntegrationChangeHistoryService.java | Duang666/louismall | 42652c14a5bbda4dbb15a65047226a70370f8dae | [
"Apache-2.0"
] | null | null | null | louismall-member/src/main/java/com/louisblogs/louismall/member/service/IntegrationChangeHistoryService.java | Duang666/louismall | 42652c14a5bbda4dbb15a65047226a70370f8dae | [
"Apache-2.0"
] | null | null | null | louismall-member/src/main/java/com/louisblogs/louismall/member/service/IntegrationChangeHistoryService.java | Duang666/louismall | 42652c14a5bbda4dbb15a65047226a70370f8dae | [
"Apache-2.0"
] | 1 | 2021-07-13T02:55:32.000Z | 2021-07-13T02:55:32.000Z | 24.428571 | 99 | 0.795322 | 12,707 | package com.louisblogs.louismall.member.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.louisblogs.common.utils.PageUtils;
import com.louisblogs.louismall.member.entity.IntegrationChangeHistoryEntity;
import java.util.Map;
/**
* 积分变化历史记录
*
* @author luqi
* @email anpch@example.com
* @date 2021-05-17 11:04:55
*/
public interface IntegrationChangeHistoryService extends IService<IntegrationChangeHistoryEntity> {
PageUtils queryPage(Map<String, Object> params);
}
|
3e1e01e73bec7d50fa60607b452c3084df0f75f7 | 3,014 | java | Java | projects/OG-Engine/src/main/java/com/opengamma/engine/marketdata/historical/HistoricalMarketDataProvider.java | emcleod/OG-Platform | dbd4e1c64907f6a2dd27a62d252e9c61e609f779 | [
"Apache-2.0"
] | 12 | 2017-03-10T13:56:52.000Z | 2021-10-03T01:21:20.000Z | projects/OG-Engine/src/main/java/com/opengamma/engine/marketdata/historical/HistoricalMarketDataProvider.java | antikas/OG-Platform | aa683c63e58d33e34cca691290370d71a454077c | [
"Apache-2.0"
] | 1 | 2021-08-02T17:20:43.000Z | 2021-08-02T17:20:43.000Z | projects/OG-Engine/src/main/java/com/opengamma/engine/marketdata/historical/HistoricalMarketDataProvider.java | antikas/OG-Platform | aa683c63e58d33e34cca691290370d71a454077c | [
"Apache-2.0"
] | 16 | 2017-01-12T10:31:58.000Z | 2019-04-19T08:17:33.000Z | 43.681159 | 165 | 0.810883 | 12,708 | /**
* Copyright (C) 2012 - present by OpenGamma Inc. and the OpenGamma group of companies
*
* Please see distribution for license.
*/
package com.opengamma.engine.marketdata.historical;
import org.threeten.bp.Instant;
import org.threeten.bp.LocalDate;
import org.threeten.bp.ZoneOffset;
import com.opengamma.core.historicaltimeseries.HistoricalTimeSeriesResolver;
import com.opengamma.core.historicaltimeseries.HistoricalTimeSeriesSource;
import com.opengamma.engine.marketdata.MarketDataSnapshot;
import com.opengamma.engine.marketdata.spec.FixedHistoricalMarketDataSpecification;
import com.opengamma.engine.marketdata.spec.MarketDataSpecification;
/**
* Historical market data provider that requires data from a specific date.
*/
public class HistoricalMarketDataProvider extends AbstractHistoricalMarketDataProvider {
/**
* Creates an instance.
*
* @param historicalTimeSeriesSource the underlying source of historical data, not null
* @param historicalTimeSeriesResolver the time series resolver, not null
* @param timeSeriesResolverKey the source resolver key, or null to use the source default
*/
public HistoricalMarketDataProvider(final HistoricalTimeSeriesSource historicalTimeSeriesSource,
final HistoricalTimeSeriesResolver historicalTimeSeriesResolver, final String timeSeriesResolverKey) {
super(historicalTimeSeriesSource, historicalTimeSeriesResolver, timeSeriesResolverKey);
}
/**
* Creates an instance.
*
* @param historicalTimeSeriesSource the underlying source of historical data, not null
* @param historicalTimeSeriesResolver the time series resolver, not null
*/
public HistoricalMarketDataProvider(final HistoricalTimeSeriesSource historicalTimeSeriesSource, final HistoricalTimeSeriesResolver historicalTimeSeriesResolver) {
super(historicalTimeSeriesSource, historicalTimeSeriesResolver);
}
@Override
protected LocalDate getHistoricalResolutionDate(final MarketDataSpecification marketDataSpec) {
return ((FixedHistoricalMarketDataSpecification) marketDataSpec).getSnapshotDate();
}
@Override
public boolean isCompatible(final MarketDataSpecification marketDataSpec) {
if (!(marketDataSpec instanceof FixedHistoricalMarketDataSpecification)) {
return false;
}
return super.isCompatible(marketDataSpec);
}
@Override
public MarketDataSnapshot snapshot(final MarketDataSpecification marketDataSpec) {
final FixedHistoricalMarketDataSpecification historicalSpec = (FixedHistoricalMarketDataSpecification) marketDataSpec;
// TODO something better thought-out here
//Instant snapshotInstant = historicalSpec.getSnapshotDate().atMidnight().atZone(ZoneOffset.UTC).toInstant();
final Instant snapshotInstant = historicalSpec.getSnapshotDate().atTime(16, 0).atZone(ZoneOffset.UTC).toInstant();
final LocalDate snapshotDate = historicalSpec.getSnapshotDate();
return new HistoricalMarketDataSnapshot(getTimeSeriesSource(), snapshotInstant, snapshotDate);
}
}
|
3e1e03435899be72450bb762dd9375d8c12fd714 | 224 | java | Java | java_study/src/main/java/com/zhb/class01/OperateDemo.java | Crazy-z/study | 47f795254a79f1aedf56f39f5739570caf972ae8 | [
"Apache-2.0"
] | null | null | null | java_study/src/main/java/com/zhb/class01/OperateDemo.java | Crazy-z/study | 47f795254a79f1aedf56f39f5739570caf972ae8 | [
"Apache-2.0"
] | null | null | null | java_study/src/main/java/com/zhb/class01/OperateDemo.java | Crazy-z/study | 47f795254a79f1aedf56f39f5739570caf972ae8 | [
"Apache-2.0"
] | null | null | null | 16 | 44 | 0.535714 | 12,709 | package com.zhb.class01;
/**
* Created by zhb on 17-3-15.
*/
public class OperateDemo {
public static void main(String[] args) {
int x=1;
int y=2;
y=x++;
System.out.println(y);
}
}
|
3e1e039288863a3854a352fbce2a379189165408 | 9,826 | java | Java | modules/indexing/src/test/java/org/apache/ignite/internal/processors/query/IgniteInsertNullableDuplicatesSqlTest.java | tsdb-io/gridgain | 6726ed9cc34a7d2671a3625600c375939d40bc35 | [
"CC0-1.0"
] | null | null | null | modules/indexing/src/test/java/org/apache/ignite/internal/processors/query/IgniteInsertNullableDuplicatesSqlTest.java | tsdb-io/gridgain | 6726ed9cc34a7d2671a3625600c375939d40bc35 | [
"CC0-1.0"
] | null | null | null | modules/indexing/src/test/java/org/apache/ignite/internal/processors/query/IgniteInsertNullableDuplicatesSqlTest.java | tsdb-io/gridgain | 6726ed9cc34a7d2671a3625600c375939d40bc35 | [
"CC0-1.0"
] | null | null | null | 38.533333 | 116 | 0.569611 | 12,710 | /*
* Copyright 2019 GridGain Systems, Inc. and Contributors.
*
* Licensed under the GridGain Community Edition License (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.gridgain.com/products/software/community-edition/gridgain-community-edition-license
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.ignite.internal.processors.query;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.ignite.cache.QueryEntity;
import org.apache.ignite.cache.query.FieldsQueryCursor;
import org.apache.ignite.cache.query.SqlFieldsQuery;
import org.apache.ignite.configuration.CacheConfiguration;
import org.apache.ignite.internal.processors.cache.index.AbstractIndexingCommonTest;
import org.apache.ignite.internal.util.typedef.F;
import org.apache.ignite.transactions.TransactionDuplicateKeyException;
import org.junit.Test;
import static org.apache.ignite.testframework.GridTestUtils.assertThrows;
/**
* Checks the impossibility of inserting duplicate keys in case part of the key or the whole key is null or not set.
*/
public class IgniteInsertNullableDuplicatesSqlTest extends AbstractIndexingCommonTest {
/** {@inheritDoc} */
@Override protected void afterTestsStopped() throws Exception {
stopAllGrids();
super.afterTestsStopped();
}
/** {@inheritDoc} */
@Override protected void beforeTestsStarted() throws Exception {
super.beforeTestsStarted();
startGrids(1);
}
/** {@inheritDoc} */
@Override protected void afterTest() throws Exception {
super.afterTest();
for (String cacheName : grid(0).cacheNames())
grid(0).cache(cacheName).destroy();
}
/**
* Checks the impossibility of inserting duplicate keys in case part of the key is missing or null.
*/
@Test
public void testInsertKeyWithNullKeyParts() {
sql("CREATE TABLE test (id1 INT, id2 INT, val INT, CONSTRAINT PK PRIMARY KEY(id1, id2))");
sql("insert into test (id1, id2, val) values (1, null, 1);");
assertThrows(log,
() -> sql("insert into test (id1, id2, val) values (1, null, 1);"),
TransactionDuplicateKeyException.class,
"Duplicate key during INSERT");
assertThrows(log,
() -> sql("insert into test (id1, val) values (1, 1);"),
TransactionDuplicateKeyException.class,
"Duplicate key during INSERT");
assertEquals(sql("SELECT * FROM test").getAll().size(), 1);
}
/**
* Checks the impossibility of inserting duplicate keys in case the whole is missing or null.
*/
@Test
public void testInsertKeyWithNullKeys() {
sql("CREATE TABLE test (id1 INT, id2 INT, val INT, CONSTRAINT PK PRIMARY KEY(id1, id2))");
sql("insert into test (id1, id2, val) values (null, null, 1);");
assertThrows(log,
() -> sql("insert into test (id1, val) values (null, 1);"),
TransactionDuplicateKeyException.class,
"Duplicate key during INSERT");
assertThrows(log,
() -> sql("insert into test (id2, val) values (null, 1);"),
TransactionDuplicateKeyException.class,
"Duplicate key during INSERT");
assertThrows(log,
() -> sql("insert into test (id2, id1, val) values (null, null, 1);"),
TransactionDuplicateKeyException.class,
"Duplicate key during INSERT");
assertEquals(sql("SELECT * FROM test").getAll().size(), 1);
}
/**
* Checks the impossibility of inserting duplicate keys in case key is not set.
*/
@Test
public void testInsertKeyWhenKeyIsNotSet() {
sql("CREATE TABLE test (id1 INT, id2 INT, val INT, CONSTRAINT PK PRIMARY KEY(id1, id2))");
sql("insert into test (val) values (1);");
assertThrows(log,
() -> sql("insert into test (val) values (1);"),
TransactionDuplicateKeyException.class,
"Duplicate key during INSERT");
}
/**
* Checks the impossibility of inserting duplicate keys in case key is not set and default values is set.
*/
@Test
public void testInsertKeyWithNullKeyPartsDefault() {
sql("CREATE TABLE test (id1 INT, id2 INT DEFAULT 20, val INT, CONSTRAINT PK PRIMARY KEY(id1, id2))");
sql("insert into test (id1, val) values (0, 1);");
sql("insert into test (val) values (2);");
assertThrows(log,
() -> sql("insert into test (id1, val) values (0, 1);"),
TransactionDuplicateKeyException.class,
"Duplicate key during INSERT");
assertThrows(log,
() -> sql("insert into test (val) values (2);"),
TransactionDuplicateKeyException.class,
"Duplicate key during INSERT");
List<List<?>> sql = sql("select * from test order by val asc;").getAll();
assertEquals(sql.size(), 2);
assertEquals(sql.get(0).get(0), 0);
assertEquals(sql.get(0).get(1), 20);
assertEquals(sql.get(0).get(2), 1);
assertNull(sql.get(1).get(0));
assertEquals(sql.get(1).get(1), 20);
assertEquals(sql.get(1).get(2), 2);
}
/**
* Same test as above, but with table created by cache api.
*/
@Test
public void testInsertKeyWithNullKeyPartsDefaultCacheApi() {
Set<String> keyFields = new LinkedHashSet<>();
keyFields.add("ID1");
keyFields.add("ID2");
Map<String, Object> defsFK2 = new HashMap<>();
defsFK2.put("ID2", 20);
grid(0).getOrCreateCache(
new CacheConfiguration<>("test")
.setSqlSchema("PUBLIC")
.setQueryEntities(F.asList(
new QueryEntity("MY_KEY_TYPE", "MY_VALUE_TYPE")
.setTableName("TEST")
.addQueryField("ID1", Integer.class.getName(), "ID1")
.addQueryField("ID2", Integer.class.getName(), "ID2")
.addQueryField("VAL", Integer.class.getName(), "VAL")
.setKeyFields(keyFields)
.setDefaultFieldValues(defsFK2)
))
);
sql("insert into test (id1, val) values (0, 1);");
sql("insert into test (val) values (2);");
assertThrows(log,
() -> sql("insert into test (id1, val) values (0, 1);"),
TransactionDuplicateKeyException.class,
"Duplicate key during INSERT");
assertThrows(log,
() -> sql("insert into test (val) values (2);"),
TransactionDuplicateKeyException.class,
"Duplicate key during INSERT");
List<List<?>> sql = sql("select * from test order by val asc;").getAll();
assertEquals(sql.size(), 2);
assertEquals(sql.get(0).get(0), 0);
assertEquals(sql.get(0).get(1), 20);
assertEquals(sql.get(0).get(2), 1);
assertNull(sql.get(1).get(0));
assertEquals(sql.get(1).get(1), 20);
assertEquals(sql.get(1).get(2), 2);
}
/**
* Same test as above, but with table created by cache api.
*/
@Test
public void testInsertKeyWithNullKeyParts2() {
Set<String> keyFields = new LinkedHashSet<>();
keyFields.add("ID1");
keyFields.add("ID2");
grid(0).getOrCreateCache(
new CacheConfiguration<>("test")
.setSqlSchema("PUBLIC")
.setQueryEntities(F.asList(
new QueryEntity()
.setTableName("TEST")
.setKeyType("MY_KEY_TYPE")
.setValueType("MY_VALUE_TYPE")
.addQueryField("ID1", Integer.class.getName(), "ID1")
.addQueryField("ID2", Integer.class.getName(), "ID2")
.addQueryField("VAL", Integer.class.getName(), "VAL")
.setKeyFields(keyFields)
))
);
sql("insert into test (id1, id2, val) values (1, null, 1);");
assertThrows(log,
() -> sql("insert into test (id1, id2, val) values (1, null, 1);"),
TransactionDuplicateKeyException.class,
"Duplicate key during INSERT");
assertThrows(log,
() -> sql("insert into test (id1, val) values (1, 1);"),
TransactionDuplicateKeyException.class,
"Duplicate key during INSERT");
assertEquals(sql("SELECT * FROM test").getAll().size(), 1);
}
/**
* @param sql SQL query.
* @param args Query parameters.
* @return Results cursor.
*/
private FieldsQueryCursor<List<?>> sql(String sql, Object... args) {
return grid(0).context().query().querySqlFields(new SqlFieldsQuery(sql)
.setArgs(args), false);
}
}
|
3e1e03da2503b808d77a81b9471eb21f4a5c8e29 | 218 | java | Java | src/test/java/br/com/exemplo/merge/ExemploMergeApplicationTests.java | eliasborgeszup/exemplo-merge | 82a8607ee9bdfff08e0cf9be17cfaa6f029f397f | [
"MIT"
] | null | null | null | src/test/java/br/com/exemplo/merge/ExemploMergeApplicationTests.java | eliasborgeszup/exemplo-merge | 82a8607ee9bdfff08e0cf9be17cfaa6f029f397f | [
"MIT"
] | null | null | null | src/test/java/br/com/exemplo/merge/ExemploMergeApplicationTests.java | eliasborgeszup/exemplo-merge | 82a8607ee9bdfff08e0cf9be17cfaa6f029f397f | [
"MIT"
] | null | null | null | 15.571429 | 60 | 0.788991 | 12,711 | package br.com.exemplo.merge;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class ExemploMergeApplicationTests {
@Test
void contextLoads() {
}
}
|
3e1e04363c421bd28ffeb979a8350bd433db32a0 | 595 | java | Java | src/main/java/com/easyqa/qa/pages/util/CardData.java | MtstU/EasyQa | 8978bb69e66208f43cb8e780d1d5e0edbea65070 | [
"Apache-2.0"
] | null | null | null | src/main/java/com/easyqa/qa/pages/util/CardData.java | MtstU/EasyQa | 8978bb69e66208f43cb8e780d1d5e0edbea65070 | [
"Apache-2.0"
] | null | null | null | src/main/java/com/easyqa/qa/pages/util/CardData.java | MtstU/EasyQa | 8978bb69e66208f43cb8e780d1d5e0edbea65070 | [
"Apache-2.0"
] | null | null | null | 24.791667 | 82 | 0.690756 | 12,712 | package com.easyqa.qa.pages.util;
public class CardData {
private String cardName;
private String cardDescription;
private int issuePriority;
public CardData (String cardName, String cardDescription, int issuePriority) {
this.cardName = cardName;
this.cardDescription = cardDescription;
this.issuePriority = issuePriority;
}
public String getCardName() {
return this.cardName;
}
public String getCardDescription() {
return this.cardDescription;
}
public int getIssuePriority() { return this.issuePriority; }
}
|
3e1e044cb3a15a9022fb16b898b51929880f20de | 992 | java | Java | testsuite/wildfly/src/test/java/a/org/fakereplace/integration/wildfly/clientproxy/remoteejb/AppScopedBean.java | markiewb/fakereplace | 6391fc6b32fa716e5e7e6d82f071453dfc5b1561 | [
"Apache-2.0"
] | 114 | 2015-03-22T09:27:36.000Z | 2022-03-19T00:04:58.000Z | testsuite/wildfly/src/test/java/a/org/fakereplace/integration/wildfly/clientproxy/remoteejb/AppScopedBean.java | hlkiltas/fakereplace | 6391fc6b32fa716e5e7e6d82f071453dfc5b1561 | [
"Apache-2.0"
] | 26 | 2016-03-24T09:36:43.000Z | 2020-06-24T07:26:55.000Z | testsuite/wildfly/src/test/java/a/org/fakereplace/integration/wildfly/clientproxy/remoteejb/AppScopedBean.java | hlkiltas/fakereplace | 6391fc6b32fa716e5e7e6d82f071453dfc5b1561 | [
"Apache-2.0"
] | 31 | 2015-07-08T11:05:47.000Z | 2022-03-21T07:36:11.000Z | 29.176471 | 76 | 0.730847 | 12,713 | /*
* Copyright 2016, Stuart Douglas, and individual contributors as indicated
* by the @authors tag.
*
* 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 a.org.fakereplace.integration.wildfly.clientproxy.remoteejb;
import javax.enterprise.context.ApplicationScoped;
/**
* @author Stuart Douglas
*/
@ApplicationScoped
public class AppScopedBean {
private String value = "a";
public void setValue(final String value) {
this.value = value;
}
}
|
3e1e05f62358405c59f7730dfa9e0f5e18b2f3d9 | 323 | java | Java | src/com/yuhuizhao/designPattern/j2ee/compositeEntity/CompositeEntity.java | amosyhpz/DesignPattern | 8db484f9b8c31ee02ef9e0691457c50bacd3607b | [
"Apache-2.0"
] | null | null | null | src/com/yuhuizhao/designPattern/j2ee/compositeEntity/CompositeEntity.java | amosyhpz/DesignPattern | 8db484f9b8c31ee02ef9e0691457c50bacd3607b | [
"Apache-2.0"
] | null | null | null | src/com/yuhuizhao/designPattern/j2ee/compositeEntity/CompositeEntity.java | amosyhpz/DesignPattern | 8db484f9b8c31ee02ef9e0691457c50bacd3607b | [
"Apache-2.0"
] | null | null | null | 21.533333 | 64 | 0.687307 | 12,714 | package com.yuhuizhao.designPattern.j2ee.compositeEntity;
public class CompositeEntity {
private CoarseGrainedObject cgo = new CoarseGrainedObject();
public void setData(String data1, String data2) {
cgo.setData(data1, data2);
}
public String[] getData() {
return cgo.getData();
}
}
|
3e1e061079201f747cb36ffb4fed4c3c7440df8e | 761 | java | Java | vanlla-core/src/main/java/com/github/vanlla/core/util/DataFormatSerializer.java | vanlla/vanlla | 399a871f0fd88432989eec03bd821860ee7d2546 | [
"MIT"
] | null | null | null | vanlla-core/src/main/java/com/github/vanlla/core/util/DataFormatSerializer.java | vanlla/vanlla | 399a871f0fd88432989eec03bd821860ee7d2546 | [
"MIT"
] | null | null | null | vanlla-core/src/main/java/com/github/vanlla/core/util/DataFormatSerializer.java | vanlla/vanlla | 399a871f0fd88432989eec03bd821860ee7d2546 | [
"MIT"
] | null | null | null | 23.78125 | 132 | 0.69908 | 12,715 | package com.github.vanlla.core.util;
import com.alibaba.fastjson.serializer.JSONSerializer;
import com.alibaba.fastjson.serializer.SimpleDateFormatSerializer;
import java.io.IOException;
import java.lang.reflect.Type;
/**
* 日期格式化
*
* @author Vanlla
* @since 1.0
*/
public class DataFormatSerializer extends SimpleDateFormatSerializer {
public DataFormatSerializer(String pattern) {
super(pattern);
}
@Override
public void write(JSONSerializer serializer, Object object, Object fieldName, Type fieldType, int features) throws IOException {
if (object == null) {
serializer.out.writeString("");
} else {
super.write(serializer, object, fieldName, fieldType, features);
}
}
}
|
3e1e074b2c5304cc09be73442515fd0a35d5a4c8 | 3,566 | java | Java | app/src/main/java/com/jjoe64/graphview_demos/fragments/AddSeriesAtRuntime.java | bharaszti/MyGraphView | ef8ea4d261e2e98d79751f7f7a3346a855a27111 | [
"MIT"
] | null | null | null | app/src/main/java/com/jjoe64/graphview_demos/fragments/AddSeriesAtRuntime.java | bharaszti/MyGraphView | ef8ea4d261e2e98d79751f7f7a3346a855a27111 | [
"MIT"
] | null | null | null | app/src/main/java/com/jjoe64/graphview_demos/fragments/AddSeriesAtRuntime.java | bharaszti/MyGraphView | ef8ea4d261e2e98d79751f7f7a3346a855a27111 | [
"MIT"
] | null | null | null | 36.387755 | 98 | 0.676949 | 12,716 | /**
* This file is licensed under MIT
*
* The MIT License (MIT)
*
* Copyright (c) 2014 Jonas Gehring
*
* 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.jjoe64.graphview_demos.fragments;
import android.app.Activity;
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.Button;
import com.jjoe64.graphview.GraphView;
import com.jjoe64.graphview.LegendRenderer;
import com.jjoe64.graphview.series.DataPoint;
import com.jjoe64.graphview.series.LineGraphSeries;
import com.jjoe64.graphview_demos.MainActivity;
import com.jjoe64.graphview_demos.R;
import java.util.Random;
/**
* Created by jonas on 26.11.14.
*/
public class AddSeriesAtRuntime extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View rootView = inflater.inflate(R.layout.fragment_main_w_button, container, false);
Button btn = (Button) rootView.findViewById(R.id.button);
btn.setText("Add series");
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
GraphView graph = (GraphView) rootView.findViewById(R.id.graph);
graph.addSeries(new LineGraphSeries(generateData()));
}
});
btn = (Button) rootView.findViewById(R.id.button2);
btn.setText("Remove all series");
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
GraphView graph = (GraphView) rootView.findViewById(R.id.graph);
graph.removeAllSeries();
}
});
return rootView;
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
((MainActivity) activity).onSectionAttached(
getArguments().getInt(MainActivity.ARG_SECTION_NUMBER));
}
private DataPoint[] generateData() {
Random rand = new Random();
int count = 30;
DataPoint[] values = new DataPoint[count];
for (int i=0; i<count; i++) {
double x = i;
double f = rand.nextDouble()*0.15+0.3;
double y = Math.sin(i*f+2) + rand.nextDouble()*0.3;
DataPoint v = new DataPoint(x, y);
values[i] = v;
}
return values;
}
}
|
3e1e076fb3dbb509de941f932371fed3186cea0b | 5,398 | java | Java | src/test/java/slimeknights/tconstruct/library/tools/layout/LayoutIconTest.java | Unleveled-Network/TinkersConstruct | bb16fbebc14ecf7a34d650d8f70650db68405cae | [
"MIT"
] | 938 | 2015-01-02T07:42:45.000Z | 2022-03-24T02:56:40.000Z | src/test/java/slimeknights/tconstruct/library/tools/layout/LayoutIconTest.java | Unleveled-Network/TinkersConstruct | bb16fbebc14ecf7a34d650d8f70650db68405cae | [
"MIT"
] | 3,401 | 2015-01-01T00:02:58.000Z | 2022-03-30T04:51:38.000Z | src/test/java/slimeknights/tconstruct/library/tools/layout/LayoutIconTest.java | Unleveled-Network/TinkersConstruct | bb16fbebc14ecf7a34d650d8f70650db68405cae | [
"MIT"
] | 782 | 2015-01-02T12:08:34.000Z | 2022-03-31T13:52:05.000Z | 35.513158 | 136 | 0.745832 | 12,717 | package slimeknights.tconstruct.library.tools.layout;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonObject;
import io.netty.buffer.Unpooled;
import net.minecraft.item.ItemStack;
import net.minecraft.item.Items;
import net.minecraft.nbt.CompoundNBT;
import net.minecraft.network.PacketBuffer;
import net.minecraft.util.JSONUtils;
import org.junit.jupiter.api.Test;
import slimeknights.tconstruct.library.recipe.partbuilder.Pattern;
import slimeknights.tconstruct.library.tools.layout.LayoutIcon.ItemStackIcon;
import slimeknights.tconstruct.library.tools.layout.LayoutIcon.PatternIcon;
import slimeknights.tconstruct.test.BaseMcTest;
import java.util.Objects;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
class LayoutIconTest extends BaseMcTest {
/* Empty */
@Test
void empty_getValue_isEmpty() {
assertThat(LayoutIcon.EMPTY.getValue(ItemStack.class)).isNull();
assertThat(LayoutIcon.EMPTY.getValue(Pattern.class)).isNull();
}
@Test
void empty_bufferReadWrite() {
PacketBuffer buffer = new PacketBuffer(Unpooled.buffer());
LayoutIcon.EMPTY.write(buffer);
LayoutIcon decoded = LayoutIcon.read(buffer);
assertThat(decoded).isSameAs(LayoutIcon.EMPTY);
}
@Test
void empty_jsonSerialize() {
JsonObject json = LayoutIcon.EMPTY.toJson();
assertThat(json.entrySet()).isEmpty();
}
@Test
void empty_jsonDeserialize() {
JsonObject json = new JsonObject();
LayoutIcon parsed = LayoutIcon.SERIALIZER.deserialize(json, LayoutIcon.class, mock(JsonDeserializationContext.class));
assertThat(parsed).isSameAs(LayoutIcon.EMPTY);
}
/* Item */
@Test
void item_getValue_hasSameItem() {
ItemStack stack = new ItemStack(Items.DIAMOND_PICKAXE);
LayoutIcon itemIcon = LayoutIcon.ofItem(stack);
ItemStack contained = itemIcon.getValue(ItemStack.class);
assertThat(contained).isNotNull();
assertThat(contained).isSameAs(stack);
assertThat(itemIcon.getValue(Pattern.class)).isNull();
}
@Test
void item_bufferReadWrite() {
ItemStack original = new ItemStack(Items.DIAMOND_PICKAXE);
LayoutIcon itemIcon = LayoutIcon.ofItem(original);
PacketBuffer buffer = new PacketBuffer(Unpooled.buffer());
itemIcon.write(buffer);
LayoutIcon decoded = LayoutIcon.read(buffer);
assertThat(decoded).isInstanceOf(ItemStackIcon.class);
ItemStack stack = decoded.getValue(ItemStack.class);
assertThat(stack).isNotNull();
assertThat(ItemStack.areItemStacksEqual(original, stack)).isTrue();
}
@Test
void item_jsonSerialize() {
ItemStack original = new ItemStack(Items.DIAMOND_PICKAXE);
LayoutIcon itemIcon = LayoutIcon.ofItem(original);
JsonObject json = itemIcon.toJson();
assertThat(json.entrySet()).hasSize(2);
assertThat(JSONUtils.getString(json, "item")).isEqualTo(Objects.requireNonNull(Items.DIAMOND_PICKAXE.getRegistryName()).toString());
assert original.getTag() != null;
assertThat(JSONUtils.getString(json, "nbt")).isEqualTo(original.getTag().toString());
}
@Test
void item_jsonDeserialize() {
JsonObject json = new JsonObject();
json.addProperty("item", Objects.requireNonNull(Items.DIAMOND.getRegistryName()).toString());
json.addProperty("nbt", "{test:1}");
LayoutIcon icon = LayoutIcon.SERIALIZER.deserialize(json, LayoutIcon.class, mock(JsonDeserializationContext.class));
assertThat(icon).isInstanceOf(ItemStackIcon.class);
ItemStack stack = icon.getValue(ItemStack.class);
assertThat(stack).isNotNull();
assertThat(stack.getItem()).isEqualTo(Items.DIAMOND);
CompoundNBT nbt = stack.getTag();
assertThat(nbt).isNotNull();
assertThat(nbt.getInt("test")).isEqualTo(1);
}
/* Pattern */
@Test
void pattern_getValue_hasSamePattern() {
Pattern pattern = new Pattern("test:the_pattern");
LayoutIcon itemIcon = LayoutIcon.ofPattern(pattern);
Pattern contained = itemIcon.getValue(Pattern.class);
assertThat(contained).isNotNull();
assertThat(contained).isEqualTo(pattern);
assertThat(itemIcon.getValue(ItemStack.class)).isNull();
}
@Test
void pattern_bufferReadWrite() {
Pattern pattern = new Pattern("test:the_pattern");
LayoutIcon icon = LayoutIcon.ofPattern(pattern);
PacketBuffer buffer = new PacketBuffer(Unpooled.buffer());
icon.write(buffer);
LayoutIcon decoded = LayoutIcon.read(buffer);
assertThat(decoded).isInstanceOf(PatternIcon.class);
Pattern contained = decoded.getValue(Pattern.class);
assertThat(contained).isNotNull();
assertThat(contained).isEqualTo(pattern);
}
@Test
void pattern_jsonSerialize() {
Pattern pattern = new Pattern("test:the_pattern");
LayoutIcon icon = LayoutIcon.ofPattern(pattern);
JsonObject json = icon.toJson();
assertThat(json.entrySet()).hasSize(1);
assertThat(JSONUtils.getString(json, "pattern")).isEqualTo(pattern.toString());
}
@Test
void pattern_jsonDeserialize() {
JsonObject json = new JsonObject();
json.addProperty("pattern", "test:json_pattern");
LayoutIcon parsed = LayoutIcon.SERIALIZER.deserialize(json, LayoutIcon.class, mock(JsonDeserializationContext.class));
Pattern contained = parsed.getValue(Pattern.class);
assertThat(contained).isNotNull();
assertThat(contained).isEqualTo(new Pattern("test:json_pattern"));
}
}
|
3e1e07d0d2dcd5842f6acfad7a0d61ade14a609e | 3,812 | java | Java | app/src/main/java/com/handsomezhou/xdesktophelper/constant/Constant.java | handsomezhou/XDesktopHelper | e9bee8386898eb3123869184af8b73c31abea98f | [
"Apache-2.0"
] | 23 | 2015-10-01T00:33:52.000Z | 2022-03-21T11:52:45.000Z | app/src/main/java/com/handsomezhou/xdesktophelper/constant/Constant.java | handsomezhou/XDesktopHelper | e9bee8386898eb3123869184af8b73c31abea98f | [
"Apache-2.0"
] | 1 | 2018-03-08T03:40:25.000Z | 2018-09-18T08:35:52.000Z | app/src/main/java/com/handsomezhou/xdesktophelper/constant/Constant.java | handsomezhou/XDesktopHelper | e9bee8386898eb3123869184af8b73c31abea98f | [
"Apache-2.0"
] | 4 | 2017-03-10T15:01:42.000Z | 2021-02-20T14:38:50.000Z | 23.677019 | 49 | 0.500262 | 12,718 |
package com.handsomezhou.xdesktophelper.constant;
/**
* Created by handsomezhou.
*/
public interface Constant {
/* start: char */
//https://en.wikipedia.org/wiki/ASCII
//start: ASCII control code chart
char NULL_CHARACTER = '\0';
char BACKSPACE = '\b';
char HORIZONTAL_TAB_CHARACTERS = '\t';
char NEW_LINE = '\n';
char PAGE_BREAK = '\f';
char CARRIAGE_RETURN = '\r';
//end: ASCII control code chart
/*start: ASCII printable code chart*/
char SPACE = ' ';
char EXCLAMATION_MARK = '!';
char QUOTATION_MARK = '"';
char NUMBER_SIGN = '#';
char DOLLAR_SIGN = '$';
char PERCENT_SIGN = '%';
char AMPERSAND = '&';
char APOSTROPHE = '\'';
char LEFT_ROUND_BRACKETS = '(';
char RIGHT_ROUND_BRACKETS = ')';
char ASTERISK = '*';
char PLUS_SIGN = '+';
char COMMA = ',';
char HYPHEN_MINUS = '-';
char FULL_STOP = '.';
char SLASH = '/';
char NUMBER_0 = '0';
char NUMBER_1 = '1';
char NUMBER_2 = '2';
char NUMBER_3 = '3';
char NUMBER_4 = '4';
char NUMBER_5 = '5';
char NUMBER_6 = '6';
char NUMBER_7 = '7';
char NUMBER_8 = '8';
char NUMBER_9 = '9';
char COLON = ':';
char SEMICOLON = ';';
char LESS_THAN_SIGN = '<';
char EQUALS_SIGN = '=';
char GREATER_THAN_SIGN = '>';
char QUESTION_MARK = '?';
char AT_SIGN = '@';
char A = 'A';
char B = 'B';
char C = 'C';
char D = 'D';
char E = 'E';
char F = 'F';
char G = 'G';
char H = 'H';
char I = 'I';
char J = 'J';
char K = 'K';
char L = 'L';
char M = 'M';
char N = 'N';
char O = 'O';
char P = 'P';
char Q = 'Q';
char R = 'R';
char S = 'S';
char T = 'T';
char U = 'U';
char V = 'V';
char W = 'W';
char X = 'X';
char Y = 'Y';
char Z = 'Z';
char LEFT_SQUARE_BRACKETS = '[';
char BACKSLASH = '\\';
char RIGHT_SQUARE_BRACKETS = ']';
char CARET = '^';
char UNDERSCORE = '_';
char GRAVE_ACCENT = '`';
char a = 'a';
char b = 'b';
char c = 'c';
char d = 'd';
char e = 'e';
char f = 'f';
char g = 'g';
char h = 'h';
char i = 'i';
char j = 'j';
char k = 'k';
char l = 'l';
char m = 'm';
char n = 'n';
char o = 'o';
char p = 'p';
char q = 'q';
char r = 'r';
char s = 's';
char t = 't';
char u = 'u';
char v = 'v';
char w = 'w';
char x = 'x';
char y = 'y';
char z = 'z';
char LEFT_CURLY_BRACKETS = '{';
char VERTICAL_BAR = '|';
char RIGHT_CURLY_BRACKETS = '}';
char TILDE = '~';
/*end: ASCII printable code chart*/
/* end: char */
/* start: String */
String UNKNOW = "--";
String NULL_STRING = "";
String NULL = "null";
String FORMAT_ONE_DECIMAL_PLACES = "%.1f";
String FORMAT_TWO_DECIMAL_PLACES = "%.2f";
String INT_TWO_DECIMAL_PLACES = "%02d";
/* end: String */
/* start: int */
int PERCENT_NUMBER = 100;
int TEN_THOUSAND = 10000;
int ZERO_OF_INTEGER = 0;
int ONE_OF_INTEGER = 1;
int TWO_OF_INTEGER = 2;
int THREE_OF_INTEGER = 3;
int FOUR_OF_INTEGER = 4;
int FIVE_OF_INTEGER = 5;
int SIX_OF_INTEGER = 6;
int SEVEN_OF_INTEGER = 7;
int EIGHT_OF_INTEGER = 8;
int NINE_OF_INTEGER = 9;
int TEN_OF_INTEGER = 10;
int HUNDRED_OF_INTEGER = 100;
int THOUSAND_OF_INTEGER = 1000;
int TRUE = 1;
int FALSE = 0;
/* end: int */
/* start: Double */
double ZERO_OF_DOUBLE_BOUNDARY = 0.000001;
double ZERO_OF_DOUBLE = 0.0;
/* end: Double */
/* start: long */
long ZERO_OF_LONG = 0;
/* end: long */
}
|
3e1e0965d762d6b00f3e1fdf6f3bc96eb75586fe | 2,020 | java | Java | jhipster-framework/src/main/java/io/github/jhipster/web/util/reactive/ResponseUtil.java | AutoscanForJavaFork/jhipster | b3d85e0b39fa3dabacaf486deaff1508484f2935 | [
"Apache-2.0"
] | 450 | 2016-12-12T19:11:54.000Z | 2022-02-07T13:28:44.000Z | jhipster-framework/src/main/java/io/github/jhipster/web/util/reactive/ResponseUtil.java | AutoscanForJavaFork/jhipster | b3d85e0b39fa3dabacaf486deaff1508484f2935 | [
"Apache-2.0"
] | 464 | 2020-07-27T06:55:53.000Z | 2022-03-31T06:03:42.000Z | jhipster-framework/src/main/java/io/github/jhipster/web/util/reactive/ResponseUtil.java | atomfrede/jhipster | 9e2ed902177de5db24a00695f80d1bee39f5d2de | [
"Apache-2.0"
] | 346 | 2016-12-14T22:23:57.000Z | 2022-02-11T18:10:11.000Z | 50.5 | 166 | 0.726238 | 12,719 | package io.github.jhipster.web.util.reactive;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.server.ResponseStatusException;
import reactor.core.publisher.Mono;
/**
* Utility class for ResponseEntity creation in a reactive context.
*/
public interface ResponseUtil {
/**
* Wrap the mono into a {@link org.springframework.http.ResponseEntity} with an {@link org.springframework.http.HttpStatus#OK} status, or if it's empty, it
* returns a {@link org.springframework.http.ResponseEntity} with {@link org.springframework.http.HttpStatus#NOT_FOUND}.
*
* @param <X> type of the response
* @param maybeResponse response to return if present
* @return response containing {@code maybeResponse} if present or {@link org.springframework.http.HttpStatus#NOT_FOUND}
*/
static <X> Mono<ResponseEntity<X>> wrapOrNotFound(Mono<X> maybeResponse) {
return wrapOrNotFound(maybeResponse, null);
}
/**
* Wrap the mono into a {@link org.springframework.http.ResponseEntity} with an {@link org.springframework.http.HttpStatus#OK} status with the headers, or if it's
* empty, throws a {@link org.springframework.web.server.ResponseStatusException} with status {@link org.springframework.http.HttpStatus#NOT_FOUND}.
*
* @param <X> type of the response
* @param maybeResponse response to return if present
* @param headers headers to be added to the response
* @return response containing {@code maybeResponse} if present or {@link org.springframework.http.HttpStatus#NOT_FOUND}
*/
static <X> Mono<ResponseEntity<X>> wrapOrNotFound(Mono<X> maybeResponse, HttpHeaders headers) {
return maybeResponse
.switchIfEmpty(Mono.error(new ResponseStatusException(HttpStatus.NOT_FOUND)))
.map(response -> ResponseEntity.ok().headers(headers).body(response));
}
}
|
3e1e09b3068de50a82333743f39b230a3b00312d | 860 | java | Java | cartes/src/main/java/fr/duforat/demos/cartes/config/CartesEndpointConfiguration.java | neokeld/deliverat | 87d46b199aae9880fc5c3097acded45329c57926 | [
"MIT"
] | null | null | null | cartes/src/main/java/fr/duforat/demos/cartes/config/CartesEndpointConfiguration.java | neokeld/deliverat | 87d46b199aae9880fc5c3097acded45329c57926 | [
"MIT"
] | 19 | 2020-02-20T17:00:14.000Z | 2021-06-05T05:17:08.000Z | cartes/src/main/java/fr/duforat/demos/cartes/config/CartesEndpointConfiguration.java | neokeld/deliverat | 87d46b199aae9880fc5c3097acded45329c57926 | [
"MIT"
] | null | null | null | 34.4 | 86 | 0.82093 | 12,720 | package fr.duforat.demos.cartes.config;
import static org.springframework.web.reactive.function.server.RequestPredicates.GET;
import static org.springframework.web.reactive.function.server.RequestPredicates.POST;
import static org.springframework.web.reactive.function.server.RouterFunctions.route;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.reactive.function.server.RouterFunction;
import org.springframework.web.reactive.function.server.ServerResponse;
import fr.duforat.demos.cartes.handler.CartesHandler;
@Configuration
public class CartesEndpointConfiguration {
@Bean
public RouterFunction<ServerResponse> routes(CartesHandler handler) {
return route(GET("/cartes"), handler::all)
.andRoute(POST("/cartes"), handler::create);
}
}
|
3e1e09ceb404fe8ad15e9ff8bee116c148b3ea8b | 833 | java | Java | src/main/java/com/sillycat/springbootcxf/web/HelloController.java | yiyikang/spring-boot2-cxf | 6276af62a370e8afa044ce5708e4b594885ec0a0 | [
"MIT"
] | null | null | null | src/main/java/com/sillycat/springbootcxf/web/HelloController.java | yiyikang/spring-boot2-cxf | 6276af62a370e8afa044ce5708e4b594885ec0a0 | [
"MIT"
] | null | null | null | src/main/java/com/sillycat/springbootcxf/web/HelloController.java | yiyikang/spring-boot2-cxf | 6276af62a370e8afa044ce5708e4b594885ec0a0 | [
"MIT"
] | null | null | null | 30.851852 | 92 | 0.801921 | 12,721 | package com.sillycat.springbootcxf.web;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/api/hello")
public class HelloController {
protected final Logger LOGGER = LoggerFactory.getLogger(this.getClass());
@GetMapping(value = "/mini")
@ResponseBody
public ResponseEntity<?> list() {
LOGGER.info("HelloController entered.");
ResponseEntity<?> response = new ResponseEntity<String>("hello YiYi Kang", HttpStatus.OK);
return response;
}
}
|
3e1e0a19e798c852005a43ffc22259cde6f5a263 | 1,559 | java | Java | alarm/AlarmService.java | Rajnita/Android-Projects | 288fc1ed2e8ed3884a389f3b2e460a579ae25b79 | [
"Apache-2.0"
] | null | null | null | alarm/AlarmService.java | Rajnita/Android-Projects | 288fc1ed2e8ed3884a389f3b2e460a579ae25b79 | [
"Apache-2.0"
] | null | null | null | alarm/AlarmService.java | Rajnita/Android-Projects | 288fc1ed2e8ed3884a389f3b2e460a579ae25b79 | [
"Apache-2.0"
] | null | null | null | 34.644444 | 92 | 0.684413 | 12,722 | package com.example.student.alarmclock;
/**
* Created by student on 5/8/16.
*/
import android.app.IntentService;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
public class AlarmService extends IntentService {
private NotificationManager alarmNotificationManager;
public AlarmService() {
super("AlarmService");
}
@Override
public void onHandleIntent(Intent intent) {
sendNotification("Wake Up! Wake Up!");
}
private void sendNotification(String msg) {
Log.d("AlarmService", "Preparing to send notification...: " + msg);
alarmNotificationManager = (NotificationManager) this
.getSystemService(Context.NOTIFICATION_SERVICE);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
new Intent(this, AlarmActivity.class), 0);
NotificationCompat.Builder alamNotificationBuilder = new NotificationCompat.Builder(
this).setContentTitle("Alarm").setSmallIcon(R.drawable.ic_launcher)
.setStyle(new NotificationCompat.BigTextStyle().bigText(msg))
.setContentText(msg);
alamNotificationBuilder.setContentIntent(contentIntent);
alarmNotificationManager.notify(1, alamNotificationBuilder.build());
Log.d("AlarmService", "Notification sent.");
}
} |
3e1e0a20185a7f90fa7bfff3dcdd0bdefd7bed8a | 11,561 | java | Java | kie-remote/kie-remote-services/src/main/java/org/kie/remote/services/rest/query/helpers/InternalTaskQueryHelper.java | cristianonicolai/droolsjbpm-integration | d8163f1f3737c8fb46da2e1a95b7e7da12e1da4e | [
"Apache-2.0"
] | null | null | null | kie-remote/kie-remote-services/src/main/java/org/kie/remote/services/rest/query/helpers/InternalTaskQueryHelper.java | cristianonicolai/droolsjbpm-integration | d8163f1f3737c8fb46da2e1a95b7e7da12e1da4e | [
"Apache-2.0"
] | null | null | null | kie-remote/kie-remote-services/src/main/java/org/kie/remote/services/rest/query/helpers/InternalTaskQueryHelper.java | cristianonicolai/droolsjbpm-integration | d8163f1f3737c8fb46da2e1a95b7e7da12e1da4e | [
"Apache-2.0"
] | null | null | null | 45.876984 | 148 | 0.683937 | 12,723 | /*
* Copyright 2015 Red Hat, Inc. and/or its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.kie.remote.services.rest.query.helpers;
import static org.kie.remote.services.rest.ResourceBase.getMaxNumResultsNeeded;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.jbpm.process.audit.JPAAuditLogService;
import org.jbpm.process.audit.VariableInstanceLog;
import org.jbpm.process.instance.command.GetProcessInstanceVariableCommand;
import org.jbpm.query.jpa.impl.QueryCriteriaUtil;
import org.jbpm.services.task.commands.TaskSummaryQueryCommand;
import org.jbpm.services.task.query.TaskSummaryImpl;
import org.kie.api.task.model.TaskSummary;
import org.kie.remote.services.rest.ResourceBase;
import org.kie.remote.services.rest.exception.KieRemoteRestOperationException;
import org.kie.remote.services.rest.query.RemoteServicesQueryCommandBuilder;
import org.kie.remote.services.rest.query.RemoteServicesQueryCommandBuilder.OrderBy;
import org.kie.remote.services.rest.query.RemoteServicesQueryJPAService;
import org.kie.services.client.serialization.jaxb.impl.query.JaxbQueryTaskInfo;
import org.kie.services.client.serialization.jaxb.impl.query.JaxbQueryTaskResult;
import org.kie.services.client.serialization.jaxb.impl.query.JaxbVariableInfo;
import org.kie.services.client.serialization.jaxb.impl.task.JaxbTaskSummary;
/**
* This class contains the core logic for processing the query parameters from a
* REST task query call to a {@link JaxbQueryTaskResult} instance.
*/
public class InternalTaskQueryHelper extends AbstractInternalQueryHelper<JaxbQueryTaskResult> {
public InternalTaskQueryHelper(ResourceBase resourceBase) {
super(resourceBase);
}
/*
* (non-Javadoc)
* @see org.kie.remote.services.rest.query.AbstractInternalQueryHelper#createAndSetQueryBuilders(java.lang.String)
*/
@Override
protected void createAndSetQueryBuilders(String identity) {
if( identity == null || identity.trim().isEmpty() ) {
throw KieRemoteRestOperationException.forbidden("Unknown and unauthorized user [" + identity + "] when querying tasks" );
}
// setup query builders
RemoteServicesQueryCommandBuilder taskQueryBuilder = new RemoteServicesQueryCommandBuilder(identity);
RemoteServicesQueryCommandBuilder varInstLogQueryBuilder = new RemoteServicesQueryCommandBuilder();
setQueryBuilders(taskQueryBuilder, varInstLogQueryBuilder);
}
/*
* (non-Javadoc)
* @see org.kie.remote.services.rest.query.AbstractInternalQueryHelper#doQueryAndCreateResultObjects(boolean, boolean)
*/
@Override
public JaxbQueryTaskResult doQueryAndCreateResultObjects( boolean onlyRetrieveLastVarLogs, boolean workFlowInstanceVariables, int [] pageInfo) {
// setup
RemoteServicesQueryCommandBuilder [] queryBuilders = getQueryBuilders();
RemoteServicesQueryCommandBuilder taskQueryBuilder = queryBuilders[0];
RemoteServicesQueryCommandBuilder varInstLogQueryBuilder = queryBuilders[1];
if( variableCriteriaInQuery(varInstLogQueryBuilder.getQueryWhere().getCriteria()) && onlyRetrieveLastVarLogs ) {
taskQueryBuilder.last();
varInstLogQueryBuilder.last();
}
/**
* TODO: Add pagination information to task query:
* The problem:
* A. Because paging is *by process instance id* and we're querying tasks, there is no normal way to set the offset or max results
* B. for big data sets, the serialization + transport costs (of retrieving the entire set and paging in memory) will always be far larger
* than any complex queries we do to limit the output.
*
* So, to solve this, we need to do 2 things:
* 1. Add a WHERE or JOIN subquery to the task (JPQL) query that limits the results to the max results (ignoring the offset if necessary)
*
* Something like:
* ---
* SELECT ..
* FROM Task t
* ..
* WHERE ..
* AND (select count(distinct p) from t.taskData.processInstanceId p ) <= :maxResultsParam
* ..
* ---
*
* 2. If possible, add a WHERE subquery to the task (JPQL) query that limits the results to the offset
* Something like:
* ---
* SELECT ..
* FROM Task t
* ..
* WHERE <ORIGINAL QUERY>
* AND t.taskData.processInstance in (
* SELECT DISTINCT t.taskData.processInstance
* FROM Task t
* WHERE <ORIGINAL QUERY>
* GROUP BY t
* OFFSET :offset)
* ---
*
* 3. Writing the above by hand is a little ridiculous (and all of the string builder stuff in the query builders).
* Realistically, the query builder implementations should be using the JPA CriteriaBuilder API. I can't remember why
* I chose not to that at the beginning, but I'm pretty sure it was a mistake not to do that!
*/
// task queries
taskQueryBuilder.ascending(OrderBy.processInstanceId);
RemoteServicesQueryJPAService jpaService = resourceBase.getJPAService();
List<TaskSummary> taskSummaries = jpaService.doTaskSummaryQuery(
taskQueryBuilder.getTaskUserId(),
resourceBase.getUserGroupCallback(),
taskQueryBuilder.getQueryWhere());
if( pageInfo[1] > 0 ) {
long [] procInstIds = getIncludedProcessInstanceIdsAndRemoveUnneededTaskSummaries(taskSummaries, pageInfo);
varInstLogQueryBuilder.processInstanceId(procInstIds);
}
// variable queries
varInstLogQueryBuilder.ascending(OrderBy.processInstanceId);
List<VariableInstanceLog> varLogs = jpaService.doQuery(
varInstLogQueryBuilder.getQueryWhere(),
VariableInstanceLog.class);
// UNFINISHED FEATURE: using in-memory/proces instance variabels instead of audit/history logs
List<JaxbVariableInfo> procVars = null;
if( workFlowInstanceVariables ) {
// TODO: you need the user to specify a deployment id
for( VariableInstanceLog varLog : varLogs ) {
String deploymentId = varLog.getExternalId();
Long processInstId = varLog.getProcessInstanceId();
GetProcessInstanceVariableCommand cmd = new GetProcessInstanceVariableCommand();
cmd.setProcessInstanceId(processInstId);
cmd.setVariableId(varLog.getVariableId());
}
}
// create result
JaxbQueryTaskResult result = createQueryTaskResult(taskSummaries, varLogs, procVars, pageInfo );
return result;
}
private long [] getIncludedProcessInstanceIdsAndRemoveUnneededTaskSummaries(List<TaskSummary> taskSummaries, int [] pageInfo) {
// manage offset (will increase performance with large sets, slow performance with small sets)
int offset = getOffset(pageInfo);
Set<Long> exclProcInstids = new HashSet<Long>();
// 1. Remove task summaries before offset (offset is per proc inst id)
Iterator<TaskSummary> iter = taskSummaries.iterator();
while( iter.hasNext() && exclProcInstids.size() < offset ) {
TaskSummary taskSum = iter.next();
exclProcInstids.add(taskSum.getProcessInstanceId());
iter.remove();
}
// 2a. Add process instance ids from included task summaries
// 2b. Remove unneeded task summaries
Set<Long> inclProcInstids = new HashSet<Long>();
iter = taskSummaries.iterator();
while( iter.hasNext() ) {
Long procInstId = iter.next().getProcessInstanceId();
if( ! exclProcInstids.contains(procInstId) && inclProcInstids.size() < pageInfo[1] ) {
inclProcInstids.add(procInstId);
continue;
}
if( ! inclProcInstids.contains(procInstId) ) {
iter.remove();
}
}
// 3. create process instance ids array (for criteria to variable log queriy)
long [] procInstIdArr = new long[inclProcInstids.size()];
int i = 0;
for( Long boxedId : inclProcInstids ) {
procInstIdArr[i++] = boxedId;
}
return procInstIdArr;
}
/**
* Create a {@link JaxbQueryTaskResult} instance from the given information.
* @param taskSummaries A list of {@link TaskSummary} instances
* @param varLogs A list of {@link VariableInstanceLog} instances
* @param processVariables A list of {@link JaxbVariableInfo} instances
* @return A {@link JaxbQueryTaskResult}
*/
private static JaxbQueryTaskResult createQueryTaskResult( List<TaskSummary> taskSummaries, List<VariableInstanceLog> varLogs,
List<JaxbVariableInfo> processVariables, int [] pageInfo ) {
JaxbQueryTaskResult result = new JaxbQueryTaskResult();
LinkedHashMap<Long, JaxbQueryTaskInfo> procInstIdTaskInfoMap = new LinkedHashMap<Long, JaxbQueryTaskInfo>();
int maxNumResultsNeeded = getMaxNumResultsNeeded(pageInfo);
int i = 0;
Set<Long> uniqueTaskSummaryIds = new HashSet<Long>(0);
while( procInstIdTaskInfoMap.size() < maxNumResultsNeeded && i < taskSummaries.size() ) {
TaskSummary taskSum = taskSummaries.get(i++);
assert uniqueTaskSummaryIds.add(taskSum.getId()) : "Duplicate task summary found with id " + taskSum.getId();
long procInstId = taskSum.getProcessInstanceId();
JaxbQueryTaskInfo taskInfo = createJaxbQueryTaskInfo(procInstId, procInstIdTaskInfoMap);
taskInfo.getTaskSummaries().add(new JaxbTaskSummary(taskSum));
}
Set<Long> uniqueVarLogIds = new HashSet<Long>(0);
for( VariableInstanceLog varLog : varLogs ) {
assert uniqueVarLogIds.add(varLog.getId()) : "Duplicate variable instance log found with id " + varLog.getId();
long procInstId = varLog.getProcessInstanceId();
// the reasoning here is that the list of task summaries may be constricted by pagination
JaxbQueryTaskInfo taskInfo = procInstIdTaskInfoMap.get(procInstId);
if( taskInfo != null ) {
taskInfo.getVariables().add(new JaxbVariableInfo(varLog));
}
}
result.getTaskInfoList().addAll(procInstIdTaskInfoMap.values());
return result;
}
private static JaxbQueryTaskInfo createJaxbQueryTaskInfo( long procInstId, Map<Long, JaxbQueryTaskInfo> procInstIdTaskInfoMap ) {
JaxbQueryTaskInfo taskInfo = procInstIdTaskInfoMap.get(procInstId);
if( taskInfo == null ) {
taskInfo = new JaxbQueryTaskInfo(procInstId);
procInstIdTaskInfoMap.put(procInstId, taskInfo);
}
return taskInfo;
}
}
|
3e1e0bf307b45d018cd02ec7066bab7b972c876b | 5,268 | java | Java | src/main/java/net/quedex/marketmaker/MarketMakerConfiguration.java | zarazek/java-market-maker | 7e31e703c07759cfda8cac54709437713463114c | [
"Apache-2.0"
] | 16 | 2017-08-10T18:19:53.000Z | 2022-03-26T17:18:04.000Z | src/main/java/net/quedex/marketmaker/MarketMakerConfiguration.java | zarazek/java-market-maker | 7e31e703c07759cfda8cac54709437713463114c | [
"Apache-2.0"
] | 1 | 2017-08-10T17:27:10.000Z | 2017-08-10T17:27:10.000Z | src/main/java/net/quedex/marketmaker/MarketMakerConfiguration.java | zarazek/java-market-maker | 7e31e703c07759cfda8cac54709437713463114c | [
"Apache-2.0"
] | 15 | 2017-08-10T10:00:38.000Z | 2021-02-21T08:03:20.000Z | 37.098592 | 116 | 0.658125 | 12,724 | package net.quedex.marketmaker;
import org.apache.commons.configuration.Configuration;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.PropertiesConfiguration;
import java.math.BigDecimal;
import static com.google.common.base.Preconditions.checkArgument;
public class MarketMakerConfiguration {
private final int timeSleepSeconds;
private final int maxBatchSize;
private final BigDecimal futuresSpreadFraction;
private final double fairVolatility;
private final double volatilitySpreadFraction;
private final int numLevels;
private final int qtyOnLevel;
private final double vegaLimit;
private final double deltaLimit;
public MarketMakerConfiguration(final int timeSleepSeconds,
final int maxBatchSize,
final BigDecimal futuresSpreadFraction,
final double fairVolatility,
final double volatilitySpreadFraction,
final int numLevels,
final int qtyOnLevel,
final double deltaLimit,
final double vegaLimit) {
checkArgument(timeSleepSeconds > 0, "timeSleepSeconds=%s <= 0", timeSleepSeconds);
checkArgument(maxBatchSize > 0, "maxBatchSize <= 0");
checkArgument(maxBatchSize <= 3000, "maxBatchSize > 3000");
checkArgument(
futuresSpreadFraction.compareTo(BigDecimal.ZERO) > 0,
"futuresSpreadFraction=%s <=0", futuresSpreadFraction
);
checkArgument(fairVolatility > 0, "fairVolatility=%s <= 0", fairVolatility);
checkArgument(volatilitySpreadFraction > 0, "volatilitySpreadFraction=%s <= 0", volatilitySpreadFraction);
checkArgument(numLevels > 0, "numLevels=%s <= 0", numLevels);
checkArgument(qtyOnLevel > 0, "qtyOnLevel=%s <= 0", qtyOnLevel);
checkArgument(deltaLimit >= 0, "deltaLimit=%s < 0", deltaLimit);
checkArgument(vegaLimit >= 0, "vegaLimit=%s < 0", vegaLimit);
checkArgument(
fairVolatility - numLevels * fairVolatility * volatilitySpreadFraction > 0,
"Nonpositive lowest level volatility"
);
this.timeSleepSeconds = timeSleepSeconds;
this.maxBatchSize = maxBatchSize;
this.futuresSpreadFraction = futuresSpreadFraction;
this.fairVolatility = fairVolatility;
this.volatilitySpreadFraction = volatilitySpreadFraction;
this.vegaLimit = vegaLimit;
this.numLevels = numLevels;
this.qtyOnLevel = qtyOnLevel;
this.deltaLimit = deltaLimit;
}
public static MarketMakerConfiguration fromPropertiesFile(final String fileName) throws ConfigurationException {
final Configuration configuration = new PropertiesConfiguration(fileName);
return new MarketMakerConfiguration(
configuration.getInt(ConfigKey.TIME_SLEEP_SECONDS.getKey()),
configuration.getInt(ConfigKey.MAX_BATCH_SIZE.getKey()),
new BigDecimal(configuration.getString(ConfigKey.SPREAD_FRACTION.getKey())),
configuration.getDouble(ConfigKey.FAIR_VOLATILITY.getKey()),
configuration.getDouble(ConfigKey.VOLATILITY_SPREAD_FRACTION.getKey()),
configuration.getInt(ConfigKey.NUM_LEVELS.getKey()),
configuration.getInt(ConfigKey.QUANTITY_ON_LEVEL.getKey()),
configuration.getDouble(ConfigKey.DELTA_LIMIT.getKey()),
configuration.getDouble(ConfigKey.VEGA_LIMIT.getKey())
);
}
public int getTimeSleepSeconds() {
return timeSleepSeconds;
}
public int getMaxBatchSize() { return maxBatchSize; }
public BigDecimal getFuturesSpreadFraction() {
return futuresSpreadFraction;
}
public double getFairVolatility() {
return fairVolatility;
}
public double getVolatilitySpreadFraction() {
return volatilitySpreadFraction;
}
public double getVegaLimit() {
return vegaLimit;
}
public int getNumLevels() {
return numLevels;
}
public int getQtyOnLevel() {
return qtyOnLevel;
}
public double getDeltaLimit() {
return deltaLimit;
}
private enum ConfigKey {
TIME_SLEEP_SECONDS("timeSleepSeconds"),
MAX_BATCH_SIZE("maxBatchSize"),
SPREAD_FRACTION("futuresSpreadFraction"),
FAIR_VOLATILITY("fairVolatility"),
VOLATILITY_SPREAD_FRACTION("volatilitySpreadFraction"),
NUM_LEVELS("numLevels"),
QUANTITY_ON_LEVEL("quantityOnLevel"),
VEGA_LIMIT("vegaLimit"),
DELTA_LIMIT("deltaLimit");
private static final String COMMON_PREFIX = "net.quedex.marketmaker";
private static final char SEPARATOR = '.';
public static String getCommonPrefix() {
return COMMON_PREFIX;
}
private final String keyFragment;
ConfigKey(final String keyFragment) {
this.keyFragment = keyFragment;
}
public String getKey() {
return COMMON_PREFIX + SEPARATOR + keyFragment;
}
}
}
|
3e1e0c5ca58c0c192d64c6502d539f82d3c72394 | 1,406 | java | Java | services/wfm/src/main/java/org/openkilda/wfm/topology/nbworker/NbWorkerTopologyConfig.java | gauravchug/open-kilda | a6ac3343a29f8934d2f872d8d50f9cc45584e273 | [
"Apache-2.0"
] | 2 | 2019-01-03T17:19:25.000Z | 2019-01-03T17:19:37.000Z | services/wfm/src/main/java/org/openkilda/wfm/topology/nbworker/NbWorkerTopologyConfig.java | gauravchug/open-kilda | a6ac3343a29f8934d2f872d8d50f9cc45584e273 | [
"Apache-2.0"
] | null | null | null | services/wfm/src/main/java/org/openkilda/wfm/topology/nbworker/NbWorkerTopologyConfig.java | gauravchug/open-kilda | a6ac3343a29f8934d2f872d8d50f9cc45584e273 | [
"Apache-2.0"
] | null | null | null | 31.244444 | 77 | 0.731863 | 12,725 | /* Copyright 2018 Telstra Open Source
*
* 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.openkilda.wfm.topology.nbworker;
import org.openkilda.wfm.topology.AbstractTopologyConfig;
import com.sabre.oss.conf4j.annotation.Configuration;
import com.sabre.oss.conf4j.annotation.Key;
@Configuration
public interface NbWorkerTopologyConfig extends AbstractTopologyConfig {
default String getKafkaTopoNbTopic() {
return getKafkaTopics().getTopoNbTopic();
}
default String getKafkaNorthboundTopic() {
return getKafkaTopics().getNorthboundTopic();
}
default String getKafkaFlowTopic() {
return getKafkaTopics().getFlowTopic();
}
default String getKafkaDiscoTopic() {
return getKafkaTopics().getTopoDiscoTopic();
}
@Key("isl.cost.when.under.maintenance")
int getIslCostWhenUnderMaintenance();
}
|
3e1e0e0146db8f1a05d3e9f6bfc2cfe5ccbb1ffa | 2,498 | java | Java | src/main/java/org/codehaus/mojo/jaxb2/shared/environment/classloading/ThreadContextClassLoaderHolder.java | dantran/jaxb2-maven-plugin | bca65dd0fda3adb99f3ebbebd461cb7e41453c55 | [
"Apache-2.0"
] | 78 | 2015-08-28T14:18:20.000Z | 2022-01-27T18:57:38.000Z | src/main/java/org/codehaus/mojo/jaxb2/shared/environment/classloading/ThreadContextClassLoaderHolder.java | dantran/jaxb2-maven-plugin | bca65dd0fda3adb99f3ebbebd461cb7e41453c55 | [
"Apache-2.0"
] | 170 | 2015-06-02T17:42:57.000Z | 2022-02-14T08:15:50.000Z | src/main/java/org/codehaus/mojo/jaxb2/shared/environment/classloading/ThreadContextClassLoaderHolder.java | dantran/jaxb2-maven-plugin | bca65dd0fda3adb99f3ebbebd461cb7e41453c55 | [
"Apache-2.0"
] | 83 | 2015-06-02T06:38:46.000Z | 2022-03-16T06:35:27.000Z | 36.115942 | 103 | 0.684189 | 12,726 | package org.codehaus.mojo.jaxb2.shared.environment.classloading;
/*
* 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.
*/
/**
* <p>Specification for how to restore the original ThreadContext ClassLoader to a Thread.
* When we support JDK 1.7, this should really be an extension of AutoCloseable instead,
* to support the try-with-resources pattern. Typical use:</p>
* <pre>
* <code>
* // Create and set the ThreadContext ClassLoader
* ThreadContextClassLoaderHolder holder = null;
*
* try {
*
* holder = ThreadContextClassLoaderBuilder.createFor(getClass())
* .addPath("some/path")
* .addURL(someURL)
* .addPaths(aPathList)
* .buildAndSet();
*
* // ... perform operations using the newly set ThreadContext ClassLoader...
*
* } finally {
* // Restore the original ClassLoader
* holder.restoreClassLoaderAndReleaseThread();
* }
* </code>
* </pre>
*
* @author <a href="mailto:ychag@example.com">Lennart Jörelid</a>, jGuru Europe AB
* @since 2.0
*/
public interface ThreadContextClassLoaderHolder {
/**
* Restores the original ThreadContext ClassLoader, and nullifies
* any references to the Thread which had its ThreadContext
* ClassLoader altered.
*/
void restoreClassLoaderAndReleaseThread();
/**
* Retrieves the ClassPath held by this ThreadContextClassLoaderHolder as a
* {@code File.pathSeparatorChar}-separated string. This is directly usable as a String argument by
* any external process.
*
* @return the ClassPath as an argument to external processes such as XJC.
*/
String getClassPathAsArgument();
}
|
3e1e0e026ce97e6dab927acc355e5c3d12669bad | 1,265 | java | Java | polardbx-calcite/src/main/java/org/apache/calcite/sql/SqlSequenceParam.java | arkbriar/galaxysql | df28f91eab772839e5df069739a065ac01c0a26e | [
"Apache-2.0"
] | 480 | 2021-10-16T06:00:00.000Z | 2022-03-28T05:54:49.000Z | polardbx-calcite/src/main/java/org/apache/calcite/sql/SqlSequenceParam.java | arkbriar/galaxysql | df28f91eab772839e5df069739a065ac01c0a26e | [
"Apache-2.0"
] | 31 | 2021-10-20T02:59:55.000Z | 2022-03-29T03:38:33.000Z | polardbx-calcite/src/main/java/org/apache/calcite/sql/SqlSequenceParam.java | arkbriar/galaxysql | df28f91eab772839e5df069739a065ac01c0a26e | [
"Apache-2.0"
] | 96 | 2021-10-17T14:19:49.000Z | 2022-03-23T09:25:37.000Z | 32.435897 | 83 | 0.718577 | 12,727 | /*
* Copyright [2013-2021], Alibaba Group Holding Limited
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.calcite.sql;
import org.apache.calcite.sql.parser.SqlParserPos;
import org.apache.calcite.sql.type.SqlTypeName;
/**
* @author chenmo.cm
*/
public class SqlSequenceParam extends SqlDynamicParam {
private final SqlNode sequenceCall;
public SqlSequenceParam(int index, SqlTypeName typeName,
SqlParserPos pos, Object value, SqlNode sequenceCall) {
super(index, typeName, pos, value);
this.sequenceCall = sequenceCall;
}
@Override
public SqlNode clone(SqlParserPos pos) {
return new SqlSequenceParam(index, typeName, pos, value, sequenceCall);
}
}
|
3e1e0e30571dc2d8aa9b4c58c7a647c46b6b38e8 | 890 | java | Java | server/src/main/java/com/blocklang/core/runner/common/ExecutionContext.java | blocklang/blocklang.com | 939074c9df037c0780e01e9a73ee724b3dcc1dc0 | [
"MIT"
] | 38 | 2019-01-28T10:32:24.000Z | 2022-03-14T15:17:35.000Z | server/src/main/java/com/blocklang/core/runner/common/ExecutionContext.java | blocklang/blocklang-release | 939074c9df037c0780e01e9a73ee724b3dcc1dc0 | [
"MIT"
] | 515 | 2019-02-08T14:26:27.000Z | 2022-01-15T01:23:22.000Z | server/src/main/java/com/blocklang/core/runner/common/ExecutionContext.java | blocklang/blocklang-release | 939074c9df037c0780e01e9a73ee724b3dcc1dc0 | [
"MIT"
] | 16 | 2019-04-08T08:07:08.000Z | 2022-03-10T07:03:26.000Z | 26.969697 | 86 | 0.755056 | 12,728 | package com.blocklang.core.runner.common;
public interface ExecutionContext {
// 将全局且必须在初始化上下文时要创建的变量名存在此处
// Action 中获取值有两种方式,一是 steps 中 action 之间传值
// 另一种是从全局上下文中获取,而 marketplaceStore 和 publishTask 就属于全局上下文
public static final String MARKETPLACE_STORE = "marketplaceStore";
public static final String PUBLISH_TASK = "publishTask";
public static final String DATA_ROOT_PATH = "dataRootPath";
// 如果 gitUrl 有值,则优先使用此值;否则使用 publishTask 中的 gitUrl
public static final String GIT_URL = "gitUrl";
public static final String STORE = "store";
public String getGitUrl();
void setLogger(CliLogger logger);
/**
* 获取日志记录对象,在调用此方法前,需要先调用 {@link #newLogger(SimpMessagingTemplate, String)} 创建日志记录对象。
*
* @return 日志记录对象
*/
CliLogger getLogger();
void putValue(String key, Object value);
String getStringValue(String key);
<T> T getValue(String key, Class<T> clazz);
}
|
3e1e0ebf350afdc629579470fec394e0ae51840b | 707 | java | Java | src/main/java/org/ic4j/agent/Serializer.java | ic4j/ic4j-agent | ea758aea402794102773df2bce2b7c5deda33f6f | [
"Apache-2.0"
] | 4 | 2022-01-18T20:00:51.000Z | 2022-03-23T04:34:20.000Z | src/main/java/org/ic4j/agent/Serializer.java | ic4j/ic4j-agent | ea758aea402794102773df2bce2b7c5deda33f6f | [
"Apache-2.0"
] | null | null | null | src/main/java/org/ic4j/agent/Serializer.java | ic4j/ic4j-agent | ea758aea402794102773df2bce2b7c5deda33f6f | [
"Apache-2.0"
] | 1 | 2022-03-14T23:13:41.000Z | 2022-03-14T23:13:41.000Z | 29.458333 | 75 | 0.738331 | 12,729 | /*
* Copyright 2021 Exilor 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.ic4j.agent;
public interface Serializer {
public <T> void serializeField(String key, T value);
}
|
3e1e116ddcc92d622033cd8cf1db016a46d0fc09 | 4,054 | java | Java | projects/web/src/test/java/com/opengamma/web/portfolio/WebPortfoliosDataTest.java | McLeodMoores/starling | 7ae0689e06704f78fd9497f8ddb57ee82974a9c8 | [
"Apache-2.0"
] | 3 | 2017-12-18T09:32:40.000Z | 2021-03-08T20:05:54.000Z | projects/web/src/test/java/com/opengamma/web/portfolio/WebPortfoliosDataTest.java | McLeodMoores/starling | 7ae0689e06704f78fd9497f8ddb57ee82974a9c8 | [
"Apache-2.0"
] | 10 | 2017-01-19T13:32:36.000Z | 2021-09-20T20:41:48.000Z | projects/web/src/test/java/com/opengamma/web/portfolio/WebPortfoliosDataTest.java | McLeodMoores/starling | 7ae0689e06704f78fd9497f8ddb57ee82974a9c8 | [
"Apache-2.0"
] | 3 | 2017-12-14T12:46:18.000Z | 2020-12-11T19:52:37.000Z | 36.854545 | 134 | 0.748397 | 12,730 | /**
* Copyright (C) 2019 - present McLeod Moores Software Limited. All rights reserved.
*/
package com.opengamma.web.portfolio;
import static org.testng.Assert.assertEquals;
import java.util.Arrays;
import org.joda.beans.Bean;
import org.testng.annotations.Test;
import org.threeten.bp.Instant;
import com.opengamma.id.UniqueId;
import com.opengamma.master.portfolio.ManageablePortfolio;
import com.opengamma.master.portfolio.ManageablePortfolioNode;
import com.opengamma.master.portfolio.PortfolioDocument;
import com.opengamma.util.test.TestGroup;
import com.opengamma.web.AbstractBeanTestCase;
/**
* Tests for {@link WebPortfoliosData}.
*/
@Test(groups = TestGroup.UNIT)
public class WebPortfoliosDataTest extends AbstractBeanTestCase {
private static final String NAME = "port";
private static final String PORTFOLIO_URI = "portfolio";
private static final String NODE_URI = "node";
private static final String POSITION_URI = "position";
private static final String VERSION_URI = "version=1";
private static final ManageablePortfolio PORTFOLIO = new ManageablePortfolio(NAME);
private static final ManageablePortfolioNode PARENT_NODE = new ManageablePortfolioNode("parent node");
private static final ManageablePortfolioNode CHILD_NODE = new ManageablePortfolioNode("child node");
private static final PortfolioDocument DOCUMENT = new PortfolioDocument();
private static final PortfolioDocument VERSIONED = new PortfolioDocument();
static {
PORTFOLIO.setRootNode(PARENT_NODE);
DOCUMENT.setPortfolio(PORTFOLIO);
VERSIONED.setPortfolio(PORTFOLIO);
VERSIONED.setVersionFromInstant(Instant.now());
}
private static final WebPortfoliosData DATA = new WebPortfoliosData();
static {
DOCUMENT.setUniqueId(UniqueId.of("prt", "0"));
CHILD_NODE.setUniqueId(UniqueId.of("prt", "1"));
DATA.setPortfolio(DOCUMENT);
DATA.setNode(CHILD_NODE);
DATA.setUriPortfolioId(PORTFOLIO_URI);
DATA.setUriNodeId(NODE_URI);
DATA.setUriPositionId(POSITION_URI);
DATA.setUriVersionId(VERSION_URI);
}
@Override
public JodaBeanProperties<? extends Bean> getJodaBeanProperties() {
return new JodaBeanProperties<>(WebPortfoliosData.class,
Arrays.asList("uriPortfolioId", "uriNodeId", "uriPositionId", "uriVersionId", "portfolio", "parentNode", "node", "versioned"),
Arrays.asList(PORTFOLIO_URI, NODE_URI, POSITION_URI, VERSION_URI, DOCUMENT, PARENT_NODE, CHILD_NODE, VERSIONED),
Arrays.asList(NODE_URI, POSITION_URI, VERSION_URI, PORTFOLIO_URI, VERSIONED, CHILD_NODE, PARENT_NODE, DOCUMENT));
}
/**
* Tests getting the best portfolio if the override id is not null.
*/
public void testBestPortfolioOverrideId() {
final UniqueId uid = UniqueId.of("pos", "1");
assertEquals(DATA.getBestPortfolioUriId(uid), uid.toString());
}
/**
* Tests getting the best portfolio if there is no portfolio document.
*/
public void testBestPortfolioNoPortfolioDocument() {
final WebPortfoliosData data = DATA.clone();
data.setPortfolio(null);
assertEquals(data.getBestPortfolioUriId(null), PORTFOLIO_URI);
}
/**
* Tests getting the best portfolio from the document.
*/
public void testBestPortfolioFromDocument() {
assertEquals(DATA.getBestPortfolioUriId(null), DOCUMENT.getUniqueId().toString());
}
/**
* Tests getting the best portfolio node if the override id is not null.
*/
public void testBestPortfolioNodeOverrideId() {
final UniqueId uid = UniqueId.of("pos", "1");
assertEquals(DATA.getBestNodeUriId(uid), uid.toString());
}
/**
* Tests getting the best portfolio node if there is no node.
*/
public void testBestNodeNoNodeDocument() {
final WebPortfoliosData data = DATA.clone();
data.setNode(null);
assertEquals(data.getBestNodeUriId(null), NODE_URI);
}
/**
* Tests getting the best portfolio node from the document.
*/
public void testBestNodeFromDocument() {
assertEquals(DATA.getBestNodeUriId(null), CHILD_NODE.getUniqueId().toString());
}
}
|
3e1e12582e185347a6dc7c3099917ecc6ac3c30d | 2,415 | java | Java | src/main/java/org/yidu/novel/filter/GzipFilter.java | thu0ng91/dudu | 487afc36f60e202584d861aca32f5a9dae636bbd | [
"Apache-2.0"
] | 4 | 2017-08-30T14:32:49.000Z | 2020-05-30T12:54:08.000Z | src/main/java/org/yidu/novel/filter/GzipFilter.java | luckyyeah/YiDu-Novel | ebe9c08b90964948a9c615ac39f095cd25d586d4 | [
"Apache-2.0"
] | null | null | null | src/main/java/org/yidu/novel/filter/GzipFilter.java | luckyyeah/YiDu-Novel | ebe9c08b90964948a9c615ac39f095cd25d586d4 | [
"Apache-2.0"
] | 5 | 2017-08-14T06:59:53.000Z | 2020-03-03T13:18:19.000Z | 27.758621 | 104 | 0.606211 | 12,731 | package org.yidu.novel.filter;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.yidu.novel.constant.YiDuConfig;
import org.yidu.novel.constant.YiDuConstants;
/**
*
* <p>
* Gzip过滤器
* </p>
* Copyright(c) 2014 YiDu-Novel. All rights reserved.
*
* @version 1.1.9
* @author shinpa.you
*/
public class GzipFilter implements Filter {
/**
* 过滤器配置
*/
private FilterConfig filterConfig = null;
/**
* 构造方法
*
* @return 过滤器配置
*/
protected final FilterConfig getFilterConfig() {
return this.filterConfig;
}
/**
* {@inheritDoc}
*
* @see javax.servlet.Filter#init(javax.servlet.FilterConfig)
*/
@Override
public void init(final FilterConfig filterConfig) throws ServletException {
this.filterConfig = filterConfig;
}
/**
* {@inheritDoc}
*
* @see javax.servlet.Filter#destroy()
*/
@Override
public void destroy() {
this.filterConfig = null;
}
@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException,
ServletException {
if (!YiDuConstants.yiduConf.getBoolean(YiDuConfig.GZIP_EFFECTIVE, false)) {
chain.doFilter(req, res);
} else {
if (req instanceof HttpServletRequest) {
if (!((HttpServletRequest) req).getRequestURI().startsWith("/download")) {
// download以外的请求做Gzip处理
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) res;
String ae = request.getHeader("accept-encoding");
if (ae != null && ae.indexOf("gzip") != -1) {
GZIPResponseWrapper wrappedResponse = new GZIPResponseWrapper(response);
chain.doFilter(req, wrappedResponse);
wrappedResponse.finishResponse();
return;
}
}
}
chain.doFilter(req, res);
}
}
}
|
3e1e12b5c2f3006624e907dc35501cf572c718de | 11,523 | java | Java | processor/src/main/java/org/firezenk/naviganto/processor/RouteProcessor.java | elrutas/Naviganto | 6085ca5b3bc308a7dd5c3ae2db305f741f62619c | [
"MIT"
] | 27 | 2016-12-29T09:21:59.000Z | 2021-08-28T15:19:25.000Z | processor/src/main/java/org/firezenk/naviganto/processor/RouteProcessor.java | elrutas/Naviganto | 6085ca5b3bc308a7dd5c3ae2db305f741f62619c | [
"MIT"
] | 3 | 2016-12-28T12:18:05.000Z | 2017-04-04T09:44:43.000Z | processor/src/main/java/org/firezenk/naviganto/processor/RouteProcessor.java | FireZenk/ConceptRouter | 0483002b06415f94501ad0e2dbb02fc64d53cd32 | [
"MIT"
] | 7 | 2016-12-29T07:53:57.000Z | 2018-01-30T21:38:06.000Z | 39.462329 | 207 | 0.579537 | 12,732 | package org.firezenk.naviganto.processor;
import com.google.auto.service.AutoService;
import com.squareup.javapoet.AnnotationSpec;
import com.squareup.javapoet.JavaFile;
import com.squareup.javapoet.MethodSpec;
import com.squareup.javapoet.TypeSpec;
import org.firezenk.naviganto.annotations.RoutableActivity;
import org.firezenk.naviganto.annotations.RoutableView;
import org.firezenk.naviganto.processor.exceptions.NotEnoughParametersException;
import org.firezenk.naviganto.processor.exceptions.ParameterNotFoundException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.UUID;
import javax.annotation.Generated;
import javax.annotation.processing.AbstractProcessor;
import javax.annotation.processing.Filer;
import javax.annotation.processing.Messager;
import javax.annotation.processing.ProcessingEnvironment;
import javax.annotation.processing.Processor;
import javax.annotation.processing.RoundEnvironment;
import javax.lang.model.SourceVersion;
import javax.lang.model.element.Element;
import javax.lang.model.element.Modifier;
import javax.lang.model.element.TypeElement;
import javax.lang.model.type.MirroredTypesException;
import javax.lang.model.type.TypeMirror;
import javax.tools.Diagnostic;
/**
* Project: Naviganto
*
* Created by Jorge Garrido Oval on 04/11/2016.
* Copyright © Jorge Garrido Oval 2016
*/
@AutoService(Processor.class)
public class RouteProcessor extends AbstractProcessor {
private Filer filer;
private Messager messager;
@Override public synchronized void init(ProcessingEnvironment env){
super.init(env);
this.filer = env.getFiler();
this.messager = env.getMessager();
}
@Override public Set<String> getSupportedAnnotationTypes() {
final Set<String> set = new HashSet<>();
set.add(RoutableActivity.class.getCanonicalName());
set.add(RoutableView.class.getCanonicalName());
return Collections.unmodifiableSet(set);
}
@Override public SourceVersion getSupportedSourceVersion() {
return SourceVersion.latestSupported();
}
@Override public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment env) {
for (Element element : env.getElementsAnnotatedWith(RoutableActivity.class)) {
JavaFile javaFile = this.generateRoute((TypeElement) element);
try {
javaFile.writeTo(filer);
} catch (Exception e) {
messager.printMessage(Diagnostic.Kind.ERROR, e.getMessage());
e.printStackTrace();
}
}
for (Element element : env.getElementsAnnotatedWith(RoutableView.class)) {
JavaFile javaFile = this.generateRoute((TypeElement) element);
try {
javaFile.writeTo(filer);
} catch (Exception e) {
messager.printMessage(Diagnostic.Kind.ERROR, e.getMessage());
e.printStackTrace();
}
}
return true;
}
private JavaFile generateRoute(TypeElement typeElement) {
messager.printMessage(Diagnostic.Kind.NOTE, "Creating route...");
final ArrayList<MethodSpec> methods = new ArrayList<>();
methods.add(this.addRouteMethod(typeElement));
final TypeSpec myClass = this.createRoute(typeElement, methods);
messager.printMessage(Diagnostic.Kind.NOTE, "Save location: " +
typeElement.getQualifiedName().toString().replace("."+typeElement.getSimpleName(), ""));
return JavaFile.builder(
typeElement.getQualifiedName().toString().replace("."+typeElement.getSimpleName(), ""),
myClass).build();
}
private MethodSpec addRouteMethod(TypeElement typeElement) {
messager.printMessage(Diagnostic.Kind.NOTE, "Generating route method");
boolean isActivity;
int requestCode;
List<TypeMirror> params;
if (isActivity = (typeElement.getAnnotation(RoutableActivity.class) != null)) {
requestCode = this.getForResult(typeElement.getAnnotation(RoutableActivity.class));
params = this.getParameters(typeElement.getAnnotation(RoutableActivity.class));
} else {
requestCode = this.getForResult(typeElement.getAnnotation(RoutableView.class));
params = this.getParameters(typeElement.getAnnotation(RoutableView.class));
}
final StringBuilder sb = new StringBuilder();
sb.append("" +
" if (parameters.length < " + params.size() + ") {\n" +
" throw new NotEnoughParametersException(\"Need " + params.size() + " params\");\n" +
" }\n");
int i = 0;
for (TypeMirror tm : params) {
sb.append("" +
" if (parameters[" + i + "] == null || !(parameters[" + i + "] instanceof " + tm.toString() + ")) {\n" +
" throw new ParameterNotFoundException(\"Need " + tm.toString() + "\");\n" +
" }\n");
++i;
}
sb.append("\n");
if (isActivity) {
sb.append(" final android.content.Intent intent = new android.content.Intent((android.content.Context) context, " + typeElement.getSimpleName() + ".class);\n");
sb.append(" android.os.Bundle bundle = new android.os.Bundle();\n\n");
sb.append(" bundle.putString(\"uuid\", uuid.toString());\n");
if (params.size() > 0) {
sb.append(this.parametersToBundle(params));
}
sb.append(" intent.putExtras(bundle);\n");
sb.append("" +
" if (context instanceof android.app.Activity) {\n" +
" ((android.app.Activity) context).startActivityForResult(intent, "+ requestCode +");\n" +
" } else if (context instanceof android.content.Context) {\n" +
" ((android.content.Context) context).startActivity(intent);\n" +
" }\n");
} else {
sb.append("" +
" if (viewParent == null || !(viewParent instanceof android.view.ViewGroup)) {\n" +
" throw new ParameterNotFoundException(\"Need a view parent or is not a ViewGroup\");\n" +
" }\n");
if (params.size() > 0) {
sb.append("" +
" ((android.view.ViewGroup) viewParent).removeAllViews();\n" +
" ((android.view.ViewGroup) viewParent).addView(" + typeElement.getSimpleName() + ".newInstance((android.content.Context) context, uuid" + this.parametersToString(params) + "));\n");
} else {
sb.append("" +
" ((android.view.ViewGroup) viewParent).removeAllViews();\n" +
" ((android.view.ViewGroup) viewParent).addView(" + typeElement.getSimpleName() + ".newInstance((android.content.Context) context, uuid));\n");
}
}
messager.printMessage(Diagnostic.Kind.NOTE, sb.toString());
return MethodSpec.methodBuilder("route")
.addModifiers(Modifier.PUBLIC)
.addAnnotation(Override.class)
.addException(ParameterNotFoundException.class)
.addException(NotEnoughParametersException.class)
.returns(void.class)
.addParameter(Object.class, "context")
.addParameter(UUID.class, "uuid")
.addParameter(Object[].class, "parameters")
.addParameter(Object.class, "viewParent")
.addCode(sb.toString())
.build();
}
private String parametersToString(List<TypeMirror> params) {
final StringBuilder sb = new StringBuilder();
int i = 0;
for (TypeMirror tm : params) {
sb.append(", (" + tm.toString() + ") parameters[" + i + "]");
++i;
}
return sb.toString();
}
private String parametersToBundle(List<TypeMirror> params) {
final StringBuilder sb = new StringBuilder();
int i = 0;
for (TypeMirror tm : params) {
final String extra = "parameters[" + i + "]);\n";
final String casting = "(" + tm.toString() + ") ";
switch (tm.toString()) {
case "java.lang.Boolean":
sb.append(" bundle.putBoolean(\"bool" + i + "\", ");
sb.append(casting);
sb.append(extra);
break;
case "java.lang.Integer":
sb.append(" bundle.putInt(\"int" + i + "\", ");
sb.append(casting);
sb.append(extra);
break;
case "java.lang.Character":
sb.append(" bundle.putChar(\"char" + i + "\", ");
sb.append(casting);
sb.append(extra);
break;
case "java.lang.Float":
sb.append(" bundle.putFloat(\"float" + i + "\", ");
sb.append(casting);
sb.append(extra);
break;
case "java.lang.Double":
sb.append(" bundle.putDouble(\"double" + i + "\", ");
sb.append(casting);
sb.append(extra);
break;
case "java.lang.String":
sb.append(" bundle.putString(\"string" + i + "\", ");
sb.append(casting);
sb.append(extra);
break;
default:
sb.append(" bundle.putParcelable(\"parcelable" + i + "\", (android.os.Parcelable) " + extra);
break;
}
sb.append("\n");
++i;
}
return sb.toString();
}
private TypeSpec createRoute(TypeElement typeElement, ArrayList<MethodSpec> methods) {
messager.printMessage(Diagnostic.Kind.NOTE, "Saving route file...");
return TypeSpec.classBuilder(typeElement.getSimpleName() + "Route")
.addAnnotation(AnnotationSpec.builder(Generated.class)
.addMember("value", "$S", this.getClass().getName())
.build())
.addModifiers(Modifier.PUBLIC)
.addSuperinterface(org.firezenk.naviganto.processor.interfaces.Routable.class)
.addMethods(methods)
.build();
}
@SuppressWarnings("unchecked") private List<TypeMirror> getParameters(RoutableActivity annotation) {
try {
annotation.params(); // TODO get forResult
} catch (MirroredTypesException e) {
return (List<TypeMirror>) e.getTypeMirrors();
}
return null;
}
@SuppressWarnings("unchecked") private List<TypeMirror> getParameters(RoutableView annotation) {
try {
annotation.params(); // TODO get forResult
} catch (MirroredTypesException e) {
return (List<TypeMirror>) e.getTypeMirrors();
}
return null;
}
private int getForResult(RoutableActivity annotation) {
return annotation.requestCode();
}
private int getForResult(RoutableView annotation) {
return annotation.requestCode();
}
}
|
3e1e135f8be2934725561715913bfe705f00af15 | 192 | java | Java | order/src/main/java/com/freedy/mall/order/constant/OrderConstant.java | Freedy001/gulimall | 3e2b3881f2f605be7f159d56b9554ccd72aef336 | [
"Apache-2.0"
] | 2 | 2021-07-10T16:20:54.000Z | 2021-07-20T02:01:42.000Z | order/src/main/java/com/freedy/mall/order/constant/OrderConstant.java | Freedy001/gulimall | 3e2b3881f2f605be7f159d56b9554ccd72aef336 | [
"Apache-2.0"
] | null | null | null | order/src/main/java/com/freedy/mall/order/constant/OrderConstant.java | Freedy001/gulimall | 3e2b3881f2f605be7f159d56b9554ccd72aef336 | [
"Apache-2.0"
] | null | null | null | 19.2 | 68 | 0.729167 | 12,733 | package com.freedy.mall.order.constant;
/**
* @author Freedy
* @date 2021/3/24 22:17
*/
public class OrderConstant {
public static final String USER_ORDER_TOKEN_PREFIX="orderToken";
}
|
3e1e1374684d94cd28bc59fb0d6f7333fd3d94d6 | 848 | java | Java | src/main/java/ewewukek/antiqueshotgun/item/SlugAmmoItem.java | Patrigan/mc-antiqueshotgun | c1a7d72b544402d08ad0a71162ddc3e6e0b69dfe | [
"MIT"
] | null | null | null | src/main/java/ewewukek/antiqueshotgun/item/SlugAmmoItem.java | Patrigan/mc-antiqueshotgun | c1a7d72b544402d08ad0a71162ddc3e6e0b69dfe | [
"MIT"
] | 1 | 2022-03-17T16:28:23.000Z | 2022-03-17T16:28:23.000Z | src/main/java/ewewukek/antiqueshotgun/item/SlugAmmoItem.java | Patrigan/mc-antiqueshotgun | c1a7d72b544402d08ad0a71162ddc3e6e0b69dfe | [
"MIT"
] | 1 | 2022-03-26T09:38:17.000Z | 2022-03-26T09:38:17.000Z | 18.844444 | 48 | 0.635613 | 12,734 | package ewewukek.antiqueshotgun.item;
public class SlugAmmoItem extends AmmoItem {
public SlugAmmoItem(Properties properties) {
super(properties);
}
public static float spreadStdDev;
public static float speed;
public static float range;
public static float damage;
public static int durabilityDamage;
public static int postFireDelay;
@Override
public float spreadStdDev() {
return spreadStdDev;
}
@Override
public float speed() {
return speed;
}
@Override
public float range() {
return range;
}
@Override
public float damage() {
return damage;
}
@Override
public int postFireDelay() {
return postFireDelay;
}
@Override
public int durabilityDamage() {
return durabilityDamage;
}
}
|
3e1e138ceedffdcd29c5a3140b707fd54d84739e | 1,623 | java | Java | SmartCredentials_aOS/pushnotifications/src/main/java/de/telekom/smartcredentials/pushnotifications/controllers/ControllerFactory.java | telekom/SmartCredentials-SDK-android | 796c7eed234c30112eea0f6a78ce1491e4b65e0f | [
"Apache-2.0"
] | 8 | 2020-02-04T15:38:40.000Z | 2022-02-16T14:15:26.000Z | SmartCredentials_aOS/pushnotifications/src/main/java/de/telekom/smartcredentials/pushnotifications/controllers/ControllerFactory.java | telekom/SmartCredentials-SDK-android | 796c7eed234c30112eea0f6a78ce1491e4b65e0f | [
"Apache-2.0"
] | 6 | 2019-11-01T15:11:01.000Z | 2021-12-29T08:55:29.000Z | SmartCredentials_aOS/pushnotifications/src/main/java/de/telekom/smartcredentials/pushnotifications/controllers/ControllerFactory.java | telekom/SmartCredentials-SDK-android | 796c7eed234c30112eea0f6a78ce1491e4b65e0f | [
"Apache-2.0"
] | null | null | null | 36.977273 | 116 | 0.751076 | 12,735 | /*
* Copyright (c) 2020 Telekom Deutschland AG
*
* 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.telekom.smartcredentials.pushnotifications.controllers;
import de.telekom.smartcredentials.core.pushnotifications.enums.ServiceType;
import de.telekom.smartcredentials.pushnotifications.di.ObjectGraphCreatorPushNotifications;
import de.telekom.smartcredentials.pushnotifications.repositories.PushNotificationsStorageRepository;
/**
* Created by anpch@example.com at 5/22/2020
*/
public class ControllerFactory {
private final PushNotificationsStorageRepository mStorageRepository;
public ControllerFactory() {
mStorageRepository = ObjectGraphCreatorPushNotifications.getInstance()
.providePushNotificationsStorageRepository();
}
public BaseController getController() {
if (mStorageRepository.getPushNotificationsConfigString(PushNotificationsStorageRepository.KEY_SERVICE_TYPE)
.equals(ServiceType.TPNS.name())) {
return new TpnsController();
} else {
return new FcmController();
}
}
}
|
3e1e149fa0b7e8501f0be0278c7d73c41c0c4cb2 | 12,378 | java | Java | moe/moe-core/moe.apple/moe.platform.ios/src/main/java/apple/foundation/NSMutableAttributedString.java | ark100/multi-os-engine | f71d66a58b3d7e5eb2a68541480b7a0d88c7b908 | [
"Apache-2.0"
] | null | null | null | moe/moe-core/moe.apple/moe.platform.ios/src/main/java/apple/foundation/NSMutableAttributedString.java | ark100/multi-os-engine | f71d66a58b3d7e5eb2a68541480b7a0d88c7b908 | [
"Apache-2.0"
] | null | null | null | moe/moe-core/moe.apple/moe.platform.ios/src/main/java/apple/foundation/NSMutableAttributedString.java | ark100/multi-os-engine | f71d66a58b3d7e5eb2a68541480b7a0d88c7b908 | [
"Apache-2.0"
] | null | null | null | 36.72997 | 118 | 0.758927 | 12,736 | /*
Copyright 2014-2016 Intel Corporation
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 apple.foundation;
import apple.NSObject;
import apple.foundation.struct.NSRange;
import apple.uikit.NSTextAttachment;
import org.moe.natj.c.ann.FunctionPtr;
import org.moe.natj.general.NatJ;
import org.moe.natj.general.Pointer;
import org.moe.natj.general.ann.ByValue;
import org.moe.natj.general.ann.Generated;
import org.moe.natj.general.ann.Library;
import org.moe.natj.general.ann.Mapped;
import org.moe.natj.general.ann.MappedReturn;
import org.moe.natj.general.ann.NInt;
import org.moe.natj.general.ann.NUInt;
import org.moe.natj.general.ann.Owned;
import org.moe.natj.general.ann.ReferenceInfo;
import org.moe.natj.general.ann.Runtime;
import org.moe.natj.general.ptr.Ptr;
import org.moe.natj.general.ptr.VoidPtr;
import org.moe.natj.objc.Class;
import org.moe.natj.objc.ObjCRuntime;
import org.moe.natj.objc.SEL;
import org.moe.natj.objc.ann.IsOptional;
import org.moe.natj.objc.ann.ObjCClassBinding;
import org.moe.natj.objc.ann.ProtocolClassMethod;
import org.moe.natj.objc.ann.Selector;
import org.moe.natj.objc.map.ObjCObjectMapper;
@Generated
@Library("Foundation")
@Runtime(ObjCRuntime.class)
@ObjCClassBinding
public class NSMutableAttributedString extends NSAttributedString {
static {
NatJ.register();
}
@Generated
protected NSMutableAttributedString(Pointer peer) {
super(peer);
}
@Generated
@Selector("accessInstanceVariablesDirectly")
public static native boolean accessInstanceVariablesDirectly();
@Generated
@Owned
@Selector("alloc")
public static native NSMutableAttributedString alloc();
@Generated
@Selector("allocWithZone:")
@MappedReturn(ObjCObjectMapper.class)
public static native Object allocWithZone(VoidPtr zone);
@Generated
@Selector("attributedStringWithAttachment:")
public static native NSAttributedString attributedStringWithAttachment(NSTextAttachment attachment);
@Generated
@Selector("automaticallyNotifiesObserversForKey:")
public static native boolean automaticallyNotifiesObserversForKey(String key);
@Generated
@Selector("cancelPreviousPerformRequestsWithTarget:")
public static native void cancelPreviousPerformRequestsWithTarget(@Mapped(ObjCObjectMapper.class) Object aTarget);
@Generated
@Selector("cancelPreviousPerformRequestsWithTarget:selector:object:")
public static native void cancelPreviousPerformRequestsWithTargetSelectorObject(
@Mapped(ObjCObjectMapper.class) Object aTarget, SEL aSelector,
@Mapped(ObjCObjectMapper.class) Object anArgument);
@Generated
@Selector("classFallbacksForKeyedArchiver")
public static native NSArray<String> classFallbacksForKeyedArchiver();
@Generated
@Selector("classForKeyedUnarchiver")
public static native Class classForKeyedUnarchiver();
@Generated
@Selector("debugDescription")
public static native String debugDescription_static();
@Generated
@Selector("description")
public static native String description_static();
@Generated
@Selector("hash")
@NUInt
public static native long hash_static();
@Generated
@Selector("instanceMethodForSelector:")
@FunctionPtr(name = "call_instanceMethodForSelector_ret")
public static native NSObject.Function_instanceMethodForSelector_ret instanceMethodForSelector(SEL aSelector);
@Generated
@Selector("instanceMethodSignatureForSelector:")
public static native NSMethodSignature instanceMethodSignatureForSelector(SEL aSelector);
@Generated
@Selector("instancesRespondToSelector:")
public static native boolean instancesRespondToSelector(SEL aSelector);
@Generated
@Selector("isSubclassOfClass:")
public static native boolean isSubclassOfClass(Class aClass);
@Generated
@Selector("keyPathsForValuesAffectingValueForKey:")
public static native NSSet<String> keyPathsForValuesAffectingValueForKey(String key);
@Generated
@Owned
@Selector("new")
@MappedReturn(ObjCObjectMapper.class)
public static native Object new_objc();
@Generated
@Selector("resolveClassMethod:")
public static native boolean resolveClassMethod(SEL sel);
@Generated
@Selector("resolveInstanceMethod:")
public static native boolean resolveInstanceMethod(SEL sel);
@Generated
@Selector("setVersion:")
public static native void setVersion_static(@NInt long aVersion);
@Generated
@Selector("superclass")
public static native Class superclass_static();
@Generated
@Selector("supportsSecureCoding")
public static native boolean supportsSecureCoding();
@Generated
@Selector("version")
@NInt
public static native long version_static();
@Generated
@Selector("addAttribute:value:range:")
public native void addAttributeValueRange(String name, @Mapped(ObjCObjectMapper.class) Object value,
@ByValue NSRange range);
@Generated
@Selector("addAttributes:range:")
public native void addAttributesRange(NSDictionary<String, ?> attrs, @ByValue NSRange range);
@Generated
@Selector("appendAttributedString:")
public native void appendAttributedString(NSAttributedString attrString);
@Generated
@Selector("beginEditing")
public native void beginEditing();
@Generated
@Selector("deleteCharactersInRange:")
public native void deleteCharactersInRange(@ByValue NSRange range);
@Generated
@Selector("endEditing")
public native void endEditing();
@Generated
@Selector("fixAttributesInRange:")
public native void fixAttributesInRange(@ByValue NSRange range);
@Generated
@Selector("init")
public native NSMutableAttributedString init();
@Generated
@Selector("initWithAttributedString:")
public native NSMutableAttributedString initWithAttributedString(NSAttributedString attrStr);
@Generated
@Selector("initWithCoder:")
public native NSMutableAttributedString initWithCoder(NSCoder aDecoder);
@Generated
@Selector("initWithData:options:documentAttributes:error:")
public native NSMutableAttributedString initWithDataOptionsDocumentAttributesError(NSData data,
NSDictionary<String, ?> options,
@ReferenceInfo(type = NSDictionary.class) Ptr<NSDictionary<String, ?>> dict,
@ReferenceInfo(type = NSError.class) Ptr<NSError> error);
@Generated
@Deprecated
@Selector("initWithFileURL:options:documentAttributes:error:")
public native NSMutableAttributedString initWithFileURLOptionsDocumentAttributesError(NSURL url,
NSDictionary<?, ?> options, @ReferenceInfo(type = NSDictionary.class) Ptr<NSDictionary<?, ?>> dict,
@ReferenceInfo(type = NSError.class) Ptr<NSError> error);
@Generated
@Selector("initWithString:")
public native NSMutableAttributedString initWithString(String str);
@Generated
@Selector("initWithString:attributes:")
public native NSMutableAttributedString initWithStringAttributes(String str, NSDictionary<String, ?> attrs);
@Generated
@Selector("initWithURL:options:documentAttributes:error:")
public native NSMutableAttributedString initWithURLOptionsDocumentAttributesError(NSURL url,
NSDictionary<String, ?> options,
@ReferenceInfo(type = NSDictionary.class) Ptr<NSDictionary<String, ?>> dict,
@ReferenceInfo(type = NSError.class) Ptr<NSError> error);
@Generated
@Selector("insertAttributedString:atIndex:")
public native void insertAttributedStringAtIndex(NSAttributedString attrString, @NUInt long loc);
@Generated
@Selector("mutableString")
public native NSMutableString mutableString();
@Generated
@Selector("readFromData:options:documentAttributes:error:")
public native boolean readFromDataOptionsDocumentAttributesError(NSData data, NSDictionary<String, ?> opts,
@ReferenceInfo(type = NSDictionary.class) Ptr<NSDictionary<String, ?>> dict,
@ReferenceInfo(type = NSError.class) Ptr<NSError> error);
@Generated
@Deprecated
@Selector("readFromFileURL:options:documentAttributes:error:")
public native boolean readFromFileURLOptionsDocumentAttributesError(NSURL url, NSDictionary<?, ?> opts,
@ReferenceInfo(type = NSDictionary.class) Ptr<NSDictionary<?, ?>> dict,
@ReferenceInfo(type = NSError.class) Ptr<NSError> error);
@Generated
@Selector("readFromURL:options:documentAttributes:error:")
public native boolean readFromURLOptionsDocumentAttributesError(NSURL url, NSDictionary<String, ?> opts,
@ReferenceInfo(type = NSDictionary.class) Ptr<NSDictionary<String, ?>> dict,
@ReferenceInfo(type = NSError.class) Ptr<NSError> error);
@Generated
@Selector("removeAttribute:range:")
public native void removeAttributeRange(String name, @ByValue NSRange range);
@Generated
@Selector("replaceCharactersInRange:withAttributedString:")
public native void replaceCharactersInRangeWithAttributedString(@ByValue NSRange range,
NSAttributedString attrString);
@Generated
@Selector("replaceCharactersInRange:withString:")
public native void replaceCharactersInRangeWithString(@ByValue NSRange range, String str);
@Generated
@Selector("setAttributedString:")
public native void setAttributedString(NSAttributedString attrString);
@Generated
@Selector("setAttributes:range:")
public native void setAttributesRange(NSDictionary<String, ?> attrs, @ByValue NSRange range);
@Generated
@ProtocolClassMethod("supportsSecureCoding")
public boolean _supportsSecureCoding() {
return supportsSecureCoding();
}
@Generated
@IsOptional
@Selector("itemProviderVisibilityForRepresentationWithTypeIdentifier:")
@NInt
public static native long itemProviderVisibilityForRepresentationWithTypeIdentifier_static(String typeIdentifier);
@Generated
@IsOptional
@ProtocolClassMethod("itemProviderVisibilityForRepresentationWithTypeIdentifier_static")
@NInt
public long _itemProviderVisibilityForRepresentationWithTypeIdentifier_static(String typeIdentifier) {
return itemProviderVisibilityForRepresentationWithTypeIdentifier_static(typeIdentifier);
}
@Generated
@Selector("objectWithItemProviderData:typeIdentifier:error:")
@MappedReturn(ObjCObjectMapper.class)
public static native Object objectWithItemProviderDataTypeIdentifierError(NSData data, String typeIdentifier,
@ReferenceInfo(type = NSError.class) Ptr<NSError> outError);
@Generated
@ProtocolClassMethod("objectWithItemProviderDataTypeIdentifierError")
@MappedReturn(ObjCObjectMapper.class)
public Object _objectWithItemProviderDataTypeIdentifierError(NSData data, String typeIdentifier,
@ReferenceInfo(type = NSError.class) Ptr<NSError> outError) {
return objectWithItemProviderDataTypeIdentifierError(data, typeIdentifier, outError);
}
@Generated
@Selector("readableTypeIdentifiersForItemProvider")
public static native NSArray<String> readableTypeIdentifiersForItemProvider();
@Generated
@ProtocolClassMethod("readableTypeIdentifiersForItemProvider")
public NSArray<String> _readableTypeIdentifiersForItemProvider() {
return readableTypeIdentifiersForItemProvider();
}
@Generated
@Selector("writableTypeIdentifiersForItemProvider")
public static native NSArray<String> writableTypeIdentifiersForItemProvider_static();
@Generated
@ProtocolClassMethod("writableTypeIdentifiersForItemProvider_static")
public NSArray<String> _writableTypeIdentifiersForItemProvider_static() {
return writableTypeIdentifiersForItemProvider_static();
}
}
|
3e1e14bb42aa4158a67fd0c5aa22d3ae4e14147e | 2,661 | java | Java | milton2/milton-server-ce/src/main/java/io/milton/servlet/StaticResourceFilter.java | skoulouzis/lobcder | 23bf0cc9c78f506193bb9ba9f6543e5f5597ae4d | [
"Apache-2.0"
] | 7 | 2015-04-30T12:13:51.000Z | 2020-04-14T15:01:09.000Z | milton2/milton-server-ce/src/main/java/io/milton/servlet/StaticResourceFilter.java | skoulouzis/lobcder | 23bf0cc9c78f506193bb9ba9f6543e5f5597ae4d | [
"Apache-2.0"
] | null | null | null | milton2/milton-server-ce/src/main/java/io/milton/servlet/StaticResourceFilter.java | skoulouzis/lobcder | 23bf0cc9c78f506193bb9ba9f6543e5f5597ae4d | [
"Apache-2.0"
] | 3 | 2015-05-07T09:58:12.000Z | 2018-09-18T12:15:23.000Z | 35.013158 | 131 | 0.665163 | 12,737 | /*
* 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 io.milton.servlet;
import java.io.File;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class StaticResourceFilter implements Filter {
private Logger log = LoggerFactory.getLogger(StaticResourceFilter.class);
private FilterConfig filterConfig = null;
public void doFilter(ServletRequest request, ServletResponse response,FilterChain chain)throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) request;
String s = MiltonUtils.stripContext(req);
log.debug("url: " + s);
s = "WEB-INF/static/" + s;
log.debug("check path: " + s);
String path = filterConfig.getServletContext().getRealPath(s);
log.debug("real path: " + path);
File f = null;
if( path != null && path.length() > 0 ) {
f = new File(path);
}
if( f != null && f.exists() && !f.isDirectory() ) { // can't forward to a folder
log.debug("static file exists. forwarding..");
req.getRequestDispatcher(s).forward(request,response);
} else {
log.debug("static file does not exist, continuing chain..");
chain.doFilter(request,response);
}
}
public FilterConfig getFilterConfig() {
return (this.filterConfig);
}
public void destroy() {
}
public void init(FilterConfig filterConfig) {
this.filterConfig = filterConfig;
}
}
|
3e1e14bd45bc6909906f94986f4f8f68f541278f | 391 | java | Java | mfmall-product/src/main/java/com/itpeige/mfmall/product/dao/CommentReplayDao.java | JcLoveCode/kaikeba1 | 5694827fa81c231c575fd7d9ce801c19202a24bf | [
"Apache-2.0"
] | null | null | null | mfmall-product/src/main/java/com/itpeige/mfmall/product/dao/CommentReplayDao.java | JcLoveCode/kaikeba1 | 5694827fa81c231c575fd7d9ce801c19202a24bf | [
"Apache-2.0"
] | null | null | null | mfmall-product/src/main/java/com/itpeige/mfmall/product/dao/CommentReplayDao.java | JcLoveCode/kaikeba1 | 5694827fa81c231c575fd7d9ce801c19202a24bf | [
"Apache-2.0"
] | null | null | null | 21.888889 | 75 | 0.77665 | 12,738 | package com.itpeige.mfmall.product.dao;
import com.itpeige.mfmall.product.entity.CommentReplayEntity;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper;
/**
* 商品评价回复关系
*
* @author peige
* @email efpyi@example.com
* @date 2021-03-03 21:03:08
*/
@Mapper
public interface CommentReplayDao extends BaseMapper<CommentReplayEntity> {
}
|
3e1e15b88b158e764c798ee4921a195bd558cdb9 | 1,989 | java | Java | mall-ware/src/main/java/com/sun/mall/ware/controller/PurchaseDetailController.java | Sunyanyanyan/mall | 14f23aae8696b635c7cded0a710543ae8b9f69fa | [
"Apache-2.0"
] | null | null | null | mall-ware/src/main/java/com/sun/mall/ware/controller/PurchaseDetailController.java | Sunyanyanyan/mall | 14f23aae8696b635c7cded0a710543ae8b9f69fa | [
"Apache-2.0"
] | null | null | null | mall-ware/src/main/java/com/sun/mall/ware/controller/PurchaseDetailController.java | Sunyanyanyan/mall | 14f23aae8696b635c7cded0a710543ae8b9f69fa | [
"Apache-2.0"
] | null | null | null | 23.4 | 74 | 0.697335 | 12,739 | package com.sun.mall.ware.controller;
import java.util.Arrays;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.sun.mall.ware.entity.PurchaseDetailEntity;
import com.sun.mall.ware.service.PurchaseDetailService;
import com.sun.common.utils.PageUtils;
import com.sun.common.utils.R;
/**
*
*
* @author sunyan
* @email hzdkv@example.com
* @date 2020-05-18 21:11:04
*/
@RestController
@RequestMapping("ware/purchasedetail")
public class PurchaseDetailController {
@Autowired
private PurchaseDetailService purchaseDetailService;
/**
* 列表
*/
@RequestMapping("/list")
public R list(@RequestParam Map<String, Object> params){
PageUtils page = purchaseDetailService.queryPage(params);
return R.ok().put("page", page);
}
/**
* 信息
*/
@RequestMapping("/info/{id}")
public R info(@PathVariable("id") Long id){
PurchaseDetailEntity purchaseDetail = purchaseDetailService.getById(id);
return R.ok().put("purchaseDetail", purchaseDetail);
}
/**
* 保存
*/
@RequestMapping("/save")
public R save(@RequestBody PurchaseDetailEntity purchaseDetail){
purchaseDetailService.save(purchaseDetail);
return R.ok();
}
/**
* 修改
*/
@RequestMapping("/update")
public R update(@RequestBody PurchaseDetailEntity purchaseDetail){
purchaseDetailService.updateById(purchaseDetail);
return R.ok();
}
/**
* 删除
*/
@RequestMapping("/delete")
public R delete(@RequestBody Long[] ids){
purchaseDetailService.removeByIds(Arrays.asList(ids));
return R.ok();
}
}
|
3e1e189f656e4757df1945d4b83d69beb9f1f12e | 3,390 | java | Java | proton-j/proton/src/main/java/org/apache/qpid/proton/engine/impl/SenderImpl.java | fusesource/qpid-proton | 99c1a029fb7c01c8c16fff2be8554d685d34ce25 | [
"Apache-2.0"
] | null | null | null | proton-j/proton/src/main/java/org/apache/qpid/proton/engine/impl/SenderImpl.java | fusesource/qpid-proton | 99c1a029fb7c01c8c16fff2be8554d685d34ce25 | [
"Apache-2.0"
] | null | null | null | proton-j/proton/src/main/java/org/apache/qpid/proton/engine/impl/SenderImpl.java | fusesource/qpid-proton | 99c1a029fb7c01c8c16fff2be8554d685d34ce25 | [
"Apache-2.0"
] | 1 | 2022-03-13T20:30:54.000Z | 2022-03-13T20:30:54.000Z | 22.905405 | 92 | 0.60413 | 12,740 | /*
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.qpid.proton.engine.impl;
import java.util.Iterator;
import org.apache.qpid.proton.engine.Delivery;
import org.apache.qpid.proton.engine.EndpointState;
import org.apache.qpid.proton.engine.Sender;
public class SenderImpl extends LinkImpl implements Sender
{
private int _offered;
private TransportSender _transportLink;
private boolean _drained;
public SenderImpl(SessionImpl session, String name)
{
super(session, name);
}
public void offer(final int credits)
{
_offered = credits;
}
public int send(final byte[] bytes, int offset, int length)
{
if( getLocalState() == EndpointState.CLOSED )
{
throw new IllegalStateException("send not allowed after the sender is closed.");
}
DeliveryImpl current = current();
if(current == null || current.getLink() != this)
{
throw new IllegalArgumentException();//TODO.
}
return current.send(bytes, offset, length);
}
public void abort()
{
//TODO.
}
public Iterator<Delivery> unsettled()
{
return null; //TODO.
}
public void free()
{
getSession().freeSender(this);
super.free();
}
@Override
public boolean advance()
{
DeliveryImpl delivery = current();
boolean advance = super.advance();
if(advance && _offered > 0)
{
_offered--;
}
if(advance)
{
decrementCredit();
delivery.addToTransportWorkList();
}
return advance;
}
boolean hasOfferedCredits()
{
return _offered > 0;
}
@Override
TransportSender getTransportLink()
{
return _transportLink;
}
void setTransportLink(TransportSender transportLink)
{
_transportLink = transportLink;
}
@Override
boolean workUpdate(DeliveryImpl delivery)
{
return (delivery == current()) && hasCredit();
}
@Override
public void setCredit(int credit)
{
super.setCredit(credit);
/* while(getQueued()>0 && getCredit()>0)
{
advance();
}*/
}
public void drained()
{
if(getDrain())
{
_drained = true;
setCredit(0);
modified();
}
}
boolean clearDrained()
{
final boolean drained = _drained;
if(drained)
{
_drained = false;
}
return drained;
}
}
|
3e1e18e76683001b8b87ffaf30f2ed1d7af3c0db | 1,751 | java | Java | src/authoring_UI/SpriteCreatorImageGrid.java | ArchanaAhlawat/Vooga | 4efe05f2af7b9a19c5dcc6c7e15989e02515d266 | [
"MIT"
] | null | null | null | src/authoring_UI/SpriteCreatorImageGrid.java | ArchanaAhlawat/Vooga | 4efe05f2af7b9a19c5dcc6c7e15989e02515d266 | [
"MIT"
] | null | null | null | src/authoring_UI/SpriteCreatorImageGrid.java | ArchanaAhlawat/Vooga | 4efe05f2af7b9a19c5dcc6c7e15989e02515d266 | [
"MIT"
] | null | null | null | 25.376812 | 104 | 0.72016 | 12,741 | package authoring_UI;
import authoring.Sprite.AbstractSpriteObject;
import javafx.geometry.Insets;
import javafx.scene.layout.Background;
import javafx.scene.layout.BackgroundFill;
import javafx.scene.layout.Border;
import javafx.scene.layout.BorderStroke;
import javafx.scene.layout.BorderStrokeStyle;
import javafx.scene.layout.BorderWidths;
import javafx.scene.layout.CornerRadii;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.StackPane;
import javafx.scene.paint.Color;
public class SpriteCreatorImageGrid extends GridPane {
private AbstractSpriteObject currentSprite;
private StackPane imageStack;
public SpriteCreatorImageGrid() {
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
StackPane sp = new StackPane();
sp.setPrefHeight(50);
sp.setPrefWidth(50);
sp.setBackground(new Background(new BackgroundFill(Color.WHITE, CornerRadii.EMPTY, Insets.EMPTY)));
BorderStroke border = new BorderStroke(Color.LIGHTGREY, BorderStrokeStyle.DOTTED, CornerRadii.EMPTY,
BorderWidths.DEFAULT);
sp.setBorder(new Border(border));
if (i == 1 && j == 1) {
imageStack = sp;
this.add(imageStack, 1, 1);
} else {
this.add(sp, j, i);
}
}
}
}
public StackPane getImageStack() {
return imageStack;
}
public void setCurrentSprite(AbstractSpriteObject s) {
currentSprite = s;
}
public void setSprite(AbstractSpriteObject s) {
if (this.getSprite() == null) {
currentSprite = s;
imageStack.getChildren().add(s);
} else {
this.getImageStack().getChildren().remove(0);
currentSprite = s;
imageStack.getChildren().add(s);
}
}
public AbstractSpriteObject getSprite() {
return currentSprite;
}
public void removeSprite() {
}
}
|
3e1e1926fff726579f325950f4bedf8c389c08e2 | 3,835 | java | Java | source/builder/src/com/ocs/indaba/action/SubmitSurveyAction.java | amida-tech/indaba | c41a237d9420231af7a119fee9ec7e77719accf0 | [
"Apache-2.0"
] | 3 | 2016-02-25T00:12:36.000Z | 2016-11-04T21:15:36.000Z | source/builder/src/com/ocs/indaba/action/SubmitSurveyAction.java | amida-tech/indaba | c41a237d9420231af7a119fee9ec7e77719accf0 | [
"Apache-2.0"
] | null | null | null | source/builder/src/com/ocs/indaba/action/SubmitSurveyAction.java | amida-tech/indaba | c41a237d9420231af7a119fee9ec7e77719accf0 | [
"Apache-2.0"
] | 1 | 2017-08-25T19:12:19.000Z | 2017-08-25T19:12:19.000Z | 44.593023 | 119 | 0.697784 | 12,742 | package com.ocs.indaba.action;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.springframework.beans.factory.annotation.Autowired;
import com.ocs.indaba.common.Constants;
import com.ocs.indaba.common.Messages;
import com.ocs.indaba.service.AssignmentService;
import com.ocs.indaba.service.SurveyService;
import com.ocs.indaba.vo.AssignmentSubmissionResult;
import com.ocs.util.StringUtils;
import com.ocs.indaba.vo.LoginUser;
import org.apache.log4j.Logger;
public class SubmitSurveyAction extends BaseAction {
private static final Logger logger = Logger.getLogger(SubmitSurveyAction.class);
private SurveyService surveyService;
private AssignmentService assignmentService;
@Autowired
public void setSurveyService(SurveyService surveyService) {
this.surveyService = surveyService;
}
@Autowired
public void setAssignmentService(AssignmentService srvc) {
this.assignmentService = srvc;
}
@Override
public ActionForward execute(ActionMapping mapping,
ActionForm form, HttpServletRequest request,
HttpServletResponse response) {
LoginUser loginUser = preprocess(mapping, request, response);
try {
final PrintWriter writer = response.getWriter();
int horseId = StringUtils.str2int(request.getParameter(PARAM_HORSE_ID), Constants.INVALID_INT_ID);
String type = request.getParameter("type");
int assignId = StringUtils.str2int(request.getParameter(PARAM_ASSIGNID), Constants.INVALID_INT_ID);
AssignmentSubmissionResult result = new AssignmentSubmissionResult();
result.setCode(AssignmentSubmissionResult.RESULT_OK);
// check for standing flags
if (assignmentService.horseHasStandingFlagsAssignedToUser(loginUser.getUid(), horseId)) {
result.setCode(AssignmentSubmissionResult.RESULT_ERROR);
result.setMessage(this.getMessage(request, Messages.KEY_COMMON_ERR_CANT_SUBMIT_TA_FLAGS_ASSIGNED));
} else if (assignmentService.horseHasStandingFlagsRaisedByUser(loginUser.getUid(), horseId)) {
result.setCode(AssignmentSubmissionResult.RESULT_ERROR);
result.setMessage(this.getMessage(request, Messages.KEY_COMMON_ERR_CANT_SUBMIT_TA_FLAGS_RAISED));
} else {
if (Constants.SURVEY_ACTION_REVIEW.equalsIgnoreCase(type)) {
surveyService.submitSurveyReviewAssignment(loginUser.getUid(), horseId, assignId);
} else if (Constants.SURVEY_ACTION_PEERREVIEW.equalsIgnoreCase(type)) {
int rc = surveyService.submitSurveyPeerReviewAssignment(loginUser.getUid(), horseId, assignId);
if (rc < 0) {
result.setCode(AssignmentSubmissionResult.RESULT_ERROR);
result.setMessage(this.getMessage(request, Messages.KEY_COMMON_ERR_TASK_ASSIGNMENT_NOT_EXIST));
} else if (rc > 0) {
result.setCode(AssignmentSubmissionResult.RESULT_ERROR);
result.setMessage(this.getMessage(request, "common.js.alert.answerleft", rc));
}
} else if (Constants.SURVEY_ACTION_PRREVIEW.equalsIgnoreCase(type)) {
surveyService.submitSurveyPrReviewAssignment(loginUser.getUid(), horseId, assignId);
}
}
this.writeRespJSON(response, result.getCode(), result.getMessage());
} catch (IOException e) {
}
return null;
}
}
|
3e1e192b696d881b70fc17a9f742be4858a55993 | 579 | java | Java | src/main/java/com/soikea/hiplunch/provider/impl/PiatoProvider.java | pennifi/hiplunch | d7fc9373c3bf7b14ffa2f2ee10bfca88a0fcafd1 | [
"CC0-1.0"
] | null | null | null | src/main/java/com/soikea/hiplunch/provider/impl/PiatoProvider.java | pennifi/hiplunch | d7fc9373c3bf7b14ffa2f2ee10bfca88a0fcafd1 | [
"CC0-1.0"
] | 3 | 2018-10-11T11:39:30.000Z | 2019-12-04T09:24:58.000Z | src/main/java/com/soikea/hiplunch/provider/impl/PiatoProvider.java | pennifi/hiplunch | d7fc9373c3bf7b14ffa2f2ee10bfca88a0fcafd1 | [
"CC0-1.0"
] | 1 | 2020-03-16T11:38:24.000Z | 2020-03-16T11:38:24.000Z | 19.965517 | 71 | 0.668394 | 12,743 | package com.soikea.hiplunch.provider.impl;
import com.soikea.hiplunch.provider.MenuProvider;
import com.soikea.hiplunch.provider.SemmaProvider;
@MenuProvider
public class PiatoProvider extends SemmaProvider {
@Override
protected String getMessageUrl() {
return "https://www.semma.fi/ravintolat2/mattilanniemi/piato/";
}
@Override
public String getName() {
return "Semma Piato";
}
@Override
public String getId() {
return "piato";
}
@Override
protected String getSemmaId() {
return "1408";
}
}
|
3e1e193e2ba9190cfbb087c98ada7c5504676748 | 1,518 | java | Java | code/jshrink/soot/src/main/java/soot/Value.java | UCLA-SEAL/JShrink | 23de49765326f09f642b7097b7334facec0e96c3 | [
"BSD-3-Clause"
] | 5 | 2020-07-10T21:02:50.000Z | 2021-01-10T11:51:16.000Z | code/jshrink/soot/src/main/java/soot/Value.java | UCLA-SEAL/JShrink | 23de49765326f09f642b7097b7334facec0e96c3 | [
"BSD-3-Clause"
] | 31 | 2020-06-27T23:54:32.000Z | 2021-04-16T06:29:14.000Z | code/jshrink/soot/src/main/java/soot/Value.java | UCLA-SEAL/JShrink | 23de49765326f09f642b7097b7334facec0e96c3 | [
"BSD-3-Clause"
] | 1 | 2022-03-14T19:58:38.000Z | 2022-03-14T19:58:38.000Z | 30.979592 | 111 | 0.720685 | 12,744 | package soot;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 1997 - 1999 Raja Vallee-Rai
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.io.Serializable;
import java.util.List;
import soot.util.Switchable;
/**
* Data used as, for instance, arguments to instructions; typical implementations are constants or expressions.
*
* Values are typed, clonable and must declare which other Values they use (contain).
*/
public interface Value extends Switchable, EquivTo, Serializable {
/**
* Returns a List of boxes corresponding to Values which are used by (ie contained within) this Value.
*/
public List<ValueBox> getUseBoxes();
/** Returns the Soot type of this Value. */
public Type getType();
/** Returns a clone of this Value. */
public Object clone();
public void toString(UnitPrinter up);
}
|
3e1e1b7459d06db29c6a89153245c0df270f1cd5 | 2,844 | java | Java | src/main/java/org/bian/dto/BQDeviceTrackingRetrieveOutputModelDeviceTrackingInstanceReport.java | bianapis/sd-atm-network-operations-v3 | 84e0854c7575def373d4a348edaaa8c9b1f48299 | [
"Apache-2.0"
] | null | null | null | src/main/java/org/bian/dto/BQDeviceTrackingRetrieveOutputModelDeviceTrackingInstanceReport.java | bianapis/sd-atm-network-operations-v3 | 84e0854c7575def373d4a348edaaa8c9b1f48299 | [
"Apache-2.0"
] | null | null | null | src/main/java/org/bian/dto/BQDeviceTrackingRetrieveOutputModelDeviceTrackingInstanceReport.java | bianapis/sd-atm-network-operations-v3 | 84e0854c7575def373d4a348edaaa8c9b1f48299 | [
"Apache-2.0"
] | null | null | null | 35.111111 | 230 | 0.805907 | 12,745 | package org.bian.dto;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonCreator;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import javax.validation.Valid;
/**
* BQDeviceTrackingRetrieveOutputModelDeviceTrackingInstanceReport
*/
public class BQDeviceTrackingRetrieveOutputModelDeviceTrackingInstanceReport {
private Object deviceTrackingInstanceReportRecord = null;
private String deviceTrackingInstanceReportType = null;
private String deviceTrackingInstanceReportParameters = null;
private Object deviceTrackingInstanceReport = null;
/**
* `status: Not Mapped` core-data-type-reference: BIAN::DataTypesLibrary::CoreDataTypes::UNCEFACT::Binary general-info: The input information used to assemble the report that can be on-going, periodic and actual and projected
* @return deviceTrackingInstanceReportRecord
**/
public Object getDeviceTrackingInstanceReportRecord() {
return deviceTrackingInstanceReportRecord;
}
public void setDeviceTrackingInstanceReportRecord(Object deviceTrackingInstanceReportRecord) {
this.deviceTrackingInstanceReportRecord = deviceTrackingInstanceReportRecord;
}
/**
* `status: Not Mapped` core-data-type-reference: BIAN::DataTypesLibrary::CoreDataTypes::UNCEFACT::Code general-info: The type of external report available
* @return deviceTrackingInstanceReportType
**/
public String getDeviceTrackingInstanceReportType() {
return deviceTrackingInstanceReportType;
}
public void setDeviceTrackingInstanceReportType(String deviceTrackingInstanceReportType) {
this.deviceTrackingInstanceReportType = deviceTrackingInstanceReportType;
}
/**
* `status: Not Mapped` core-data-type-reference: BIAN::DataTypesLibrary::CoreDataTypes::UNCEFACT::Text general-info: The selection parameters for the report (e.g. period, content type)
* @return deviceTrackingInstanceReportParameters
**/
public String getDeviceTrackingInstanceReportParameters() {
return deviceTrackingInstanceReportParameters;
}
public void setDeviceTrackingInstanceReportParameters(String deviceTrackingInstanceReportParameters) {
this.deviceTrackingInstanceReportParameters = deviceTrackingInstanceReportParameters;
}
/**
* `status: Not Mapped` core-data-type-reference: BIAN::DataTypesLibrary::CoreDataTypes::UNCEFACT::Binary general-info: The external report in any suitable form including selection filters where appropriate
* @return deviceTrackingInstanceReport
**/
public Object getDeviceTrackingInstanceReport() {
return deviceTrackingInstanceReport;
}
public void setDeviceTrackingInstanceReport(Object deviceTrackingInstanceReport) {
this.deviceTrackingInstanceReport = deviceTrackingInstanceReport;
}
}
|
3e1e1ba82752bea91f614139f20a42532189283f | 3,112 | java | Java | lab-5/initial-resource-server/src/main/java/com/example/library/server/dataaccess/Book.java | medimohammadise/reactive-spring-security-5-workshop | bcda596a8c7df440089fb7f8e80e0f1a601086c8 | [
"Apache-2.0"
] | 90 | 2018-09-17T16:50:08.000Z | 2021-09-03T07:36:22.000Z | lab-5/initial-resource-server/src/main/java/com/example/library/server/dataaccess/Book.java | medimohammadise/reactive-spring-security-5-workshop | bcda596a8c7df440089fb7f8e80e0f1a601086c8 | [
"Apache-2.0"
] | 25 | 2018-10-16T12:38:46.000Z | 2020-12-11T19:10:43.000Z | lab-5/initial-resource-server/src/main/java/com/example/library/server/dataaccess/Book.java | medimohammadise/reactive-spring-security-5-workshop | bcda596a8c7df440089fb7f8e80e0f1a601086c8 | [
"Apache-2.0"
] | 36 | 2018-10-12T18:49:36.000Z | 2022-02-09T21:42:46.000Z | 21.462069 | 85 | 0.656491 | 12,746 | package com.example.library.server.dataaccess;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.springframework.data.annotation.Id;
import org.springframework.data.annotation.PersistenceConstructor;
import org.springframework.data.mongodb.core.index.Indexed;
import org.springframework.data.mongodb.core.index.TextIndexed;
import org.springframework.data.mongodb.core.mapping.Document;
import java.util.List;
import java.util.Objects;
import java.util.UUID;
@Document(collection = "books")
public class Book {
@Id private UUID id;
@Indexed(unique = true)
private String isbn;
@Indexed private String title;
@TextIndexed private String description;
private List<String> authors;
private boolean borrowed;
private User borrowedBy;
public Book() {}
@PersistenceConstructor
public Book(
UUID id,
String isbn,
String title,
String description,
List<String> authors,
boolean borrowed,
User borrowedBy) {
this.id = id;
this.isbn = isbn;
this.title = title;
this.description = description;
this.authors = authors;
this.borrowed = borrowed;
this.borrowedBy = borrowedBy;
}
public UUID getId() {
return id;
}
public void setId(UUID id) {
this.id = id;
}
public String getIsbn() {
return isbn;
}
public void setIsbn(String isbn) {
this.isbn = isbn;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public List<String> getAuthors() {
return authors;
}
public void setAuthors(List<String> authors) {
this.authors = authors;
}
public boolean isBorrowed() {
return borrowed;
}
public User getBorrowedBy() {
return borrowedBy;
}
public void doBorrow(User user) {
if (!this.borrowed) {
this.borrowed = true;
this.borrowedBy = user;
}
}
public void doReturn(User user) {
if (this.borrowed) {
this.borrowed = false;
this.borrowedBy = null;
}
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Book book = (Book) o;
return borrowed == book.borrowed
&& id.equals(book.id)
&& isbn.equals(book.isbn)
&& title.equals(book.title)
&& Objects.equals(description, book.description)
&& authors.equals(book.authors)
&& Objects.equals(borrowedBy, book.borrowedBy);
}
@Override
public int hashCode() {
return Objects.hash(id, isbn, title, description, authors, borrowed, borrowedBy);
}
@Override
public String toString() {
return new ToStringBuilder(this)
.append("id", id)
.append("title", title)
.append("isbn", isbn)
.append("description", description)
.append("borrowed", borrowed)
.append("borrowedBy", borrowedBy)
.toString();
}
}
|
3e1e1ded69e7cc5df048186937001a9b074509ad | 823 | java | Java | score-http/score-repo-api/src/main/java/org/oagi/score/repo/api/corecomponent/seqkey/model/MoveAfterRequest.java | OAGi/Score | 3094555ea14624fe180e921957a418b0bd33147b | [
"MIT"
] | 5 | 2020-02-03T16:02:12.000Z | 2021-07-29T18:18:52.000Z | score-http/score-repo-api/src/main/java/org/oagi/score/repo/api/corecomponent/seqkey/model/MoveAfterRequest.java | OAGi/Score | 3094555ea14624fe180e921957a418b0bd33147b | [
"MIT"
] | 566 | 2019-12-09T17:06:44.000Z | 2022-03-28T14:15:48.000Z | score-http/score-repo-api/src/main/java/org/oagi/score/repo/api/corecomponent/seqkey/model/MoveAfterRequest.java | OAGi/Score | 3094555ea14624fe180e921957a418b0bd33147b | [
"MIT"
] | 2 | 2019-12-06T19:33:58.000Z | 2020-10-25T07:20:15.000Z | 19.595238 | 59 | 0.64034 | 12,747 | package org.oagi.score.repo.api.corecomponent.seqkey.model;
import org.oagi.score.repo.api.base.Request;
import org.oagi.score.repo.api.user.model.ScoreUser;
public class MoveAfterRequest extends Request {
private SeqKey item;
private SeqKey after;
public MoveAfterRequest(ScoreUser requester) {
super(requester);
}
public SeqKey getItem() {
return item;
}
public void setItem(SeqKey item) {
this.item = item;
}
public MoveAfterRequest withItem(SeqKey item) {
setItem(item);
return this;
}
public SeqKey getAfter() {
return after;
}
public void setAfter(SeqKey after) {
this.after = after;
}
public MoveAfterRequest withAfter(SeqKey after) {
setAfter(after);
return this;
}
}
|
3e1e1e528ab9e4ea0cef107a143e04b88a8fc01f | 1,233 | java | Java | src/main/java/com/strawren/jpress/dao/CmsLinkMapper.java | strawren/jpress | 33ec35c3ab8c6d6501c57f01cb496c4006d38d0d | [
"FTL"
] | 2 | 2016-06-03T04:04:16.000Z | 2018-05-09T08:47:29.000Z | src/main/java/com/strawren/jpress/dao/CmsLinkMapper.java | strawren/jpress | 33ec35c3ab8c6d6501c57f01cb496c4006d38d0d | [
"FTL"
] | null | null | null | src/main/java/com/strawren/jpress/dao/CmsLinkMapper.java | strawren/jpress | 33ec35c3ab8c6d6501c57f01cb496c4006d38d0d | [
"FTL"
] | null | null | null | 20.55 | 77 | 0.605028 | 12,748 | /**
* Copyright : http://www.strawren.com , since 2013
* Project : jpress
* $Id$
* $Revision$
* Last Changed by fuhy at 2014-4-2 上午10:02:22
* $URL$
*
* Change Log
* Author Change Date Comments
*-------------------------------------------------------------
* fuhy 2014-4-2 Initailized
*/
package com.strawren.jpress.dao;
import java.util.List;
import org.apache.ibatis.session.RowBounds;
import com.strawren.bsp.dao.Dao;
import com.strawren.bsp.dao.BspMapper;
import com.strawren.bsp.orm.query.BspCriterion;
import com.strawren.jpress.dto.CmsLinkDTO;
import com.strawren.jpress.model.CmsLink;
/**
* Mapper类,链接,对应表CMS_LINK
*/
@BspMapper
public interface CmsLinkMapper extends Dao<CmsLink, Long>{
/**
* 查询所有链接
* @param name
* @return
*/
List<CmsLinkDTO> findAllLink(String name);
/**
* 根据ID查找链接
* @param id
* @return
*/
CmsLinkDTO findLinkById(Long id);
/**
* 获取链接总数
* @param criterion
* @return
*/
long countLink(BspCriterion criterion);
/**
* 分页查询链接
* @param criterion
* @param rowBounds
* @return
*/
List<CmsLinkDTO> searchLink(BspCriterion criterion, RowBounds rowBounds);
} |
3e1e1e59042d281c28ec0f576ab5a92c7e897690 | 1,416 | java | Java | sorter/src/main/java/sortpom/wrapper/ElementSortOrderMap.java | hnrreddy/hari | 320709a0887fabde105b083532ed1e523521945e | [
"BSD-3-Clause"
] | 241 | 2015-03-15T22:01:02.000Z | 2022-03-31T14:40:17.000Z | sorter/src/main/java/sortpom/wrapper/ElementSortOrderMap.java | hnrreddy/hari | 320709a0887fabde105b083532ed1e523521945e | [
"BSD-3-Clause"
] | 76 | 2015-03-20T17:41:32.000Z | 2022-03-07T08:41:26.000Z | sorter/src/main/java/sortpom/wrapper/ElementSortOrderMap.java | hnrreddy/hari | 320709a0887fabde105b083532ed1e523521945e | [
"BSD-3-Clause"
] | 109 | 2015-05-17T11:50:40.000Z | 2022-03-18T06:44:49.000Z | 32.930233 | 115 | 0.707627 | 12,749 | package sortpom.wrapper;
import org.jdom.Element;
import java.util.HashMap;
import java.util.Map;
import static sortpom.wrapper.ElementUtil.getDeepName;
/**
* All elements from the chosen sort order (from predefined sort order or custom sort order) are placed in this map
* along with an index that describes in which order the elements should be sorted.
*/
class ElementSortOrderMap {
/** Contains sort order element names and their index. */
private final Map<String, Integer> elementNameSortOrderMap = new HashMap<>();
/**
* Add an Xml element to the map
*
* @param element Xml element
* @param sortOrder an index describing the sort order (lower number == element towards the start of the file)
*/
public void addElement(Element element, int sortOrder) {
final String deepName = getDeepName(element);
elementNameSortOrderMap.put(deepName, sortOrder);
}
/** Returns true if element is in the map */
public boolean containsElement(Element element) {
String deepName = getDeepName(element);
return elementNameSortOrderMap.containsKey(deepName);
}
/** Gets the index describing the sort order (lower number == element towards the start of the file) */
public int getSortOrder(Element element) {
String deepName = getDeepName(element);
return elementNameSortOrderMap.get(deepName);
}
}
|
3e1e1e6614200cdd5aeb4db39598709413071648 | 23,230 | java | Java | cwms_radar_api/src/main/java/cwms/radar/data/dao/TimeSeriesDaoImpl.java | rma-bryson/cwms-radar-api | b3c5d14f26ac72b82892168d399d6c5dcf8dfd29 | [
"MIT"
] | null | null | null | cwms_radar_api/src/main/java/cwms/radar/data/dao/TimeSeriesDaoImpl.java | rma-bryson/cwms-radar-api | b3c5d14f26ac72b82892168d399d6c5dcf8dfd29 | [
"MIT"
] | null | null | null | cwms_radar_api/src/main/java/cwms/radar/data/dao/TimeSeriesDaoImpl.java | rma-bryson/cwms-radar-api | b3c5d14f26ac72b82892168d399d6c5dcf8dfd29 | [
"MIT"
] | null | null | null | 36.873016 | 175 | 0.72669 | 12,750 | package cwms.radar.data.dao;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.time.Duration;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAccessor;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Optional;
import java.util.logging.Logger;
import java.util.stream.Collectors;
import cwms.radar.data.dto.Catalog;
import cwms.radar.data.dto.CwmsDTOPaginated;
import cwms.radar.data.dto.RecentValue;
import cwms.radar.data.dto.TimeSeries;
import cwms.radar.data.dto.Tsv;
import cwms.radar.data.dto.TsvDqu;
import cwms.radar.data.dto.TsvDquId;
import cwms.radar.data.dto.TsvId;
import cwms.radar.data.dto.catalog.CatalogEntry;
import cwms.radar.data.dto.catalog.TimeseriesCatalogEntry;
import org.jetbrains.annotations.NotNull;
import org.jooq.Condition;
import org.jooq.DSLContext;
import org.jooq.Field;
import org.jooq.Record;
import org.jooq.Record1;
import org.jooq.Record3;
import org.jooq.Record5;
import org.jooq.Result;
import org.jooq.SQL;
import org.jooq.SelectConditionStep;
import org.jooq.SelectHavingStep;
import org.jooq.SelectJoinStep;
import org.jooq.SelectSelectStep;
import org.jooq.conf.ParamType;
import org.jooq.exception.DataAccessException;
import org.jooq.impl.DSL;
import usace.cwms.db.dao.ifc.ts.CwmsDbTs;
import usace.cwms.db.dao.util.services.CwmsDbServiceLookup;
import usace.cwms.db.jooq.codegen.packages.CWMS_ROUNDING_PACKAGE;
import usace.cwms.db.jooq.codegen.packages.CWMS_TS_PACKAGE;
import usace.cwms.db.jooq.codegen.packages.CWMS_UTIL_PACKAGE;
import usace.cwms.db.jooq.codegen.tables.AV_CWMS_TS_ID2;
import usace.cwms.db.jooq.codegen.tables.AV_TSV;
import usace.cwms.db.jooq.codegen.tables.AV_TSV_DQU;
import usace.cwms.db.jooq.codegen.tables.AV_TS_GRP_ASSGN;
import static org.jooq.impl.DSL.asterisk;
import static org.jooq.impl.DSL.count;
import static org.jooq.impl.DSL.field;
import static org.jooq.impl.DSL.max;
import static org.jooq.impl.DSL.partitionBy;
import static usace.cwms.db.jooq.codegen.tables.AV_CWMS_TS_ID2.AV_CWMS_TS_ID2;
public class TimeSeriesDaoImpl extends JooqDao<TimeSeries> implements TimeSeriesDao
{
private static final Logger logger = Logger.getLogger(TimeSeriesDaoImpl.class.getName());
public static final boolean OVERRIDE_PROTECTION = true;
public TimeSeriesDaoImpl(DSLContext dsl)
{
super(dsl);
}
public String getTimeseries(String format, String names, String office, String units, String datum, String begin,
String end, String timezone) {
return CWMS_TS_PACKAGE.call_RETRIEVE_TIME_SERIES_F(dsl.configuration(),
names, format, units,datum, begin, end, timezone, office);
}
public ZonedDateTime asZonedDateTime(String timeStr, ZonedDateTime fallback, String timezone){
if(timeStr == null){
timeStr = fallback.toLocalDateTime().toString();
}
ZoneId zone = timezone == null ? ZoneOffset.UTC.normalized() : ZoneId.of(timezone);
// Parse the date time in the best format it can find. Timezone is optional, but use it if it's found.
TemporalAccessor beginParsed = DateTimeFormatter.ISO_DATE_TIME.parseBest(timeStr, ZonedDateTime::from, LocalDateTime::from);
ZonedDateTime beginTime;
if(beginParsed instanceof ZonedDateTime)
{
beginTime = ZonedDateTime.from(beginParsed);
}
else
{
beginTime = LocalDateTime.from(beginParsed).atZone(zone);
}
return beginTime;
}
public TimeSeries getTimeseries(String page, int pageSize, String names, String office, String units, String datum, String begin, String end, String timezone) {
if(begin == null)
{
begin = ZonedDateTime.now().minusDays(1).toLocalDateTime().toString();
}
if(end == null)
{
end = ZonedDateTime.now().toLocalDateTime().toString();
}
ZoneId zone = timezone == null ? ZoneOffset.UTC.normalized() : ZoneId.of(timezone);
// Parse the date time in the best format it can find. Timezone is optional, but use it if it's found.
TemporalAccessor beginParsed = DateTimeFormatter.ISO_DATE_TIME.parseBest(begin, ZonedDateTime::from, LocalDateTime::from);
TemporalAccessor endParsed = DateTimeFormatter.ISO_DATE_TIME.parseBest(end, ZonedDateTime::from, LocalDateTime::from);
ZonedDateTime beginTime = beginParsed instanceof ZonedDateTime ? ZonedDateTime.from(beginParsed) : LocalDateTime.from(beginParsed).atZone(zone);
// If the end time doesn't have a timezone, but begin did, use begin's timezone as end's.
ZonedDateTime endTime = endParsed instanceof ZonedDateTime ? ZonedDateTime.from(endParsed) : LocalDateTime.from(endParsed).atZone(beginTime.getZone());
if(timezone == null) {
if(beginTime.getZone().equals(beginTime.getOffset()))
throw new IllegalArgumentException("Time cannot contain only an offset without the timezone.");
// If no timezone was found, get it from begin_time
zone = beginTime.getZone();
}
String cursor = null;
Timestamp tsCursor = null;
Integer total = null;
if(page != null && !page.isEmpty())
{
String[] parts = CwmsDTOPaginated.decodeCursor(page);
logger.fine("Decoded cursor");
for( String p: parts){
logger.finest(p);
}
if(parts.length > 1)
{
cursor = parts[0];
tsCursor = Timestamp.from(Instant.ofEpochMilli(Long.parseLong(parts[0])));
if(parts.length > 2)
total = Integer.parseInt(parts[1]);
// Use the pageSize from the original cursor, for consistent paging
pageSize = Integer.parseInt(parts[parts.length - 1]); // Last item is pageSize
}
}
final String recordCursor = cursor;
final int recordPageSize = pageSize;
Field<String> officeId = CWMS_UTIL_PACKAGE.call_GET_DB_OFFICE_ID(office != null ? DSL.val(office) : CWMS_UTIL_PACKAGE.call_USER_OFFICE_ID());
Field<String> tsId = CWMS_TS_PACKAGE.call_GET_TS_ID__2(DSL.val(names), officeId);
Field<BigDecimal> tsCode = CWMS_TS_PACKAGE.call_GET_TS_CODE__2(tsId, officeId);
Field<String> unit = units.compareToIgnoreCase("SI") == 0 || units.compareToIgnoreCase("EN") == 0 ?
CWMS_UTIL_PACKAGE.call_GET_DEFAULT_UNITS(CWMS_TS_PACKAGE.call_GET_BASE_PARAMETER_ID(tsCode), DSL.val(units, String.class)) :
DSL.val(units, String.class);
// This code assumes the database timezone is in UTC (per Oracle recommendation)
// Wrap in table() so JOOQ can parse the result
@SuppressWarnings("deprecated") SQL retrieveTable = DSL.sql("table(" + CWMS_TS_PACKAGE.call_RETRIEVE_TS_OUT_TAB(
tsId,
unit,
CWMS_UTIL_PACKAGE.call_TO_TIMESTAMP__2(DSL.val(beginTime.toInstant().toEpochMilli())),
CWMS_UTIL_PACKAGE.call_TO_TIMESTAMP__2(DSL.val(endTime.toInstant().toEpochMilli())),
DSL.inline("UTC", String.class), // All times are sent as UTC to the database, regardless of requested timezone.
null,
null,
null,
null,
null,
null,
null,
officeId) + ")"
);
SelectSelectStep<Record5<String,String,String,BigDecimal,Integer>> metadataQuery = dsl.select(
tsId.as("NAME"),
officeId.as("OFFICE_ID"),
unit.as("UNITS"),
CWMS_TS_PACKAGE.call_GET_INTERVAL(tsId).as("INTERVAL"),
// If we don't know the total, fetch it from the database (only for first fetch).
// Total is only an estimate, as it can change if fetching current data, or the timeseries otherwise changes between queries.
total != null ? DSL.val(total).as("TOTAL") : DSL.selectCount().from(retrieveTable).asField("TOTAL")
);
logger.finest( () -> metadataQuery.getSQL(ParamType.INLINED));
TimeSeries timeseries = metadataQuery.fetchOne(tsMetadata ->
new TimeSeries(recordCursor,
recordPageSize,
tsMetadata.getValue("TOTAL", Integer.class),
tsMetadata.getValue("NAME", String.class),
tsMetadata.getValue("OFFICE_ID", String.class),
beginTime,
endTime,
tsMetadata.getValue("UNITS", String.class),
Duration.ofMinutes(tsMetadata.get("INTERVAL") == null ? 0 : tsMetadata.getValue("INTERVAL", Long.class)))
);
if(pageSize != 0) {
SelectConditionStep<Record3<Timestamp, Double, BigDecimal>> query = dsl.select(
DSL.field("DATE_TIME", Timestamp.class).as("DATE_TIME"),
CWMS_ROUNDING_PACKAGE.call_ROUND_DD_F(DSL.field("VALUE", Double.class), DSL.inline("5567899996"), DSL.inline('T')).as("VALUE"),
CWMS_TS_PACKAGE.call_NORMALIZE_QUALITY(DSL.nvl(DSL.field("QUALITY_CODE", Integer.class), DSL.inline(5))).as("QUALITY_CODE")
)
.from(retrieveTable)
.where(DSL.field("DATE_TIME", Timestamp.class)
.greaterOrEqual(CWMS_UTIL_PACKAGE.call_TO_TIMESTAMP__2(
DSL.nvl(DSL.val(tsCursor == null ? null : tsCursor.toInstant().toEpochMilli()),
DSL.val(beginTime.toInstant().toEpochMilli())))))
.and(DSL.field("DATE_TIME", Timestamp.class)
.lessOrEqual(CWMS_UTIL_PACKAGE.call_TO_TIMESTAMP__2(DSL.val(endTime.toInstant().toEpochMilli())))
);
if(pageSize > 0)
query.limit(DSL.val(pageSize + 1));
logger.finest( () -> query.getSQL(ParamType.INLINED));
query.fetchInto(tsRecord -> timeseries.addValue(
tsRecord.getValue("DATE_TIME", Timestamp.class),
tsRecord.getValue("VALUE", Double.class),
tsRecord.getValue("QUALITY_CODE", Integer.class)
)
);
}
return timeseries;
}
public Catalog getTimeSeriesCatalog(String page, int pageSize, Optional<String> office){
int total = 0;
String tsCursor = "*";
if( page == null || page.isEmpty() ){
SelectJoinStep<Record1<Integer>> count = dsl.select(count(asterisk())).from(AV_CWMS_TS_ID2);
if( office.isPresent() ){
count.where(AV_CWMS_TS_ID2.DB_OFFICE_ID.eq(office.get()));
}
total = count.fetchOne().value1();
} else {
logger.fine("getting non-default page");
// get totally from page
String[] parts = CwmsDTOPaginated.decodeCursor(page, "|||");
logger.fine("decoded cursor: " + String.join("|||", parts));
for( String p: parts){
logger.finest(p);
}
if(parts.length > 1) {
tsCursor = parts[0].split("/")[1];
total = Integer.parseInt(parts[1]);
}
}
SelectJoinStep<Record3<String, String, String>> query = dsl.select(
AV_CWMS_TS_ID2.DB_OFFICE_ID,
AV_CWMS_TS_ID2.CWMS_TS_ID,
AV_CWMS_TS_ID2.UNIT_ID
)
.from(AV_CWMS_TS_ID2);
if( office.isPresent() ){
query.where(AV_CWMS_TS_ID2.DB_OFFICE_ID.upper().eq(office.get().toUpperCase()))
.and(AV_CWMS_TS_ID2.CWMS_TS_ID.upper().greaterThan(tsCursor));
} else {
query.where(AV_CWMS_TS_ID2.CWMS_TS_ID.upper().gt(tsCursor));
}
query.orderBy(AV_CWMS_TS_ID2.CWMS_TS_ID).limit(pageSize);
logger.finest( () -> query.getSQL(ParamType.INLINED));
Result<Record3<String, String, String>> result = query.fetch();
List<? extends CatalogEntry> entries = result.stream()
//.map( e -> e.into(usace.cwms.db.jooq.codegen.tables.records.AV_CWMS_TIMESERIES_ID2) )
.map( e -> new TimeseriesCatalogEntry(e.get(AV_CWMS_TS_ID2.DB_OFFICE_ID),
e.get(AV_CWMS_TS_ID2.CWMS_TS_ID),
e.get(AV_CWMS_TS_ID2.UNIT_ID) )
)
.collect(Collectors.toList());
return new Catalog(tsCursor,total,pageSize,entries);
}
// Finds the single most recent TsvDqu within the time window.
public TsvDqu findMostRecent(String tOfficeId, String tsId, String unit, Timestamp twoWeeksFromNow, Timestamp twoWeeksAgo)
{
TsvDqu retval = null;
AV_TSV_DQU view = AV_TSV_DQU.AV_TSV_DQU;
Condition nestedCondition = view.ALIASED_ITEM.isNull()
.and(view.VALUE.isNotNull())
.and(view.CWMS_TS_ID.eq(tsId))
.and(view.OFFICE_ID.eq(tOfficeId));
if(twoWeeksFromNow != null){
nestedCondition = nestedCondition.and(view.DATE_TIME.lt(twoWeeksFromNow));
}
// Is this really optional?
if(twoWeeksAgo != null){
nestedCondition = nestedCondition.and(view.DATE_TIME.gt(twoWeeksAgo));
}
String maxFieldName = "MAX_DATE_TIME";
SelectHavingStep<Record1<Timestamp>> select = dsl.select(max(view.DATE_TIME).as(maxFieldName)).from(
view).where(nestedCondition).groupBy(view.TS_CODE);
Record dquRecord = dsl.select(asterisk()).from(view).where(view.DATE_TIME.in(select)).and(
view.CWMS_TS_ID.eq(tsId)).and(view.OFFICE_ID.eq(tOfficeId)).and(view.UNIT_ID.eq(unit)).and(
view.VALUE.isNotNull()).and(view.ALIASED_ITEM.isNull()).fetchOne();
if(dquRecord != null)
{
retval = dquRecord.map(r -> {
usace.cwms.db.jooq.codegen.tables.records.AV_TSV_DQU dqu = r.into(view);
TsvDqu tsv = null;
if(r != null)
{
TsvDquId id = new TsvDquId(dqu.getOFFICE_ID(), dqu.getTS_CODE(), dqu.getUNIT_ID(), dqu.getDATE_TIME());
tsv = new TsvDqu(id, dqu.getCWMS_TS_ID(), dqu.getVERSION_DATE(), dqu.getDATA_ENTRY_DATE(), dqu.getVALUE(), dqu.getQUALITY_CODE(), dqu.getSTART_DATE(), dqu.getEND_DATE());
}
return tsv;
});
}
return retval;
}
// This is similar to the code used for sparklines...
// Finds all the Tsv data points in the time range for all the specified tsIds.
public List<Tsv> findInDateRange(Collection<String> tsIds, Date startDate, Date endDate) {
List<Tsv> retval = Collections.emptyList();
if (tsIds != null && !tsIds.isEmpty()) {
Timestamp start = new Timestamp(startDate.getTime());
Timestamp end = new Timestamp(endDate.getTime());
AV_TSV tsvView = AV_TSV.AV_TSV;
usace.cwms.db.jooq.codegen.tables.AV_CWMS_TS_ID2 tsView = AV_CWMS_TS_ID2;
retval = dsl.select(tsvView.asterisk(), tsView.CWMS_TS_ID)
.from(tsvView.join(tsView).on(tsvView.TS_CODE.eq(tsView.TS_CODE.cast(Long.class))))
.where(
tsView.CWMS_TS_ID.in(tsIds).and(tsvView.DATE_TIME.ge(start)).and(tsvView.DATE_TIME.lt(end)).and(
tsvView.START_DATE.le(end)).and(tsvView.END_DATE.gt(start))).orderBy(tsvView.DATE_TIME).fetch(
jrecord -> buildTsvFromViewRow(jrecord.into(tsvView)));
}
return retval;
}
@NotNull
private Tsv buildTsvFromViewRow(usace.cwms.db.jooq.codegen.tables.records.AV_TSV into)
{
TsvId id = new TsvId(into.getTS_CODE(), into.getDATE_TIME(), into.getVERSION_DATE(), into.getDATA_ENTRY_DATE());
return new Tsv(id, into.getVALUE(), into.getQUALITY_CODE(), into.getSTART_DATE(), into.getEND_DATE());
}
// Finds single most recent value within the window for each of the tsCodes
public List<RecentValue> findMostRecentsInRange(List<String> tsIds, Timestamp pastdate, Timestamp futuredate) {
final List<RecentValue> retval = new ArrayList<>();
if (tsIds != null && !tsIds.isEmpty()) {
AV_TSV_DQU tsvView = AV_TSV_DQU.AV_TSV_DQU;
AV_CWMS_TS_ID2 tsView = AV_CWMS_TS_ID2;
SelectConditionStep<Record> innerSelect
= dsl.select(tsvView.asterisk(),
max(tsvView.DATE_TIME).over(partitionBy(tsvView.TS_CODE)).as("max_date_time"), tsView.CWMS_TS_ID)
.from(tsvView.join(tsView).on(tsvView.TS_CODE.eq(tsView.TS_CODE.cast(Long.class))))
.where(
tsView.CWMS_TS_ID.in(tsIds)
.and(tsvView.VALUE.isNotNull())
.and(tsvView.DATE_TIME.lt(futuredate))
.and(tsvView.DATE_TIME.gt(pastdate))
.and(tsvView.START_DATE.le(futuredate))
.and(tsvView.END_DATE.gt(pastdate)));
Field[] queryFields = new Field[]{
tsView.CWMS_TS_ID,
tsvView.OFFICE_ID,
tsvView.TS_CODE,
tsvView.UNIT_ID,
tsvView.DATE_TIME,
tsvView.VERSION_DATE,
tsvView.DATA_ENTRY_DATE,
tsvView.VALUE,
tsvView.QUALITY_CODE,
tsvView.START_DATE,
tsvView.END_DATE,
};
// look them back up by name b/c we are using them on results of innerselect.
List<Field<Object>> fields = Arrays.stream(queryFields)
.map(Field::getName)
.map(DSL::field).collect(
Collectors.toList());
// I want to select tsvView.asterisk but we are selecting from an inner select and
// even though the inner select selects tsvView.asterisk it isn't the same.
// So we will just select the fields we want. Unfortunately that means our results
// won't map into AV_TSV.AV_TSV
dsl.select(fields)
.from(innerSelect)
.where(field("DATE_TIME").eq(innerSelect.field("max_date_time")))
.forEach( jrecord -> {
RecentValue recentValue = buildRecentValue(tsvView, tsView, jrecord);
retval.add(recentValue);
});
}
return retval;
}
@NotNull
private RecentValue buildRecentValue(AV_TSV_DQU tsvView, usace.cwms.db.jooq.codegen.tables.AV_CWMS_TS_ID2 tsView,
Record jrecord)
{
return buildRecentValue(tsvView, jrecord, tsView.CWMS_TS_ID.getName());
}
@NotNull
private RecentValue buildRecentValue(AV_TSV_DQU tsvView, AV_TS_GRP_ASSGN tsView, Record jrecord)
{
return buildRecentValue(tsvView, jrecord, tsView.TS_ID.getName());
}
@NotNull
private RecentValue buildRecentValue(AV_TSV_DQU tsvView, Record jrecord, String tsColumnName)
{
Timestamp dataEntryDate;
// TODO:
// !!! skipping DATA_ENTRY_DATE for now. Need to figure out how to fix mapping in jooq.
// !! dataEntryDate= jrecord.getValue("data_entry_date", Timestamp.class); // maps to oracle.sql.TIMESTAMP
// !!!
dataEntryDate = null;
// !!!
TsvDqu tsv = buildTsvDqu(tsvView, jrecord, dataEntryDate);
String tsId = jrecord.getValue(tsColumnName, String.class);
return new RecentValue(tsId, tsv);
}
@NotNull
private TsvDqu buildTsvDqu(AV_TSV_DQU tsvView, Record jrecord, Timestamp dataEntryDate)
{
TsvDquId id = buildDquId(tsvView, jrecord);
return new TsvDqu(id, jrecord.getValue(tsvView.CWMS_TS_ID.getName(), String.class),
jrecord.getValue(tsvView.VERSION_DATE.getName(), Timestamp.class), dataEntryDate,
jrecord.getValue(tsvView.VALUE.getName(), Double.class),
jrecord.getValue(tsvView.QUALITY_CODE.getName(), Long.class),
jrecord.getValue(tsvView.START_DATE.getName(), Timestamp.class),
jrecord.getValue(tsvView.END_DATE.getName(), Timestamp.class));
}
public List<RecentValue> findRecentsInRange(String office, String categoryId, String groupId, Timestamp pastLimit, Timestamp futureLimit)
{
List<RecentValue> retval = new ArrayList<>();
if (categoryId != null && groupId != null) {
AV_TSV_DQU tsvView = AV_TSV_DQU.AV_TSV_DQU; // should we look at the daterange and possible use 30D view?
AV_TS_GRP_ASSGN tsView = AV_TS_GRP_ASSGN.AV_TS_GRP_ASSGN;
SelectConditionStep<Record> innerSelect
= dsl.select(tsvView.asterisk(), tsView.TS_ID, tsView.ATTRIBUTE,
max(tsvView.DATE_TIME).over(partitionBy(tsvView.TS_CODE)).as("max_date_time"), tsView.TS_ID)
.from(tsvView.join(tsView).on(tsvView.TS_CODE.eq(tsView.TS_CODE.cast(Long.class))))
.where(
tsView.DB_OFFICE_ID.eq(office)
.and(tsView.CATEGORY_ID.eq(categoryId))
.and(tsView.GROUP_ID.eq(groupId))
.and(tsvView.VALUE.isNotNull())
.and(tsvView.DATE_TIME.lt(futureLimit))
.and(tsvView.DATE_TIME.gt(pastLimit))
.and(tsvView.START_DATE.le(futureLimit))
.and(tsvView.END_DATE.gt(pastLimit)));
Field[] queryFields = new Field[]{
tsvView.OFFICE_ID,
tsvView.TS_CODE,
tsvView.DATE_TIME,
tsvView.VERSION_DATE,
tsvView.DATA_ENTRY_DATE,
tsvView.VALUE,
tsvView.QUALITY_CODE,
tsvView.START_DATE,
tsvView.END_DATE,
tsvView.UNIT_ID,
tsView.TS_ID, tsView.ATTRIBUTE};
List<Field<Object>> fields = Arrays.stream(queryFields)
.map(Field::getName)
.map(DSL::field).collect(
Collectors.toList());
// I want to select tsvView.asterisk but we are selecting from an inner select and
// even though the inner select selects tsvView.asterisk it isn't the same.
// So we will just select the fields we want.
// Unfortunately that means our results won't map into AV_TSV.AV_TSV
dsl.select(fields)
.from(innerSelect)
.where(field(tsvView.DATE_TIME.getName()).eq(innerSelect.field("max_date_time")))
.orderBy(field(tsView.ATTRIBUTE.getName()))
.forEach( jrecord -> {
RecentValue recentValue = buildRecentValue(tsvView, tsView, jrecord);
retval.add(recentValue);
});
}
return retval;
}
@NotNull
private TsvDquId buildDquId(AV_TSV_DQU tsvView, Record jrecord)
{
return new TsvDquId(jrecord.getValue(tsvView.OFFICE_ID.getName(), String.class),
jrecord.getValue(tsvView.TS_CODE.getName(), Long.class),
jrecord.getValue(tsvView.UNIT_ID.getName(), String.class),
jrecord.getValue(tsvView.DATE_TIME.getName(), Timestamp.class));
}
public void create(TimeSeries input)
{
dsl.connection(connection -> {
CwmsDbTs tsDao = CwmsDbServiceLookup.buildCwmsDb(CwmsDbTs.class, connection);
int utcOffsetMinutes = 0;
int intervalForward = 0;
int intervalBackward = 0;
boolean versionedFlag = false;
boolean activeFlag = true;
BigInteger tsCode = tsDao.createTsCodeBigInteger(connection, input.getOfficeId(), input.getName(),
utcOffsetMinutes, intervalForward, intervalBackward, versionedFlag, activeFlag);
});
}
public void store(TimeSeries input, Timestamp versionDate)
{
dsl.connection(connection -> {
store(connection, input.getOfficeId(), input.getName(), input.getUnits(), versionDate, input.getValues());
});
}
public void update(TimeSeries input) throws SQLException
{
String name = input.getName();
if(!timeseriesExists(name)){
throw new SQLException("Cannot update a non-existant Timeseries. Create " + name + " first.");
}
dsl.connection(connection -> {
store(connection, input.getOfficeId(), name, input.getUnits(), NON_VERSIONED, input.getValues());
});
}
public void store(Connection connection, String officeId, String tsId, String units, Timestamp versionDate,
List<TimeSeries.Record> values) throws SQLException
{
CwmsDbTs tsDao = CwmsDbServiceLookup.buildCwmsDb(CwmsDbTs.class, connection);
final int count = values == null ? 0 : values.size();
final long[] timeArray = new long[count];
final double[] valueArray = new double[count];
final int[] qualityArray = new int[count];
if(values != null && !values.isEmpty())
{
Iterator<TimeSeries.Record> iter = values.iterator();
for(int i = 0; iter.hasNext(); i++)
{
TimeSeries.Record value = iter.next();
timeArray[i] = value.getDateTime().getTime();
valueArray[i] = value.getValue();
qualityArray[i] = value.getQualityCode();
}
}
final boolean createAsLrts = false;
StoreRule storeRule = StoreRule.DELETE_INSERT;
long completedAt = tsDao.store(connection, officeId, tsId, units, timeArray, valueArray, qualityArray, count,
storeRule.getRule(), OVERRIDE_PROTECTION, versionDate, createAsLrts);
}
public void delete(String officeId, String tsId)
{
dsl.connection(connection -> {
CwmsDbTs tsDao = CwmsDbServiceLookup.buildCwmsDb(CwmsDbTs.class, connection);
tsDao.deleteAll(connection, officeId, tsId);
});
}
protected BigDecimal retrieveTsCode(String tsId)
{
return dsl.select(AV_CWMS_TS_ID2.AV_CWMS_TS_ID2.TS_CODE).from(
AV_CWMS_TS_ID2.AV_CWMS_TS_ID2).where(AV_CWMS_TS_ID2.AV_CWMS_TS_ID2.CWMS_TS_ID.eq(tsId))
.fetchOptional(AV_CWMS_TS_ID2.AV_CWMS_TS_ID2.TS_CODE).orElse(null);
}
public boolean timeseriesExists(String tsId)
{
return retrieveTsCode(tsId) != null;
}
}
|
3e1e1ecc7a48682bb5c71f7d8627831725388919 | 663 | java | Java | src/main/java/cays/spring/vo/User.java | CaysHub/SpringBootStudy | 6d6507bbba1da101baf620c9eab3190b8fa590d8 | [
"Apache-2.0"
] | null | null | null | src/main/java/cays/spring/vo/User.java | CaysHub/SpringBootStudy | 6d6507bbba1da101baf620c9eab3190b8fa590d8 | [
"Apache-2.0"
] | null | null | null | src/main/java/cays/spring/vo/User.java | CaysHub/SpringBootStudy | 6d6507bbba1da101baf620c9eab3190b8fa590d8 | [
"Apache-2.0"
] | null | null | null | 18.942857 | 58 | 0.651584 | 12,751 | package cays.spring.vo;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
/**
* 用户类
*
* @author Chai yansheng
* @create 2019-07-24 16:26
**/
@Component
public class User {
@Value("${user.userName:cays}")
String userName;
@Value("${user.password:123456}")
String password;
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.