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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
923555a14177338d5024b4c166dd23a848f87dd4 | 489 | java | Java | src/main/java/com/github/ddth/queue/jclient/utils/QueueClientUtils.java | btnguyen2k/queue-jclient | 2ff288b696106af62550e80da701d40e021f1cde | [
"MIT"
] | null | null | null | src/main/java/com/github/ddth/queue/jclient/utils/QueueClientUtils.java | btnguyen2k/queue-jclient | 2ff288b696106af62550e80da701d40e021f1cde | [
"MIT"
] | null | null | null | src/main/java/com/github/ddth/queue/jclient/utils/QueueClientUtils.java | btnguyen2k/queue-jclient | 2ff288b696106af62550e80da701d40e021f1cde | [
"MIT"
] | null | null | null | 24.6 | 75 | 0.686992 | 997,255 | package com.github.ddth.queue.jclient.utils;
import org.apache.commons.codec.binary.Base64;
/**
* Utility class.
*
* @author Thanh Nguyen <anpch@example.com>
* @since 0.1.0
*/
public class QueueClientUtils {
public static byte[] base64Decode(String encodedStr) {
return encodedStr != null ? Base64.decodeBase64(encodedStr) : null;
}
public static String base64Encode(byte[] data) {
return data != null ? Base64.encodeBase64String(data) : null;
}
}
|
923557072844453505f30a6b73524ffcb76193d2 | 1,825 | java | Java | data/src/main/java/com/vml/listofthings/data/di/DataModule.java | VML/ListOfThings-Android | 01461349b971dae2a460cc0039b985d66e66921f | [
"Apache-2.0"
] | 177 | 2016-08-12T03:36:09.000Z | 2021-05-21T11:53:50.000Z | data/src/main/java/com/vml/listofthings/data/di/DataModule.java | VML/ListOfThings-Android | 01461349b971dae2a460cc0039b985d66e66921f | [
"Apache-2.0"
] | 2 | 2016-09-18T17:44:47.000Z | 2016-12-29T09:21:40.000Z | data/src/main/java/com/vml/listofthings/data/di/DataModule.java | VML/ListOfThings-Android | 01461349b971dae2a460cc0039b985d66e66921f | [
"Apache-2.0"
] | 22 | 2016-06-01T14:10:45.000Z | 2020-06-17T13:04:48.000Z | 26.838235 | 101 | 0.725479 | 997,256 | package com.vml.listofthings.data.di;
import com.toddway.shelf.Shelf;
import com.vml.listofthings.data.base.DataUtil;
import com.vml.listofthings.core.environment.Environment;
import com.vml.listofthings.data.base.RxUtil;
import com.vml.listofthings.data.base.ServiceFactory;
import com.vml.listofthings.data.things.ThingRepositoryImpl;
import com.vml.listofthings.data.things.ThingService;
import java.io.File;
import java.util.Arrays;
import java.util.List;
import javax.inject.Singleton;
import dagger.Module;
import dagger.Provides;
import retrofit.RestAdapter;
/**
* Created by tway on 5/10/16.
*/
@Module
public class DataModule {
protected File cacheDir;
protected RxUtil rxUtil;
public DataModule(File cacheDir, RxUtil rxUtil) {
this.cacheDir = cacheDir;
this.rxUtil = rxUtil;
}
@Provides
public List<Environment> provideEnvironments() {
return Arrays.asList(
Environment.create("stage", "Stage", "https://example.com", "https://example.com")
);
}
@Provides
public Shelf provideShelf() {
return new Shelf(cacheDir);
}
@Provides @Singleton
public DataUtil provideDataUtil(Shelf shelf, List<Environment> environments) {
return new DataUtil(rxUtil, shelf, environments);
}
@Provides
public ServiceFactory provideServiceFactory(DataUtil dataUtil) {
return new ServiceFactory(dataUtil, RestAdapter.LogLevel.NONE);
}
@Provides @Singleton
public ThingService provideThingService(ServiceFactory serviceFactory) {
return serviceFactory.create(ThingService.class);
}
@Provides
public ThingRepositoryImpl provideThingRepository(ThingService thingService, DataUtil dataUtil) {
return new ThingRepositoryImpl(thingService, dataUtil);
}
}
|
923557124f27c3c4adf95aaf16af65f2fc1a5f56 | 1,341 | java | Java | engine/src/org/pentaho/di/trans/steps/wmiinput/WMIInputData.java | jjeb/kettle-trunk | 3d5a009ac6551962560b4af4cbb5b2b6b1ebc8a6 | [
"Apache-2.0"
] | 2 | 2017-02-15T02:04:27.000Z | 2020-07-02T08:27:43.000Z | engine/src/org/pentaho/di/trans/steps/wmiinput/WMIInputData.java | jjeb/kettle-trunk | 3d5a009ac6551962560b4af4cbb5b2b6b1ebc8a6 | [
"Apache-2.0"
] | null | null | null | engine/src/org/pentaho/di/trans/steps/wmiinput/WMIInputData.java | jjeb/kettle-trunk | 3d5a009ac6551962560b4af4cbb5b2b6b1ebc8a6 | [
"Apache-2.0"
] | null | null | null | 27.9375 | 80 | 0.607755 | 997,257 | /*******************************************************************************
*
* Pentaho Data Integration
*
* Copyright (C) 2002-2012 by Pentaho : http://www.pentaho.com
*
*******************************************************************************
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
******************************************************************************/
package org.pentaho.di.trans.steps.wmiinput;
import org.pentaho.di.core.row.RowMetaInterface;
import org.pentaho.di.trans.step.BaseStepData;
import org.pentaho.di.trans.step.StepDataInterface;
/**
* @author Samatar
* @since 01-10-2011
*/
public class WMIInputData extends BaseStepData implements StepDataInterface
{
public WMIQuery query;
public RowMetaInterface outputRowMeta;
public WMIInputData()
{
super();
}
}
|
9235578f50ff56ed6f52adbad62b973480438e0c | 1,620 | java | Java | Server/src/main/java/com/hackmann/polarity/websocket/Server.java | totoro987123/Polarity-HackMann-2021 | 1f465b5538084868d09bb725bd1efcdee12f6d46 | [
"MIT"
] | null | null | null | Server/src/main/java/com/hackmann/polarity/websocket/Server.java | totoro987123/Polarity-HackMann-2021 | 1f465b5538084868d09bb725bd1efcdee12f6d46 | [
"MIT"
] | null | null | null | Server/src/main/java/com/hackmann/polarity/websocket/Server.java | totoro987123/Polarity-HackMann-2021 | 1f465b5538084868d09bb725bd1efcdee12f6d46 | [
"MIT"
] | null | null | null | 23.478261 | 89 | 0.599383 | 997,258 | package com.hackmann.polarity.websocket;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Controller;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
@Controller
public class Server implements Runnable {
@Autowired
private ApplicationContext context;
private final int PORT = 16568;
private ServerSocket serverSocket;
private boolean running = false;
private int id = 0;
public Server() {
try {
serverSocket = new ServerSocket(this.PORT);
}catch(IOException e) {
e.printStackTrace();
}
this.start();
}
public void start() {
new Thread(this).start();
}
@Override
public void run() {
this.running = true;
System.out.println(String.format("\n\nServer started on port: %s\n", this.PORT));
while (this.running) {
try {
Socket socket = serverSocket.accept();
this.initSocket(socket);
}catch(IOException e) {
e.printStackTrace();
}
}
this.shutdown();
}
private void initSocket(Socket socket) {
Connection connection = context.getBean(Connection.class, socket, id);
new Thread(connection).start();
this.id++;
}
public void shutdown() {
this.running = false;
try {
serverSocket.close();
}catch(IOException e) {
e.printStackTrace();
}
}
}
|
923557aceaa4beb053767fc16d822d3763694d91 | 45,431 | java | Java | pulsar-broker-common/src/main/java/org/apache/pulsar/broker/ServiceConfiguration.java | tkb77/pulsar | 1a6ffbfc12812373957d36a23779066505d107de | [
"Apache-2.0"
] | 3 | 2017-11-10T02:43:58.000Z | 2021-04-21T17:06:50.000Z | pulsar-broker-common/src/main/java/org/apache/pulsar/broker/ServiceConfiguration.java | tkb77/pulsar | 1a6ffbfc12812373957d36a23779066505d107de | [
"Apache-2.0"
] | null | null | null | pulsar-broker-common/src/main/java/org/apache/pulsar/broker/ServiceConfiguration.java | tkb77/pulsar | 1a6ffbfc12812373957d36a23779066505d107de | [
"Apache-2.0"
] | null | null | null | 40.745291 | 155 | 0.769519 | 997,259 | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.pulsar.broker;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.util.Set;
import org.apache.pulsar.common.configuration.FieldContext;
import org.apache.pulsar.common.configuration.PulsarConfiguration;
import com.google.common.collect.Sets;
/**
* Pulsar service configuration object.
*/
public class ServiceConfiguration implements PulsarConfiguration {
/***** --- pulsar configuration --- ****/
// Zookeeper quorum connection string
@FieldContext(required = true)
private String zookeeperServers;
// Global Zookeeper quorum connection string
@FieldContext(required = false)
private String globalZookeeperServers;
private int brokerServicePort = 6650;
private int brokerServicePortTls = 6651;
// Port to use to server HTTP request
private int webServicePort = 8080;
// Port to use to server HTTPS request
private int webServicePortTls = 8443;
// Hostname or IP address the service binds on.
private String bindAddress = "0.0.0.0";
// Controls which hostname is advertised to the discovery service via ZooKeeper.
private String advertisedAddress;
// Enable the WebSocket API service
private boolean webSocketServiceEnabled = false;
// Name of the cluster to which this broker belongs to
@FieldContext(required = true)
private String clusterName;
// Zookeeper session timeout in milliseconds
private long zooKeeperSessionTimeoutMillis = 30000;
// Time to wait for broker graceful shutdown. After this time elapses, the
// process will be killed
@FieldContext(dynamic = true)
private long brokerShutdownTimeoutMs = 3000;
// Enable backlog quota check. Enforces action on topic when the quota is
// reached
private boolean backlogQuotaCheckEnabled = true;
// How often to check for topics that have reached the quota
private int backlogQuotaCheckIntervalInSeconds = 60;
// Default per-topic backlog quota limit
private long backlogQuotaDefaultLimitGB = 50;
// Enable the deletion of inactive topics
private boolean brokerDeleteInactiveTopicsEnabled = true;
// How often to check for inactive topics
private long brokerDeleteInactiveTopicsFrequencySeconds = 60;
// How frequently to proactively check and purge expired messages
private int messageExpiryCheckIntervalInMinutes = 5;
// Enable check for minimum allowed client library version
private boolean clientLibraryVersionCheckEnabled = false;
// Allow client libraries with no version information
private boolean clientLibraryVersionCheckAllowUnversioned = true;
// Path for the file used to determine the rotation status for the broker
// when responding to service discovery health checks
private String statusFilePath;
// Max number of unacknowledged messages allowed to receive messages by a consumer on a shared subscription. Broker
// will stop sending messages to consumer once, this limit reaches until consumer starts acknowledging messages back
// and unack count reaches to maxUnackedMessagesPerConsumer/2 Using a value of 0, is disabling unackedMessage-limit
// check and consumer can receive messages without any restriction
private int maxUnackedMessagesPerConsumer = 50000;
// Max number of unacknowledged messages allowed per shared subscription. Broker will stop dispatching messages to
// all consumers of the subscription once this limit reaches until consumer starts acknowledging messages back and
// unack count reaches to limit/2. Using a value of 0, is disabling unackedMessage-limit
// check and dispatcher can dispatch messages without any restriction
private int maxUnackedMessagesPerSubscription = 4 * 50000;
// Max number of unacknowledged messages allowed per broker. Once this limit reaches, broker will stop dispatching
// messages to all shared subscription which has higher number of unack messages until subscriptions start
// acknowledging messages back and unack count reaches to limit/2. Using a value of 0, is disabling
// unackedMessage-limit check and broker doesn't block dispatchers
private int maxUnackedMessagesPerBroker = 0;
// Once broker reaches maxUnackedMessagesPerBroker limit, it blocks subscriptions which has higher unacked messages
// than this percentage limit and subscription will not receive any new messages until that subscription acks back
// limit/2 messages
private double maxUnackedMessagesPerSubscriptionOnBrokerBlocked = 0.16;
// Default number of message dispatching throttling-limit for every topic. Using a value of 0, is disabling default
// message dispatch-throttling
@FieldContext(dynamic = true)
private int dispatchThrottlingRatePerTopicInMsg = 0;
// Default number of message-bytes dispatching throttling-limit for every topic. Using a value of 0, is disabling
// default message-byte dispatch-throttling
@FieldContext(dynamic = true)
private long dispatchThrottlingRatePerTopicInByte = 0;
// Max number of concurrent lookup request broker allows to throttle heavy incoming lookup traffic
@FieldContext(dynamic = true)
private int maxConcurrentLookupRequest = 10000;
// Max number of concurrent topic loading request broker allows to control number of zk-operations
@FieldContext(dynamic = true)
private int maxConcurrentTopicLoadRequest = 5000;
// Max concurrent non-persistent message can be processed per connection
private int maxConcurrentNonPersistentMessagePerConnection = 1000;
// Number of worker threads to serve non-persistent topic
private int numWorkerThreadsForNonPersistentTopic = 8;
// Enable broker to load persistent topics
private boolean enablePersistentTopics = true;
// Enable broker to load non-persistent topics
private boolean enableNonPersistentTopics = true;
/***** --- TLS --- ****/
// Enable TLS
private boolean tlsEnabled = false;
// Path for the TLS certificate file
private String tlsCertificateFilePath;
// Path for the TLS private key file
private String tlsKeyFilePath;
// Path for the trusted TLS certificate file
private String tlsTrustCertsFilePath = "";
// Accept untrusted TLS certificate from client
private boolean tlsAllowInsecureConnection = false;
/***** --- Authentication --- ****/
// Enable authentication
private boolean authenticationEnabled = false;
// Autentication provider name list, which is a list of class names
private Set<String> authenticationProviders = Sets.newTreeSet();
// Enforce authorization
private boolean authorizationEnabled = false;
// Role names that are treated as "super-user", meaning they will be able to
// do all admin operations and publish/consume from all topics
private Set<String> superUserRoles = Sets.newTreeSet();
// Allow wildcard matching in authorization
// (wildcard matching only applicable if wildcard-char:
// * presents at first or last position eg: *.pulsar.service, pulsar.service.*)
private boolean authorizationAllowWildcardsMatching = false;
// Authentication settings of the broker itself. Used when the broker connects
// to other brokers, either in same or other clusters. Default uses plugin which disables authentication
private String brokerClientAuthenticationPlugin = "org.apache.pulsar.client.impl.auth.AuthenticationDisabled";
private String brokerClientAuthenticationParameters = "";
/**** --- BookKeeper Client --- ****/
// Authentication plugin to use when connecting to bookies
private String bookkeeperClientAuthenticationPlugin;
// BookKeeper auth plugin implementatation specifics parameters name and values
private String bookkeeperClientAuthenticationParametersName;
private String bookkeeperClientAuthenticationParameters;
// Timeout for BK add / read operations
private long bookkeeperClientTimeoutInSeconds = 30;
// Speculative reads are initiated if a read request doesn't complete within
// a certain time Using a value of 0, is disabling the speculative reads
private int bookkeeperClientSpeculativeReadTimeoutInMillis = 0;
// Enable bookies health check. Bookies that have more than the configured
// number of failure within the interval will be quarantined for some time.
// During this period, new ledgers won't be created on these bookies
private boolean bookkeeperClientHealthCheckEnabled = true;
private long bookkeeperClientHealthCheckIntervalSeconds = 60;
private long bookkeeperClientHealthCheckErrorThresholdPerInterval = 5;
private long bookkeeperClientHealthCheckQuarantineTimeInSeconds = 1800;
// Enable rack-aware bookie selection policy. BK will chose bookies from
// different racks when forming a new bookie ensemble
private boolean bookkeeperClientRackawarePolicyEnabled = true;
// Enable bookie isolation by specifying a list of bookie groups to choose
// from. Any bookie outside the specified groups will not be used by the
// broker
@FieldContext(required = false)
private String bookkeeperClientIsolationGroups;
/**** --- Managed Ledger --- ****/
// Number of bookies to use when creating a ledger
@FieldContext(minValue = 1)
private int managedLedgerDefaultEnsembleSize = 1;
// Number of copies to store for each message
@FieldContext(minValue = 1)
private int managedLedgerDefaultWriteQuorum = 1;
// Number of guaranteed copies (acks to wait before write is complete)
@FieldContext(minValue = 1)
private int managedLedgerDefaultAckQuorum = 1;
// Amount of memory to use for caching data payload in managed ledger. This
// memory
// is allocated from JVM direct memory and it's shared across all the topics
// running in the same broker
private int managedLedgerCacheSizeMB = 1024;
// Threshold to which bring down the cache level when eviction is triggered
private double managedLedgerCacheEvictionWatermark = 0.9f;
// Rate limit the amount of writes per second generated by consumer acking the messages
private double managedLedgerDefaultMarkDeleteRateLimit = 1.0;
// Max number of entries to append to a ledger before triggering a rollover
// A ledger rollover is triggered on these conditions Either the max
// rollover time has been reached or max entries have been written to the
// ledged and at least min-time has passed
private int managedLedgerMaxEntriesPerLedger = 50000;
// Minimum time between ledger rollover for a topic
private int managedLedgerMinLedgerRolloverTimeMinutes = 10;
// Maximum time before forcing a ledger rollover for a topic
private int managedLedgerMaxLedgerRolloverTimeMinutes = 240;
// Max number of entries to append to a cursor ledger
private int managedLedgerCursorMaxEntriesPerLedger = 50000;
// Max time before triggering a rollover on a cursor ledger
private int managedLedgerCursorRolloverTimeInSeconds = 14400;
// Max number of "acknowledgment holes" that are going to be persistently stored.
// When acknowledging out of order, a consumer will leave holes that are supposed
// to be quickly filled by acking all the messages. The information of which
// messages are acknowledged is persisted by compressing in "ranges" of messages
// that were acknowledged. After the max number of ranges is reached, the information
// will only be tracked in memory and messages will be redelivered in case of
// crashes.
private int managedLedgerMaxUnackedRangesToPersist = 1000;
/*** --- Load balancer --- ****/
// Enable load balancer
private boolean loadBalancerEnabled = false;
// load placement strategy
private String loadBalancerPlacementStrategy = "weightedRandomSelection"; // weighted random selection
// Percentage of change to trigger load report update
@FieldContext(dynamic = true)
private int loadBalancerReportUpdateThresholdPercentage = 10;
// maximum interval to update load report
@FieldContext(dynamic = true)
private int loadBalancerReportUpdateMaxIntervalMinutes = 15;
// Frequency of report to collect
private int loadBalancerHostUsageCheckIntervalMinutes = 1;
// Load shedding interval. Broker periodically checks whether some traffic
// should be offload from
// some over-loaded broker to other under-loaded brokers
private int loadBalancerSheddingIntervalMinutes = 30;
// Prevent the same topics to be shed and moved to other broker more that
// once within this timeframe
private long loadBalancerSheddingGracePeriodMinutes = 30;
// Usage threshold to determine a broker as under-loaded
private int loadBalancerBrokerUnderloadedThresholdPercentage = 50;
// Usage threshold to determine a broker as over-loaded
private int loadBalancerBrokerOverloadedThresholdPercentage = 85;
// interval to flush dynamic resource quota to ZooKeeper
private int loadBalancerResourceQuotaUpdateIntervalMinutes = 15;
// Usage threshold to defermine a broker is having just right level of load
private int loadBalancerBrokerComfortLoadLevelPercentage = 65;
// enable/disable automatic namespace bundle split
private boolean loadBalancerAutoBundleSplitEnabled = false;
// maximum topics in a bundle, otherwise bundle split will be triggered
private int loadBalancerNamespaceBundleMaxTopics = 1000;
// maximum sessions (producers + consumers) in a bundle, otherwise bundle split will be triggered
private int loadBalancerNamespaceBundleMaxSessions = 1000;
// maximum msgRate (in + out) in a bundle, otherwise bundle split will be triggered
private int loadBalancerNamespaceBundleMaxMsgRate = 1000;
// maximum bandwidth (in + out) in a bundle, otherwise bundle split will be triggered
private int loadBalancerNamespaceBundleMaxBandwidthMbytes = 100;
// maximum number of bundles in a namespace
private int loadBalancerNamespaceMaximumBundles = 128;
/**** --- Replication --- ****/
// Enable replication metrics
private boolean replicationMetricsEnabled = false;
// Max number of connections to open for each broker in a remote cluster
// More connections host-to-host lead to better throughput over high-latency
// links.
private int replicationConnectionsPerBroker = 16;
@FieldContext(required = false)
// replicator prefix used for replicator producer name and cursor name
private String replicatorPrefix = "pulsar.repl";
// Replicator producer queue size;
private int replicationProducerQueueSize = 1000;
// Default message retention time
private int defaultRetentionTimeInMinutes = 0;
// Default retention size
private int defaultRetentionSizeInMB = 0;
// How often to check pulsar connection is still alive
private int keepAliveIntervalSeconds = 30;
// How often broker checks for inactive topics to be deleted (topics with no subscriptions and no one connected)
private int brokerServicePurgeInactiveFrequencyInSeconds = 60;
private List<String> bootstrapNamespaces = new ArrayList<String>();
private Properties properties = new Properties();
// Name of load manager to use
@FieldContext(dynamic = true)
private String loadManagerClassName = "org.apache.pulsar.broker.loadbalance.impl.SimpleLoadManagerImpl";
// If true, (and ModularLoadManagerImpl is being used), the load manager will attempt to
// use only brokers running the latest software version (to minimize impact to bundles)
@FieldContext(dynamic = true)
private boolean preferLaterVersions = false;
/**** --- WebSocket --- ****/
// Number of IO threads in Pulsar Client used in WebSocket proxy
private int webSocketNumIoThreads = Runtime.getRuntime().availableProcessors();
// Number of connections per Broker in Pulsar Client used in WebSocket proxy
private int webSocketConnectionsPerBroker = Runtime.getRuntime().availableProcessors();
public String getZookeeperServers() {
return zookeeperServers;
}
public void setZookeeperServers(String zookeeperServers) {
this.zookeeperServers = zookeeperServers;
}
public String getGlobalZookeeperServers() {
if (this.globalZookeeperServers == null || this.globalZookeeperServers.isEmpty()) {
// If the configuration is not set, assuming that the globalZK is not enabled and all data is in the same
// ZooKeeper cluster
return this.getZookeeperServers();
}
return globalZookeeperServers;
}
public void setGlobalZookeeperServers(String globalZookeeperServers) {
this.globalZookeeperServers = globalZookeeperServers;
}
public int getBrokerServicePort() {
return brokerServicePort;
}
public void setBrokerServicePort(int brokerServicePort) {
this.brokerServicePort = brokerServicePort;
}
public int getBrokerServicePortTls() {
return brokerServicePortTls;
}
public void setBrokerServicePortTls(int brokerServicePortTls) {
this.brokerServicePortTls = brokerServicePortTls;
}
public int getWebServicePort() {
return webServicePort;
}
public void setWebServicePort(int webServicePort) {
this.webServicePort = webServicePort;
}
public int getWebServicePortTls() {
return webServicePortTls;
}
public void setWebServicePortTls(int webServicePortTls) {
this.webServicePortTls = webServicePortTls;
}
public String getBindAddress() {
return this.bindAddress;
}
public void setBindAddress(String bindAddress) {
this.bindAddress = bindAddress;
}
public String getAdvertisedAddress() {
return this.advertisedAddress;
}
public void setAdvertisedAddress(String advertisedAddress) {
this.advertisedAddress = advertisedAddress;
}
public boolean isWebSocketServiceEnabled() {
return webSocketServiceEnabled;
}
public void setWebSocketServiceEnabled(boolean webSocketServiceEnabled) {
this.webSocketServiceEnabled = webSocketServiceEnabled;
}
public String getClusterName() {
return clusterName;
}
public void setClusterName(String clusterName) {
this.clusterName = clusterName;
}
public long getBrokerShutdownTimeoutMs() {
return brokerShutdownTimeoutMs;
}
public void setBrokerShutdownTimeoutMs(long brokerShutdownTimeoutMs) {
this.brokerShutdownTimeoutMs = brokerShutdownTimeoutMs;
}
public boolean isBacklogQuotaCheckEnabled() {
return backlogQuotaCheckEnabled;
}
public void setBacklogQuotaCheckEnabled(boolean backlogQuotaCheckEnabled) {
this.backlogQuotaCheckEnabled = backlogQuotaCheckEnabled;
}
public int getBacklogQuotaCheckIntervalInSeconds() {
return backlogQuotaCheckIntervalInSeconds;
}
public void setBacklogQuotaCheckIntervalInSeconds(int backlogQuotaCheckIntervalInSeconds) {
this.backlogQuotaCheckIntervalInSeconds = backlogQuotaCheckIntervalInSeconds;
}
public long getBacklogQuotaDefaultLimitGB() {
return backlogQuotaDefaultLimitGB;
}
public void setBacklogQuotaDefaultLimitGB(long backlogQuotaDefaultLimitGB) {
this.backlogQuotaDefaultLimitGB = backlogQuotaDefaultLimitGB;
}
public boolean isBrokerDeleteInactiveTopicsEnabled() {
return brokerDeleteInactiveTopicsEnabled;
}
public void setBrokerDeleteInactiveTopicsEnabled(boolean brokerDeleteInactiveTopicsEnabled) {
this.brokerDeleteInactiveTopicsEnabled = brokerDeleteInactiveTopicsEnabled;
}
public long getBrokerDeleteInactiveTopicsFrequencySeconds() {
return brokerDeleteInactiveTopicsFrequencySeconds;
}
public void setBrokerDeleteInactiveTopicsFrequencySeconds(long brokerDeleteInactiveTopicsFrequencySeconds) {
this.brokerDeleteInactiveTopicsFrequencySeconds = brokerDeleteInactiveTopicsFrequencySeconds;
}
public int getMessageExpiryCheckIntervalInMinutes() {
return messageExpiryCheckIntervalInMinutes;
}
public void setMessageExpiryCheckIntervalInMinutes(int messageExpiryCheckIntervalInMinutes) {
this.messageExpiryCheckIntervalInMinutes = messageExpiryCheckIntervalInMinutes;
}
public boolean isClientLibraryVersionCheckEnabled() {
return clientLibraryVersionCheckEnabled;
}
public void setClientLibraryVersionCheckEnabled(boolean clientLibraryVersionCheckEnabled) {
this.clientLibraryVersionCheckEnabled = clientLibraryVersionCheckEnabled;
}
public boolean isClientLibraryVersionCheckAllowUnversioned() {
return clientLibraryVersionCheckAllowUnversioned;
}
public void setClientLibraryVersionCheckAllowUnversioned(boolean clientLibraryVersionCheckAllowUnversioned) {
this.clientLibraryVersionCheckAllowUnversioned = clientLibraryVersionCheckAllowUnversioned;
}
public String getStatusFilePath() {
return statusFilePath;
}
public void setStatusFilePath(String statusFilePath) {
this.statusFilePath = statusFilePath;
}
public int getMaxUnackedMessagesPerConsumer() {
return maxUnackedMessagesPerConsumer;
}
public void setMaxUnackedMessagesPerConsumer(int maxUnackedMessagesPerConsumer) {
this.maxUnackedMessagesPerConsumer = maxUnackedMessagesPerConsumer;
}
public int getMaxUnackedMessagesPerSubscription() {
return maxUnackedMessagesPerSubscription;
}
public void setMaxUnackedMessagesPerSubscription(int maxUnackedMessagesPerSubscription) {
this.maxUnackedMessagesPerSubscription = maxUnackedMessagesPerSubscription;
}
public int getMaxUnackedMessagesPerBroker() {
return maxUnackedMessagesPerBroker;
}
public void setMaxUnackedMessagesPerBroker(int maxUnackedMessagesPerBroker) {
this.maxUnackedMessagesPerBroker = maxUnackedMessagesPerBroker;
}
public double getMaxUnackedMessagesPerSubscriptionOnBrokerBlocked() {
return maxUnackedMessagesPerSubscriptionOnBrokerBlocked;
}
public void setMaxUnackedMessagesPerSubscriptionOnBrokerBlocked(
double maxUnackedMessagesPerSubscriptionOnBrokerBlocked) {
this.maxUnackedMessagesPerSubscriptionOnBrokerBlocked = maxUnackedMessagesPerSubscriptionOnBrokerBlocked;
}
public int getDispatchThrottlingRatePerTopicInMsg() {
return dispatchThrottlingRatePerTopicInMsg;
}
public void setDispatchThrottlingRatePerTopicInMsg(int dispatchThrottlingRatePerTopicInMsg) {
this.dispatchThrottlingRatePerTopicInMsg = dispatchThrottlingRatePerTopicInMsg;
}
public long getDispatchThrottlingRatePerTopicInByte() {
return dispatchThrottlingRatePerTopicInByte;
}
public void setDispatchThrottlingRatePerTopicInByte(long dispatchThrottlingRatePerTopicInByte) {
this.dispatchThrottlingRatePerTopicInByte = dispatchThrottlingRatePerTopicInByte;
}
public int getMaxConcurrentLookupRequest() {
return maxConcurrentLookupRequest;
}
public void setMaxConcurrentLookupRequest(int maxConcurrentLookupRequest) {
this.maxConcurrentLookupRequest = maxConcurrentLookupRequest;
}
public int getMaxConcurrentTopicLoadRequest() {
return maxConcurrentTopicLoadRequest;
}
public void setMaxConcurrentTopicLoadRequest(int maxConcurrentTopicLoadRequest) {
this.maxConcurrentTopicLoadRequest = maxConcurrentTopicLoadRequest;
}
public int getMaxConcurrentNonPersistentMessagePerConnection() {
return maxConcurrentNonPersistentMessagePerConnection;
}
public void setMaxConcurrentNonPersistentMessagePerConnection(int maxConcurrentNonPersistentMessagePerConnection) {
this.maxConcurrentNonPersistentMessagePerConnection = maxConcurrentNonPersistentMessagePerConnection;
}
public int getNumWorkerThreadsForNonPersistentTopic() {
return numWorkerThreadsForNonPersistentTopic;
}
public void setNumWorkerThreadsForNonPersistentTopic(int numWorkerThreadsForNonPersistentTopic) {
this.numWorkerThreadsForNonPersistentTopic = numWorkerThreadsForNonPersistentTopic;
}
public boolean isEnablePersistentTopics() {
return enablePersistentTopics;
}
public void setEnablePersistentTopics(boolean enablePersistentTopics) {
this.enablePersistentTopics = enablePersistentTopics;
}
public boolean isEnableNonPersistentTopics() {
return enableNonPersistentTopics;
}
public void setEnableNonPersistentTopics(boolean enableNonPersistentTopics) {
this.enableNonPersistentTopics = enableNonPersistentTopics;
}
public boolean isTlsEnabled() {
return tlsEnabled;
}
public void setTlsEnabled(boolean tlsEnabled) {
this.tlsEnabled = tlsEnabled;
}
public String getTlsCertificateFilePath() {
return tlsCertificateFilePath;
}
public void setTlsCertificateFilePath(String tlsCertificateFilePath) {
this.tlsCertificateFilePath = tlsCertificateFilePath;
}
public String getTlsKeyFilePath() {
return tlsKeyFilePath;
}
public void setTlsKeyFilePath(String tlsKeyFilePath) {
this.tlsKeyFilePath = tlsKeyFilePath;
}
public String getTlsTrustCertsFilePath() {
return tlsTrustCertsFilePath;
}
public void setTlsTrustCertsFilePath(String tlsTrustCertsFilePath) {
this.tlsTrustCertsFilePath = tlsTrustCertsFilePath;
}
public boolean isTlsAllowInsecureConnection() {
return tlsAllowInsecureConnection;
}
public void setTlsAllowInsecureConnection(boolean tlsAllowInsecureConnection) {
this.tlsAllowInsecureConnection = tlsAllowInsecureConnection;
}
public boolean isAuthenticationEnabled() {
return authenticationEnabled;
}
public void setAuthenticationEnabled(boolean authenticationEnabled) {
this.authenticationEnabled = authenticationEnabled;
}
public void setAuthenticationProviders(Set<String> providersClassNames) {
authenticationProviders = providersClassNames;
}
public Set<String> getAuthenticationProviders() {
return authenticationProviders;
}
public boolean isAuthorizationEnabled() {
return authorizationEnabled;
}
public void setAuthorizationEnabled(boolean authorizationEnabled) {
this.authorizationEnabled = authorizationEnabled;
}
public Set<String> getSuperUserRoles() {
return superUserRoles;
}
public boolean getAuthorizationAllowWildcardsMatching() {
return authorizationAllowWildcardsMatching;
}
public void setAuthorizationAllowWildcardsMatching(boolean authorizationAllowWildcardsMatching) {
this.authorizationAllowWildcardsMatching = authorizationAllowWildcardsMatching;
}
public void setSuperUserRoles(Set<String> superUserRoles) {
this.superUserRoles = superUserRoles;
}
public String getBrokerClientAuthenticationPlugin() {
return brokerClientAuthenticationPlugin;
}
public void setBrokerClientAuthenticationPlugin(String brokerClientAuthenticationPlugin) {
this.brokerClientAuthenticationPlugin = brokerClientAuthenticationPlugin;
}
public String getBrokerClientAuthenticationParameters() {
return brokerClientAuthenticationParameters;
}
public void setBrokerClientAuthenticationParameters(String brokerClientAuthenticationParameters) {
this.brokerClientAuthenticationParameters = brokerClientAuthenticationParameters;
}
public String getBookkeeperClientAuthenticationPlugin() {
return bookkeeperClientAuthenticationPlugin;
}
public void setBookkeeperClientAuthenticationPlugin(String bookkeeperClientAuthenticationPlugin) {
this.bookkeeperClientAuthenticationPlugin = bookkeeperClientAuthenticationPlugin;
}
public String getBookkeeperClientAuthenticationParametersName() {
return bookkeeperClientAuthenticationParametersName;
}
public void setBookkeeperClientAuthenticationParametersName(String bookkeeperClientAuthenticationParametersName) {
this.bookkeeperClientAuthenticationParametersName = bookkeeperClientAuthenticationParametersName;
}
public String getBookkeeperClientAuthenticationParameters() {
return bookkeeperClientAuthenticationParameters;
}
public void setBookkeeperClientAuthenticationParameters(String bookkeeperClientAuthenticationParameters) {
this.bookkeeperClientAuthenticationParameters = bookkeeperClientAuthenticationParameters;
}
public long getBookkeeperClientTimeoutInSeconds() {
return bookkeeperClientTimeoutInSeconds;
}
public void setBookkeeperClientTimeoutInSeconds(long bookkeeperClientTimeoutInSeconds) {
this.bookkeeperClientTimeoutInSeconds = bookkeeperClientTimeoutInSeconds;
}
public int getBookkeeperClientSpeculativeReadTimeoutInMillis() {
return bookkeeperClientSpeculativeReadTimeoutInMillis;
}
public void setBookkeeperClientSpeculativeReadTimeoutInMillis(int bookkeeperClientSpeculativeReadTimeoutInMillis) {
this.bookkeeperClientSpeculativeReadTimeoutInMillis = bookkeeperClientSpeculativeReadTimeoutInMillis;
}
public boolean isBookkeeperClientHealthCheckEnabled() {
return bookkeeperClientHealthCheckEnabled;
}
public void setBookkeeperClientHealthCheckEnabled(boolean bookkeeperClientHealthCheckEnabled) {
this.bookkeeperClientHealthCheckEnabled = bookkeeperClientHealthCheckEnabled;
}
public long getBookkeeperClientHealthCheckIntervalSeconds() {
return bookkeeperClientHealthCheckIntervalSeconds;
}
public void setBookkeeperClientHealthCheckIntervalSeconds(long bookkeeperClientHealthCheckIntervalSeconds) {
this.bookkeeperClientHealthCheckIntervalSeconds = bookkeeperClientHealthCheckIntervalSeconds;
}
public long getBookkeeperClientHealthCheckErrorThresholdPerInterval() {
return bookkeeperClientHealthCheckErrorThresholdPerInterval;
}
public void setBookkeeperClientHealthCheckErrorThresholdPerInterval(
long bookkeeperClientHealthCheckErrorThresholdPerInterval) {
this.bookkeeperClientHealthCheckErrorThresholdPerInterval = bookkeeperClientHealthCheckErrorThresholdPerInterval;
}
public long getBookkeeperClientHealthCheckQuarantineTimeInSeconds() {
return bookkeeperClientHealthCheckQuarantineTimeInSeconds;
}
public void setBookkeeperClientHealthCheckQuarantineTimeInSeconds(
long bookkeeperClientHealthCheckQuarantineTimeInSeconds) {
this.bookkeeperClientHealthCheckQuarantineTimeInSeconds = bookkeeperClientHealthCheckQuarantineTimeInSeconds;
}
public boolean isBookkeeperClientRackawarePolicyEnabled() {
return bookkeeperClientRackawarePolicyEnabled;
}
public void setBookkeeperClientRackawarePolicyEnabled(boolean bookkeeperClientRackawarePolicyEnabled) {
this.bookkeeperClientRackawarePolicyEnabled = bookkeeperClientRackawarePolicyEnabled;
}
public String getBookkeeperClientIsolationGroups() {
return bookkeeperClientIsolationGroups;
}
public void setBookkeeperClientIsolationGroups(String bookkeeperClientIsolationGroups) {
this.bookkeeperClientIsolationGroups = bookkeeperClientIsolationGroups;
}
public int getManagedLedgerDefaultEnsembleSize() {
return managedLedgerDefaultEnsembleSize;
}
public void setManagedLedgerDefaultEnsembleSize(int managedLedgerDefaultEnsembleSize) {
this.managedLedgerDefaultEnsembleSize = managedLedgerDefaultEnsembleSize;
}
public int getManagedLedgerDefaultWriteQuorum() {
return managedLedgerDefaultWriteQuorum;
}
public void setManagedLedgerDefaultWriteQuorum(int managedLedgerDefaultWriteQuorum) {
this.managedLedgerDefaultWriteQuorum = managedLedgerDefaultWriteQuorum;
}
public int getManagedLedgerDefaultAckQuorum() {
return managedLedgerDefaultAckQuorum;
}
public void setManagedLedgerDefaultAckQuorum(int managedLedgerDefaultAckQuorum) {
this.managedLedgerDefaultAckQuorum = managedLedgerDefaultAckQuorum;
}
public int getManagedLedgerCacheSizeMB() {
return managedLedgerCacheSizeMB;
}
public void setManagedLedgerCacheSizeMB(int managedLedgerCacheSizeMB) {
this.managedLedgerCacheSizeMB = managedLedgerCacheSizeMB;
}
public double getManagedLedgerCacheEvictionWatermark() {
return managedLedgerCacheEvictionWatermark;
}
public void setManagedLedgerCacheEvictionWatermark(double managedLedgerCacheEvictionWatermark) {
this.managedLedgerCacheEvictionWatermark = managedLedgerCacheEvictionWatermark;
}
public double getManagedLedgerDefaultMarkDeleteRateLimit() {
return managedLedgerDefaultMarkDeleteRateLimit;
}
public void setManagedLedgerDefaultMarkDeleteRateLimit(double managedLedgerDefaultMarkDeleteRateLimit) {
this.managedLedgerDefaultMarkDeleteRateLimit = managedLedgerDefaultMarkDeleteRateLimit;
}
public int getManagedLedgerMaxEntriesPerLedger() {
return managedLedgerMaxEntriesPerLedger;
}
public void setManagedLedgerMaxEntriesPerLedger(int managedLedgerMaxEntriesPerLedger) {
this.managedLedgerMaxEntriesPerLedger = managedLedgerMaxEntriesPerLedger;
}
public int getManagedLedgerMinLedgerRolloverTimeMinutes() {
return managedLedgerMinLedgerRolloverTimeMinutes;
}
public void setManagedLedgerMinLedgerRolloverTimeMinutes(int managedLedgerMinLedgerRolloverTimeMinutes) {
this.managedLedgerMinLedgerRolloverTimeMinutes = managedLedgerMinLedgerRolloverTimeMinutes;
}
public int getManagedLedgerMaxLedgerRolloverTimeMinutes() {
return managedLedgerMaxLedgerRolloverTimeMinutes;
}
public void setManagedLedgerMaxLedgerRolloverTimeMinutes(int managedLedgerMaxLedgerRolloverTimeMinutes) {
this.managedLedgerMaxLedgerRolloverTimeMinutes = managedLedgerMaxLedgerRolloverTimeMinutes;
}
public int getManagedLedgerCursorMaxEntriesPerLedger() {
return managedLedgerCursorMaxEntriesPerLedger;
}
public void setManagedLedgerCursorMaxEntriesPerLedger(int managedLedgerCursorMaxEntriesPerLedger) {
this.managedLedgerCursorMaxEntriesPerLedger = managedLedgerCursorMaxEntriesPerLedger;
}
public int getManagedLedgerCursorRolloverTimeInSeconds() {
return managedLedgerCursorRolloverTimeInSeconds;
}
public void setManagedLedgerCursorRolloverTimeInSeconds(int managedLedgerCursorRolloverTimeInSeconds) {
this.managedLedgerCursorRolloverTimeInSeconds = managedLedgerCursorRolloverTimeInSeconds;
}
public int getManagedLedgerMaxUnackedRangesToPersist() {
return managedLedgerMaxUnackedRangesToPersist;
}
public void setManagedLedgerMaxUnackedRangesToPersist(int managedLedgerMaxUnackedRangesToPersist) {
this.managedLedgerMaxUnackedRangesToPersist = managedLedgerMaxUnackedRangesToPersist;
}
public boolean isLoadBalancerEnabled() {
return loadBalancerEnabled;
}
public void setLoadBalancerEnabled(boolean loadBalancerEnabled) {
this.loadBalancerEnabled = loadBalancerEnabled;
}
public void setLoadBalancerPlacementStrategy(String placementStrategy) {
this.loadBalancerPlacementStrategy = placementStrategy;
}
public String getLoadBalancerPlacementStrategy() {
return this.loadBalancerPlacementStrategy;
}
public int getLoadBalancerReportUpdateThresholdPercentage() {
return loadBalancerReportUpdateThresholdPercentage;
}
public void setLoadBalancerReportUpdateThresholdPercentage(int loadBalancerReportUpdateThresholdPercentage) {
this.loadBalancerReportUpdateThresholdPercentage = loadBalancerReportUpdateThresholdPercentage;
}
public int getLoadBalancerReportUpdateMaxIntervalMinutes() {
return loadBalancerReportUpdateMaxIntervalMinutes;
}
public void setLoadBalancerReportUpdateMaxIntervalMinutes(int loadBalancerReportUpdateMaxIntervalMinutes) {
this.loadBalancerReportUpdateMaxIntervalMinutes = loadBalancerReportUpdateMaxIntervalMinutes;
}
public int getLoadBalancerHostUsageCheckIntervalMinutes() {
return loadBalancerHostUsageCheckIntervalMinutes;
}
public void setLoadBalancerHostUsageCheckIntervalMinutes(int loadBalancerHostUsageCheckIntervalMinutes) {
this.loadBalancerHostUsageCheckIntervalMinutes = loadBalancerHostUsageCheckIntervalMinutes;
}
public int getLoadBalancerSheddingIntervalMinutes() {
return loadBalancerSheddingIntervalMinutes;
}
public void setLoadBalancerSheddingIntervalMinutes(int loadBalancerSheddingIntervalMinutes) {
this.loadBalancerSheddingIntervalMinutes = loadBalancerSheddingIntervalMinutes;
}
public long getLoadBalancerSheddingGracePeriodMinutes() {
return loadBalancerSheddingGracePeriodMinutes;
}
public void setLoadBalancerSheddingGracePeriodMinutes(long loadBalancerSheddingGracePeriodMinutes) {
this.loadBalancerSheddingGracePeriodMinutes = loadBalancerSheddingGracePeriodMinutes;
}
public int getLoadBalancerResourceQuotaUpdateIntervalMinutes() {
return this.loadBalancerResourceQuotaUpdateIntervalMinutes;
}
public void setLoadBalancerResourceQuotaUpdateIntervalMinutes(int interval) {
this.loadBalancerResourceQuotaUpdateIntervalMinutes = interval;
}
public int getLoadBalancerBrokerUnderloadedThresholdPercentage() {
return loadBalancerBrokerUnderloadedThresholdPercentage;
}
public void setLoadBalancerBrokerUnderloadedThresholdPercentage(
int loadBalancerBrokerUnderloadedThresholdPercentage) {
this.loadBalancerBrokerUnderloadedThresholdPercentage = loadBalancerBrokerUnderloadedThresholdPercentage;
}
public int getLoadBalancerBrokerOverloadedThresholdPercentage() {
return loadBalancerBrokerOverloadedThresholdPercentage;
}
public void setLoadBalancerNamespaceBundleMaxTopics(int topics) {
this.loadBalancerNamespaceBundleMaxTopics = topics;
}
public int getLoadBalancerNamespaceBundleMaxTopics() {
return this.loadBalancerNamespaceBundleMaxTopics;
}
public void setLoadBalancerNamespaceBundleMaxSessions(int sessions) {
this.loadBalancerNamespaceBundleMaxSessions = sessions;
}
public int getLoadBalancerNamespaceBundleMaxSessions() {
return this.loadBalancerNamespaceBundleMaxSessions;
}
public void setLoadBalancerNamespaceBundleMaxMsgRate(int msgRate) {
this.loadBalancerNamespaceBundleMaxMsgRate = msgRate;
}
public int getLoadBalancerNamespaceBundleMaxMsgRate() {
return this.loadBalancerNamespaceBundleMaxMsgRate;
}
public void setLoadBalancerNamespaceBundleMaxBandwidthMbytes(int bandwidth) {
this.loadBalancerNamespaceBundleMaxBandwidthMbytes = bandwidth;
}
public int getLoadBalancerNamespaceBundleMaxBandwidthMbytes() {
return this.loadBalancerNamespaceBundleMaxBandwidthMbytes;
}
public void setLoadBalancerBrokerOverloadedThresholdPercentage(
int loadBalancerBrokerOverloadedThresholdPercentage) {
this.loadBalancerBrokerOverloadedThresholdPercentage = loadBalancerBrokerOverloadedThresholdPercentage;
}
public int getLoadBalancerBrokerComfortLoadLevelPercentage() {
return this.loadBalancerBrokerComfortLoadLevelPercentage;
}
public void setLoadBalancerBrokerComfortLoadLevelPercentage(int percentage) {
this.loadBalancerBrokerComfortLoadLevelPercentage = percentage;
}
public boolean getLoadBalancerAutoBundleSplitEnabled() {
return this.loadBalancerAutoBundleSplitEnabled;
}
public void setLoadBalancerAutoBundleSplitEnabled(boolean enabled) {
this.loadBalancerAutoBundleSplitEnabled = enabled;
}
public void setLoadBalancerNamespaceMaximumBundles(int bundles) {
this.loadBalancerNamespaceMaximumBundles = bundles;
}
public int getLoadBalancerNamespaceMaximumBundles() {
return this.loadBalancerNamespaceMaximumBundles;
}
public boolean isReplicationMetricsEnabled() {
return replicationMetricsEnabled;
}
public void setReplicationMetricsEnabled(boolean replicationMetricsEnabled) {
this.replicationMetricsEnabled = replicationMetricsEnabled;
}
public int getReplicationConnectionsPerBroker() {
return replicationConnectionsPerBroker;
}
public void setReplicationConnectionsPerBroker(int replicationConnectionsPerBroker) {
this.replicationConnectionsPerBroker = replicationConnectionsPerBroker;
}
public int getReplicationProducerQueueSize() {
return replicationProducerQueueSize;
}
public void setReplicationProducerQueueSize(int replicationProducerQueueSize) {
this.replicationProducerQueueSize = replicationProducerQueueSize;
}
public List<String> getBootstrapNamespaces() {
return bootstrapNamespaces;
}
public Object getProperty(String key) {
return properties.get(key);
}
@Override
public Properties getProperties() {
return properties;
}
@Override
public void setProperties(Properties properties) {
this.properties = properties;
}
public int getDefaultRetentionTimeInMinutes() {
return defaultRetentionTimeInMinutes;
}
public void setDefaultRetentionTimeInMinutes(int defaultRetentionTimeInMinutes) {
this.defaultRetentionTimeInMinutes = defaultRetentionTimeInMinutes;
}
public int getDefaultRetentionSizeInMB() {
return defaultRetentionSizeInMB;
}
public void setDefaultRetentionSizeInMB(int defaultRetentionSizeInMB) {
this.defaultRetentionSizeInMB = defaultRetentionSizeInMB;
}
public int getBookkeeperHealthCheckIntervalSec() {
return (int) bookkeeperClientHealthCheckIntervalSeconds;
}
public void setBootstrapNamespaces(List<String> bootstrapNamespaces) {
this.bootstrapNamespaces = bootstrapNamespaces;
}
public void setBrokerServicePurgeInactiveFrequencyInSeconds(int brokerServicePurgeInactiveFrequencyInSeconds) {
this.brokerServicePurgeInactiveFrequencyInSeconds = brokerServicePurgeInactiveFrequencyInSeconds;
}
public int getKeepAliveIntervalSeconds() {
return keepAliveIntervalSeconds;
}
public void setKeepAliveIntervalSeconds(int keepAliveIntervalSeconds) {
this.keepAliveIntervalSeconds = keepAliveIntervalSeconds;
}
public int getBrokerServicePurgeInactiveFrequencyInSeconds() {
return brokerServicePurgeInactiveFrequencyInSeconds;
}
public long getZooKeeperSessionTimeoutMillis() {
return zooKeeperSessionTimeoutMillis;
}
public void setZooKeeperSessionTimeoutMillis(long zooKeeperSessionTimeoutMillis) {
this.zooKeeperSessionTimeoutMillis = zooKeeperSessionTimeoutMillis;
}
public String getReplicatorPrefix() {
return replicatorPrefix;
}
public void setReplicatorPrefix(String replicatorPrefix) {
this.replicatorPrefix = replicatorPrefix;
}
public String getLoadManagerClassName() {
return loadManagerClassName;
}
public void setLoadManagerClassName(String loadManagerClassName) {
this.loadManagerClassName = loadManagerClassName;
}
public boolean isPreferLaterVersions() {
return preferLaterVersions;
}
public void setPreferLaterVersions(boolean preferLaterVersions) {
this.preferLaterVersions = preferLaterVersions;
}
public int getWebSocketNumIoThreads() { return webSocketNumIoThreads; }
public void setWebSocketNumIoThreads(int webSocketNumIoThreads) { this.webSocketNumIoThreads = webSocketNumIoThreads; }
public int getWebSocketConnectionsPerBroker() { return webSocketConnectionsPerBroker; }
public void setWebSocketConnectionsPerBroker(int webSocketConnectionsPerBroker) { this.webSocketConnectionsPerBroker = webSocketConnectionsPerBroker; }
}
|
923557e2b88593522c986ebb33bae24b95f45b42 | 7,726 | java | Java | src/main/java/org/mtransit/android/commons/PackageManagerUtils.java | mtransitapps/commons-android | 26e2f437a99e6b4d9589b543df3642b734344918 | [
"Apache-2.0"
] | 2 | 2017-12-01T10:18:25.000Z | 2019-08-29T17:20:52.000Z | src/main/java/org/mtransit/android/commons/PackageManagerUtils.java | mtransitapps/commons-android | 26e2f437a99e6b4d9589b543df3642b734344918 | [
"Apache-2.0"
] | null | null | null | src/main/java/org/mtransit/android/commons/PackageManagerUtils.java | mtransitapps/commons-android | 26e2f437a99e6b4d9589b543df3642b734344918 | [
"Apache-2.0"
] | 2 | 2019-05-30T12:52:50.000Z | 2019-08-29T06:17:18.000Z | 34.959276 | 122 | 0.754077 | 997,260 | package org.mtransit.android.commons;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.ProviderInfo;
import android.content.pm.ResolveInfo;
import android.net.Uri;
import android.text.TextUtils;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.pm.PackageInfoCompat;
import org.mtransit.android.commons.ui.ModuleRedirectActivity;
import java.util.List;
@SuppressWarnings({"WeakerAccess", "unused"})
public final class PackageManagerUtils {
private static final String LOG_TAG = PackageManagerUtils.class.getSimpleName();
public static void removeModuleLauncherIcon(@Nullable Context context) {
removeLauncherIcon(context, ModuleRedirectActivity.class);
}
public static void removeLauncherIcon(@Nullable Context context, @NonNull Class<?> activityClass) {
try {
if (context != null && activityClass.getCanonicalName() != null) {
context.getPackageManager().setComponentEnabledSetting( //
new ComponentName(context.getPackageName(), activityClass.getCanonicalName()), //
PackageManager.COMPONENT_ENABLED_STATE_DISABLED, //
PackageManager.DONT_KILL_APP);
}
} catch (Exception e) {
MTLog.w(LOG_TAG, e, "Error while removing launcher icon!");
}
}
public static void resetModuleLauncherIcon(@Nullable Context context) {
resetLauncherIcon(context, ModuleRedirectActivity.class);
}
public static void resetLauncherIcon(@Nullable Context context, @NonNull Class<?> activityClass) {
try {
if (context != null && activityClass.getCanonicalName() != null) {
context.getPackageManager().setComponentEnabledSetting( //
new ComponentName(context.getPackageName(), activityClass.getCanonicalName()), //
PackageManager.COMPONENT_ENABLED_STATE_DEFAULT, //
PackageManager.DONT_KILL_APP);
}
} catch (Exception e) {
MTLog.w(LOG_TAG, e, "Error while adding launcher icon!");
}
}
public static void openApp(@NonNull Context context, @NonNull String pkg, @Nullable int... intentFlags) {
try {
Intent intent = context.getPackageManager().getLaunchIntentForPackage(pkg);
if (intent == null) {
throw new PackageManager.NameNotFoundException();
}
intent.addCategory(Intent.CATEGORY_LAUNCHER);
if (intentFlags != null) {
for (int intentFlag : intentFlags) {
intent.addFlags(intentFlag);
}
}
context.startActivity(intent);
} catch (Exception e) {
MTLog.w(LOG_TAG, e, "Error while opening the application!");
}
}
// adb shell pm disable-user --user 0 org.mtransit.android...
// adb shell pm list users
// adb shell pm list packages -d
// https://developer.android.com/topic/performance/power/test-power
public static boolean isAppEnabled(@NonNull Context context, @NonNull String pkg) {
try {
int appEnabledSetting = context.getPackageManager().getApplicationEnabledSetting(pkg);
return appEnabledSetting == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
|| appEnabledSetting == PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
} catch (IllegalArgumentException e) {
return false; // app does not exist
}
}
public static int getAppEnabledState(@NonNull Context context, @NonNull String pkg) {
try {
return context.getPackageManager().getApplicationEnabledSetting(pkg);
} catch (IllegalArgumentException e) {
return -1; // app does not exist
}
}
public static boolean isAppInstalled(@NonNull Context context, @NonNull String pkg) {
try {
context.getPackageManager().getPackageInfo(pkg, PackageManager.GET_ACTIVITIES);
return true;
} catch (PackageManager.NameNotFoundException e) {
return false;
}
}
public static boolean isAppInstalledDefault(@NonNull Context context, @NonNull Intent intent) {
try {
ResolveInfo info = context.getPackageManager().resolveActivity(intent, PackageManager.MATCH_DEFAULT_ONLY);
return info != null;
} catch (Exception e) {
return false;
}
}
/**
* Requires {@link android.Manifest.permission#REQUEST_DELETE_PACKAGES}
* since {@link android.os.Build.VERSION_CODES#P}.
*/
public static void uninstall(@NonNull Activity activity, @NonNull Context context) {
uninstallApp(activity, context.getPackageName());
}
/**
* Requires {@link android.Manifest.permission#REQUEST_DELETE_PACKAGES}
* since {@link android.os.Build.VERSION_CODES#P}.
*/
public static void uninstallApp(@NonNull Activity activity, @NonNull String pkg) {
Uri uri = Uri.parse("package:" + pkg);
Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE, uri);
activity.startActivity(intent);
}
@Nullable
public static ProviderInfo[] findContentProvidersWithMetaData(@NonNull Context context, @Nullable String packageName) {
if (TextUtils.isEmpty(packageName)) {
return null;
}
List<PackageInfo> allInstalledProvidersWithMetaData = getAllInstalledProvidersWithMetaData(context.getPackageManager());
if (allInstalledProvidersWithMetaData != null) {
for (PackageInfo packageInfo : allInstalledProvidersWithMetaData) {
if (packageInfo.packageName.equals(packageName)) {
return packageInfo.providers;
}
}
}
return null;
}
@SuppressLint("QueryPermissionsNeeded")
@Nullable
private static List<PackageInfo> getAllInstalledProvidersWithMetaData(@NonNull PackageManager pm) {
try {
return pm.getInstalledPackages(PackageManager.GET_PROVIDERS | PackageManager.GET_META_DATA);
} catch (Exception e) {
MTLog.w(LOG_TAG, e, "Error while reading installed providers w/ meta-data!"); // #Android5 #Android6
return null;
}
}
@NonNull
public static CharSequence getAppName(@NonNull Context context) {
try {
ApplicationInfo appInfo = context.getPackageManager().getApplicationInfo(context.getPackageName(), 0);
return context.getPackageManager().getApplicationLabel(appInfo);
} catch (PackageManager.NameNotFoundException e) {
MTLog.w(LOG_TAG, e, "Error while looking up app name!");
return context.getString(R.string.ellipsis);
}
}
@NonNull
public static String getAppVersionName(@NonNull Context context) {
return getAppVersionName(context, context.getPackageName());
}
@NonNull
public static String getAppVersionName(@NonNull Context context, @NonNull String pkg) {
try {
return context.getPackageManager().getPackageInfo(pkg, 0).versionName;
} catch (PackageManager.NameNotFoundException e) {
MTLog.w(LOG_TAG, e, "Error while looking up '%s' version name!", pkg);
return context.getString(R.string.ellipsis);
}
}
public static int getAppVersionCode(@NonNull Context context) {
return getAppVersionCode(context, context.getPackageName());
}
public static int getAppVersionCode(@NonNull Context context, @NonNull String pkg) {
try {
return context.getPackageManager().getPackageInfo(pkg, 0).versionCode;
} catch (PackageManager.NameNotFoundException e) {
MTLog.w(LOG_TAG, e, "Error while looking up '%s' version code!", pkg);
return -1;
}
}
public static long getThisAppLongVersionCode(@NonNull Context context) {
return getAppLongVersionCode(context, context.getPackageName());
}
public static long getAppLongVersionCode(@NonNull Context context, @NonNull String pkg) {
try {
return PackageInfoCompat.getLongVersionCode(context.getPackageManager().getPackageInfo(pkg, 0));
} catch (PackageManager.NameNotFoundException e) {
MTLog.w(LOG_TAG, e, "Error while looking up '%s' long version code!", pkg);
return -1L;
}
}
private PackageManagerUtils() {
}
}
|
9235588c61fb95b4b6c0d1f7942c491a8c8299a9 | 1,829 | java | Java | src/main/java/ch/hslu/ad/sw07/DemoBlockingQueue/Producer.java | cyrillkuettel/ad | 3698ebc1ffeeec7403c472edfaad739e6f0aa801 | [
"Apache-2.0"
] | 1 | 2021-03-23T21:32:55.000Z | 2021-03-23T21:32:55.000Z | src/main/java/ch/hslu/ad/sw07/DemoBlockingQueue/Producer.java | cyrillkuettel/ad | 3698ebc1ffeeec7403c472edfaad739e6f0aa801 | [
"Apache-2.0"
] | null | null | null | src/main/java/ch/hslu/ad/sw07/DemoBlockingQueue/Producer.java | cyrillkuettel/ad | 3698ebc1ffeeec7403c472edfaad739e6f0aa801 | [
"Apache-2.0"
] | null | null | null | 28.138462 | 80 | 0.576818 | 997,261 | package ch.hslu.ad.sw07.DemoBlockingQueue;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.BlockingQueue;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
/**
* Produzent, der eine maximale Anzahl Werte produziert und diese in eine Queue
* oder in einer List speichert.
*/
public final class Producer implements Callable<Long> {
private static final Logger LOG = LogManager.getLogger(Producer.class);
private final List<Integer> list;
private final int maxRange;
private final BlockingQueue<Integer> queue;
/**
* Erzeugt einen Produzent, der eine bestimmte Anzahl Integer-Werte
* produziert.
*
* @param list Queue zum Speichern der Integer-Werte.
* @param max Anzahl Integer-Werte.
*/
public Producer(final List<Integer> list, final int max) {
this.queue = null;
this.list = list;
this.maxRange = max;
}
public Producer(final BlockingQueue<Integer> queue, final int max) {
this.list = null;
this.queue = queue;
this.maxRange = max;
}
/**
* Liefert die Summe aller zusammengezählter Integer Werte.
*
* @return Summe.
* @throws java.lang.Exception falls Ausnahmen passieren.
*/
@Override
public Long call() throws Exception { // it can handle both queue and List
long sum = 0;
if (list == null) {
for (int i = 1; i <= maxRange; i++) {
sum += i;
queue.add(i);
}
}
if (queue == null) {
for (int i = 1; i <= maxRange; i++) {
sum += i;
list.add(i);
}
}
return sum;
}
}
|
923558ab4f0f9c191184707e59f8efb560941c67 | 7,089 | java | Java | java/java-tests/testSrc/com/intellij/java/codeInsight/daemon/quickFix/StreamApiMigrationInspectionTestSuite.java | nvartolomei/intellij-community | 1aac326dadacf65d45decc25cef21f94f7b80d69 | [
"Apache-2.0"
] | 2 | 2019-04-28T07:48:50.000Z | 2020-12-11T14:18:08.000Z | java/java-tests/testSrc/com/intellij/java/codeInsight/daemon/quickFix/StreamApiMigrationInspectionTestSuite.java | nvartolomei/intellij-community | 1aac326dadacf65d45decc25cef21f94f7b80d69 | [
"Apache-2.0"
] | 2 | 2022-02-19T09:45:05.000Z | 2022-02-27T20:32:55.000Z | java/java-tests/testSrc/com/intellij/java/codeInsight/daemon/quickFix/StreamApiMigrationInspectionTestSuite.java | nvartolomei/intellij-community | 1aac326dadacf65d45decc25cef21f94f7b80d69 | [
"Apache-2.0"
] | 2 | 2020-03-15T08:57:37.000Z | 2020-04-07T04:48:14.000Z | 29.661088 | 134 | 0.757935 | 997,262 | /*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.java.codeInsight.daemon.quickFix;
import com.intellij.codeInsight.daemon.quickFix.ActionHint;
import com.intellij.codeInsight.daemon.quickFix.LightQuickFixParameterizedTestCase;
import com.intellij.codeInsight.intention.IntentionManager;
import com.intellij.codeInsight.intention.impl.config.IntentionManagerImpl;
import com.intellij.codeInspection.LocalInspectionTool;
import com.intellij.codeInspection.streamMigration.StreamApiMigrationInspection;
import com.intellij.pom.java.LanguageLevel;
import org.jetbrains.annotations.NotNull;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
@RunWith(Suite.class)
@Suite.SuiteClasses({
StreamApiMigrationInspectionTestSuite.AddAllTest.class,
StreamApiMigrationInspectionTestSuite.AfterAllActionsTest.class,
StreamApiMigrationInspectionTestSuite.AllMatchTest.class,
StreamApiMigrationInspectionTestSuite.AnyMatchTest.class,
StreamApiMigrationInspectionTestSuite.BufferedReaderTest.class,
StreamApiMigrationInspectionTestSuite.CollectTest.class,
StreamApiMigrationInspectionTestSuite.ContinueTest.class,
StreamApiMigrationInspectionTestSuite.CountTest.class,
StreamApiMigrationInspectionTestSuite.FilterTest.class,
StreamApiMigrationInspectionTestSuite.FindFirstTest.class,
StreamApiMigrationInspectionTestSuite.FlatMapFirstTest.class,
StreamApiMigrationInspectionTestSuite.ForEachTest.class,
StreamApiMigrationInspectionTestSuite.JoiningTest.class,
StreamApiMigrationInspectionTestSuite.LimitTest.class,
StreamApiMigrationInspectionTestSuite.MinMaxTest.class,
StreamApiMigrationInspectionTestSuite.NoneMatchTest.class,
StreamApiMigrationInspectionTestSuite.OtherTest.class,
StreamApiMigrationInspectionTestSuite.ReductionTest.class,
StreamApiMigrationInspectionTestSuite.SummingTest.class,
StreamApiMigrationInspectionTestSuite.Java9Test.class,
StreamApiMigrationInspectionTestSuite.Java10Test.class,
StreamApiMigrationInspectionTestSuite.Java14Test.class,
})
public class StreamApiMigrationInspectionTestSuite {
public static abstract class StreamApiMigrationInspectionBaseTest extends LightQuickFixParameterizedTestCase {
@Override
protected LocalInspectionTool @NotNull [] configureLocalInspectionTools() {
StreamApiMigrationInspection inspection = new StreamApiMigrationInspection();
inspection.SUGGEST_FOREACH = true;
return new LocalInspectionTool[]{
inspection
};
}
@Override
protected LanguageLevel getDefaultLanguageLevel() {
return LanguageLevel.JDK_1_8;
}
@Override
protected void doAction(@NotNull ActionHint actionHint, @NotNull String testFullPath, @NotNull String testName) throws Exception {
((IntentionManagerImpl)IntentionManager.getInstance())
.withDisabledIntentions(() -> super.doAction(actionHint, testFullPath, testName));
}
abstract String getFolder();
@Override
protected String getBasePath() {
return "/codeInsight/daemonCodeAnalyzer/quickFix/streamApiMigration/" + getFolder();
}
}
public static class AddAllTest extends StreamApiMigrationInspectionBaseTest {
@Override
String getFolder() {
return "addAll";
}
}
public static class AfterAllActionsTest extends StreamApiMigrationInspectionBaseTest {
@Override
String getFolder() {
return "afterAllActions";
}
}
public static class AllMatchTest extends StreamApiMigrationInspectionBaseTest {
@Override
String getFolder() {
return "allMatch";
}
}
public static class AnyMatchTest extends StreamApiMigrationInspectionBaseTest {
@Override
String getFolder() {
return "anyMatch";
}
}
public static class BufferedReaderTest extends StreamApiMigrationInspectionBaseTest {
@Override
String getFolder() {
return "bufferedReader";
}
}
public static class CollectTest extends StreamApiMigrationInspectionBaseTest {
@Override
String getFolder() {
return "collect";
}
}
public static class ContinueTest extends StreamApiMigrationInspectionBaseTest {
@Override
String getFolder() {
return "continue";
}
}
public static class CountTest extends StreamApiMigrationInspectionBaseTest {
@Override
String getFolder() {
return "count";
}
}
public static class FilterTest extends StreamApiMigrationInspectionBaseTest {
@Override
String getFolder() {
return "filter";
}
}
public static class FindFirstTest extends StreamApiMigrationInspectionBaseTest {
@Override
String getFolder() {
return "findFirst";
}
}
public static class FlatMapFirstTest extends StreamApiMigrationInspectionBaseTest {
@Override
String getFolder() {
return "flatMap";
}
}
public static class ForEachTest extends StreamApiMigrationInspectionBaseTest {
@Override
String getFolder() {
return "foreach";
}
}
public static class JoiningTest extends StreamApiMigrationInspectionBaseTest {
@Override
String getFolder() {
return "joining";
}
}
public static class LimitTest extends StreamApiMigrationInspectionBaseTest {
@Override
String getFolder() {
return "limit";
}
}
public static class MinMaxTest extends StreamApiMigrationInspectionBaseTest {
@Override
String getFolder() {
return "minMax";
}
}
public static class NoneMatchTest extends StreamApiMigrationInspectionBaseTest {
@Override
String getFolder() {
return "noneMatch";
}
}
public static class OtherTest extends StreamApiMigrationInspectionBaseTest {
@Override
String getFolder() {
return "other";
}
}
public static class ReductionTest extends StreamApiMigrationInspectionBaseTest {
@Override
String getFolder() {
return "reduce";
}
}
public static class SummingTest extends StreamApiMigrationInspectionBaseTest {
@Override
String getFolder() {
return "sum";
}
}
public static class Java9Test extends StreamApiMigrationInspectionBaseTest {
@Override
String getFolder() {
return "java9";
}
}
public static class Java10Test extends StreamApiMigrationInspectionBaseTest {
@Override
String getFolder() {
return "java10";
}
}
public static class Java14Test extends StreamApiMigrationInspectionBaseTest {
@Override
String getFolder() {
return "java14";
}
}
} |
923558ad2b4c3ed1fa919b62be19175b2242e733 | 2,446 | java | Java | src/dp/ArithmeticSlices.java | Bishwa05/Algorithms | 8f317ebc70d11a4c980b4ba86e0e42c3a270a5ea | [
"MIT"
] | 2 | 2020-02-27T13:44:33.000Z | 2020-02-27T13:44:37.000Z | src/dp/ArithmeticSlices.java | Bishwa05/Algorithms | 8f317ebc70d11a4c980b4ba86e0e42c3a270a5ea | [
"MIT"
] | null | null | null | src/dp/ArithmeticSlices.java | Bishwa05/Algorithms | 8f317ebc70d11a4c980b4ba86e0e42c3a270a5ea | [
"MIT"
] | 1 | 2019-08-01T12:45:59.000Z | 2019-08-01T12:45:59.000Z | 23.980392 | 154 | 0.428863 | 997,263 | package dp;
/**
* 413. Arithmetic Slices
* Leetcode
* An integer array is called arithmetic if it consists of at least three elements and if the difference between any two consecutive elements is the same.
* Input: nums = [1,2,3,4]
* Output: 3
* Explanation: We have 3 arithmetic slices in nums: [1, 2, 3], [2, 3, 4] and [1,2,3,4] itself.
*/
public class ArithmeticSlices
{
/**
* Brute force
*/
public int numberOfArithmeticSlicesBF (int[] A)
{
int count = 0;
for (int s = 0; s < A.length - 2; s++) {
int d = A[s + 1] - A[s];
for (int e = s + 2; e < A.length; e++) {
if (A[e] - A[e - 1] == d)
count++;
else
break;
}
}
return count;
}
/**
* Recursive approach.
* time complexity O(n).
*/
public int numberOfArithmeticSlicesRec (int[] arr)
{
int[] sum = new int[1];
slices(arr, arr.length - 1, sum);
return sum[0];
}
public int slices (int[] arr, int n, int[] sum)
{
if (n < 2) {
return 0;
}
int ap = 0;
if (arr[n] - arr[n - 1] == arr[n - 1] - arr[n - 2]) {
ap = 1 + slices(arr, n - 1, sum);
sum[0] = sum[0] + ap;
}
else {
slices(arr, n - 1, sum);
}
return ap;
}
public int numberOfArithmeticSlices (int[] A)
{
int startSlice = 0;
int total = 0;
for (int i = 2; i < A.length; i++) {
if (A[i] - A[i - 1] == A[i - 1] - A[i - 2]) {
total += 1 + i - 3 - startSlice + 1;
}
else {
startSlice = i - 1;
}
}
return total;
}
public int numberOfArithmeticSlicesSimple (int[] a)
{
int len = a.length;
int dp[] = new int[len];
int sum = 0;
if (a.length < 3) {
return 0;
}
for (int i = 2; i < len; i++) {
if (a[i] - a[i - 1] == a[i - 1] - a[i - 2]) {
dp[i] = dp[i - 1] + 1;
sum += dp[i];
}
}
return sum;
}
public static void main (String arg[])
{
int arr[] = { 1, 2, 3, 8, 9, 10 };
ArithmeticSlices a = new ArithmeticSlices();
System.out.println(a.numberOfArithmeticSlicesRec(arr));
}
}
|
923558bc540fa7b3534bbf910d6454c74de808aa | 18,468 | java | Java | output/f3a82fed3b8f4e9a9229ade696a9e804.java | comprakt/comprakt-fuzz-tests | c0082d105d7c54ad31ab4ea461c3b8319358eaaa | [
"Apache-2.0",
"MIT"
] | null | null | null | output/f3a82fed3b8f4e9a9229ade696a9e804.java | comprakt/comprakt-fuzz-tests | c0082d105d7c54ad31ab4ea461c3b8319358eaaa | [
"Apache-2.0",
"MIT"
] | null | null | null | output/f3a82fed3b8f4e9a9229ade696a9e804.java | comprakt/comprakt-fuzz-tests | c0082d105d7c54ad31ab4ea461c3b8319358eaaa | [
"Apache-2.0",
"MIT"
] | null | null | null | 38.635983 | 365 | 0.487546 | 997,264 | class ehw7G4q {
public boolean ZTcGUSiRMi;
public boolean DUrNdsNfw () throws CrZac26dM_J {
;
{
{
if ( --hZy68txt()[ new boolean[ true.ts6()].X__MY]) if ( lEXoThJi.ZRsxF5d7GLJm2W()) if ( null.vzbufsNKR) if ( !new LV().U()) return;
}
;
if ( true[ new boolean[ -!null.Vn1PB0N()][ null.v8mygX]]) ;
}
boolean[][][] lceG1lxK = t2CLFzfb()[ --null.fH()] = true.vwcF4ANNxO;
if ( true.C9Lipj0fO9BrO) if ( 0964.eRCFI3rvh1VU()) if ( !new boolean[ !this[ !-!-( this.RFAhvyRwp)[ true.dfz2iby0e15]]][ -( sBkJF().S5PAKqYL8tCL())[ ( ( !null.Svbza9MC8NZqd).Z_jJz_YzEoCaaB())[ zqG6N3B_8BE7v.rn2]]]) if ( -new Uhdf8GkGN().Fli) while ( Dyc8p2hbuXR9ke().SbTE3()) -true.kQJ;
while ( -new boolean[ !new XCB5IC().xDRo6][ null[ -!false[ !-35.COtjG_]]]) if ( zi8_KcpTB._tlYaT()) {
void s_U;
}
}
public static void J7vF_VgaXu8kNS (String[] zLhSQC) {
while ( !true.suvwCGvm6zRf()) {
boolean[] QebhZ8zWT;
}
;
return !( true[ !false[ -new void[ !!--!!-!9446130.SCLlpi7_U()].XSovDTP5__O]]).GYuOoYwDsWP;
void x8gB = -null.U49W5n() = RyR6lZe().Maglud;
{
qc3zAsb_fCe18f[][] CNc84sr0Z_p;
return;
void yoy;
;
;
}
ElJ3fmnNu.u6yffbuH9();
{
void[] bTI05FRkRTKqi;
;
if ( -new int[ r6SWQiV.XGuuS_m()].s583D()) -AsyGPqV1Z().vffWyeIs;
while ( --!new void[ KXpYXWcspoCUB9().Dl()][ this.TdG]) e3t[ ( new void[ JAq5phHY1HsIX.Jp3][ !this.kYVm89OR5jPFb()]).YTDTnErJIRls];
int zKAM7oHTXHt;
;
;
;
int mRoPAz9S7;
VCty5[] vewdYSK8od;
return;
boolean oNsh9Qxi;
if ( new PAK7XWaqnr11Z().EpAtkVh) ;
;
int[][][][] OkA;
;
void j;
if ( !this[ !!false.BuFcv()]) ;
boolean[][] vBg6qs5G;
}
B[] L_1h1fNq9jrg8P;
return this.jDzk;
{
void[] Of0FTuA48;
while ( true[ this.A5CV2F2tHs]) if ( !false[ !!this.q5r]) ;
;
iH5j V;
return;
!!!false.yGS20u0b4B;
if ( -Spf().CWlmYuLF()) if ( !new _W()[ ( !true.tEGK7Y56LD4S()).SzoXTcF7bRuE]) ;
{
while ( !3803536.G()) while ( !746301[ new boolean[ !!( false[ !( -!!dzm_p4K6g9wr()[ !false.mvo3GLXfcYXSO])[ !409545.n3Leusz]]).yjc()].UOBe()]) return;
}
boolean[] RC_K9sC6;
C6 csn;
while ( !!-new int[ !-!new LWU_pr1ihn()[ !-TpDQF[ A8F()[ ( new void[ -CAXw6Zk3B.z0AEtOQ7MYMC()].UvZh())[ -!Im_TzFDSoY.wOq()]]]]][ true[ !y.yka()]]) if ( -( null[ gPIt9IUfl8mw4F[ p[ !new int[ this.Qmmf_YpquVD()][ eSYuFfLXmY[ new boolean[ !null[ ZX7KIrIjeHSJS.LRUnL6Z]].K()]]]]]).JDTgitlu_d()) while ( null.gIS4l2xbPLX8kL) if ( !wcrPtSWx.D3u4vDXS) return;
{
void[][] sPGFEnjtbG;
}
{
if ( -true.hP6Sz) while ( -!----!!this[ this.BVG()]) ;
}
while ( new int[ nBc6n()[ --JN_v96qM0pX2().yO8dpVpzo()]].pbfg6QVzjw()) while ( !!!-( !( -( -!-!!-1.OzO).UIuP()).h4).MFIGxHtI4()) while ( false[ !-bGmwTHm.GAg92VZWIOJWga]) while ( !!new m9DaXLUvB().HX) {
if ( new VD()[ -this.tPBpfc]) if ( YChGap45THs.NuFdSb2kXgb) return;
}
}
new ZLc6j8FWJSa().sEyPCqbc4Z2();
boolean mUexwp;
;
XzWtSFndAFo[][] EoDR_l = this.wiSV4EB9Ojae() = ---XSkM.RRy1Yr1MJig7();
boolean[][] N2 = -this[ -this.ScymmnekyNu()] = null[ this[ ( true.VfyNyfxHpu())[ BAgGZxn5d.sI9rlhzu1aDInr()]]];
boolean[] WOSEi8_BCGZJxB = 840995551.KCZxHx;
return;
}
public boolean aKrm3O87V;
public int[] dwE;
public int[][][][] kn1x9HyQCi0g;
public static void FdLRb79r (String[] n) throws N7h8vt1PCq1Oe {
;
while ( !( false.NrS).dHVf()) ;
}
public void n;
}
class GeIv {
public static void k1l9XT (String[] IG0) {
Q7fwf kp5CImAE2pG79T;
void[] JoxY83lFWIZ;
boolean Ay7cRlEDXr_s2;
;
{
void htVNK;
}
while ( --!!false.S3IeCby_TlK8j()) while ( -!-89885788.QE) {
void[] pltN2sn;
}
boolean[][][] CmKOL9Y6hzA4e = this.q() = false[ tHoFhL[ !true.a]];
KlZMxV mcAqfTIlvuWk = false.JwW3E;
( OmCI4UkyOq0().Blrl1yls())[ !-false[ v9awvIp6z[ !( this.Y4ICnVl47OEw).T1]]];
return;
boolean EhO = false[ true._];
!null.GVpoLOw3cVp;
boolean[] Q8_7DYFZ;
int[] SOka;
boolean[] N2lMo = this.uv0s() = !bB()[ -!new a2nlpdZ().lfGfa7G];
}
public static void kMfdVIwi_2Pv5 (String[] kESGfGbXD) {
;
void[] Lnbb;
zb[][][][] YFOG9V;
int OT8g = false.VVBk0f() = !new RziYCIAa[ c4qXCte5.PJ2bRun()].l2Nb;
}
public static void GrBY49SH (String[] XQoeYhieW) {
while ( -new boolean[ 83.ODdkZeZs].YYribbH) {
while ( -!yfsWh4KXgS1_Db().Z()) {
int[][][] A5J2uo1tkM;
}
}
if ( false[ V1V_jS()[ !-!!v[ !new qd85F4().nA_AO4Dfgu]]]) ;else {
int[] c;
}
!this.JIsn3();
mow9C8[] LteVu4qo;
}
public void r;
public static void HTCFW (String[] imq3sCCZudTT1c) throws LsQrskAt {
{
int[][] JT4xAUS;
jiyW3 WLfouOsK;
-this[ !this.L4tUnuNmAtL];
boolean Akf06m;
_Y7Fa5J[] fBtMF;
int qzwT8q;
return;
!--OayCXdcSr3i9E.UXxyJrjkW;
}
while ( -!!!!new int[ !this.i_h0x].XtR0E784j6Sa()) !null.wSYGOK8Wea2H9v();
enefz().vUC();
boolean DL47Z = !new ksUG0Dj4()[ null.FgZva7r4uyvSuL] = ( !-!!( --null.D84dbX_0xi0dS())[ -!239749967.mep8bbY4ycI7R()]).y8YDd2QmhN3();
{
return;
boolean DO;
jqfUr2qA0lH[] nL9v5CtL2iyf;
if ( false.KzHv()) return;
TvYkHt1Sh R;
hI4EoXjMsL[] vksU5rwr3GK0q;
while ( new void[ 4.k].iM6PjhF9A()) {
{
return;
}
}
while ( new f7WBni[ this.QSr][ !H().RK9PfGDU]) ;
while ( M1.vyMzaT9D()) false.yvYbQz9FA8();
;
void[] uw85UI3v;
int[][][][][] E;
}
Mee5BwGKoOza70 lw3sseKVaSqPh = -4.qIM1;
;
boolean s3NMZF6dNp2;
;
while ( -false.IK4FkOO_wPBZJ()) while ( !this[ !!!-new pOrclMgbWz()[ -zjoKzx0[ Wq4TFWUzlRJN[ -fJnupqyYz[ -null.WfJyxnF]]]]]) while ( -!true[ -true.ksMNCmhbx0Z()]) {
void g;
}
if ( tPj4_d8BEE_gb1().d4BzzI1dF3oU9q) return;
void[][][] lYKt_zeMEwR;
}
public int[] YQD;
public void W6lc (int QLR_49UiCn3keX, int YmGaPtxb, w9Vnfk9MrF DgMEeQY7MkfMlv, int xYyo9pj7) throws ZfZ {
if ( ---!!null.Knj2xdtdX()) {
while ( new boolean[ new int[ new iMxDMmWYMdg().JUO8MkIpieb()].RNKxygXSzU2W()][ -false.rfvhLEBMtJE6()]) ;
}else return;
;
if ( new DYFqzDIhVx().HsUk_l88uhb()) return;else while ( aN6aU().epHS()) while ( true.o9n) ;
atYh7fXW0[] A1z;
{
while ( -!null.mbZQ) {
boolean LU;
}
while ( false.dyU()) if ( ( !zX5fqL().eJDg())[ !-( -!true[ null[ -null.ZAHw]]).Kr()]) {
if ( -new int[ -!5880.eF7eYC6G6qgpO()].takXB5wohYsaf_) while ( new dTz4thDpZM3()[ new KfOiDB6U1Bg8gE().P9i4y26bwqfg]) ;
}
return;
int[][] gxVd1ZfgM;
;
return;
boolean eq93UTg;
boolean[] eIGLA2yfEUmAdA;
{
while ( null[ -( !--new gvTRejL5P0b862()[ new anFv2khn5().Rc7]).Hpoldz8yi()]) return;
}
while ( -!null.QKGcpLD6NNbx()) while ( 43533873.yzE7LOLyHF()) while ( ( this.M).a) Ng3oTHZ5r7C()[ new V().mtomp()];
boolean l8b8sDZ1;
if ( !Z4U0KfQAiYQkUK.bBCc3bsXRTjnA()) if ( this.vRRQw) while ( new lIoP().dtSU()) {
if ( !this[ ( 668138.EDs2r()).Q6WZuauFdA1Li5()]) return;
}
}
void[][] fGCi = -!!!( !!!nQotvzi1Ez()[ -!!null.WfjfKprVQvvB2h]).GdFxrYSsYZ = new boolean[ -!false.hWy7Sj4wJALJ].Khkc4F61i();
SLUOjRztN1Q[][] j3HQFxVon3U = null[ f6xk7Dxlf()[ -73[ --new t29()._iB3O1_ZSRnE]]];
if ( -false.mC0UqtB3Q7Qu) {
int mNdmu;
}
}
public void _HCX2Hgakq_P2G;
public static void pFG0J (String[] S7KQQ) {
void rxuMJx;
int A5cEEUNXTD = new h1NQkRRIm6T().cHX;
int[] Kk0wbTuByZE;
void hFu9zWs1 = !-null.ThUkM();
int[] ufA0bT4t9abOD7 = KPI().ZzU3guAkYQYdBo() = -( !!y4wqpOx5[ ----!new boolean[ --!--HS.RO68sD()][ -M_bAnW1Fk_aF[ DHfNixVjOnGUWo().ZWPPp()]]]).LIdB55Ld();
int[] hhAb;
{
boolean b;
boolean[] mEKOcv;
( !null.t0Ub1lkOgk6)[ null[ true.knICaAUC1x()]];
{
WHR[] Et;
}
{
boolean NFQmYrvLVXt0e;
}
int hLQ1nca;
new SUgrTU().sWEhnOiiveot();
while ( this.J5k8gnljE0HD()) return;
boolean[][][] apwdi4iKKHE;
while ( !-null.zY()) ;
int[][] _vHX7MwZ8b4it1;
T7CCGjgOW JZ9uu;
boolean[] U;
int A7U;
return;
void[][] rWOdEmmc5;
pWk3zK iilHscz;
w[] YAEoFQOGz;
{
{
while ( this.ksHTnvxD6N0X()) {
boolean FE;
}
}
}
int cEwEOn4WSLtidU;
}
-new boolean[ --c_1k()[ -044.OtfNihXNxOw2()]].wLz_TbV7CIUPWc();
;
if ( this.eXSn()) return;
{
int[] SJ1La;
while ( !H2UM()[ ( ( !-!this.X1V4uMGtVzgN)[ -ldCKTKb().x68()])[ new s().rGlPH0OQPrBy2()]]) {
void[] QCNk192;
}
while ( !false[ -!!mUy().dm]) while ( new int[ !awSlalMn9vRB().PUELVm4e].Arndjh8F()) false[ bKLCQdIYh2V7h.D7ew06d];
int Qno8j3;
void[] M7;
false[ --new m().VkW8K4e6()];
{
int[] Y_d3VuSt;
}
while ( !WG0DRAwh.Q()) {
;
}
}
return;
}
public nrZjGqay[][] falTh;
public static void U5g (String[] Z4f3ZrDx735) throws Wm {
{
return;
{
boolean[][] _;
}
int[][][][][][] iZIjriHRapofZ;
if ( -!!-new _xgXvk8L[ !-!false[ 274384010.vET24aK7ATFP]][ !-777557059.GhtQJu()]) while ( !new yd().zkGsU5arP8j()) return;
G457M5[][] vXtJ9Q2wbwS;
int[][][] Pr;
;
wuZx yCiTrq;
int[][] YoHI3Tg;
false.jDV2;
JlRqRqat5cJN[][][] oo;
void[] PDYg;
yhOQi[][] ACPDGkj;
ud2E1R[][] lxfCDKWUS;
return;
w nkrb6tS;
UEe7vV j;
if ( !-!BlOCqCH4ch().wCSL2Iusxsn()) 3.rNV5Tm66ovpH();
}
int[][][][][] oOxkFw = !true.K8h3QXGSz() = -( this.NeBfNX9wk8f())[ -!!!!l.f3o6sVl05St];
int q5Oz;
emvBA1jkIYCE eK = --true.UPHv2D13BLq = --( -!--sw1Z2btXUU()[ u806UMVXCsV6zv[ -new PY6e().l3gS]]).f3Qv6xr4n;
void[][][][] cBX;
return null[ !!true.WHgAJac];
int L3 = -this.pNf5Cs();
{
return;
W77 ZEPOVI2;
int[][][][][][][] yoQIisMaRCn;
boolean[][][][][] HnZfhq;
if ( gkhtkwZj.iTphHvhd) ;
Ob7ggITfb_Osl[][][] EgKiUwNT;
;
{
int D6S;
}
boolean qWnMWRTK;
void[][] a;
;
boolean[][] NN8ZTD1oDo;
}
kNGg8[] NmCJRIdOre2;
int[] pILd = new boolean[ --null.SJWk].g0KSS;
boolean[] fLULkNDF5 = ( !true.ZVQ2TcklE)[ !new m8().Ot3REVWjRcl3BY()] = BnDg.b0PEW84o;
boolean[][][] Fe = false[ !true.Jrzur_bVl_Zx] = 22.K0;
;
void X0OdlGLXzpLC = null.o_HWDUp6_BFT;
{
{
return;
}
int[][][] Y1;
USgSFnQ[] cdHRBR;
while ( this[ !-0[ null[ null[ -F1XbpYbplf6xx2.SvrlqRlTK]]]]) ;
return;
;
while ( -new Lcvpwjc4tBx()[ false.SFjdeQWLrM]) ;
void[][][][][] FqCDENQ;
{
int GSDC;
}
int CGYqZhkS1k1;
void[] fqrm7n1rKfyFu;
while ( -!xJMss7Y()[ XSU()[ !-!false.nRlLkSm()]]) return;
return;
}
boolean pwkMxeSH1AK = false[ 6319[ !!!null.O5gv]];
boolean JR = -null[ -!-!0029.DsQXoOyW3t2()];
;
{
oplXiPe6[] hOOj5WS27;
-!!new void[ E.DE7JL4].qMf1s3();
boolean[][] tOVslTS;
return;
int[] l5YuxbZnGnBl;
return;
int[][][][][] JR;
new int[ !-true[ this[ false[ ( !null.KKqGOaX8V6g)[ new boolean[ null.v4p7DOIG()][ --!true.hqc()]]]]]].qPa5k();
return;
--new G5u9iuqDuv5Ki()[ this[ !_oqChpBhOCTNf.fGJXT3hM()]];
-new void[ false.Gln0LG0t3bolTk()].BGDZHb7();
while ( false.hsBj()) ;
!new YErGHy6[ 4152275[ !-!!!!--!--Lczp7anb.pxQaZO]][ !true.W_zZ4C_vAim()];
return;
if ( true[ -!!false[ !!---!-!-!false[ -!q89g4I.MsWi]]]) if ( null.ixbcffg()) while ( null.vfhjH) !null.alKRdFRz0Bfz();
void C8ABhXO;
}
}
public boolean GC8dJI;
public boolean[] sLhPvsjlomVeyc (void crasc, boolean bpHQ, a0o7Q[][] l, boolean bkqo, void B, boolean j24EZrvi4ghje) {
int xiJAVT = !825127[ new n1o5h6TCEtTVft().azApAwvu135c1];
ttmQvvvxr DxXek8V = -!---new void[ u()[ !!new gAZafdNevcY71W[ true.yeGwlcT()].XsYvIipm()]].fK5rpvK9K = i_2().wNSh();
SMNNbiDXM2F.L6W_fK1soqk();
new VYxpS().jAx();
void ctyDhy2;
while ( !-7651[ new kAEAP_I7B().pHl0]) ;
Sj[][][][] eGoG6C9jZ_RmQ = !-873823.jN();
void WvNvIryagCP;
int MqxprsJdJI;
while ( true.wlAvc_) !-this[ !true[ new boolean[ ---5290.WeP].zYozgbCdyE0YFi()]];
void[] LZpY7S = true[ ---!-new EpF[ !-!!-( -!new _kbl()[ null[ ( 18.sP())[ q.tyoPy3F()]]]).hZFQIUhJ].MuLB] = -5625761.Xw;
}
public int ucyYC0nE (void lnnJEGurMSR, void RoL) {
while ( 47.Pjo) return;
}
public vYcxjWAz m9krLoHb;
}
class hPBtFy9AJ6cC {
public boolean[][][][] uH_ () {
boolean[][] K3B7YecL = !-new BnI[ k74()[ -!this[ 88.XpW0YE()]]].s0HHwygPY() = false.ufyD9nGACH3Tli();
boolean dPP2 = !lI9aynNOc().Lv4jcB1t3d = c[ new SuBQ34SsJMFkXa()[ this.eka09u5c]];
Il3Ghls4_7[] Ia4KL5hJa;
while ( !!true.T) mfm9xMFDG().K0OUvAGP;
void TaT9ovkFIS = false.M7pq9;
P3BFT[][][] W8LKV_zI = USOroT()[ -jR5Gc().YIF8s6QXaS];
int[] mfcT6aR6ya;
;
{
void[][] Jr_5i4IM2u43;
boolean[][] YG5nFZv;
H6h32qJp9n[][][] KcELFb8r;
}
OWwA[][] qx7flDZl7tk8EG = -!3429518.WJdIVAf0mUn() = null.qXcQ6yhToKIGa();
ac1PwaLWgyea7[][][] zXf_2VK_fC54_A;
boolean[] dmr54HQ6rw = 4.kB8LS0;
void[] qQbACcUsG9iRgz;
int skqJ;
if ( !-!this.Q) ;
OvbNpxm[][] IxGyW = NrmYes.aZ = muSdWjPS()[ this.OK9siR];
;
{
;
{
boolean[] ljcvhcKgeA;
}
if ( new void[ !-!-2.grZYf].eFbi6D) -new ZPNjKOml()[ --this.J9BiO1];
return;
int[][][][][][] Gvi6tfPlhuj;
null.I9eQH3NbAwBx;
!DahK().FfRBiM;
boolean NeHfgefKKeoua;
while ( this.jMuC()) n()[ new void[ null.dRJGfjrv2()].y1y5];
return;
if ( -true[ new boolean[ !( !null._P5me5az).w0h55B5ukNsx1i()][ new sr().s()]]) while ( !this.SmmEDd5) return;
if ( v3ruVl().LJL10rtLVBTJ) if ( 01900.Nu5J68yFN()) return;
mdLrm e;
{
N37[] U2BMDFHqWgfSEC;
}
while ( !cukX4fB4S5RMF().KQkG) return;
return;
while ( -( -!k5cdiHa()[ -null.O7NfbP()])[ false[ ---!-true[ !!IlQFlfp.y5JXKG102()]]]) while ( ( !!false.Klx1LCWVAu).xj) -738807343.QVaVNnNpGqA3X();
}
int[] JQol;
}
public boolean[] BOW2ANDVr;
public boolean _jSGhifdlqoJ () {
int D5ph3Ufs3x3OK6;
if ( false.UaJsoIGDk) {
if ( 9655.IAzsBm3lLGuy1Y) return;
}
}
}
class QAUklN {
public void[] GzJmJsjZqx1;
public CGsZX y;
public int[][][] UxJVhOR_j4wzt1;
public static void yxJo1t (String[] EWQktx4YJcn) {
;
int jtkM7vi0;
int vS_XYDL = -582893.Iemv_ws2e;
qiKja[][] nKinB;
int[] y4T2QxLY40x = true.meIjeMsv1t;
boolean YLuGJfwN79 = !new p().DDPGX9HoC() = !( new int[ new SdYT0().b6fExgL2kMhTK()].QgN9IOlvEG426I).jD_A3();
while ( !true.AJo5b54()) this[ !( ( new RxFQF56X4gW()[ E_ikt9.fp4S]).XWFLTScRok())[ !gPU().SXw]];
if ( PAS.jSHtw) FQMhZtsX4gDl().HofpptW();else while ( ---!!new FDowcur5liGu().vsb0xo()) if ( !-!-!!-!!false[ XpRRVsWjXr[ true.sYmub12()]]) while ( !50.oe) if ( ULOqO4i().XbPzk68prN) new T8XQaOVCwS().DrK6Ak8MHr3Y0();
void[][][] Hxgh_m = ( !563037088.K_mtfdb1l22UD)[ -( -false[ !-!!!null.d_XhFi()]).xqHFS_yfD6jd()] = ( new int[ !!--!bLIAdKAQDROW().GDcQ2Kape9XeVR()].SRUZ5i272aplTM()).H();
new int[ this[ new iktpQV().MB0wzTpi()]].p8uQ0Fz();
this.Z2dQv();
while ( !95595583.m()) true.JASQ7daliHg;
sLpUdCWgX[][][] awVeUtH;
if ( !false.bfRp) return;else {
int yfpgG2AUpDT;
}
!-new mvfo_o_Rui()[ -!!!-!false.xpRA5];
( !!( Y9O3AOLJhUOnWu[ -false.kaYrzShWmY3qV])._h()).sv87Rz7uK();
int Az6ZfR = 16[ --new mBYxX[ !-!!!new boolean[ --new boolean[ new j6nq4eWnXBx[ --!!!-!-!!-new ieQ3qjMAa5().PtP_GJ2G_()].n3E1hZq()].YP][ null[ !true.B()]]][ !--this.oeA7zA7AOxlQ()]];
}
}
class NvL {
}
|
92355a034fca83412e9332f7a24f8f0625ba56e6 | 637 | java | Java | projects/bank/account/src/main/java/com/redhat/developers/account/view/AccountNumberJsonDeserializer.java | brian-avery/eda-tutorial | 88c7b8e503355a2876a337b91a3b599cd4367583 | [
"Apache-2.0"
] | 49 | 2018-10-31T16:12:37.000Z | 2021-09-01T14:31:29.000Z | projects/bank/account/src/main/java/com/redhat/developers/account/view/AccountNumberJsonDeserializer.java | brian-avery/eda-tutorial | 88c7b8e503355a2876a337b91a3b599cd4367583 | [
"Apache-2.0"
] | null | null | null | projects/bank/account/src/main/java/com/redhat/developers/account/view/AccountNumberJsonDeserializer.java | brian-avery/eda-tutorial | 88c7b8e503355a2876a337b91a3b599cd4367583 | [
"Apache-2.0"
] | 19 | 2018-10-30T20:09:54.000Z | 2021-06-22T06:46:27.000Z | 33.526316 | 127 | 0.814757 | 997,265 | package com.redhat.developers.account.view;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.redhat.developers.account.model.AccountNumber;
import java.io.IOException;
public class AccountNumberJsonDeserializer extends JsonDeserializer<AccountNumber> {
@Override
public AccountNumber deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException {
Integer value = jsonParser.readValueAs(Integer.class);
return AccountNumber.of(value);
}
}
|
92355a07a155bdf38449a7679a471cafaa1c7060 | 11,751 | java | Java | modules/core/src/main/java/org/apache/ignite/internal/jdbc/thin/ConnectionProperties.java | go-barbarians/badh-ignite | 37cad4757d372020473ac4fdb01c5e62a855f773 | [
"CC0-1.0"
] | 2 | 2021-11-09T12:22:10.000Z | 2022-01-18T00:12:23.000Z | modules/core/src/main/java/org/apache/ignite/internal/jdbc/thin/ConnectionProperties.java | go-barbarians/badh-ignite | 37cad4757d372020473ac4fdb01c5e62a855f773 | [
"CC0-1.0"
] | 6 | 2021-05-18T20:53:44.000Z | 2022-02-01T01:07:58.000Z | modules/core/src/main/java/org/apache/ignite/internal/jdbc/thin/ConnectionProperties.java | go-barbarians/badh-ignite | 37cad4757d372020473ac4fdb01c5e62a855f773 | [
"CC0-1.0"
] | 1 | 2018-07-27T20:42:14.000Z | 2018-07-27T20:42:14.000Z | 30.443005 | 118 | 0.65637 | 997,266 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.ignite.internal.jdbc.thin;
import java.sql.SQLException;
import org.apache.ignite.internal.util.HostAndPortRange;
/**
* Provide access and manipulations with connection JDBC properties.
*/
public interface ConnectionProperties {
/** SSL mode: DISABLE. */
public static final String SSL_MODE_DISABLE = "disable";
/** SSL mode: REQUIRE. */
public static final String SSL_MODE_REQUIRE = "require";
/**
* @return Schema name of the connection.
*/
public String getSchema();
/**
* @param schema Schema name of the connection.
*/
public void setSchema(String schema);
/**
* @return The URL of the connection.
*/
public String getUrl();
/**
* @param url The URL of the connection.
* @throws SQLException On invalid URL.
*/
public void setUrl(String url) throws SQLException;
/**
* @return Ignite nodes addresses.
*/
public HostAndPortRange[] getAddresses();
/**
* @param addrs Ignite nodes addresses.
*/
public void setAddresses(HostAndPortRange[] addrs);
/**
* @return Distributed joins flag.
*/
public boolean isDistributedJoins();
/**
* @param distributedJoins Distributed joins flag.
*/
public void setDistributedJoins(boolean distributedJoins);
/**
* @return Enforce join order flag.
*/
public boolean isEnforceJoinOrder();
/**
* @param enforceJoinOrder Enforce join order flag.
*/
public void setEnforceJoinOrder(boolean enforceJoinOrder);
/**
* @return Collocated flag.
*/
public boolean isCollocated();
/**
* @param collocated Collocated flag.
*/
public void setCollocated(boolean collocated);
/**
* @return Replicated only flag.
*/
public boolean isReplicatedOnly();
/**
* @param replicatedOnly Replicated only flag.
*/
public void setReplicatedOnly(boolean replicatedOnly);
/**
* @return Auto close server cursors flag.
*/
public boolean isAutoCloseServerCursor();
/**
* @param autoCloseServerCursor Auto close server cursors flag.
*/
public void setAutoCloseServerCursor(boolean autoCloseServerCursor);
/**
* @return Socket send buffer size.
*/
public int getSocketSendBuffer();
/**
* @param size Socket send buffer size.
* @throws SQLException On error.
*/
public void setSocketSendBuffer(int size) throws SQLException;
/**
* @return Socket receive buffer size.
*/
public int getSocketReceiveBuffer();
/**
* @param size Socket receive buffer size.
* @throws SQLException On error.
*/
public void setSocketReceiveBuffer(int size) throws SQLException;
/**
* @return TCP no delay flag.
*/
public boolean isTcpNoDelay();
/**
* @param tcpNoDelay TCP no delay flag.
*/
public void setTcpNoDelay(boolean tcpNoDelay);
/**
* @return Lazy query execution flag.
*/
public boolean isLazy();
/**
* @param lazy Lazy query execution flag.
*/
public void setLazy(boolean lazy);
/**
* @return Skip reducer on update flag.
*/
public boolean isSkipReducerOnUpdate();
/**
* @param skipReducerOnUpdate Skip reducer on update flag.
*/
public void setSkipReducerOnUpdate(boolean skipReducerOnUpdate);
/**
* Gets SSL connection mode.
*
* @return Use SSL flag.
* @see #setSslMode(String).
*/
public String getSslMode();
/**
* Use SSL connection to Ignite node. In case set to {@code "require"} SSL context must be configured.
* {@link #setSslClientCertificateKeyStoreUrl} property and related properties must be set up
* or JSSE properties must be set up (see {@code javax.net.ssl.keyStore} and other {@code javax.net.ssl.*}
* properties)
*
* In case set to {@code "disable"} plain connection is used.
* Available modes: {@code "disable", "require"}. Default value is {@code "disable"}
*
* @param mode SSL mode.
*/
public void setSslMode(String mode);
/**
* Gets protocol for secure transport.
*
* @return SSL protocol name.
*/
public String getSslProtocol();
/**
* Sets protocol for secure transport. If not specified, TLS protocol will be used.
* Protocols implementations supplied by JSEE: SSLv3 (SSL), TLSv1 (TLS), TLSv1.1, TLSv1.2
*
* <p>See more at JSSE Reference Guide.
*
* @param sslProtocol SSL protocol name.
*/
public void setSslProtocol(String sslProtocol);
/**
* Gets algorithm that will be used to create a key manager.
*
* @return Key manager algorithm.
*/
public String getSslKeyAlgorithm();
/**
* Sets key manager algorithm that will be used to create a key manager. Notice that in most cased default value
* suites well, however, on Android platform this value need to be set to <tt>X509<tt/>.
* Algorithms implementations supplied by JSEE: PKIX (X509 or SunPKIX), SunX509
*
* <p>See more at JSSE Reference Guide.
*
* @param keyAlgorithm Key algorithm name.
*/
public void setSslKeyAlgorithm(String keyAlgorithm);
/**
* Gets the key store URL.
*
* @return Client certificate KeyStore URL.
*/
public String getSslClientCertificateKeyStoreUrl();
/**
* Sets path to the key store file. This is a mandatory parameter since
* ssl context could not be initialized without key manager.
*
* In case {@link #getSslMode()} is {@code required} and key store URL isn't specified by Ignite properties
* (e.g. at JDBC URL) the JSSE property {@code javax.net.ssl.keyStore} will be used.
*
* @param url Client certificate KeyStore URL.
*/
public void setSslClientCertificateKeyStoreUrl(String url);
/**
* Gets key store password.
*
* @return Client certificate KeyStore password.
*/
public String getSslClientCertificateKeyStorePassword();
/**
* Sets key store password.
*
* In case {@link #getSslMode()} is {@code required} and key store password isn't specified by Ignite properties
* (e.g. at JDBC URL) the JSSE property {@code javax.net.ssl.keyStorePassword} will be used.
*
* @param passwd Client certificate KeyStore password.
*/
public void setSslClientCertificateKeyStorePassword(String passwd);
/**
* Gets key store type used for context creation.
*
* @return Client certificate KeyStore type.
*/
public String getSslClientCertificateKeyStoreType();
/**
* Sets key store type used in context initialization.
*
* In case {@link #getSslMode()} is {@code required} and key store type isn't specified by Ignite properties
* (e.g. at JDBC URL)the JSSE property {@code javax.net.ssl.keyStoreType} will be used.
* In case both Ignite properties and JSSE properties are not set the default 'JKS' type is used.
*
* <p>See more at JSSE Reference Guide.
*
* @param ksType Client certificate KeyStore type.
*/
public void setSslClientCertificateKeyStoreType(String ksType);
/**
* Gets the trust store URL.
*
* @return Trusted certificate KeyStore URL.
*/
public String getSslTrustCertificateKeyStoreUrl();
/**
* Sets path to the trust store file. This is an optional parameter,
* however one of the {@code setSslTrustCertificateKeyStoreUrl(String)}, {@link #setSslTrustAll(boolean)}
* properties must be set.
*
* In case {@link #getSslMode()} is {@code required} and trust store URL isn't specified by Ignite properties
* (e.g. at JDBC URL) the JSSE property {@code javax.net.ssl.trustStore} will be used.
*
* @param url Trusted certificate KeyStore URL.
*/
public void setSslTrustCertificateKeyStoreUrl(String url);
/**
* Gets trust store password.
*
* @return Trusted certificate KeyStore password.
*/
public String getSslTrustCertificateKeyStorePassword();
/**
* Sets trust store password.
*
* In case {@link #getSslMode()} is {@code required} and trust store password isn't specified by Ignite properties
* (e.g. at JDBC URL) the JSSE property {@code javax.net.ssl.trustStorePassword} will be used.
*
* @param passwd Trusted certificate KeyStore password.
*/
public void setSslTrustCertificateKeyStorePassword(String passwd);
/**
* Gets trust store type.
*
* @return Trusted certificate KeyStore type.
*/
public String getSslTrustCertificateKeyStoreType();
/**
* Sets trust store type.
*
* In case {@link #getSslMode()} is {@code required} and trust store type isn't specified by Ignite properties
* (e.g. at JDBC URL) the JSSE property {@code javax.net.ssl.trustStoreType} will be used.
* In case both Ignite properties and JSSE properties are not set the default 'JKS' type is used.
*
* @param ksType Trusted certificate KeyStore type.
*/
public void setSslTrustCertificateKeyStoreType(String ksType);
/**
* Gets trust any server certificate flag.
*
* @return Trust all certificates flag.
*/
public boolean isSslTrustAll();
/**
* Sets to {@code true} to trust any server certificate (revoked, expired or self-signed SSL certificates).
*
* <p> Defaults is {@code false}.
*
* Note: Do not enable this option in production you are ever going to use
* on a network you do not entirely trust. Especially anything going over the public internet.
*
* @param trustAll Trust all certificates flag.
*/
public void setSslTrustAll(boolean trustAll);
/**
* Gets the class name of the custom implementation of the Factory<SSLSocketFactory>.
*
* @return Custom class name that implements Factory<SSLSocketFactory>.
*/
public String getSslFactory();
/**
* Sets the class name of the custom implementation of the Factory<SSLSocketFactory>.
* If {@link #getSslMode()} is {@code required} and factory is specified the custom factory will be used
* instead of JSSE socket factory. So, other SSL properties will be ignored.
*
* @param sslFactory Custom class name that implements Factory<SSLSocketFactory>.
*/
public void setSslFactory(String sslFactory);
/**
* @param name User name to authentication.
*/
public void setUsername(String name);
/**
* @return User name to authentication.
*/
public String getUsername();
/**
* @param passwd User's password.
*/
public void setPassword(String passwd);
/**
* @return User's password.
*/
public String getPassword();
}
|
92355a1000a8eec8ffa3697140b65f716d639371 | 778 | java | Java | 01_Language/03_Java/spring-boot-security/src/main/java/com/onevgo/springboot/security/controller/BookController.java | cliff363825/TwentyFour | 09df59bd5d275e66463e343647f46027397d1233 | [
"MIT"
] | 3 | 2020-06-28T07:42:51.000Z | 2021-01-15T10:32:11.000Z | 01_Language/03_Java/spring-boot-security/src/main/java/com/onevgo/springboot/security/controller/BookController.java | cliff363825/TwentyFour | 09df59bd5d275e66463e343647f46027397d1233 | [
"MIT"
] | 9 | 2021-03-10T22:45:40.000Z | 2022-02-27T06:53:20.000Z | 01_Language/03_Java/spring-boot-security/src/main/java/com/onevgo/springboot/security/controller/BookController.java | cliff363825/TwentyFour | 09df59bd5d275e66463e343647f46027397d1233 | [
"MIT"
] | 1 | 2021-01-15T10:51:24.000Z | 2021-01-15T10:51:24.000Z | 24.3125 | 64 | 0.670951 | 997,267 | package com.onevgo.springboot.security.controller;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
@Controller
public class BookController {
@GetMapping("/login")
public String login() {
return "book/login";
}
@PreAuthorize("hasAuthority('BookList')")
@GetMapping("/book/list")
public String list() {
return "book/list";
}
@PreAuthorize("hasAuthority('BookAdd')")
@GetMapping("/book/add")
public String add() {
return "book/add";
}
@PreAuthorize("hasAuthority('BookDetail')")
@GetMapping("/book/detail")
public String detail() {
return "book/detail";
}
}
|
92355b6ef89c6edf482dd5cb6232297ab862e5b7 | 7,355 | java | Java | kmdp-ops/terms-owl-to-skos/src/main/java/edu/mayo/kmdp/terms/util/JenaUtil.java | API4KBs/kmdp-models | 18440e6cf69f2fad08f2dece7dfc18ef3fecd690 | [
"Apache-2.0"
] | 1 | 2019-04-17T15:17:29.000Z | 2019-04-17T15:17:29.000Z | kmdp-ops/terms-owl-to-skos/src/main/java/edu/mayo/kmdp/terms/util/JenaUtil.java | API4KBs/kmdp-models | 18440e6cf69f2fad08f2dece7dfc18ef3fecd690 | [
"Apache-2.0"
] | null | null | null | kmdp-ops/terms-owl-to-skos/src/main/java/edu/mayo/kmdp/terms/util/JenaUtil.java | API4KBs/kmdp-models | 18440e6cf69f2fad08f2dece7dfc18ef3fecd690 | [
"Apache-2.0"
] | 1 | 2019-04-19T00:19:49.000Z | 2019-04-19T00:19:49.000Z | 34.246512 | 123 | 0.686677 | 997,268 | /**
* Copyright © 2018 Mayo Clinic (upchh@example.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package edu.mayo.kmdp.terms.util;
import static edu.mayo.kmdp.util.NameUtils.strip;
import edu.mayo.kmdp.terms.mireot.EntityTypes;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import org.apache.jena.ontology.OntModel;
import org.apache.jena.ontology.Ontology;
import org.apache.jena.rdf.model.Model;
import org.apache.jena.rdf.model.RDFNode;
import org.apache.jena.rdf.model.Resource;
import org.apache.jena.rdf.model.ResourceFactory;
import org.apache.jena.rdf.model.Statement;
import org.apache.jena.util.FileManager;
import org.apache.jena.vocabulary.OWL;
import org.apache.jena.vocabulary.OWL2;
import org.apache.jena.vocabulary.RDF;
public class JenaUtil {
static {
FileManager.get().addLocatorClassLoader(edu.mayo.kmdp.util.JenaUtil.class.getClassLoader());
FileManager.get().addLocatorClassLoader(Thread.currentThread().getContextClassLoader());
}
private JenaUtil() { }
public static EntityTypes detectType(String targetURI, Model source) {
if (source.contains(source.createResource(targetURI),
RDF.type,
OWL2.NamedIndividual)) {
return EntityTypes.INST;
} else if (source.contains(source.createResource(targetURI),
RDF.type,
OWL2.Class)) {
return EntityTypes.CLASS;
} else if (source.contains(source.createResource(targetURI),
RDF.type,
OWL2.ObjectProperty)) {
return EntityTypes.OBJ_PROP;
} else if (source.contains(source.createResource(targetURI),
RDF.type,
OWL2.DatatypeProperty)) {
return EntityTypes.DATA_PROP;
} else {
return EntityTypes.UNKNOWN;
}
}
/**
* Copies the 'ontology' axioms from an OntModel to a regular Model
* @param root
* @param ontologyModel
*/
public static void addOntologyAxioms(Model root, OntModel ontologyModel) {
Ontology onto = ontologyModel.listOntologies().next();
List<Statement> ontos =
ontologyModel.listStatements()
.filterKeep(st -> st.getSubject().getURI() != null && st.getSubject().getURI().equals(onto.getURI())).toList();
root.add(ontos);
}
/**
* Copies the 'ontology' axioms from an OntModel to a regular Model
* @param root
* @param ontologyModel
*/
public static void addOntologyAxioms(Model root, Model ontologyModel) {
List<Resource> ontologies = ontologyModel.listStatements()
.filterKeep(st -> st.getPredicate().equals(RDF.type) && st.getObject().equals(OWL2.Ontology))
.mapWith(Statement::getSubject)
.toList();
List<Statement> ontos =
ontologyModel.listStatements()
.filterKeep(st -> st.getSubject().getURI() != null && ontologies.contains(st.getSubject())).toList();
root.add(ontos);
}
public static Optional<String> detectVersionIRI(Model source, String ontologyURI) {
Set<String> versions = source
.listStatements(ResourceFactory.createResource(ontologyURI), OWL2.versionIRI,
(RDFNode) null)
.mapWith(s -> s.getObject().toString())
.toSet();
if (versions.size() > 1) {
throw new UnsupportedOperationException(
"Found multiple version IRIs for ontology " + ontologyURI + " :: " + versions);
}
return versions.isEmpty() ? Optional.empty() : Optional.ofNullable(versions.iterator().next());
}
public static Optional<String> detectVersionFragment(Model source) {
Optional<String> ontologyUri = detectOntologyIRI(source);
if (ontologyUri.isPresent()) {
String uri = ontologyUri.get();
Optional<String> versionUri = detectVersionIRI(source, uri);
if (versionUri.isPresent()) {
String vuri = versionUri.get();
return Optional.of(strip(uri, vuri));
}
}
return Optional.empty();
}
public static Optional<String> detectOntologyIRI(Model source) {
return detectOntologyIRI(source, null);
}
public static Optional<String> detectOntologyIRI(Model source, String baseURIHint) {
String baseURI;
Set<String> uris = source.listStatements(null, RDF.type, OWL.Ontology)
.mapWith(s -> s.getSubject().toString())
.toSet();
if (uris.size() > 1) {
throw new UnsupportedOperationException("Unable to handle multiple ontologies :: " + uris);
}
if (uris.isEmpty() && baseURIHint != null) {
baseURI = source.getNsPrefixMap().getOrDefault("", baseURIHint);
} else {
baseURI = uris.isEmpty() ? null : uris.iterator().next();
}
return Optional.ofNullable(baseURI);
}
public static String applyVersionToURI(String baseURI, String versionFragment, int index, String sep) {
URI uri = URI.create(baseURI);
boolean hasPath = uri.getPath() != null;
String core = hasPath ? uri.getPath() : uri.getSchemeSpecificPart();
List<String> hops = new LinkedList<>(Arrays.asList(core.split(sep)));
boolean needsInitialPadding = hops.isEmpty();
boolean needFinalPadding = core.endsWith(sep);
boolean reverse = index < 0;
if (needsInitialPadding) {
// ensure the host and path will be separated
hops.add("");
}
if (reverse) {
// reverse the index
index = hops.size() - 1 + index;
}
// prevent under/overflow
index = Math.max(1, Math.min(index + 1, hops.size()));
if (needFinalPadding) {
// ensure a trailing separator will be added back at the end
hops.add("");
if (reverse) {
index++;
}
}
String effectiveVersionFragment = versionFragment;
if (versionFragment.startsWith(sep)) {
effectiveVersionFragment = effectiveVersionFragment.substring(sep.length());
}
if (versionFragment.endsWith(sep)) {
effectiveVersionFragment = effectiveVersionFragment.substring(0,effectiveVersionFragment.lastIndexOf(sep));
}
// insert the version fragment in the path
hops.add(index, effectiveVersionFragment);
try {
URI versionUri = hasPath
? new URI(uri.getScheme(), uri.getHost(), String.join(sep, hops), uri.getFragment())
: new URI(uri.getScheme(), String.join(sep, hops), uri.getFragment());
return versionUri.toString();
} catch (URISyntaxException e) {
e.printStackTrace();
return null;
}
}
public static String applyVersionToURI(String baseURI, String versionFragment) {
return applyVersionToURI(baseURI, versionFragment, Integer.MAX_VALUE - 1);
}
public static String applyVersionToURI(String baseURI, String versionFragment, int pos) {
String sep = baseURI.startsWith("urn") ? ":" : "/";
return applyVersionToURI(baseURI, versionFragment, pos, sep);
}
}
|
92355b7b1db63f751c04757890a2642903526cf6 | 2,295 | java | Java | src/test/java/org/apache/camel/component/casper/producer/CasperProducerWith_DEPLOY_OperationTest.java | caspercommunityio/camel-casper | d1e4c8be5f5a0e11605120d0f81891475b4dab06 | [
"MIT"
] | null | null | null | src/test/java/org/apache/camel/component/casper/producer/CasperProducerWith_DEPLOY_OperationTest.java | caspercommunityio/camel-casper | d1e4c8be5f5a0e11605120d0f81891475b4dab06 | [
"MIT"
] | null | null | null | src/test/java/org/apache/camel/component/casper/producer/CasperProducerWith_DEPLOY_OperationTest.java | caspercommunityio/camel-casper | d1e4c8be5f5a0e11605120d0f81891475b4dab06 | [
"MIT"
] | 3 | 2022-02-22T08:50:21.000Z | 2022-03-18T20:48:58.000Z | 35.859375 | 126 | 0.796514 | 997,269 | package org.apache.camel.component.casper.producer;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.apache.camel.CamelExchangeException;
import org.apache.camel.Exchange;
import org.apache.camel.Produce;
import org.apache.camel.ProducerTemplate;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.casper.CasperConstants;
import org.apache.camel.component.casper.CasperTestSupport;
import org.apache.commons.cli.MissingArgumentException;
import org.junit.jupiter.api.Test;
class CasperProducerWith_DEPLOY_OperationTest extends CasperTestSupport {
@Produce("direct:start")
protected ProducerTemplate template;
@Override
public boolean isUseAdviceWith() {
return false;
}
@Test
void testCallWith_DEPLOY_HASH_Parameter() throws Exception {
Exchange exchange = createExchangeWithBodyAndHeader(null, CasperConstants.OPERATION, CasperConstants.DEPLOY);
exchange.getIn().setHeader(CasperConstants.DEPLOY_HASH, "5ff526617848b4416f818009dc90dd35485b4270a54d52f33652995472ef1fa9");
template.send(exchange);
Object body = exchange.getIn().getBody();
assertTrue(true);
// assert Object is a Deploy
/*
* assertTrue(body instanceof Deploy); Deploy deploy = (Deploy) body;
* assertTrue(deploy != null); assertTrue(deploy.getHash().toLowerCase().equals(
* "5ff526617848b4416f818009dc90dd35485b4270a54d52f33652995472ef1fa9"));
*/
}
@Test
void testCallWithout_DEPLOY_HASH_Parameter() throws Exception {
Exchange exchange = createExchangeWithBodyAndHeader(null, CasperConstants.OPERATION, CasperConstants.DEPLOY);
template.send(exchange);
Exception exception = exchange.getException();
assertTrue(exception instanceof CamelExchangeException);
String expectedMessage = "deployHash parameter is required with endpoint operation DEPLOY.";
String actualMessage = exception.getMessage();
// assert Exception message
assertTrue(actualMessage.contains(expectedMessage));
// Cause
Object cause = exchange.getMessage().getHeader(CasperConstants.ERROR_CAUSE);
assertTrue(cause instanceof MissingArgumentException);
}
@Override
protected RouteBuilder createRouteBuilder() throws Exception {
return new RouteBuilder() {
public void configure() {
from("direct:start").to(getUrl());
}
};
}
}
|
92355b936532d8689b9efe0f56aefeec0ea3d6f8 | 547 | java | Java | usermgr/src/main/java/com/composum/sling/core/usermanagement/view/ServiceUser.java | golinski/composum-nodes | a88aad8cdad7161095e227803af405dcc89f5c38 | [
"MIT"
] | 56 | 2015-09-27T18:35:35.000Z | 2020-10-23T12:51:31.000Z | usermgr/src/main/java/com/composum/sling/core/usermanagement/view/ServiceUser.java | golinski/composum-nodes | a88aad8cdad7161095e227803af405dcc89f5c38 | [
"MIT"
] | 80 | 2015-09-30T14:57:33.000Z | 2021-01-30T12:01:40.000Z | usermgr/src/main/java/com/composum/sling/core/usermanagement/view/ServiceUser.java | golinski/composum-nodes | a88aad8cdad7161095e227803af405dcc89f5c38 | [
"MIT"
] | 34 | 2015-10-07T19:42:40.000Z | 2020-10-09T02:39:21.000Z | 26.047619 | 80 | 0.751371 | 997,270 | package com.composum.sling.core.usermanagement.view;
import com.composum.sling.core.usermanagement.model.ServiceUserModel;
import org.apache.jackrabbit.api.security.user.Authorizable;
import org.jetbrains.annotations.NotNull;
/**
*
*/
public class ServiceUser extends View {
@Override
protected @NotNull Class<? extends Authorizable> getSelector() {
return com.composum.sling.core.usermanagement.service.ServiceUser.class;
}
public ServiceUserModel getService(){
return (ServiceUserModel) getModel();
}
}
|
92355bb3ec6ab060df4a55ec0c5b89370ed38aec | 308 | java | Java | src/main/java/org/ht/id/externalcrm/model/sub/PhoneNumber.java | phancdinh/ht-crm-server | a7ab7e3cbd840d4687b5c50be52bbc462f1c4cec | [
"MIT"
] | null | null | null | src/main/java/org/ht/id/externalcrm/model/sub/PhoneNumber.java | phancdinh/ht-crm-server | a7ab7e3cbd840d4687b5c50be52bbc462f1c4cec | [
"MIT"
] | null | null | null | src/main/java/org/ht/id/externalcrm/model/sub/PhoneNumber.java | phancdinh/ht-crm-server | a7ab7e3cbd840d4687b5c50be52bbc462f1c4cec | [
"MIT"
] | null | null | null | 19.25 | 53 | 0.779221 | 997,271 | package org.ht.id.externalcrm.model.sub;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Builder;
import lombok.Getter;
import lombok.Setter;
@Builder
@Getter
@Setter
public class PhoneNumber {
private String value;
@JsonProperty("is_primary")
private boolean is_primary;
}
|
92355c383e700cb30f2fa6c28158260c790ada3f | 4,210 | java | Java | src/main/java/com/example/dao/NutritionDaoImpl.java | matto483/mvcjdbc | cc77bd820bb1f22d9ead96509b2f2b9af51abdf0 | [
"Unlicense"
] | null | null | null | src/main/java/com/example/dao/NutritionDaoImpl.java | matto483/mvcjdbc | cc77bd820bb1f22d9ead96509b2f2b9af51abdf0 | [
"Unlicense"
] | null | null | null | src/main/java/com/example/dao/NutritionDaoImpl.java | matto483/mvcjdbc | cc77bd820bb1f22d9ead96509b2f2b9af51abdf0 | [
"Unlicense"
] | null | null | null | 32.137405 | 193 | 0.642755 | 997,272 | package com.example.dao;
import com.example.common.FoodType;
import com.example.domain.Nutrition;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
@Repository
public class NutritionDaoImpl implements NutritionDao {
private static final Logger log = LoggerFactory.getLogger(NutritionDaoImpl.class);
@Autowired
JdbcTemplate jdbcTemplate;
//Methods
@Override
@Transactional
public void add(Nutrition nutrition) {
log.info("adding " + nutrition);
jdbcTemplate.update("INSERT INTO nutrition(product, calories, carbs, clean, foodType, product_id) VALUES (?,?,?,?,?,?)",
nutrition.getProduct(),
nutrition.getCalories(),
nutrition.getCarbs(),
nutrition.isClean(),
nutrition.getFoodType().name(),
nutrition.getProductId());
}
@Override
public Nutrition find(long id) {
log.info("finding Nutrition object with id -->" + id);
String sql = "select * from nutrition where id= ?;";
try {
Nutrition nut = jdbcTemplate.queryForObject(
sql, new NutritionMapper(), new Long(id));
return nut;
} catch (EmptyResultDataAccessException e) {
return null;
}
}
@Override
public List<Nutrition> findAll() {
List<Nutrition> nutritions = this.jdbcTemplate.query(
"select * from nutrition",
new NutritionMapper());
log.info("Found " + nutritions.size() + " nutritions");
return nutritions;
}
@Override
@Transactional
public void update(Nutrition nutrition) {
log.info("UPDATING Nut called --> " + nutrition);
String sql = "update nutrition set product = ?, calories = ?, carbs = ?, clean = ?, foodType = ? WHERE id = ?";
int numUpdated = jdbcTemplate.update(sql, nutrition.getProduct(), nutrition.getCalories(), nutrition.getCarbs(), nutrition.isClean(), nutrition.getFoodType().name(), nutrition.getId());
System.out.println("\n\n\n num updated ---> " + numUpdated);
}
@Override
@Transactional
public void delete(long id) {
log.info("finding/deleting Nutrition object with id -->" + id);
String sql = "delete from nutrition where id = ?";
jdbcTemplate.update(sql, new Long(id));
}
@Override
@Transactional
public void add(List<Nutrition> nutritions) {
for (Nutrition nutrition : nutritions) {
this.add(nutrition);
}
}
@Override
public List<Nutrition> findByProductId(int id) {
List<Nutrition> nutritions = jdbcTemplate.query(
"select * from nutrition where product_id = ?",
new NutritionMapper(),
new Integer(id));
log.info("Found " + nutritions.size() + " nutritions");
return nutritions;
}
// find all the nutritions that have productId = passed int id
//Do this with a SQL statement:
// Select * from nutritions where productId = ?
// ? = int id passed.
//populate the list
//return the list.
private static class NutritionMapper implements RowMapper<Nutrition> {
@Override
public Nutrition mapRow(ResultSet rs, int rowNum) throws SQLException {
Nutrition nutrition = new Nutrition();
nutrition.setId(rs.getLong("id"));
nutrition.setProduct(rs.getString("product"));
nutrition.setCalories(rs.getInt("calories"));
nutrition.setCarbs(rs.getInt("carbs"));
nutrition.setClean(rs.getBoolean("clean"));
nutrition.setFoodType(FoodType.valueOf(rs.getString("foodType")));
nutrition.setProductId(rs.getInt("product_id"));
return nutrition;
}
}
}
|
92355c92fadb7e218fa82cea16016ab53e6d3717 | 6,263 | java | Java | core/src/main/java/io/undertow/server/handlers/proxy/mod_cluster/VirtualHost.java | aspan/undertow | cbcdcf8780535708f70304b111e49b148ffe68a1 | [
"Apache-2.0"
] | 2,869 | 2015-01-01T21:29:34.000Z | 2022-03-31T03:59:06.000Z | core/src/main/java/io/undertow/server/handlers/proxy/mod_cluster/VirtualHost.java | aspan/undertow | cbcdcf8780535708f70304b111e49b148ffe68a1 | [
"Apache-2.0"
] | 655 | 2015-01-05T03:40:15.000Z | 2022-03-30T14:03:54.000Z | core/src/main/java/io/undertow/server/handlers/proxy/mod_cluster/VirtualHost.java | aspan/undertow | cbcdcf8780535708f70304b111e49b148ffe68a1 | [
"Apache-2.0"
] | 953 | 2015-01-01T03:48:48.000Z | 2022-03-21T06:31:20.000Z | 31.791878 | 111 | 0.598116 | 997,273 | /*
* JBoss, Home of Professional Open Source.
* Copyright 2014 Red Hat, Inc., and individual contributors
* as indicated by the @author tags.
*
* 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.undertow.server.handlers.proxy.mod_cluster;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Set;
import java.util.TreeSet;
import java.util.concurrent.ConcurrentMap;
import io.undertow.UndertowMessages;
import io.undertow.util.CopyOnWriteMap;
import io.undertow.util.PathMatcher;
import io.undertow.util.URLUtils;
/**
* The virtual host handler.
*
* @author Emanuel Muckenhuber
*/
public class VirtualHost {
private static final String STRING_PATH_SEPARATOR = "/";
private final HostEntry defaultHandler = new HostEntry(STRING_PATH_SEPARATOR);
private final ConcurrentMap<String, HostEntry> contexts = new CopyOnWriteMap<>();
/**
* lengths of all registered contexts
*/
private volatile int[] lengths = {};
protected VirtualHost() {
//
}
/**
* Matches a path against the registered handlers.
*
* @param path The relative path to match
* @return The match match. This will never be null, however if none matched its value field will be
*/
PathMatcher.PathMatch<HostEntry> match(String path){
int length = path.length();
final int[] lengths = this.lengths;
for (int i = 0; i < lengths.length; ++i) {
int pathLength = lengths[i];
if (pathLength == length) {
HostEntry next = contexts.get(path);
if (next != null) {
return new PathMatcher.PathMatch<>(path, "", next);
}
} else if (pathLength < length) {
char c = path.charAt(pathLength);
if (c == '/') {
String part = path.substring(0, pathLength);
HostEntry next = contexts.get(part);
if (next != null) {
return new PathMatcher.PathMatch<>(part, path.substring(pathLength), next);
}
}
}
}
if(defaultHandler.contexts.isEmpty()) {
return new PathMatcher.PathMatch<>("", path, null);
}
return new PathMatcher.PathMatch<>("", path, defaultHandler);
}
public synchronized void registerContext(final String path, final String jvmRoute, final Context context) {
if (path.isEmpty()) {
throw UndertowMessages.MESSAGES.pathMustBeSpecified();
}
final String normalizedPath = URLUtils.normalizeSlashes(path);
if (STRING_PATH_SEPARATOR.equals(normalizedPath)) {
defaultHandler.contexts.put(jvmRoute, context);
return;
}
boolean rebuild = false;
HostEntry hostEntry = contexts.get(normalizedPath);
if (hostEntry == null) {
rebuild = true;
hostEntry = new HostEntry(normalizedPath);
contexts.put(normalizedPath, hostEntry);
}
assert !hostEntry.contexts.containsKey(jvmRoute);
hostEntry.contexts.put(jvmRoute, context);
if (rebuild) {
buildLengths();
}
}
public synchronized void removeContext(final String path, final String jvmRoute, final Context context) {
if (path == null || path.isEmpty()) {
throw UndertowMessages.MESSAGES.pathMustBeSpecified();
}
final String normalizedPath = URLUtils.normalizeSlashes(path);
if (STRING_PATH_SEPARATOR.equals(normalizedPath)) {
defaultHandler.contexts.remove(jvmRoute, context);
}
final HostEntry hostEntry = contexts.get(normalizedPath);
if (hostEntry != null) {
if (hostEntry.contexts.remove(jvmRoute, context)) {
if (hostEntry.contexts.isEmpty()) {
contexts.remove(normalizedPath);
buildLengths();
}
}
}
}
boolean isEmpty() {
return contexts.isEmpty() && defaultHandler.contexts.isEmpty();
}
private void buildLengths() {
final Set<Integer> lengths = new TreeSet<>(new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
return -o1.compareTo(o2);
}
});
for (String p : contexts.keySet()) {
lengths.add(p.length());
}
int[] lengthArray = new int[lengths.size()];
int pos = 0;
for (int i : lengths) {
lengthArray[pos++] = i;
}
this.lengths = lengthArray;
}
static class HostEntry {
// node > context
private final ConcurrentMap<String, Context> contexts = new CopyOnWriteMap<>();
private final String contextPath;
HostEntry(String contextPath) {
this.contextPath = contextPath;
}
protected String getContextPath() {
return contextPath;
}
/**
* Get a context for a jvmRoute.
*
* @param jvmRoute the jvm route
*/
protected Context getContextForNode(final String jvmRoute) {
return contexts.get(jvmRoute);
}
/**
* Get list of nodes as jvmRoutes.
*/
protected Collection<String> getNodes() {
return Collections.unmodifiableCollection(contexts.keySet());
}
/**
* Get all registered contexts.
*/
protected Collection<Context> getContexts() {
return Collections.unmodifiableCollection(contexts.values());
}
}
}
|
92355cc3c84ce782d3acfb9127684153d6fb248d | 5,062 | java | Java | src/main/java/net/epoxide/discordanddragons/util/Utilities.java | Epoxide-Software/Discord-and-Dragons | 4b12087d5410cda4f9621202e3474459940ad6c8 | [
"MIT"
] | 1 | 2016-05-02T04:12:37.000Z | 2016-05-02T04:12:37.000Z | src/main/java/net/epoxide/discordanddragons/util/Utilities.java | Epoxide-Software/Discord-and-Dragons | 4b12087d5410cda4f9621202e3474459940ad6c8 | [
"MIT"
] | null | null | null | src/main/java/net/epoxide/discordanddragons/util/Utilities.java | Epoxide-Software/Discord-and-Dragons | 4b12087d5410cda4f9621202e3474459940ad6c8 | [
"MIT"
] | null | null | null | 31.440994 | 100 | 0.581786 | 997,274 | package net.epoxide.discordanddragons.util;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import org.apache.commons.io.FileUtils;
import net.epoxide.discordanddragons.DiscordAndDragons;
import sx.blah.discord.handle.obj.IChannel;
import sx.blah.discord.handle.obj.IUser;
import sx.blah.discord.util.DiscordException;
import sx.blah.discord.util.HTTP429Exception;
import sx.blah.discord.util.MissingPermissionsException;
public class Utilities {
public static File downloadFile (String site) {
final File file = new File("Image.png");
try {
FileUtils.copyURLToFile(new URL(site), file);
}
catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return file;
}
/**
* Creates a ping message for a user based upon their user ID.
*
* @param userID The user ID of the user to generate a ping message for.
* @return String A short string which will ping the specified user when sent into the
* chat.
*/
public static String getPingMessage (String userID) {
return "<@" + userID + ">";
}
/**
* Makes a String message italicized. This only applies to chat.
*
* @param message The message to format.
* @return String The message with the formatting codes applied.
*/
public static String makeItalic (String message) {
return "*" + message + "*";
}
/**
* Makes a String message bold. This only applies to chat.
*
* @param message The message to format.
* @return String The message with the bold formatting codes applied.
*/
public static String makeBold (String message) {
return "**" + message + "**";
}
/**
* Makes a String message scratched out. This only applies to chat.
*
* @param message The message to format.
* @return String The message with the scratched out formatting codes applied.
*/
public static String makeScratched (String message) {
return "~~" + message + "~~";
}
/**
* Makes a String message underlined. This only applies to chat.
*
* @param message The message to format.
* @return String The message with the underlined formatting codes applied.
*/
public static String makeUnderlined (String message) {
return "__" + message + "__";
}
/**
* Makes a String message appear in a code block. This only applies to chat.
*
* @param message The message to format.
* @return String The message with the code block format codes applied.
*/
public static String makeCodeBlock (String message) {
return "`" + message + "`";
}
/**
* Makes a String message appear in a multi-lined code block. This only applies to chat.
*
* @param message The message to format.
* @return String The message with the multi-lined code block format codes applied.
*/
public static String makeMultiCodeBlock (String message) {
return "```" + message + "```";
}
/**
* Attempts to send a private message to a user. If a private message channel does not
* already exist, it will be created.
*
* @param instance An instance of your IDiscordClient.
* @param user The user to send the private message to.
* @param message The message to send to the user.
*/
public static void sendPrivateMessage (IUser user, String message) {
try {
sendMessage(DiscordAndDragons.instance.getOrCreatePMChannel(user), message);
}
catch (final Exception e) {
e.printStackTrace();
}
}
/**
* Sends a message into the chat. This version of the method will handle exceptions for
* you.
*
* @param channel The channel to send to message to.
* @param message The message to send to the channel.
*/
public static void sendMessage (IChannel channel, String message) {
try {
channel.sendMessage(message);
}
catch (MissingPermissionsException | HTTP429Exception | DiscordException e) {
if (e instanceof DiscordException && e.toString().contains("String value is too long"))
sendMessage(channel, "I tried to send a message, but it was too long.");
else
e.printStackTrace();
}
}
public static void getUserFromName () {
}
} |
92355cd8246d8246c7ffcadda082ea6eead57d51 | 22,137 | java | Java | src/main/java/com/b1n_ry/yigd/block/GraveBlock.java | B1n-ry/Youre-in-grave-danger | 1fd7f63dc631c046b3dc5207e0139d5f556a2ee5 | [
"MIT"
] | 22 | 2021-11-16T19:35:44.000Z | 2022-03-12T06:53:21.000Z | src/main/java/com/b1n_ry/yigd/block/GraveBlock.java | B1n-ry/Youre-in-grave-danger | 1fd7f63dc631c046b3dc5207e0139d5f556a2ee5 | [
"MIT"
] | 37 | 2021-11-14T20:45:24.000Z | 2022-03-26T14:28:09.000Z | src/main/java/com/b1n_ry/yigd/block/GraveBlock.java | B1n-ry/Youre-in-grave-danger | 1fd7f63dc631c046b3dc5207e0139d5f556a2ee5 | [
"MIT"
] | 2 | 2022-01-16T22:24:51.000Z | 2022-01-28T07:38:48.000Z | 47.200426 | 206 | 0.669287 | 997,275 | package com.b1n_ry.yigd.block;
import com.b1n_ry.yigd.Yigd;
import com.b1n_ry.yigd.api.YigdApi;
import com.b1n_ry.yigd.block.entity.GraveBlockEntity;
import com.b1n_ry.yigd.config.DropTypeConfig;
import com.b1n_ry.yigd.config.RetrievalTypeConfig;
import com.b1n_ry.yigd.config.YigdConfig;
import com.b1n_ry.yigd.core.DeadPlayerData;
import com.b1n_ry.yigd.core.DeathInfoManager;
import com.b1n_ry.yigd.core.GraveHelper;
import com.b1n_ry.yigd.item.KeyItem;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.mojang.authlib.GameProfile;
import net.minecraft.block.*;
import net.minecraft.block.entity.BlockEntity;
import net.minecraft.block.entity.BlockEntityTicker;
import net.minecraft.block.entity.BlockEntityType;
import net.minecraft.entity.Entity;
import net.minecraft.entity.ExperienceOrbEntity;
import net.minecraft.entity.LivingEntity;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.fluid.FluidState;
import net.minecraft.fluid.Fluids;
import net.minecraft.item.ItemPlacementContext;
import net.minecraft.item.ItemStack;
import net.minecraft.item.Items;
import net.minecraft.nbt.NbtCompound;
import net.minecraft.nbt.NbtElement;
import net.minecraft.nbt.NbtHelper;
import net.minecraft.server.MinecraftServer;
import net.minecraft.server.network.ServerPlayerEntity;
import net.minecraft.server.world.ServerWorld;
import net.minecraft.state.StateManager;
import net.minecraft.state.property.BooleanProperty;
import net.minecraft.state.property.DirectionProperty;
import net.minecraft.state.property.Properties;
import net.minecraft.text.TranslatableText;
import net.minecraft.util.ActionResult;
import net.minecraft.util.Hand;
import net.minecraft.util.ItemScatterer;
import net.minecraft.util.collection.DefaultedList;
import net.minecraft.util.hit.BlockHitResult;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.Direction;
import net.minecraft.util.math.Vec3d;
import net.minecraft.util.shape.VoxelShape;
import net.minecraft.util.shape.VoxelShapes;
import net.minecraft.world.BlockView;
import net.minecraft.world.World;
import net.minecraft.world.WorldAccess;
import net.minecraft.world.tick.OrderedTick;
import org.apache.commons.lang3.StringUtils;
import org.jetbrains.annotations.Nullable;
import java.util.*;
@SuppressWarnings("deprecation")
public class GraveBlock extends BlockWithEntity implements BlockEntityProvider, Waterloggable {
public static JsonObject customModel;
public static final DirectionProperty FACING;
protected static VoxelShape SHAPE_NORTH;
protected static final VoxelShape SHAPE_BASE_NORTH;
protected static final VoxelShape SHAPE_FOOT_NORTH;
protected static final VoxelShape SHAPE_CORE_NORTH;
protected static final VoxelShape SHAPE_TOP_NORTH;
protected static VoxelShape SHAPE_WEST;
protected static final VoxelShape SHAPE_BASE_WEST;
protected static final VoxelShape SHAPE_FOOT_WEST;
protected static final VoxelShape SHAPE_CORE_WEST;
protected static final VoxelShape SHAPE_TOP_WEST;
protected static VoxelShape SHAPE_EAST;
protected static final VoxelShape SHAPE_BASE_EAST;
protected static final VoxelShape SHAPE_FOOT_EAST;
protected static final VoxelShape SHAPE_CORE_EAST;
protected static final VoxelShape SHAPE_TOP_EAST;
protected static VoxelShape SHAPE_SOUTH;
protected static final VoxelShape SHAPE_BASE_SOUTH;
protected static final VoxelShape SHAPE_FOOT_SOUTH;
protected static final VoxelShape SHAPE_CORE_SOUTH;
protected static final VoxelShape SHAPE_TOP_SOUTH;
protected static final BooleanProperty WATERLOGGED;
private String customName = null;
public GraveBlock(Settings settings) {
super(settings.nonOpaque());
this.setDefaultState(this.stateManager.getDefaultState().with(Properties.HORIZONTAL_FACING, Direction.NORTH).with(Properties.WATERLOGGED, false));
}
public static void reloadVoxelShapes(JsonObject graveModel) {
if (graveModel == null) return;
JsonElement shapesArray = graveModel.get("elements");
if (shapesArray == null || !shapesArray.isJsonArray()) return;
VoxelShape groundShapeNorth = Block.createCuboidShape(0, 0, 0, 0, 0, 0);
VoxelShape groundShapeWest = Block.createCuboidShape(0, 0, 0, 0, 0, 0);
VoxelShape groundShapeSouth = Block.createCuboidShape(0, 0, 0, 0, 0, 0);
VoxelShape groundShapeEast = Block.createCuboidShape(0, 0, 0, 0, 0, 0);
List<VoxelShape> shapesNorth = new ArrayList<>();
List<VoxelShape> shapesWest = new ArrayList<>();
List<VoxelShape> shapesSouth = new ArrayList<>();
List<VoxelShape> shapesEast = new ArrayList<>();
for (JsonElement e : (JsonArray) shapesArray) {
if (!e.isJsonObject()) continue;
JsonObject o = e.getAsJsonObject();
if (o.get("name") != null && o.get("name").getAsString().equals("Base_Layer")) {
Map<String, VoxelShape> groundShapes = getShapeFromJson(o);
groundShapeNorth = groundShapes.get("NORTH");
groundShapeWest = groundShapes.get("WEST");
groundShapeSouth = groundShapes.get("SOUTH");
groundShapeEast = groundShapes.get("EAST");
} else {
Map<String, VoxelShape> directionShapes = getShapeFromJson(o);
shapesNorth.add(directionShapes.get("NORTH"));
shapesWest.add(directionShapes.get("WEST"));
shapesSouth.add(directionShapes.get("SOUTH"));
shapesEast.add(directionShapes.get("EAST"));
}
}
SHAPE_NORTH = VoxelShapes.union(groundShapeNorth, shapesNorth.toArray(new VoxelShape[0]));
SHAPE_WEST = VoxelShapes.union(groundShapeWest, shapesWest.toArray(new VoxelShape[0]));
SHAPE_SOUTH = VoxelShapes.union(groundShapeSouth, shapesSouth.toArray(new VoxelShape[0]));
SHAPE_EAST = VoxelShapes.union(groundShapeEast, shapesEast.toArray(new VoxelShape[0]));
}
private static Map<String, VoxelShape> getShapeFromJson(JsonObject object) {
Map<String, VoxelShape> shapes = new HashMap<>();
JsonArray from = object.get("from").getAsJsonArray();
float x1 = from.get(0).getAsFloat();
float y1 = from.get(1).getAsFloat();
float z1 = from.get(2).getAsFloat();
JsonArray to = object.getAsJsonArray("to").getAsJsonArray();
float x2 = to.get(0).getAsFloat();
float y2 = to.get(1).getAsFloat();
float z2 = to.get(2).getAsFloat();
shapes.put("NORTH", Block.createCuboidShape(x1, y1, z1, x2, y2, z2));
shapes.put("EAST", Block.createCuboidShape(16 - z2, y1, x1, 16 - z1, y2, x2));
shapes.put("SOUTH", Block.createCuboidShape(16 - x2, y1, 16 - z2, 16 - x1, y2, 16 - z1));
shapes.put("WEST", Block.createCuboidShape(z1, y1, 16 - x2, z2, y2, 16 - x1));
return shapes;
}
@Override
public BlockRenderType getRenderType(BlockState state) {
if (YigdConfig.getConfig().graveSettings.graveRenderSettings.useRenderFeatures) return BlockRenderType.INVISIBLE;
return BlockRenderType.MODEL;
}
@Override
protected void appendProperties(StateManager.Builder<Block, BlockState> builder) {
builder.add(Properties.HORIZONTAL_FACING, WATERLOGGED);
}
@Override
public ActionResult onUse(BlockState state, World world, BlockPos pos, PlayerEntity player, Hand hand, BlockHitResult hit) {
RetrievalTypeConfig retrievalType = YigdConfig.getConfig().graveSettings.retrievalType;
BlockEntity be = world.getBlockEntity(pos);
if (!(be instanceof GraveBlockEntity grave)) return super.onUse(state, world, pos, player, hand, hit);
if ((retrievalType == RetrievalTypeConfig.ON_USE || retrievalType == null) && grave.getGraveOwner() != null) {
RetrieveItems(player, world, pos);
return ActionResult.SUCCESS;
}
ItemStack heldItem = player.getStackInHand(hand);
if (heldItem.getItem() == Items.PLAYER_HEAD) {
NbtCompound nbt = heldItem.getNbt();
if (nbt != null) {
GameProfile gameProfile = null;
if (nbt.contains("SkullOwner", NbtElement.COMPOUND_TYPE)) {
gameProfile = NbtHelper.toGameProfile(nbt.getCompound("SkullOwner"));
} else if (nbt.contains("SkullOwner", NbtElement.STRING_TYPE) && !StringUtils.isBlank(nbt.getString("SkullOwner"))) {
gameProfile = new GameProfile(null, nbt.getString("SkullOwner"));
}
// Set skull and decrease count of items
if (gameProfile != null) {
if (grave.getGraveSkull() != null) {
grave.dropCosmeticSkull();
}
grave.setGraveSkull(gameProfile);
heldItem.decrement(1);
return ActionResult.SUCCESS;
}
}
}
return super.onUse(state, world, pos, player, hand, hit);
}
@Override
public void onSteppedOn(World world, BlockPos pos, BlockState state, Entity entity) {
if (YigdConfig.getConfig().graveSettings.retrievalType == RetrievalTypeConfig.ON_STAND && entity instanceof PlayerEntity player) {
RetrieveItems(player, world, pos);
} else if (YigdConfig.getConfig().graveSettings.retrievalType == RetrievalTypeConfig.ON_SNEAK && entity instanceof PlayerEntity player) {
if (player.isInSneakingPose()) {
RetrieveItems(player, world, pos);
}
}
super.onSteppedOn(world, pos, state, entity);
}
@Override
public void afterBreak(World world, PlayerEntity player, BlockPos pos, BlockState state, BlockEntity be, ItemStack stack) {
if (!(be instanceof GraveBlockEntity graveBlockEntity) || graveBlockEntity.getGraveOwner() == null) {
super.afterBreak(world, player, pos, state, be, stack);
return;
}
if (YigdConfig.getConfig().graveSettings.retrievalType == RetrievalTypeConfig.ON_BREAK) {
if (RetrieveItems(player, world, pos, be)) return;
}
boolean bs = world.setBlockState(pos, state);
if (bs) {
world.addBlockEntity(be);
} else {
Yigd.LOGGER.warn("Did not manage to safely replace grave data at " + pos.getX() + ", " + pos.getY() + ", " + pos.getZ() + ". If grave contained items they've been deleted as no data was found");
}
}
@Override
public void onStateReplaced(BlockState state, World world, BlockPos pos, BlockState newState, boolean moved) {
Yigd.LOGGER.info("Grave at " + pos.getX() + ", " + pos.getY() + ", " + pos.getZ() + " was replaced with " + newState.getBlock());
super.onStateReplaced(state, world, pos, newState, moved);
}
@Override
public float calcBlockBreakingDelta(BlockState state, PlayerEntity player, BlockView world, BlockPos pos) {
BlockEntity blockEntity = world.getBlockEntity(pos);
if (blockEntity instanceof GraveBlockEntity graveEntity) {
YigdConfig.GraveSettings config = YigdConfig.getConfig().graveSettings;
YigdConfig.GraveRobbing graveRobbing = config.graveRobbing;
boolean canRobGrave = graveRobbing.enableRobbing && (!graveRobbing.onlyMurderer || graveEntity.getKiller() == player.getUuid());
if ((config.retrievalType == RetrievalTypeConfig.ON_BREAK && (player.getGameProfile().equals(graveEntity.getGraveOwner()) || canRobGrave)) || graveEntity.getGraveOwner() == null) {
return super.calcBlockBreakingDelta(state, player, world, pos);
}
}
return 0f;
}
@Override
public void onPlaced(World world, BlockPos pos, BlockState state, @Nullable LivingEntity placer, ItemStack itemStack) {
if (itemStack.hasCustomName()) {
customName = itemStack.getName().asString();
BlockEntity blockEntity = world.getBlockEntity(pos);
if (blockEntity instanceof GraveBlockEntity graveBlockEntity) {
graveBlockEntity.setCustomName(customName);
}
}
}
private VoxelShape getShape(Direction dir) {
return switch (dir) {
case NORTH -> SHAPE_NORTH;
case SOUTH -> SHAPE_SOUTH;
case EAST -> SHAPE_EAST;
case WEST -> SHAPE_WEST;
default -> VoxelShapes.fullCube();
};
}
@Override
public VoxelShape getOutlineShape(BlockState state, BlockView view, BlockPos pos, ShapeContext ct) {
Direction dir = state.get(FACING);
return getShape(dir);
}
@Override
public BlockState getPlacementState(ItemPlacementContext context) {
BlockPos blockPos = context.getBlockPos();
FluidState fluidState = context.getWorld().getFluidState(blockPos);
return this.getDefaultState().with(Properties.HORIZONTAL_FACING, context.getPlayerFacing().getOpposite()).with(WATERLOGGED, fluidState.getFluid() == Fluids.WATER);
}
@Override
public BlockState getStateForNeighborUpdate(BlockState state, Direction direction, BlockState neighborState, WorldAccess world, BlockPos pos, BlockPos neighborPos) {
if (state.get(WATERLOGGED)) {
world.getFluidTickScheduler().scheduleTick(OrderedTick.create(Fluids.WATER, pos));
}
return direction.getAxis().isHorizontal() ? state : super.getStateForNeighborUpdate(state, direction, neighborState, world, pos, neighborPos);
}
@Override
public FluidState getFluidState(BlockState state) {
return state.get(WATERLOGGED) ? Fluids.WATER.getStill(false) : super.getFluidState(state);
}
@Override
public <T extends BlockEntity> BlockEntityTicker<T> getTicker(World world, BlockState state, BlockEntityType<T> type) {
return checkType(type, Yigd.GRAVE_BLOCK_ENTITY, GraveBlockEntity::tick);
}
@Override
public boolean canReplace(BlockState state, ItemPlacementContext context) {
return false;
}
@Nullable
@Override
public BlockEntity createBlockEntity(BlockPos pos, BlockState state) {
return new GraveBlockEntity(customName, pos, state);
}
private void RetrieveItems(PlayerEntity player, World world, BlockPos pos) {
BlockEntity blockEntity = world.getBlockEntity(pos);
RetrieveItems(player, world, pos, blockEntity);
}
private boolean RetrieveItems(PlayerEntity player, World world, BlockPos pos, BlockEntity blockEntity) {
if (world.isClient) return false;
if (player == null || player.isDead()) return false;
if (!(blockEntity instanceof GraveBlockEntity graveEntity)) return false;
GameProfile graveOwner = graveEntity.getGraveOwner();
if (graveOwner == null) return false;
if (graveEntity.getGraveOwner() != null && graveEntity.age < 20) {
player.sendMessage(new TranslatableText("text.yigd.message.too_fast"), false);
return false;
}
int xp = graveEntity.getStoredXp();
DefaultedList<ItemStack> items = graveEntity.getStoredInventory();
if (items == null) return false;
YigdConfig config = YigdConfig.getConfig();
YigdConfig.GraveRobbing graveRobbing = config.graveSettings.graveRobbing;
boolean canRobGrave = graveRobbing.enableRobbing && (!graveRobbing.onlyMurderer || graveEntity.getKiller() == player.getUuid());
canRobGrave = canRobGrave || (config.graveSettings.unlockableGraves && DeathInfoManager.INSTANCE.unlockedGraves.contains(graveEntity.getGraveId()));
int age = graveEntity.age;
int requiredAge = graveRobbing.afterTime * graveRobbing.timeType.tickFactor();
boolean isRobbing = false;
boolean timePassed = age > requiredAge;
boolean isGraveOwner = player.getGameProfile().getId().equals(graveOwner.getId());
if (!isGraveOwner) {
if (!(canRobGrave && timePassed)) {
if (config.utilitySettings.graveKeySettings.enableKeys) {
ItemStack heldStack = player.getMainHandStack();
isRobbing = KeyItem.isKeyForGrave(heldStack, graveEntity);
}
if (canRobGrave && !isRobbing) {
double timeRemaining = ((double) requiredAge - age) / 20;
int hours = (int) (timeRemaining / 3600);
timeRemaining %= 3600;
int minutes = (int) (timeRemaining / 60);
timeRemaining %= 60;
int seconds = (int) timeRemaining;
player.sendMessage(new TranslatableText("text.yigd.message.retrieve.rob_cooldown", hours, minutes, seconds), true);
} else {
player.sendMessage(new TranslatableText("text.yigd.message.retrieve.missing_permission"), true);
}
if (!isRobbing) return false;
} else {
isRobbing = true;
}
} else if(config.utilitySettings.graveKeySettings.alwaysRequire) {
ItemStack stack = player.getMainHandStack();
if (!KeyItem.isKeyForGrave(stack, graveEntity)) {
player.sendMessage(new TranslatableText("text.yigd.message.retrieve.missing_key"), true);
return false;
}
}
Map<String, Object> graveModItems = graveEntity.getModdedInventories();
DeadPlayerData data = DeathInfoManager.findUserGrave(graveOwner.getId(), graveEntity.getGraveId());
if (data != null) {
data.availability = 0;
DeathInfoManager.INSTANCE.markDirty();
} else {
Yigd.LOGGER.warn("Tried to change status of grave for %s (%s) at %s, but grave was not found".formatted(graveOwner.getName(), graveOwner.getId(), pos));
}
if (config.graveSettings.dropType == DropTypeConfig.ON_GROUND) {
for (YigdApi yigdApi : Yigd.apiMods) {
Object o = graveModItems.get(yigdApi.getModName());
items.addAll(yigdApi.toStackList(o));
}
if (world instanceof ServerWorld sWorld) ExperienceOrbEntity.spawn(sWorld, Vec3d.of(pos), graveEntity.getStoredXp());
ItemScatterer.spawn(world, pos, items);
if (config.graveSettings.dropGraveBlock) {
ItemScatterer.spawn(world, pos.getX(), pos.getY(), pos.getZ(), Yigd.GRAVE_BLOCK.asItem().getDefaultStack());
}
if (config.graveSettings.replaceWhenClaimed) {
world.setBlockState(pos, graveEntity.getPreviousState());
} else {
world.removeBlock(pos, false);
}
return true;
}
if (config.graveSettings.dropGraveBlock) {
ItemScatterer.spawn(world, pos.getX(), pos.getY(), pos.getZ(), Yigd.GRAVE_BLOCK.asItem().getDefaultStack());
}
if (config.graveSettings.replaceWhenClaimed) {
world.setBlockState(pos, graveEntity.getPreviousState());
} else {
world.removeBlock(pos, false);
}
Yigd.LOGGER.info(player.getDisplayName().asString() + " is retrieving " + (isRobbing ? "someone else's" : "their") + " grave at " + pos.getX() + ", " + pos.getY() + ", " + pos.getZ());
MinecraftServer server = world.getServer();
if (isRobbing && server != null) {
UUID playerId = graveOwner.getId();
ServerPlayerEntity robbedPlayer = server.getPlayerManager().getPlayer(playerId);
if (robbedPlayer != null) {
robbedPlayer.sendMessage(new TranslatableText("text.yigd.message.robbed"), false);
} else {
Yigd.notNotifiedRobberies.add(playerId);
}
}
GraveHelper.RetrieveItems(player, items, graveModItems, xp, isRobbing);
return true;
}
static {
FACING = HorizontalFacingBlock.FACING;
SHAPE_BASE_NORTH = Block.createCuboidShape(0.0f, 0.0f, 0.0f, 16.0f, 1.0f, 16.0f);
SHAPE_FOOT_NORTH = Block.createCuboidShape(2.0f, 1.0f, 10.0f, 14.0f, 3.0f, 15.0f);
SHAPE_CORE_NORTH = Block.createCuboidShape(3.0f, 3.0f, 11.0f, 13.0f, 15.0f, 14.0f);
SHAPE_TOP_NORTH = Block.createCuboidShape(4.0f, 15.0f, 11.0f, 12.0f, 16.0f, 14.0f);
SHAPE_BASE_EAST = Block.createCuboidShape(0.0f, 0.0f, 0.0f, 16.0f, 1.0f, 16.0f);
SHAPE_FOOT_EAST = Block.createCuboidShape(1.0f, 1.0f, 2.0f, 6.0f, 3.0f, 14.0f);
SHAPE_CORE_EAST = Block.createCuboidShape(2.0f, 3.0f, 3.0f, 5.0f, 15.0f, 13.0f);
SHAPE_TOP_EAST = Block.createCuboidShape(2.0f, 15.0f, 4.0f, 5.0f, 16.0f, 12.0f);
SHAPE_BASE_WEST = Block.createCuboidShape(0.0f, 0.0f, 0.0f, 16.0f, 1.0f, 16.0f);
SHAPE_FOOT_WEST = Block.createCuboidShape(10.0f, 1.0f, 2.0f, 15.0f, 3.0f, 14.0f);
SHAPE_CORE_WEST = Block.createCuboidShape(11.0f, 3.0f, 3.0f, 14.0f, 15.0f, 13.0f);
SHAPE_TOP_WEST = Block.createCuboidShape(11.0f, 15.0f, 4.0f, 14.0f, 16.0f, 12.0f);
SHAPE_BASE_SOUTH = Block.createCuboidShape(0.0f, 0.0f, 0.0f, 16.0f, 1.0f, 16.0f);
SHAPE_FOOT_SOUTH = Block.createCuboidShape(2.0f, 1.0f, 1.0f, 14.0f, 3.0f, 6.0f);
SHAPE_CORE_SOUTH = Block.createCuboidShape(3.0f, 3.0f, 2.0f, 13.0f, 15.0f, 5.0f);
SHAPE_TOP_SOUTH = Block.createCuboidShape(4.0f, 15.0f, 2.0f, 12.0f, 16.0f, 5.0f);
SHAPE_NORTH = VoxelShapes.union(SHAPE_BASE_NORTH, SHAPE_FOOT_NORTH, SHAPE_CORE_NORTH, SHAPE_TOP_NORTH);
SHAPE_WEST = VoxelShapes.union(SHAPE_BASE_WEST, SHAPE_FOOT_WEST, SHAPE_CORE_WEST, SHAPE_TOP_WEST);
SHAPE_EAST = VoxelShapes.union(SHAPE_BASE_EAST, SHAPE_FOOT_EAST, SHAPE_CORE_EAST, SHAPE_TOP_EAST);
SHAPE_SOUTH = VoxelShapes.union(SHAPE_BASE_SOUTH, SHAPE_FOOT_SOUTH, SHAPE_CORE_SOUTH, SHAPE_TOP_SOUTH);
WATERLOGGED = Properties.WATERLOGGED;
}
}
|
92355d608d90bbdaf7e5579194a0113101530cf0 | 456 | java | Java | TeamCode/src/main/java/org/firstinspires/ftc/teamcode/modules/positioning/NavigationOnThread.java | EHSRobotics3397/FTC-2018 | 989f883f63c20377c22a63915e00c6c77359486f | [
"MIT"
] | null | null | null | TeamCode/src/main/java/org/firstinspires/ftc/teamcode/modules/positioning/NavigationOnThread.java | EHSRobotics3397/FTC-2018 | 989f883f63c20377c22a63915e00c6c77359486f | [
"MIT"
] | null | null | null | TeamCode/src/main/java/org/firstinspires/ftc/teamcode/modules/positioning/NavigationOnThread.java | EHSRobotics3397/FTC-2018 | 989f883f63c20377c22a63915e00c6c77359486f | [
"MIT"
] | null | null | null | 24 | 70 | 0.736842 | 997,276 | package org.firstinspires.ftc.teamcode.modules.positioning;
import org.firstinspires.ftc.teamcode.modules.positioning.*;
import org.firstinspires.ftc.robotcore.external.matrices.OpenGLMatrix;
public class NavigationOnThread extends Thread {
private VuforiaNavigation nav;
public OpenGLMatrix mat;
public NavigationOnThread(VuforiaNavigation n) {
nav = n;
}
public void run() {
mat = nav.getRobotPosition();
}
}
|
92355d9367c7d1deefbca0aad8717cd9a493a0be | 1,940 | java | Java | src/main/java/com/lambdazen/bitsy/ads/dict/DictionaryMax.java | leonpeek/bitsy | 9ad1c307e76724346ac732f594553ad8a4cfc011 | [
"Apache-2.0"
] | 125 | 2017-09-22T16:50:32.000Z | 2022-03-15T05:21:22.000Z | src/main/java/com/lambdazen/bitsy/ads/dict/DictionaryMax.java | leonpeek/bitsy | 9ad1c307e76724346ac732f594553ad8a4cfc011 | [
"Apache-2.0"
] | 33 | 2017-09-22T16:47:33.000Z | 2022-02-25T11:07:42.000Z | src/main/java/com/lambdazen/bitsy/ads/dict/DictionaryMax.java | leonpeek/bitsy | 9ad1c307e76724346ac732f594553ad8a4cfc011 | [
"Apache-2.0"
] | 21 | 2017-09-22T14:48:45.000Z | 2022-02-15T12:42:17.000Z | 21.555556 | 78 | 0.664948 | 997,277 | package com.lambdazen.bitsy.ads.dict;
import java.util.Arrays;
public class DictionaryMax extends PrimitiveDictionary implements Dictionary {
int capacity;
String[] keys;
Object[] values;
// Expand constructor
public DictionaryMax(Dictionary16 base, String key, Object value) {
this.capacity = 24;
keys = Arrays.copyOf(base.keys(), capacity);
values = Arrays.copyOf(base.values(), capacity);
keys[16] = key;
values[16] = value;
}
// Copy constructor
public DictionaryMax(DictionaryMax base) {
this.capacity = base.capacity;
keys = Arrays.copyOf(base.keys(), capacity);
values = Arrays.copyOf(base.values(), capacity);
}
// FromMap constructor
public DictionaryMax(String[] keys, Object[] values) {
this.capacity = Math.max(24, keys.length + keys.length / 2);
this.keys = Arrays.copyOf(keys, capacity);
this.values = Arrays.copyOf(values, capacity);
}
@Override
String[] keys() {
return keys;
}
@Override
Object[] values() {
return values;
}
@Override
void write(int index, String key, Object value) {
keys[index] = key;
values[index] = value;
}
@Override
Dictionary expand(String key, Object value) {
int newCapacity = capacity + (capacity / 2);
keys = Arrays.copyOf(keys, newCapacity);
values = Arrays.copyOf(values, newCapacity);
keys[capacity] = key;
values[capacity] = value;
this.capacity = newCapacity;
return this;
}
@Override
int contractThreshold() {
return capacity / 2;
}
@Override
Dictionary contract() {
if (capacity < 14) {
// Move to Dictionary16
return new Dictionary16(this);
} else {
int newCapacity = capacity * 3 / 4;
keys = Arrays.copyOf(keys, newCapacity);
values = Arrays.copyOf(values, newCapacity);
this.capacity = newCapacity;
return this;
}
}
@Override
public Dictionary copyOf() {
return new DictionaryMax(this);
}
}
|
92355de4feed212faae97b2969e07723784969d7 | 1,070 | java | Java | eagle-core/src/main/java/eagle/jfaster/org/transport/HeartBeatFactory.java | fang-yan-peng/eagle | 963a3631a824289e52258939f9b0759850856a4a | [
"Apache-2.0"
] | 73 | 2017-08-17T09:30:00.000Z | 2021-04-10T00:47:01.000Z | eagle-core/src/main/java/eagle/jfaster/org/transport/HeartBeatFactory.java | fang-yan-peng/eagle | 963a3631a824289e52258939f9b0759850856a4a | [
"Apache-2.0"
] | 11 | 2017-11-09T09:40:38.000Z | 2022-01-04T13:47:51.000Z | eagle-core/src/main/java/eagle/jfaster/org/transport/HeartBeatFactory.java | fang-yan-peng/eagle | 963a3631a824289e52258939f9b0759850856a4a | [
"Apache-2.0"
] | 21 | 2017-08-17T09:28:18.000Z | 2020-03-29T17:45:07.000Z | 26.097561 | 75 | 0.711215 | 997,278 | /*
* Copyright 2017 eagle.jfaster.org.
* <p>
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* </p>
*/
package eagle.jfaster.org.transport;
import eagle.jfaster.org.config.common.MergeConfig;
import eagle.jfaster.org.rpc.Request;
import eagle.jfaster.org.spi.Scope;
import eagle.jfaster.org.spi.Spi;
/**
* Created by fangyanpeng1 on 2017/7/31.
*/
@Spi(scope = Scope.SINGLETON)
public interface HeartBeatFactory {
/**
* 创建心跳包
*/
Request createRequest();
/**
* 心跳响应
*/
HeartBeat createHeartBeat(MergeConfig config);
}
|
92355e0e1f68b90252ffa43c8e6fe7ba8d5eb4cd | 502 | java | Java | src/test/resources/test-input/StringLengthSort.java | picadoh/imc | b8d1d2d2862c3fd1aa72945df1d1a194af73be1d | [
"MIT"
] | 12 | 2016-10-05T00:51:53.000Z | 2021-10-18T01:50:04.000Z | src/test/resources/test-input/StringLengthSort.java | picadoh/imc | b8d1d2d2862c3fd1aa72945df1d1a194af73be1d | [
"MIT"
] | 2 | 2018-08-31T08:14:48.000Z | 2020-06-30T12:01:52.000Z | src/test/resources/test-input/StringLengthSort.java | picadoh/imc | b8d1d2d2862c3fd1aa72945df1d1a194af73be1d | [
"MIT"
] | 6 | 2018-01-21T12:24:12.000Z | 2020-10-16T08:27:10.000Z | 27.888889 | 60 | 0.603586 | 997,279 | import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class StringLengthSort {
public void sort(List<String> strings) {
Collections.sort(strings, new Comparator<String>() {
@Override
public int compare(String left, String right) {
Integer leftLength = left.length();
Integer rightLength = right.length();
return leftLength.compareTo(rightLength);
}
});
}
} |
92355f3016a41cee2399e9bb2e626f34bbb58d81 | 1,171 | java | Java | core/src/main/java/org/narrative/network/core/versioning/PatchRunnerLock.java | NarrativeCompany/narrative | 84829f0178a0b34d4efc5b7dfa82a8929b5b06b5 | [
"MIT"
] | 8 | 2020-01-08T20:13:42.000Z | 2020-06-19T23:10:17.000Z | core/src/main/java/org/narrative/network/core/versioning/PatchRunnerLock.java | NarrativeCompany/narrative | 84829f0178a0b34d4efc5b7dfa82a8929b5b06b5 | [
"MIT"
] | 5 | 2020-01-09T17:49:55.000Z | 2020-06-15T19:31:04.000Z | core/src/main/java/org/narrative/network/core/versioning/PatchRunnerLock.java | NarrativeCompany/narrative | 84829f0178a0b34d4efc5b7dfa82a8929b5b06b5 | [
"MIT"
] | 5 | 2020-01-09T02:01:47.000Z | 2021-06-01T13:34:46.000Z | 22.960784 | 71 | 0.719898 | 997,280 | package org.narrative.network.core.versioning;
import org.narrative.common.persistence.DAOObject;
import org.narrative.common.persistence.OID;
import org.narrative.network.core.versioning.dao.PatchRunnerLockDAO;
import org.narrative.network.shared.daobase.NetworkDAOImpl;
import org.hibernate.annotations.Cache;
import org.hibernate.annotations.CacheConcurrencyStrategy;
import org.hibernate.annotations.Proxy;
import javax.persistence.Entity;
import javax.persistence.Id;
/**
* Date: Mar 24, 2010
* Time: 8:27:51 AM
*
* @author brian
*/
@Entity
@Proxy
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
public class PatchRunnerLock implements DAOObject<PatchRunnerLockDAO> {
public static final OID LOCK_OID = new OID(1L);
private OID oid;
/**
* @deprecated for hibernate use only
*/
public PatchRunnerLock() {}
public PatchRunnerLock(OID oid) {
this.oid = oid;
}
@Id
public OID getOid() {
return oid;
}
public void setOid(OID oid) {
this.oid = oid;
}
public static PatchRunnerLockDAO dao() {
return NetworkDAOImpl.getDAO(PatchRunnerLock.class);
}
}
|
92355f5785376d39bdd73a45c1c1022e8185916f | 1,678 | java | Java | java/year-service/src/main/java/io/honeycomb/examples/javaotlp/YearController.java | honeycombio/example-greeting-service | 52365a5f2ae434d0b3a84b10889486184042cbc3 | [
"Apache-2.0"
] | 8 | 2020-12-29T17:44:16.000Z | 2021-11-18T22:18:42.000Z | java/year-service/src/main/java/io/honeycomb/examples/javaotlp/YearController.java | honeycombio/example-greeting-service | 52365a5f2ae434d0b3a84b10889486184042cbc3 | [
"Apache-2.0"
] | 36 | 2021-04-08T14:30:02.000Z | 2022-03-30T22:06:44.000Z | java/year-service/src/main/java/io/honeycomb/examples/javaotlp/YearController.java | honeycombio/example-greeting-service | 52365a5f2ae434d0b3a84b10889486184042cbc3 | [
"Apache-2.0"
] | 1 | 2021-04-05T10:52:23.000Z | 2021-04-05T10:52:23.000Z | 35.702128 | 92 | 0.687128 | 997,281 | package io.honeycomb.examples.javaotlp;
import io.opentelemetry.context.Context;
import io.opentelemetry.context.Scope;
import io.opentelemetry.context.propagation.ContextPropagators;
import io.opentelemetry.context.propagation.TextMapGetter;
import io.opentelemetry.context.propagation.TextMapPropagator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.lang.Nullable;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.Map;
import static io.opentelemetry.api.GlobalOpenTelemetry.getPropagators;
@RestController
public class YearController {
@Autowired
private YearService yearService;
@RequestMapping("/year")
public String index(@RequestHeader Map<String, String> headers) {
final ContextPropagators propagators = getPropagators();
TextMapPropagator propagator = propagators.getTextMapPropagator();
Context ctx = propagator.extract(Context.current(), headers, new TextMapGetter<>() {
@Override
public Iterable<String> keys(Map<String, String> carrier) {
return carrier.keySet();
}
@Override
public String get(@Nullable Map<String, String> carrier, String key) {
if (carrier != null) {
return carrier.get(key);
} else {
return null;
}
}
});
try (Scope ignored = ctx.makeCurrent()) {
return yearService.getYear();
}
}
}
|
92355f6fd944dc61af616016a42c1a3f65bc8ed2 | 2,346 | java | Java | android/PayTabsSample/obj/Debug/110/android/src/mono/com/paytabs/paytabscardrecognizer/cards/pay/paycardsrecognizer/sdk/ndk/RecognitionStatusListenerImplementor.java | amr-Magdy-PT/xamarin-paytabs-binding | ab29ba464276fe3689f77f1d7f619c8e5e9fbf02 | [
"MIT"
] | null | null | null | android/PayTabsSample/obj/Debug/110/android/src/mono/com/paytabs/paytabscardrecognizer/cards/pay/paycardsrecognizer/sdk/ndk/RecognitionStatusListenerImplementor.java | amr-Magdy-PT/xamarin-paytabs-binding | ab29ba464276fe3689f77f1d7f619c8e5e9fbf02 | [
"MIT"
] | 1 | 2022-03-03T08:43:49.000Z | 2022-03-03T08:43:49.000Z | android/PayTabsSample/obj/Debug/110/android/src/mono/com/paytabs/paytabscardrecognizer/cards/pay/paycardsrecognizer/sdk/ndk/RecognitionStatusListenerImplementor.java | amr-Magdy-PT/xamarin-paytabs-binding | ab29ba464276fe3689f77f1d7f619c8e5e9fbf02 | [
"MIT"
] | 1 | 2022-03-13T15:40:15.000Z | 2022-03-13T15:40:15.000Z | 40.448276 | 374 | 0.820972 | 997,282 | package mono.com.paytabs.paytabscardrecognizer.cards.pay.paycardsrecognizer.sdk.ndk;
public class RecognitionStatusListenerImplementor
extends java.lang.Object
implements
mono.android.IGCUserPeer,
com.paytabs.paytabscardrecognizer.cards.pay.paycardsrecognizer.sdk.ndk.RecognitionStatusListener
{
/** @hide */
public static final String __md_methods;
static {
__md_methods =
"n_onCardImageReceived:(Landroid/graphics/Bitmap;)V:GetOnCardImageReceived_Landroid_graphics_Bitmap_Handler:Com.Paytabs.Paytabscardrecognizer.Cards.Pay.Paycardsrecognizer.Sdk.Ndk.IRecognitionStatusListenerInvoker, CardScanBindingLib\n" +
"n_onRecognitionComplete:(Lcom/paytabs/paytabscardrecognizer/cards/pay/paycardsrecognizer/sdk/ndk/RecognitionResult;)V:GetOnRecognitionComplete_Lcom_paytabs_paytabscardrecognizer_cards_pay_paycardsrecognizer_sdk_ndk_RecognitionResult_Handler:Com.Paytabs.Paytabscardrecognizer.Cards.Pay.Paycardsrecognizer.Sdk.Ndk.IRecognitionStatusListenerInvoker, CardScanBindingLib\n" +
"";
mono.android.Runtime.register ("Com.Paytabs.Paytabscardrecognizer.Cards.Pay.Paycardsrecognizer.Sdk.Ndk.IRecognitionStatusListenerImplementor, CardScanBindingLib", RecognitionStatusListenerImplementor.class, __md_methods);
}
public RecognitionStatusListenerImplementor ()
{
super ();
if (getClass () == RecognitionStatusListenerImplementor.class)
mono.android.TypeManager.Activate ("Com.Paytabs.Paytabscardrecognizer.Cards.Pay.Paycardsrecognizer.Sdk.Ndk.IRecognitionStatusListenerImplementor, CardScanBindingLib", "", this, new java.lang.Object[] { });
}
public void onCardImageReceived (android.graphics.Bitmap p0)
{
n_onCardImageReceived (p0);
}
private native void n_onCardImageReceived (android.graphics.Bitmap p0);
public void onRecognitionComplete (com.paytabs.paytabscardrecognizer.cards.pay.paycardsrecognizer.sdk.ndk.RecognitionResult p0)
{
n_onRecognitionComplete (p0);
}
private native void n_onRecognitionComplete (com.paytabs.paytabscardrecognizer.cards.pay.paycardsrecognizer.sdk.ndk.RecognitionResult p0);
private java.util.ArrayList refList;
public void monodroidAddReference (java.lang.Object obj)
{
if (refList == null)
refList = new java.util.ArrayList ();
refList.add (obj);
}
public void monodroidClearReferences ()
{
if (refList != null)
refList.clear ();
}
}
|
923564e7186a64b2d7cd1d778d1ba3eb1ae6efd0 | 351 | java | Java | app/src/main/java/com/zzh/simplenews/data/RepositoryComponent.java | PlexPt/SimpleNews | eb27c44c7006de897bddc0e7ab65ff4ad4eb299a | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/zzh/simplenews/data/RepositoryComponent.java | PlexPt/SimpleNews | eb27c44c7006de897bddc0e7ab65ff4ad4eb299a | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/zzh/simplenews/data/RepositoryComponent.java | PlexPt/SimpleNews | eb27c44c7006de897bddc0e7ab65ff4ad4eb299a | [
"Apache-2.0"
] | null | null | null | 23.4 | 93 | 0.792023 | 997,283 | package com.zzh.simplenews.data;
import com.zzh.simplenews.data.remote.RemoteRepositoryComponent;
import dagger.Component;
/**
* Created by zzh on 16/6/8.
*/
@RepositoryScope
@Component(dependencies = RemoteRepositoryComponent.class , modules = RepositoryModule.class)
public interface RepositoryComponent {
Repository provideRepository();
}
|
923566124990aba94011d8275608da4aba27663d | 7,348 | java | Java | part-2/week-7/week7-week7_06.PromissoryNote/test/PromissoryNoteTest.java | rohansachdeva1990/helsinki-mooc-oo-java | a732c2f600bf0da514f57ccb52e3826704fbb3a2 | [
"MIT"
] | 2 | 2017-07-08T00:47:25.000Z | 2017-08-03T04:22:43.000Z | 2013-OOProgrammingWithJava-PART2/week7-week7_06.PromissoryNote/test/PromissoryNoteTest.java | gengwg/java_mooc_fi | 041d5dbf57dfe89d1eb963b7581b95b20ef4e118 | [
"Apache-2.0"
] | null | null | null | 2013-OOProgrammingWithJava-PART2/week7-week7_06.PromissoryNote/test/PromissoryNoteTest.java | gengwg/java_mooc_fi | 041d5dbf57dfe89d1eb963b7581b95b20ef4e118 | [
"Apache-2.0"
] | null | null | null | 39.294118 | 240 | 0.616766 | 997,284 |
import fi.helsinki.cs.tmc.edutestutils.Points;
import fi.helsinki.cs.tmc.edutestutils.ReflectionUtils;
import fi.helsinki.cs.tmc.edutestutils.Reflex;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import static org.junit.Assert.*;
import org.junit.Before;
import org.junit.Test;
@Points("6")
public class PromissoryNoteTest {
String klassName = "PromissoryNote";
Reflex.ClassRef<Object> klass;
@Before
public void setup() {
klass = Reflex.reflect(klassName);
}
@Test
public void classIsPublic() {
assertTrue("Class " + klassName + " should be public, so it must be defined as\npublic class " + klassName + " {...\n}", klass.isPublic());
}
@Test
public void noRedundantVariables() {
saniteettitarkastus(klassName, 1, "an instance variable of type HashMap<String,Double> to keep track of debts");
}
@Test
public void isHashMap() {
Field[] kentat = ReflectionUtils.findClass(klassName).getDeclaredFields();
assertTrue("Add to "+klassName+" an instance variable of type HashMap<String, Double>", kentat.length==1 );
assertTrue("Class "+klassName+" should have an instance variable of type Map<String, Double>", kentat[0].toString().contains("Map"));
}
@Test
public void testConstructor() throws Throwable {
Reflex.MethodRef0<Object, Object> ctor = klass.constructor().takingNoParams().withNiceError();
assertTrue("Define for " + klassName + " a public constructor: public " + klassName + "()", ctor.isPublic());
String v = "Error caused by code new PromissoryNote();";
ctor.withNiceError(v).invoke();
}
public Object luo() throws Throwable {
Reflex.MethodRef0<Object, Object> ctor = klass.constructor().takingNoParams().withNiceError();
return ctor.invoke();
}
@Test
public void setLoan() throws Throwable {
String metodi = "setLoan";
Object olio = luo();
assertTrue("Create method public void " + metodi + "(String toWhom, double value) for class " + klassName,
klass.method(olio, metodi)
.returningVoid().taking(String.class, double.class).isPublic());
String v = "\nError caused by code PromissoryNote debts = new PromissoryNote(); "
+ "v.setLoan(\"Pekka\", 5.0);";
klass.method(olio, metodi)
.returningVoid().taking(String.class, double.class).withNiceError(v).invoke("Pekka", 5.0);
}
@Test
public void howMuchIsTheDebt() throws Throwable {
String metodi = "howMuchIsTheDebt";
Object olio = luo();
assertTrue("Create method " + metodi + "(String whose) for class " + klassName,
klass.method(olio, metodi)
.returning(double.class).taking(String.class).isPublic());
String v = "\nError caused by code PromissoryNote debts = new PromissoryNote(); "
+ "v.howMuchIsTheDebt(\"Pekka\");";
klass.method(olio, metodi)
.returning(double.class).taking(String.class).withNiceError(v).invoke("Pekka");
}
@Test
public void testPromissoryNote() throws Exception {
Object velkakirja = luoPromissoryNote();
testaaVelka(velkakirja, "Arto", 919.83);
testaaVelka(velkakirja, "Matti", 32.1);
testaaVelka(velkakirja, "Joel", -5);
testaaAsettamatonVelka(velkakirja, "Mikael");
}
private void testaaVelka(Object velkakirja, String kenelle, double maara) {
setLoan(velkakirja, kenelle, maara);
double velka = howMuchIsTheDebt(velkakirja, kenelle);
if (velka <= (maara - 0.1) || velka >= (maara + 0.1)) {
fail("Person " + kenelle + " was set to have a loan of " + maara
+ ", but returned debt was: " + velka);
}
}
private void testaaAsettamatonVelka(Object velkakirja, String kenelle) {
double velka = howMuchIsTheDebt(velkakirja, kenelle);
if (velka != 0) {
fail("Person " + kenelle + " wasn't set to have any loan, "
+ "but returned debt was: " + velka);
}
}
private Object luoPromissoryNote() throws Exception {
return Class.forName("PromissoryNote").getConstructor().newInstance();
}
private void setLoan(Object velkakirja, String kenelle, double maara) {
Method metodi;
try {
metodi = velkakirja.getClass().getMethod("setLoan", String.class, double.class);
} catch (Exception e) {
fail("Class PromissoryNote doesn't have method: public void setLoan(String toWhom, double value).");
return;
}
if (!metodi.getReturnType().equals(void.class)) {
fail("PromissoryNote's method setLoan(String toWhom, double value) shouldn't have a return value.");
return;
}
try {
metodi.invoke(velkakirja, kenelle, maara);
} catch (Exception e) {
fail("There happened an exception in PromissoryNote's method setLoan: " + e.toString());
}
}
private double howMuchIsTheDebt(Object velkakirja, String kuka) {
Method metodi;
try {
metodi = velkakirja.getClass().getMethod("howMuchIsTheDebt", String.class);
} catch (Exception e) {
fail("PromissoryNote doesn't have method: public double howMuchIsTheDebt(String whose).");
return -1;
}
if (!metodi.getReturnType().equals(double.class)) {
fail("PromissoryNote's method howMuchIsTheDebt(String whose) should return a value of type double.");
return -1;
}
try {
return (Double) metodi.invoke(velkakirja, kuka);
} catch (java.lang.reflect.InvocationTargetException e) {
fail("Check that null-references aren't tried to change to variables of primitive data type.");
return -1;
} catch (Exception e) {
fail("There happened an exception in PromissoryNote's method howMuchIsTheDebt: " + e.toString());
return -1;
}
}
private void saniteettitarkastus(String klassName, int n, String m) throws SecurityException {
Field[] kentat = ReflectionUtils.findClass(klassName).getDeclaredFields();
for (Field field : kentat) {
assertFalse("you do not need \"static variables\", remove from class " + klassName + " the following variable: " + kentta(field.toString(), klassName), field.toString().contains("static") && !field.toString().contains("final"));
assertTrue("All instance variables should be private but class " + klassName + " had: " + kentta(field.toString(), klassName), field.toString().contains("private"));
}
if (kentat.length > 1) {
int var = 0;
for (Field field : kentat) {
if (!field.toString().contains("final")) {
var++;
}
}
assertTrue("The class " + klassName + " should only have " + m + ", remove others", var <= n);
}
}
private String kentta(String toString, String klassName) {
return toString.replace(klassName + ".", "").replace("java.lang.", "").replace("java.util.", "");
}
}
|
92356644355e46be6233efe9d43a8cc667dfb119 | 1,512 | java | Java | registry-pipelines/src/main/java/pro/biocontainers/pipelines/jobs/AbstractJob.java | chakrabandla/registry-backend | f536195bd046f57dad09535bab28e5d59ab1fe6c | [
"Apache-2.0"
] | null | null | null | registry-pipelines/src/main/java/pro/biocontainers/pipelines/jobs/AbstractJob.java | chakrabandla/registry-backend | f536195bd046f57dad09535bab28e5d59ab1fe6c | [
"Apache-2.0"
] | 9 | 2018-07-26T01:12:00.000Z | 2018-09-30T15:31:03.000Z | registry-pipelines/src/main/java/pro/biocontainers/pipelines/jobs/AbstractJob.java | chakrabandla/registry-backend | f536195bd046f57dad09535bab28e5d59ab1fe6c | [
"Apache-2.0"
] | 1 | 2018-07-23T16:38:04.000Z | 2018-07-23T16:38:04.000Z | 32.212766 | 85 | 0.791942 | 997,285 | package pro.biocontainers.pipelines.jobs;
import lombok.extern.slf4j.Slf4j;
import org.springframework.batch.core.configuration.annotation.EnableBatchProcessing;
import org.springframework.batch.core.configuration.annotation.JobBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepBuilderFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
/**
* This code is licensed under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* ==Overview==
* <p>
*
* This class create the default Job and Step handler for every job.
*
* <p>
* Created by ypriverol (kenaa@example.com) on 05/06/2018.
*/
@Configuration
@Slf4j
@EnableBatchProcessing
public class AbstractJob{
@SuppressWarnings("SpringJavaAutowiredFieldsWarningInspection")
@Autowired
protected JobBuilderFactory jobBuilderFactory;
@SuppressWarnings("SpringJavaAutowiredFieldsWarningInspection")
@Autowired
protected StepBuilderFactory stepBuilderFactory;
@Bean
public static PropertySourcesPlaceholderConfigurer propertyConfigInDev() {
return new PropertySourcesPlaceholderConfigurer();
}
}
|
923566903a369b0e9e5747254a7083ea4cb425c4 | 2,289 | java | Java | drools-verifier/src/main/java/org/drools/verifier/components/VerifierAccumulateDescr.java | bobmcwhirter/drools | 62a0a5907ca1f4505cea2f4c55302da846b1cc75 | [
"Apache-2.0"
] | 13 | 2016-05-08T12:40:40.000Z | 2017-01-09T05:02:36.000Z | drools-verifier/src/main/java/org/drools/verifier/components/VerifierAccumulateDescr.java | rapidan/drools | 62a0a5907ca1f4505cea2f4c55302da846b1cc75 | [
"Apache-2.0"
] | 7 | 2020-06-30T23:18:02.000Z | 2022-02-01T01:05:08.000Z | drools-verifier/src/main/java/org/drools/verifier/components/VerifierAccumulateDescr.java | rapidan/drools | 62a0a5907ca1f4505cea2f4c55302da846b1cc75 | [
"Apache-2.0"
] | 6 | 2015-12-04T06:09:37.000Z | 2019-07-19T07:20:44.000Z | 20.4375 | 65 | 0.721713 | 997,286 | package org.drools.verifier.components;
/**
*
* @author Toni Rikkola
*/
public class VerifierAccumulateDescr extends VerifierComponent {
private static int index = 0;
private int inputPatternId;
private String initCode;
private String actionCode;
private String reverseCode;
private String resultCode;
private String[] declarations;
private String className;
private boolean externalFunction = false;
private String functionIdentifier;
private String expression;
public VerifierAccumulateDescr() {
super(index++);
}
@Override
public VerifierComponentType getComponentType() {
return VerifierComponentType.ACCUMULATE;
}
public String getActionCode() {
return actionCode;
}
public void setActionCode(String actionCode) {
this.actionCode = actionCode;
}
public String getClassName() {
return className;
}
public void setClassName(String className) {
this.className = className;
}
public String[] getDeclarations() {
return declarations;
}
public void setDeclarations(String[] declarations) {
this.declarations = declarations;
}
public String getExpression() {
return expression;
}
public void setExpression(String expression) {
this.expression = expression;
}
public boolean isExternalFunction() {
return externalFunction;
}
public void setExternalFunction(boolean externalFunction) {
this.externalFunction = externalFunction;
}
public String getFunctionIdentifier() {
return functionIdentifier;
}
public void setFunctionIdentifier(String functionIdentifier) {
this.functionIdentifier = functionIdentifier;
}
public String getInitCode() {
return initCode;
}
public void setInitCode(String initCode) {
this.initCode = initCode;
}
public int getInputPatternId() {
return inputPatternId;
}
public void setInputPatternId(int inputPatternId) {
this.inputPatternId = inputPatternId;
}
public String getResultCode() {
return resultCode;
}
public void setResultCode(String resultCode) {
this.resultCode = resultCode;
}
public String getReverseCode() {
return reverseCode;
}
public void setReverseCode(String reverseCode) {
this.reverseCode = reverseCode;
}
}
|
923566cc15344a811294e92771439c09307261a1 | 5,866 | java | Java | services/cloudbuild/src/main/java/com/huaweicloud/sdk/cloudbuild/v3/CloudBuildClient.java | huaweicloud/huaweicloud-sdk-java-v3 | a01cd21a3d03f6dffc807bea7c522e34adfa368d | [
"Apache-2.0"
] | 50 | 2020-05-18T11:35:20.000Z | 2022-03-15T02:07:05.000Z | services/cloudbuild/src/main/java/com/huaweicloud/sdk/cloudbuild/v3/CloudBuildClient.java | huaweicloud/huaweicloud-sdk-java-v3 | a01cd21a3d03f6dffc807bea7c522e34adfa368d | [
"Apache-2.0"
] | 45 | 2020-07-06T03:34:12.000Z | 2022-03-31T09:41:54.000Z | services/cloudbuild/src/main/java/com/huaweicloud/sdk/cloudbuild/v3/CloudBuildClient.java | huaweicloud/huaweicloud-sdk-java-v3 | a01cd21a3d03f6dffc807bea7c522e34adfa368d | [
"Apache-2.0"
] | 27 | 2020-05-28T11:08:44.000Z | 2022-03-30T03:30:37.000Z | 40.736111 | 120 | 0.756904 | 997,287 | package com.huaweicloud.sdk.cloudbuild.v3;
import com.huaweicloud.sdk.cloudbuild.v3.model.*;
import com.huaweicloud.sdk.core.ClientBuilder;
import com.huaweicloud.sdk.core.HcClient;
import com.huaweicloud.sdk.core.invoker.SyncInvoker;
public class CloudBuildClient {
protected HcClient hcClient;
public CloudBuildClient(HcClient hcClient) {
this.hcClient = hcClient;
}
public static ClientBuilder<CloudBuildClient> newBuilder() {
return new ClientBuilder<>(CloudBuildClient::new);
}
/** KeyStore文件下载 下载指定租户下的KeyStore文件
*
* @param DownloadKeystoreRequest 请求对象
* @return DownloadKeystoreResponse */
public DownloadKeystoreResponse downloadKeystore(DownloadKeystoreRequest request) {
return hcClient.syncInvokeHttp(request, CloudBuildMeta.downloadKeystore);
}
/** KeyStore文件下载 下载指定租户下的KeyStore文件
*
* @param DownloadKeystoreRequest 请求对象
* @return SyncInvoker<DownloadKeystoreRequest, DownloadKeystoreResponse> */
public SyncInvoker<DownloadKeystoreRequest, DownloadKeystoreResponse> downloadKeystoreInvoker(
DownloadKeystoreRequest request) {
return new SyncInvoker<DownloadKeystoreRequest, DownloadKeystoreResponse>(request,
CloudBuildMeta.downloadKeystore, hcClient);
}
/** 执行构建任务 执行构建任务,可传自定义参数。
*
* @param RunJobRequest 请求对象
* @return RunJobResponse */
public RunJobResponse runJob(RunJobRequest request) {
return hcClient.syncInvokeHttp(request, CloudBuildMeta.runJob);
}
/** 执行构建任务 执行构建任务,可传自定义参数。
*
* @param RunJobRequest 请求对象
* @return SyncInvoker<RunJobRequest, RunJobResponse> */
public SyncInvoker<RunJobRequest, RunJobResponse> runJobInvoker(RunJobRequest request) {
return new SyncInvoker<RunJobRequest, RunJobResponse>(request, CloudBuildMeta.runJob, hcClient);
}
/** 查看项目下用户的构建任务列表 查看项目下用户的构建任务列表
*
* @param ShowJobListByProjectIdRequest 请求对象
* @return ShowJobListByProjectIdResponse */
public ShowJobListByProjectIdResponse showJobListByProjectId(ShowJobListByProjectIdRequest request) {
return hcClient.syncInvokeHttp(request, CloudBuildMeta.showJobListByProjectId);
}
/** 查看项目下用户的构建任务列表 查看项目下用户的构建任务列表
*
* @param ShowJobListByProjectIdRequest 请求对象
* @return SyncInvoker<ShowJobListByProjectIdRequest, ShowJobListByProjectIdResponse> */
public SyncInvoker<ShowJobListByProjectIdRequest, ShowJobListByProjectIdResponse> showJobListByProjectIdInvoker(
ShowJobListByProjectIdRequest request) {
return new SyncInvoker<ShowJobListByProjectIdRequest, ShowJobListByProjectIdResponse>(request,
CloudBuildMeta.showJobListByProjectId, hcClient);
}
/** 查看任务运行状态 查看任务运行状态
*
* @param ShowJobStatusRequest 请求对象
* @return ShowJobStatusResponse */
public ShowJobStatusResponse showJobStatus(ShowJobStatusRequest request) {
return hcClient.syncInvokeHttp(request, CloudBuildMeta.showJobStatus);
}
/** 查看任务运行状态 查看任务运行状态
*
* @param ShowJobStatusRequest 请求对象
* @return SyncInvoker<ShowJobStatusRequest, ShowJobStatusResponse> */
public SyncInvoker<ShowJobStatusRequest, ShowJobStatusResponse> showJobStatusInvoker(ShowJobStatusRequest request) {
return new SyncInvoker<ShowJobStatusRequest, ShowJobStatusResponse>(request, CloudBuildMeta.showJobStatus,
hcClient);
}
/** 查询指定代码仓库最近一次成功的构建历史 查询指定代码仓库最近一次成功的构建历史
*
* @param ShowLastHistoryRequest 请求对象
* @return ShowLastHistoryResponse */
public ShowLastHistoryResponse showLastHistory(ShowLastHistoryRequest request) {
return hcClient.syncInvokeHttp(request, CloudBuildMeta.showLastHistory);
}
/** 查询指定代码仓库最近一次成功的构建历史 查询指定代码仓库最近一次成功的构建历史
*
* @param ShowLastHistoryRequest 请求对象
* @return SyncInvoker<ShowLastHistoryRequest, ShowLastHistoryResponse> */
public SyncInvoker<ShowLastHistoryRequest, ShowLastHistoryResponse> showLastHistoryInvoker(
ShowLastHistoryRequest request) {
return new SyncInvoker<ShowLastHistoryRequest, ShowLastHistoryResponse>(request, CloudBuildMeta.showLastHistory,
hcClient);
}
/** 查看构建任务的构建历史列表 查看构建任务的构建历史列表
*
* @param ShowListHistoryRequest 请求对象
* @return ShowListHistoryResponse */
public ShowListHistoryResponse showListHistory(ShowListHistoryRequest request) {
return hcClient.syncInvokeHttp(request, CloudBuildMeta.showListHistory);
}
/** 查看构建任务的构建历史列表 查看构建任务的构建历史列表
*
* @param ShowListHistoryRequest 请求对象
* @return SyncInvoker<ShowListHistoryRequest, ShowListHistoryResponse> */
public SyncInvoker<ShowListHistoryRequest, ShowListHistoryResponse> showListHistoryInvoker(
ShowListHistoryRequest request) {
return new SyncInvoker<ShowListHistoryRequest, ShowListHistoryResponse>(request, CloudBuildMeta.showListHistory,
hcClient);
}
/** 根据开始时间和结束时间查看构建任务的构建历史列表 根据开始时间和结束时间查看构建任务的构建历史列表
*
* @param ShowListPeriodHistoryRequest 请求对象
* @return ShowListPeriodHistoryResponse */
public ShowListPeriodHistoryResponse showListPeriodHistory(ShowListPeriodHistoryRequest request) {
return hcClient.syncInvokeHttp(request, CloudBuildMeta.showListPeriodHistory);
}
/** 根据开始时间和结束时间查看构建任务的构建历史列表 根据开始时间和结束时间查看构建任务的构建历史列表
*
* @param ShowListPeriodHistoryRequest 请求对象
* @return SyncInvoker<ShowListPeriodHistoryRequest, ShowListPeriodHistoryResponse> */
public SyncInvoker<ShowListPeriodHistoryRequest, ShowListPeriodHistoryResponse> showListPeriodHistoryInvoker(
ShowListPeriodHistoryRequest request) {
return new SyncInvoker<ShowListPeriodHistoryRequest, ShowListPeriodHistoryResponse>(request,
CloudBuildMeta.showListPeriodHistory, hcClient);
}
}
|
923566d27957167f5da3804f5a55fdfccbb11fc5 | 354 | java | Java | clients/java-pkmst/generated/src/test/java/com/prokarma/pkmst/cucumber/PkmstTest.java | hoomaan-kh/swagger-aem | 0b19225bb6e071df761d176cbc13565891fe895f | [
"Apache-2.0"
] | 39 | 2016-10-02T06:45:12.000Z | 2021-09-08T20:39:53.000Z | clients/java-pkmst/generated/src/test/java/com/prokarma/pkmst/cucumber/PkmstTest.java | hoomaan-kh/swagger-aem | 0b19225bb6e071df761d176cbc13565891fe895f | [
"Apache-2.0"
] | 35 | 2017-06-14T03:28:15.000Z | 2022-02-14T10:25:54.000Z | clients/java-pkmst/generated/src/test/java/com/prokarma/pkmst/cucumber/PkmstTest.java | hoomaan-kh/swagger-aem | 0b19225bb6e071df761d176cbc13565891fe895f | [
"Apache-2.0"
] | 23 | 2016-11-07T04:14:42.000Z | 2021-02-15T09:49:13.000Z | 27.230769 | 73 | 0.79661 | 997,288 | package com.prokarma.pkmst.cucumber;
import org.junit.runner.RunWith;
import org.springframework.test.context.ActiveProfiles;
import cucumber.api.CucumberOptions;
import cucumber.api.junit.Cucumber;
@RunWith(Cucumber.class)
@ActiveProfiles("test")
@CucumberOptions(format = { "pretty", "html:target/cucumber-html-report",
})
public class PkmstTest {
} |
923568f7039e3a6505468d050b23405fa2b39476 | 2,196 | java | Java | src/main/java/ubc/pavlab/ndb/beans/PublicationsView.java | JacobsonMT/ndb | 259a94bca90038ae5ec77dd7cf2095dfcd826acf | [
"Apache-2.0"
] | 3 | 2016-01-18T23:49:55.000Z | 2017-01-26T18:46:07.000Z | src/main/java/ubc/pavlab/ndb/beans/PublicationsView.java | JacobsonMT/ndb | 259a94bca90038ae5ec77dd7cf2095dfcd826acf | [
"Apache-2.0"
] | 46 | 2015-11-19T23:16:31.000Z | 2017-11-15T23:44:08.000Z | src/main/java/ubc/pavlab/ndb/beans/PublicationsView.java | PavlidisLab/ndb | 319b5e8d43633b45d026a0ffe7b05bedaf77baf2 | [
"Apache-2.0"
] | null | null | null | 25.241379 | 90 | 0.686703 | 997,289 | package ubc.pavlab.ndb.beans;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import org.apache.log4j.Logger;
import ubc.pavlab.ndb.beans.services.CacheService;
import ubc.pavlab.ndb.beans.services.StatsService;
import ubc.pavlab.ndb.model.Paper;
@ManagedBean
@ViewScoped
public class PublicationsView implements Serializable {
/**
*
*/
private static final long serialVersionUID = -401169062920170155L;
private static final Logger log = Logger.getLogger( PublicationsView.class );
@ManagedProperty("#{cacheService}")
private CacheService cacheService;
@ManagedProperty("#{statsService}")
private StatsService statsService;
private List<Paper> papers;
private List<Paper> filteredPapers;
public PublicationsView() {
log.info( "create PublicationsView" );
}
@PostConstruct
public void init() {
if ( FacesContext.getCurrentInstance().getPartialViewContext().isAjaxRequest() ) {
return; // Skip ajax requests.
}
log.info( "init PublicationsView" );
setPapers( new ArrayList<>( cacheService.listPapers() ) );
}
public void setCacheService( CacheService cacheService ) {
this.cacheService = cacheService;
}
public void setStatsService( StatsService statsService ) {
this.statsService = statsService;
}
/**
* @return the papers
*/
public List<Paper> getPapers() {
return papers;
}
/**
* @param papers the papers to set
*/
public void setPapers( List<Paper> papers ) {
this.papers = papers;
}
public List<Paper> getFilteredPapers() {
return filteredPapers;
}
public void setFilteredPapers(List<Paper> filteredPapers) {
this.filteredPapers = filteredPapers;
}
public Integer getEventCnt(Integer paperId) {
Integer eventCnt = statsService.getEventCntByPaperId( paperId );
return eventCnt;
}
} |
9235691ca48215620aa613b0f71e0d779852c88c | 10,775 | java | Java | src/main/java/org/scify/jedai/blockprocessing/blockcleaning/BlockFiltering.java | allan-shoup/JedAIToolkit | 1fafb9f708697ad529642f353c4f4d29985453ad | [
"Apache-2.0"
] | 173 | 2017-01-30T09:17:58.000Z | 2022-03-04T11:14:40.000Z | src/main/java/org/scify/jedai/blockprocessing/blockcleaning/BlockFiltering.java | allan-shoup/JedAIToolkit | 1fafb9f708697ad529642f353c4f4d29985453ad | [
"Apache-2.0"
] | 40 | 2017-01-03T09:52:55.000Z | 2021-11-04T10:58:44.000Z | src/main/java/org/scify/jedai/blockprocessing/blockcleaning/BlockFiltering.java | allan-shoup/JedAIToolkit | 1fafb9f708697ad529642f353c4f4d29985453ad | [
"Apache-2.0"
] | 38 | 2017-10-10T02:36:43.000Z | 2022-03-11T16:28:13.000Z | 35.678808 | 134 | 0.586265 | 997,290 | /*
* Copyright [2016-2020] [George Papadakis (dycjh@example.com)]
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.scify.jedai.blockprocessing.blockcleaning;
import com.esotericsoftware.minlog.Log;
import gnu.trove.iterator.TIntIterator;
import gnu.trove.list.TIntList;
import gnu.trove.list.array.TIntArrayList;
import org.apache.jena.atlas.json.JsonArray;
import org.apache.jena.atlas.json.JsonObject;
import org.scify.jedai.blockprocessing.AbstractBlockProcessing;
import org.scify.jedai.configuration.gridsearch.DblGridSearchConfiguration;
import org.scify.jedai.configuration.randomsearch.DblRandomSearchConfiguration;
import org.scify.jedai.datamodel.AbstractBlock;
import org.scify.jedai.datamodel.BilateralBlock;
import org.scify.jedai.datamodel.UnilateralBlock;
import org.scify.jedai.utilities.comparators.IncBlockCardinalityComparator;
import java.util.ArrayList;
import java.util.List;
/**
*
* @author gap2
*/
public class BlockFiltering extends AbstractBlockProcessing {
protected float ratio;
protected int entitiesD1;
protected int entitiesD2;
protected int[] counterD1;
protected int[] counterD2;
protected int[] limitsD1;
protected int[] limitsD2;
protected final DblGridSearchConfiguration gridRatio;
protected final DblRandomSearchConfiguration randomRatio;
public BlockFiltering() {
this(0.8f);
}
public BlockFiltering(float r) {
ratio = r;
gridRatio = new DblGridSearchConfiguration(1.0f, 0.025f, 0.025f);
randomRatio = new DblRandomSearchConfiguration(1.0f, 0.01f);
}
protected void countEntities(List<AbstractBlock> blocks) {
entitiesD1 = Integer.MIN_VALUE;
entitiesD2 = Integer.MIN_VALUE;
if (blocks.get(0) instanceof BilateralBlock) {
blocks.stream().map((block) -> (BilateralBlock) block).map((bilBlock) -> {
for (int id1 : bilBlock.getIndex1Entities()) {
if (entitiesD1 < id1 + 1) {
entitiesD1 = id1 + 1;
}
}
return bilBlock;
}).forEachOrdered((bilBlock) -> {
for (int id2 : bilBlock.getIndex2Entities()) {
if (entitiesD2 < id2 + 1) {
entitiesD2 = id2 + 1;
}
}
});
} else if (blocks.get(0) instanceof UnilateralBlock) {
blocks.stream().map((block) -> (UnilateralBlock) block).forEachOrdered((uniBlock) -> {
for (int id : uniBlock.getEntities()) {
if (entitiesD1 < id + 1) {
entitiesD1 = id + 1;
}
}
});
}
}
protected void getBilateralLimits(List<AbstractBlock> blocks) {
limitsD1 = new int[entitiesD1];
limitsD2 = new int[entitiesD2];
blocks.stream().map((block) -> (BilateralBlock) block).map((bilBlock) -> {
for (int id1 : bilBlock.getIndex1Entities()) {
limitsD1[id1]++;
}
return bilBlock;
}).forEachOrdered((bilBlock) -> {
for (int id2 : bilBlock.getIndex2Entities()) {
limitsD2[id2]++;
}
});
for (int i = 0; i < limitsD1.length; i++) {
limitsD1[i] = Math.round(ratio * limitsD1[i]);
}
for (int i = 0; i < limitsD2.length; i++) {
limitsD2[i] = Math.round(ratio * limitsD2[i]);
}
}
protected void getLimits(List<AbstractBlock> blocks) {
if (blocks.get(0) instanceof BilateralBlock) {
getBilateralLimits(blocks);
} else if (blocks.get(0) instanceof UnilateralBlock) {
getUnilateralLimits(blocks);
}
}
@Override
public String getMethodConfiguration() {
return getParameterName(0) + "=" + ratio;
}
@Override
public String getMethodInfo() {
return getMethodName() + ": it retains every entity in a subset of its smallest blocks.";
}
@Override
public String getMethodName() {
return "Block Filtering";
}
@Override
public String getMethodParameters() {
return getMethodName() + " involves a single parameter:\n"
+ "1)" + getParameterDescription(0) + ".\n";
}
@Override
public int getNumberOfGridConfigurations() {
return gridRatio.getNumberOfConfigurations();
}
@Override
public JsonArray getParameterConfiguration() {
final JsonObject obj = new JsonObject();
obj.put("class", "java.lang.Float");
obj.put("name", getParameterName(0));
obj.put("defaultValue", "0.8");
obj.put("minValue", "0.025");
obj.put("maxValue", "1.0");
obj.put("stepValue", "0.025");
obj.put("description", getParameterDescription(0));
final JsonArray array = new JsonArray();
array.add(obj);
return array;
}
@Override
public String getParameterDescription(int parameterId) {
switch (parameterId) {
case 0:
return "The " + getParameterName(0) + " specifies the portion of the retained smaller blocks per entity.";
default:
return "invalid parameter id";
}
}
@Override
public String getParameterName(int parameterId) {
switch (parameterId) {
case 0:
return "Filtering Ratio";
default:
return "invalid parameter id";
}
}
protected void getUnilateralLimits(List<AbstractBlock> blocks) {
limitsD1 = new int[entitiesD1];
limitsD2 = null;
blocks.stream().map((block) -> (UnilateralBlock) block).forEachOrdered((uniBlock) -> {
for (int id : uniBlock.getEntities()) {
limitsD1[id]++;
}
});
for (int i = 0; i < limitsD1.length; i++) {
limitsD1[i] = Math.round(ratio * limitsD1[i]);
}
}
protected void initializeCounters() {
counterD1 = new int[entitiesD1];
counterD2 = null;
if (0 < entitiesD2) {
counterD2 = new int[entitiesD2];
}
}
@Override
public List<AbstractBlock> refineBlocks(List<AbstractBlock> blocks) {
Log.info("Applying " + getMethodName() + " with the following configuration : " + getMethodConfiguration());
if (blocks.isEmpty()) {
Log.warn("Empty set of blocks was given as input!");
return blocks;
}
printOriginalStatistics(blocks);
countEntities(blocks);
sortBlocks(blocks);
getLimits(blocks);
initializeCounters();
return restructureBlocks(blocks);
}
protected List<AbstractBlock> restructureBilateraBlocks(List<AbstractBlock> blocks) {
final List<AbstractBlock> newBlocks = new ArrayList<>();
blocks.stream().map((block) -> (BilateralBlock) block).forEachOrdered((oldBlock) -> {
final TIntList retainedEntitiesD1 = new TIntArrayList();
for (int entityId : oldBlock.getIndex1Entities()) {
if (counterD1[entityId] < limitsD1[entityId]) {
retainedEntitiesD1.add(entityId);
}
}
final TIntList retainedEntitiesD2 = new TIntArrayList();
for (int entityId : oldBlock.getIndex2Entities()) {
if (counterD2[entityId] < limitsD2[entityId]) {
retainedEntitiesD2.add(entityId);
}
}
if (!retainedEntitiesD1.isEmpty() && !retainedEntitiesD2.isEmpty()) {
for (TIntIterator iterator1 = retainedEntitiesD1.iterator(); iterator1.hasNext();) {
counterD1[iterator1.next()]++;
}
for (TIntIterator iterator2 = retainedEntitiesD2.iterator(); iterator2.hasNext();) {
counterD2[iterator2.next()]++;
}
newBlocks.add(new BilateralBlock(oldBlock.getEntropy(), retainedEntitiesD1.toArray(), retainedEntitiesD2.toArray()));
}
});
return newBlocks;
}
protected List<AbstractBlock> restructureBlocks(List<AbstractBlock> blocks) {
if (blocks.get(0) instanceof BilateralBlock) {
return restructureBilateraBlocks(blocks);
}
return restructureUnilateraBlocks(blocks);
}
protected List<AbstractBlock> restructureUnilateraBlocks(List<AbstractBlock> blocks) {
final List<AbstractBlock> newBlocks = new ArrayList<>();
blocks.stream().map((block) -> (UnilateralBlock) block).forEachOrdered((oldBlock) -> {
final TIntList retainedEntities = new TIntArrayList();
for (int entityId : oldBlock.getEntities()) {
if (counterD1[entityId] < limitsD1[entityId]) {
retainedEntities.add(entityId);
}
}
if (1 < retainedEntities.size()) {
for (TIntIterator iterator = retainedEntities.iterator(); iterator.hasNext();) {
counterD1[iterator.next()]++;
}
newBlocks.add(new UnilateralBlock(oldBlock.getEntropy(), retainedEntities.toArray()));
}
});
return newBlocks;
}
@Override
public void setNextRandomConfiguration() {
ratio = (Float) randomRatio.getNextRandomValue();
}
@Override
public void setNumberedGridConfiguration(int iterationNumber) {
ratio = (Float) gridRatio.getNumberedValue(iterationNumber);
}
@Override
public void setNumberedRandomConfiguration(int iterationNumber) {
ratio = (Float) randomRatio.getNumberedRandom(iterationNumber);
}
protected void sortBlocks(List<AbstractBlock> blocks) {
blocks.sort(new IncBlockCardinalityComparator());
}
}
|
92356ac7a7d6e90bfb585f0b76b1913217488728 | 10,171 | java | Java | src/test/java/com/github/qaware/adcl/information/DatamodelVersioningTest.java | qaware/adcl | 20703a1f7bfd3ee2bd27dd31f06dc4eacc1f5be0 | [
"MIT"
] | 1 | 2020-07-27T08:46:36.000Z | 2020-07-27T08:46:36.000Z | src/test/java/com/github/qaware/adcl/information/DatamodelVersioningTest.java | qaware/adcl | 20703a1f7bfd3ee2bd27dd31f06dc4eacc1f5be0 | [
"MIT"
] | 77 | 2019-12-10T22:37:56.000Z | 2020-09-11T02:05:47.000Z | src/test/java/com/github/qaware/adcl/information/DatamodelVersioningTest.java | qaware/adcl | 20703a1f7bfd3ee2bd27dd31f06dc4eacc1f5be0 | [
"MIT"
] | null | null | null | 51.110553 | 176 | 0.586078 | 997,291 | package com.github.qaware.adcl.information;
import com.github.qaware.adcl.PomDependencyExtractor;
import com.github.qaware.adcl.depex.DependencyExtractor;
import com.github.qaware.adcl.pm.MavenProjectManager;
import com.github.qaware.adcl.report.DiffExtractor;
import org.apache.maven.shared.invoker.MavenInvocationException;
import org.jetbrains.annotations.NotNull;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Set;
import static com.github.qaware.adcl.util.DataGenerationUtil.*;
import static org.assertj.core.api.Assertions.assertThat;
public class DatamodelVersioningTest {
Ref<ProjectInformation, RootInformation> proj;
Ref<PackageInformation<ProjectInformation>, ProjectInformation> pa, pb;
Ref<ClassInformation<PackageInformation<?>>, PackageInformation<?>> ca, cabase, cb;
Ref<ClassInformation<ProjectInformation>, ProjectInformation> cc, ce, cca, cci;
Ref<MethodInformation, ClassInformation<?>> caMa, caMb, caE, cabaseE, cbC, cbGia1, ccRca, ccC, ccaC, ccaGcc, cciC, cciRca, ceEm, caC, cbCC, cbM, cbL, cbGia2;
private RootInformation dm;
@BeforeEach
void generateDataModel() {
dm = root(
proj = project("proj", true, "v1.0.0",
pa = pir("packageA",
ca = cio("ClassA", false,
caC = mi("<init>()"),
caMa = mi("methodA()"),
caMb = mi("methodB(packageB.ClassB)"),
caE = mi("empty()")
),
cabase = cio("ClassABase", false,
cabaseE = mi("empty()")
)
),
pb = pir("packageB",
cb = cio("ClassB", true,
cbC = mi("<init>()"),
cbCC = mi("<clinit>()"),
cbGia1 = mi("getInstanceA()"),
cbM = mi("method(java.com.github.qaware.adcl.util.function.Predicate)"),
cbL = mi("lambda$getInstanceA$0(java.lang.String)"),
cbGia2 = mi("getInstanceA(java.lang.String, int, packageA.ClassA[])")
),
pis("emptyPackage")
),
cc = cir("ClassC", false,
ccC = mi("<init>()"),
ccRca = mi("retrieveClassA()")
),
cca = cir("ClassC$1", false,
ccaC = mi("<init>(ClassC)"),
ccaGcc = mi("getClassC()")
),
cci = cir("ClassC$ClassCInner", false,
cciC = mi("<init>(ClassC)"),
cciRca = mi("retrieveClassA()")
),
ce = cir("ExternalClass", false,
ceEm = mi("extMethod()")
)
)
);
p(cbM, proj);
p(cbGia1, pa);
p(caMb, cb);
p(ccC, cca, ccaC);
p(caMa, cbC);
p(cbCC, caC);
}
@Test
void versionTraversalTest() {
VersionInformation v1 = proj.getStored().getLatestVersion();
VersionInformation v2 = proj.getStored().addVersion("2.0.0");
assertThat(v1.previous()).isNull();
assertThat(v1.next()).isEqualTo(v2);
assertThat(v2.previous()).isEqualTo(v1);
assertThat(v2.next()).isNull();
}
@Test
void test() throws IOException {
RootInformation root = new RootInformation();
ProjectInformation project = new ProjectInformation(root, "proj", true, "<unknown>");
VersionInformation v1 = runDepEx(project, "testproject", "0.0.1");
VersionInformation v2 = runDepEx(project, "testproject2", "0.0.2");
VersionInformation v3 = runDepEx(project, "testproject3", "0.0.3");
assertThat(new DiffExtractor(v1, v2).generateDependencyDiff(false, false).stream().map(Object::toString)).containsExactlyInAnyOrder(
"proj.packageB.ClassB->null.org.springframework.stereotype.Service",
"proj.packageA.MyAnnotation.notNullRef()->null.org.jetbrains.annotations.NotNull",
"proj.packageA.ClassA->proj.packageA.MyAnnotation",
"proj.packageA.ClassA.methodC(boolean, byte, char, short, int, long, float, double, java.lang.String)->proj.packageA.ClassA.$$$reportNull$$$0(int)",
"proj.packageA.ClassA->null.org.jetbrains.annotations.Nullable",
"proj.packageA.ClassA.methodC(boolean, byte, char, short, int, long, float, double, java.lang.String)->null.org.springframework.context.NoSuchMessageException",
"proj.packageA.ClassA->null.org.jetbrains.annotations.NotNull",
"proj.packageA.ClassA.methodC(boolean, byte, char, short, int, long, float, double, java.lang.String)->null.org.jetbrains.annotations.NotNull",
"proj.packageA.ClassA.methodC(boolean, byte, char, short, int, long, float, double, java.lang.String)->proj.packageA.ClassA.methodA()"
);
assertThat(new DiffExtractor(v2, v3).generateDependencyDiff(false, false).stream().map(Object::toString)).containsExactlyInAnyOrder(
"proj.packageA.ClassA.newMethod()+>proj.packageA.ClassABase"
);
}
@NotNull
private VersionInformation runDepEx(@NotNull ProjectInformation project, String folderName, String versionName) throws IOException {
VersionInformation result = project.addVersion(versionName);
new DependencyExtractor(Paths.get("src", "test", "resources", "testclassfiles2", folderName, "target", "classes"), result, null).runAnalysis();
return result;
}
@Test
void pomDependencyTest() throws MavenInvocationException {
RootInformation root = new RootInformation();
ProjectInformation project = new ProjectInformation(root, "proj", true, "<unknown>");
VersionInformation v1 = runPomAnalysis(project, "testproject", "0.0.1");
VersionInformation v2 = runPomAnalysis(project, "testproject2", "0.0.2");
VersionInformation v3 = runPomAnalysis(project, "testproject3", "0.0.3");
assertThat(new DiffExtractor(v1, v2).generatePomDiff().stream().map(Object::toString)).containsExactlyInAnyOrder(
"-> null@org-springframework:spring-context",
"-> 18.0.0@org-jetbrains:annotations"
);
assertThat(new DiffExtractor(v2, v3).generatePomDiff().stream().map(Object::toString)).containsExactlyInAnyOrder(
"-> 5.2.1.RELEASE@org-springframework:spring-context",
"-> null@org-jetbrains:annotations"
);
}
@NotNull
private VersionInformation runPomAnalysis(@NotNull ProjectInformation project, String folderName, String versionName) throws MavenInvocationException {
VersionInformation result = project.addVersion(versionName);
Path basedir = Paths.get("src", "test", "resources", "testclassfiles2", folderName);
PomDependencyExtractor.updatePomDependencies(new MavenProjectManager(basedir, basedir.resolve("pom.xml")), result);
return result;
}
@Test
void versionTest() {
VersionInformation v1 = proj.getStored().addVersion("2.0.0");
VersionInformation vx = null;
proj.getStored().addClassDependency(ce.getStored(), v1);
assertThat(proj.getStored().getLatestVersion().getName().equals(v1.getName())).isTrue();
Set<ClassInformation<?>> classInformation = proj.getStored().getClassDependencies(v1);
for (ClassInformation<?> information : classInformation) {
if (information.getName().equals(ce.getStored().getName())) {
classInformation.remove(information);
vx = proj.getStored().addVersion("3.0.0");
}
}
assert (vx != null);
assertThat(proj.getStored().getLatestVersion().getName().equals(vx.getName())).isTrue();
proj.getStored().addMethodDependency(new MethodInformation(cc.getStored(), "what()"), vx);
Set<MethodInformation> mInformation = proj.getStored().getMethodDependencies(vx);
for (MethodInformation del : mInformation) {
if (del.getParent().getName().equals(cc.getStored().getName())) {
mInformation.remove(del);
vx = proj.getStored().addVersion("4.0.0");
}
}
assertThat(proj.getStored().getLatestVersion().getName().equals(vx.getName())).isTrue();
proj.getStored().addPackageDependency(pa.getStored(), vx);
Set<PackageInformation<?>> pInformation = proj.getStored().getPackageDependencies(vx);
for (PackageInformation<?> packageInformation : pInformation) {
if (packageInformation.getName().equals(pa.getStored().getName())) {
pInformation.remove(packageInformation);
vx = proj.getStored().addVersion("5.0.0");
}
}
assertThat(proj.getStored().getLatestVersion().getName().equals(vx.getName())).isTrue();
ProjectInformation px = new ProjectInformation(dm, "testproj", true, vx.getName());
proj.getStored().addProjectDependency(px, vx);
Set<ProjectInformation> paInformation = proj.getStored().getProjectDependencies(vx);
for (ProjectInformation del : paInformation) {
if (del.getName().equals(px.getName())) {
paInformation.remove(del);
vx = proj.getStored().addVersion("6.0.0");
}
}
assertThat(proj.getStored().getLatestVersion().getName().equals(vx.getName())).isTrue();
}
}
|
92356acf15a33640cd3fd6d5a120acd81a222ef9 | 547 | java | Java | templates/api-template-java/src/main/java/com/slf/model/Request.java | rkothapalli/jazz | f04449735603ee19b228521e486a779a8609eae5 | [
"Apache-2.0"
] | 5 | 2019-02-14T19:33:49.000Z | 2021-02-26T00:12:15.000Z | templates/api-template-java/src/main/java/com/slf/model/Request.java | rkothapalli/jazz | f04449735603ee19b228521e486a779a8609eae5 | [
"Apache-2.0"
] | 7 | 2018-12-20T01:21:48.000Z | 2019-02-21T19:19:42.000Z | templates/api-template-java/src/main/java/com/slf/model/Request.java | rkothapalli/jazz | f04449735603ee19b228521e486a779a8609eae5 | [
"Apache-2.0"
] | 4 | 2018-12-03T21:59:03.000Z | 2019-02-04T03:59:17.000Z | 13.341463 | 48 | 0.674589 | 997,292 | package com.slf.model;
import java.util.Map;
public class Request {
private String stage;
private String method;
private Map<String, String> body;
public Request() {
}
public String getStage() {
return stage;
}
public void setStage(String stage) {
this.stage = stage;
}
public String getMethod() {
return method;
}
public void setMethod(String method) {
this.method = method;
}
public Map<String, String> getBody() {
return body;
}
public void setBody(Map<String, String> body) {
this.body = body;
}
}
|
92356b427018247cbed80e1c9a94616a6edc57b4 | 119 | java | Java | src/main/java/com/swingfrog/summer/ecs/bean/Bean.java | 767214481/Summer | e759ea49e8373aff6d3c2f579603651cced52db5 | [
"Apache-2.0"
] | 456 | 2018-12-05T08:56:09.000Z | 2022-03-31T06:27:38.000Z | src/main/java/com/swingfrog/summer/ecs/bean/Bean.java | 767214481/Summer | e759ea49e8373aff6d3c2f579603651cced52db5 | [
"Apache-2.0"
] | 18 | 2019-03-10T06:19:47.000Z | 2022-02-08T11:08:46.000Z | src/main/java/com/swingfrog/summer/ecs/bean/Bean.java | 767214481/Summer | e759ea49e8373aff6d3c2f579603651cced52db5 | [
"Apache-2.0"
] | 130 | 2018-12-06T03:07:54.000Z | 2022-03-07T03:02:12.000Z | 13.222222 | 38 | 0.680672 | 997,293 | package com.swingfrog.summer.ecs.bean;
public interface Bean<K> {
K getEntityId();
void setEntityId(K k);
}
|
92356cc337c40d0ed9b61d64bf481acc5c464106 | 26,386 | java | Java | corelibrary/src/main/java/com/axway/ats/core/atsconfig/AtsInfrastructureManager.java | jsa34/ats-framework | cafad83ccbe518c54789d1d51ad9e244795f567f | [
"Apache-2.0"
] | 33 | 2017-03-08T13:23:21.000Z | 2021-12-01T08:29:15.000Z | corelibrary/src/main/java/com/axway/ats/core/atsconfig/AtsInfrastructureManager.java | jsa34/ats-framework | cafad83ccbe518c54789d1d51ad9e244795f567f | [
"Apache-2.0"
] | 20 | 2017-04-04T11:23:54.000Z | 2021-09-30T15:20:45.000Z | corelibrary/src/main/java/com/axway/ats/core/atsconfig/AtsInfrastructureManager.java | jsa34/ats-framework | cafad83ccbe518c54789d1d51ad9e244795f567f | [
"Apache-2.0"
] | 61 | 2017-04-05T14:23:22.000Z | 2021-09-28T14:33:36.000Z | 34.902116 | 115 | 0.700826 | 997,294 | /*
* Copyright 2017 Axway Software
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.axway.ats.core.atsconfig;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import com.axway.ats.common.systemproperties.AtsSystemProperties;
import com.axway.ats.core.atsconfig.exceptions.AtsConfigurationException;
import com.axway.ats.core.atsconfig.exceptions.AtsManagerException;
import com.axway.ats.core.atsconfig.model.AbstractApplicationController;
import com.axway.ats.core.atsconfig.model.AgentController;
import com.axway.ats.core.atsconfig.model.AgentInfo;
import com.axway.ats.core.atsconfig.model.ApplicationController;
import com.axway.ats.core.atsconfig.model.ApplicationInfo;
import com.axway.ats.core.atsconfig.model.PathInfo;
import com.axway.ats.core.log.AbstractAtsLogger;
import com.axway.ats.core.ssh.JschSftpClient;
import com.axway.ats.core.ssh.JschSshClient;
import com.axway.ats.core.utils.IoUtils;
import com.axway.ats.core.utils.StringUtils;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
public class AtsInfrastructureManager {
private static AbstractAtsLogger log = AbstractAtsLogger.getDefaultInstance(AtsInfrastructureManager.class);
private static final String TOP_LEVEL_ACTION_PREFIX = "***** ";
private AtsProjectConfiguration projectConfiguration;
private Map<String, String> sshClientConfigurationProperties;
public enum ApplicationStatus {
STARTED, STOPPED, NOT_INSTALLED, BUSY, UNKNOWN;
}
public AtsInfrastructureManager(String atsConfigurationFile) throws AtsConfigurationException {
this.projectConfiguration = new AtsProjectConfiguration(atsConfigurationFile);
this.sshClientConfigurationProperties = new HashMap<>();
}
public void reloadConfigurationFile() {
this.projectConfiguration.loadConfigurationFile();
}
/**
*
* @return the ATS project configuration. Parsed from the configuration file
*/
public AtsProjectConfiguration getProjectConfiguration() {
return this.projectConfiguration;
}
/**
* Set configuration property
* <p/>
* Currently we use internally JCraft's JSch library which can be configured
* through this method.
* <p/>
* You need to find the acceptable key-value configuration pairs in the JSch
* documentation. They might be also available in the source code of
* com.jcraft.jsch.JSch
* <p/>
* <p>
* Example: The default value of "PreferredAuthentications" is
* "gssapi-with-mic,publickey,keyboard-interactive,password"
* </p>
* ATS uses two types of properties to configure the ssh client: <br>
* <ul>
* <li>global - equivalent to {@link JSch#setConfig(String, String)}, example
* <strong>global.RequestTTY</strong>=true</li>
* <li>session - equivalent to {@link Session#setConfig(String, String)},
* example <strong>session.StrictHostKeyChecking</strong>=no <br>
* Note that if there is no global. or session. prefix, the property is assumed
* to be a session one</li>
* </ul>
* <p/>
*
* @param key
* configuration key
* @param value
* configuration value
*/
public void setSshClientConfigurationProperty(String key, String value) {
sshClientConfigurationProperties.put(key, value);
}
/**
* Start all the ATS Agents declared in the configuration
*
* @throws AtsManagerException
*/
public void startAllAgents() throws AtsManagerException {
for (Entry<String, AgentInfo> agentData : projectConfiguration.getAgents().entrySet()) {
startAnyApplication(agentData.getKey(), true);
}
}
/**
* Restart all the ATS Agents declared in the configuration
*
* @throws AtsManagerException
*/
public void restartAllAgents() throws AtsManagerException {
for (Entry<String, AgentInfo> agentData : projectConfiguration.getAgents().entrySet()) {
restartAnyApplication(agentData.getKey());
}
}
/**
* Stop all the ATS Agents declared in the configuration
*
* @throws AtsManagerException
*/
public void stopAllAgents() throws AtsManagerException {
for (Entry<String, AgentInfo> agentData : projectConfiguration.getAgents().entrySet()) {
stopAnyApplication(agentData.getKey(), true);
}
}
public ApplicationStatus startAnyApplication(String anyApplicationAlias, boolean isTopLevelAction)
throws AtsManagerException {
AbstractApplicationController controller = getController(anyApplicationAlias, sshClientConfigurationProperties);
try {
return controller.start(isTopLevelAction);
} finally {
controller.disconnect();
}
}
public ApplicationStatus stopAnyApplication(String anyApplicationAlias, boolean isTopLevelAction)
throws AtsManagerException {
AbstractApplicationController controller = getController(anyApplicationAlias, sshClientConfigurationProperties);
try {
return controller.stop(isTopLevelAction);
} finally {
controller.disconnect();
}
}
public ApplicationStatus restartAnyApplication(String anyApplicationAlias) throws AtsManagerException {
AbstractApplicationController controller = getController(anyApplicationAlias, sshClientConfigurationProperties);
try {
return controller.restart();
} finally {
controller.disconnect();
}
}
/**
* Get the status of ATS Agent by its alias
*
* @param agentAlias
* the agent alias declared in the configuration
* @return the {@link ApplicationStatus}
* @throws AtsManagerException
*/
public ApplicationStatus getAnyApplicationStatus(String anyApplicationAlias) throws AtsManagerException {
AbstractApplicationController controller = getController(anyApplicationAlias, sshClientConfigurationProperties);
try {
return controller.getStatus(true);
} finally {
controller.disconnect();
}
}
/**
* Install the ATS Agent by alias
*
* @param agentAlias
* the agent alias declared in the configuration
* @throws AtsManagerException
*/
public ApplicationStatus installAgent(String agentAlias) throws AtsManagerException {
AgentInfo agentInfo = getAgentInfo(agentAlias);
log.info(TOP_LEVEL_ACTION_PREFIX + "Now we will try to install " + agentInfo.getDescription());
String agentZip = projectConfiguration.getSourceProject().getAgentZip();
if (StringUtils.isNullOrEmpty(agentZip)) {
throw new AtsManagerException("The agent zip source file is not specified in the configuration");
}
// extract agent.zip to a temporary local directory
String agentFolder = IoUtils.normalizeDirPath(extractAgentZip(agentZip));
JschSftpClient sftpClient = createNewSftpClient();
try {
// upload clean agent
log.info("Upload clean " + agentInfo.getDescription());
sftpClient.connect(agentInfo.getSystemUser(), agentInfo.getSystemPassword(), agentInfo.getHost(),
agentInfo.getSSHPort(), agentInfo.getSSHPrivateKey(), agentInfo.getSSHPrivateKeyPassword());
if (sftpClient.isRemoteFileOrDirectoryExisting(agentInfo.getSftpHome())) {
sftpClient.purgeRemoteDirectoryContents(agentInfo.getSftpHome());
}
sftpClient.uploadDirectory(agentFolder, agentInfo.getSftpHome(), true);
// upload custom agent dependencies
log.info("Upload custom agent dependencies");
for (PathInfo pathInfo : agentInfo.getPaths()) {
if (pathInfo.isFile()) {
if (!sftpClient.isRemoteFileOrDirectoryExisting(pathInfo.getSftpPath())) {
String fileName = IoUtils.getFileName(pathInfo.getSftpPath());
String filePath = projectConfiguration.getSourceProject().findFile(fileName);
if (filePath == null) {
log.warn("File '" + fileName + "' can't be found in the source project libraries,"
+ " so it can't be uploaded to " + agentInfo.getDescription());
continue;
}
if (!new File(filePath).exists()) {
log.warn("Local file '" + filePath + "' does not exist on the local system,"
+ " so it can't be uploaded to " + agentInfo.getDescription());
continue;
}
int lastSlashIdx = pathInfo.getSftpPath().lastIndexOf('/');
if (lastSlashIdx > 0) {
sftpClient.makeRemoteDirectories(pathInfo.getSftpPath().substring(0, lastSlashIdx));
}
sftpClient.uploadFile(filePath, pathInfo.getSftpPath());
}
} else {
log.warn("Uploading directories into ATS agent is still not supported");
}
}
// make agent start file to be executable
makeScriptsExecutable(agentInfo);
// execute post install shell command, if any
executePostActionShellCommand(agentInfo, "install", agentInfo.getPostInstallShellCommand());
log.info(TOP_LEVEL_ACTION_PREFIX + "Successfully installed " + agentInfo.getDescription());
return ApplicationStatus.STOPPED;
} finally {
sftpClient.disconnect();
}
}
/**
* Light upgrade the ATS Agent by alias. Which means upgrade of specific
* directories only
*
* @param agentAlias
* the agent alias declared in the configuration
* @throws AtsManagerException
*/
public ApplicationStatus lightUpgradeAgent(String agentAlias, ApplicationStatus previousStatus)
throws AtsManagerException {
// we enter here when the agent is STARTED or STOPPED
ApplicationStatus newStatus = previousStatus;
AgentInfo agentInfo = getAgentInfo(agentAlias);
log.info(TOP_LEVEL_ACTION_PREFIX + "Now we will try to perform light upgrade on " + agentInfo.getDescription());
JschSftpClient sftpClient = createNewSftpClient();
try {
sftpClient.connect(agentInfo.getSystemUser(), agentInfo.getSystemPassword(), agentInfo.getHost(),
agentInfo.getSSHPort(), agentInfo.getSSHPrivateKey(), agentInfo.getSSHPrivateKeyPassword());
// Stop the agent if at least one of the file upgrades requires it
if (newStatus == ApplicationStatus.STARTED) {
for (PathInfo pathInfo : agentInfo.getPaths()) {
if (pathInfo.isUpgrade() && mustUpgradeOnStoppedAgent(pathInfo.getSftpPath())) {
log.info("We must stop the agent prior to upgrading " + pathInfo.getPath());
try {
newStatus = stopAnyApplication(agentAlias, false);
break;
} catch (AtsManagerException e) {
throw new AtsManagerException("Canceling upgrade as could not stop the agent", e);
}
}
}
}
// Do the actual upgrade
for (PathInfo pathInfo : agentInfo.getPaths()) {
if (pathInfo.isUpgrade()) {
if (pathInfo.isFile()) {
String fileName = IoUtils.getFileName(pathInfo.getSftpPath());
String filePath = projectConfiguration.getSourceProject().findFile(fileName);
if (filePath == null) {
log.warn("File '" + fileName + "' can not be found in the source project libraries,"
+ " so we can not upgrade it on the target agent");
continue;
}
// create directories to the file, only if not exist
int lastSlashIdx = pathInfo.getSftpPath().lastIndexOf('/');
if (lastSlashIdx > 0) {
sftpClient.makeRemoteDirectories(pathInfo.getSftpPath().substring(0, lastSlashIdx));
}
sftpClient.uploadFile(filePath, pathInfo.getSftpPath());
} else {
// TODO: upgrade directory
}
}
}
// Start the agent if we stopped it
if (previousStatus == ApplicationStatus.STARTED && newStatus == ApplicationStatus.STOPPED) {
log.info("We stopped the agent while upgrading. Now we will start it back on");
newStatus = startAnyApplication(agentAlias, false);
log.info(TOP_LEVEL_ACTION_PREFIX + agentInfo.getDescription() + " is successfully upgraded");
return newStatus;
} else {
// agent status was not changed in this method
log.info(TOP_LEVEL_ACTION_PREFIX + agentInfo.getDescription() + " is successfully upgraded");
return previousStatus;
}
} finally {
sftpClient.disconnect();
}
}
/**
* Upgrade the ATS Agent by alias
*
* @param agentAlias
* the agent alias declared in the configuration
* @throws AtsManagerException
*/
public ApplicationStatus upgradeAgent(String agentAlias, ApplicationStatus previousStatus)
throws AtsManagerException {
// we enter here when the agent is STARTED or STOPPED
AgentInfo agentInfo = getAgentInfo(agentAlias);
log.info(TOP_LEVEL_ACTION_PREFIX + "Now we will try to perform full upgrade on " + agentInfo.getDescription());
String agentZip = projectConfiguration.getSourceProject().getAgentZip();
if (StringUtils.isNullOrEmpty(agentZip)) {
throw new AtsManagerException("The agent zip file is not specified in the configuration");
}
// extract agent.zip to a temporary local directory
String agentFolder = IoUtils.normalizeDirPath(extractAgentZip(agentZip));
JschSftpClient sftpClient = createNewSftpClient();
try {
sftpClient.connect(agentInfo.getSystemUser(), agentInfo.getSystemPassword(), agentInfo.getHost(),
agentInfo.getSSHPort(), agentInfo.getSSHPrivateKey(), agentInfo.getSSHPrivateKeyPassword());
if (!sftpClient.isRemoteFileOrDirectoryExisting(agentInfo.getSftpHome())) {
throw new AtsManagerException("The " + agentInfo.getDescription() + " is not installed in "
+ agentInfo.getSftpHome() + ". You must install it first.");
}
if (previousStatus == ApplicationStatus.STARTED) {
// agent is started, stop it before the upgrade
log.info("We must stop the agent prior to upgrading");
try {
stopAnyApplication(agentAlias, false);
} catch (AtsManagerException e) {
throw new AtsManagerException("Canceling upgrade as could not stop the agent", e);
}
}
// cleanup the remote directories content
List<String> preservedPaths = getPreservedPathsList(agentInfo.getPaths());
sftpClient.purgeRemoteDirectoryContents(agentInfo.getSftpHome(), preservedPaths);
agentInfo.markPathsUnchecked();
updateAgentFolder(sftpClient, agentInfo, agentFolder, "");
for (PathInfo pathInfo : agentInfo.getUnckeckedPaths()) {
if (pathInfo.isUpgrade()) {
if (pathInfo.isFile()) {
String fileName = IoUtils.getFileName(pathInfo.getSftpPath());
String filePath = projectConfiguration.getSourceProject().findFile(fileName);
if (filePath == null) {
log.warn("File '" + fileName + "' can not be found in the source project libraries,"
+ " so we can not upgrade it on the target agent");
continue;
}
int lastSlashIdx = pathInfo.getSftpPath().lastIndexOf('/');
if (lastSlashIdx > 0) {
sftpClient.makeRemoteDirectories(pathInfo.getSftpPath().substring(0, lastSlashIdx));
}
sftpClient.uploadFile(filePath, pathInfo.getSftpPath());
} else {
// TODO: upgrade directory
}
}
}
// make agent start file to be executable
makeScriptsExecutable(agentInfo);
// execute post install shell command, if any
executePostActionShellCommand(agentInfo, "install", agentInfo.getPostInstallShellCommand());
if (previousStatus == ApplicationStatus.STARTED) {
log.info("We stopped the agent while upgrading. Now we will start it back on");
ApplicationStatus newStatus = startAnyApplication(agentAlias, false);
log.info(TOP_LEVEL_ACTION_PREFIX + agentInfo.getDescription() + " is successfully upgraded");
return newStatus;
} else {
// agent status was not changed in this method
log.info(TOP_LEVEL_ACTION_PREFIX + agentInfo.getDescription() + " is successfully upgraded");
return ApplicationStatus.STOPPED;
}
} finally {
sftpClient.disconnect();
}
}
/**
* Execute a shell command on the host where the application is located
*
* @param applicationAlias
* the application alias declared in the configuration
* @param command
* the command to run
* @return information about the execution result containing exit code, STD OUT
* and STD ERR
* @throws AtsManagerException
*/
public String executeShellCommand(String anyApplicationAlias, String command) throws AtsManagerException {
AbstractApplicationController controller = getController(anyApplicationAlias, sshClientConfigurationProperties);
try {
return controller.executeShellCommand(controller.getApplicationInfo(), command);
} finally {
controller.disconnect();
}
}
/**
*
* @param agentAlias
* the agent alias declared in the configuration
* @return the {@link AgentInfo} instance
* @throws AtsManagerException
*/
private AgentInfo getAgentInfo(String agentAlias) throws AtsManagerException {
if (!projectConfiguration.getAgents().containsKey(agentAlias)) {
throw new AtsManagerException("Can't find agent with alias '" + agentAlias + "' in the configuration");
}
return projectConfiguration.getAgents().get(agentAlias);
}
private AbstractApplicationController getController(String alias,
Map<String, String> sshClientConfigurationProperties) throws AtsManagerException {
AgentInfo agentInfo = projectConfiguration.getAgents().get(alias);
if (agentInfo != null) {
return new AgentController(agentInfo, projectConfiguration.getSourceProject(),
sshClientConfigurationProperties);
}
ApplicationInfo applicationInfo = projectConfiguration.getApplications().get(alias);
if (applicationInfo != null) {
return new ApplicationController(applicationInfo, sshClientConfigurationProperties);
}
throw new AtsManagerException("Can't find application with alias '" + alias + "' in the configuration");
}
/**
*
* @param path
* file or directory path
* @return <code>true</code> if must stop the agent
*/
private boolean mustUpgradeOnStoppedAgent(String path) {
return !path.contains("/agentactions/");
}
/**
* @param pathInfos
* a {@link List} with {@link PathInfo}s
* @return a {@link List} with the SFTP full paths as {@link String}s
*/
private List<String> getPreservedPathsList(List<PathInfo> pathInfos) {
List<String> preservedPaths = new ArrayList<String>();
if (pathInfos != null) {
for (PathInfo path : pathInfos) {
preservedPaths.add(path.getSftpPath());
}
}
return preservedPaths;
}
/**
*
* @param sftpClient
* {@link JschSftpClient} instance
* @param agentInfo
* the current agent information
* @param localAgentFolder
* local agent folder
* @param relativeFolderPath
* the relative path of the current folder for update
* @throws AtsManagerException
*/
private void updateAgentFolder(JschSftpClient sftpClient, AgentInfo agentInfo, String localAgentFolder,
String relativeFolderPath) throws AtsManagerException {
String remoteFolderPath = agentInfo.getSftpHome() + relativeFolderPath;
if (!sftpClient.isRemoteFileOrDirectoryExisting(remoteFolderPath)) {
sftpClient.uploadDirectory(localAgentFolder + relativeFolderPath, remoteFolderPath, true);
return;
}
File localFolder = new File(localAgentFolder + relativeFolderPath);
File[] localEntries = localFolder.listFiles();
if (localEntries != null && localEntries.length > 0) {
for (File localEntry : localEntries) {
String remoteFilePath = remoteFolderPath + localEntry.getName();
PathInfo pathInfo = agentInfo.getPathInfo(remoteFilePath, localEntry.isFile(), true);
if (pathInfo != null) {
pathInfo.setChecked(true);
if (!pathInfo.isUpgrade()) {
log.info("Skipping upgrade of '" + remoteFilePath + "', because its 'upgrade' flag is 'false'");
continue;
}
}
if (localEntry.isDirectory()) {
updateAgentFolder(sftpClient, agentInfo, localAgentFolder,
relativeFolderPath + localEntry.getName() + "/");
} else {
String localFilePath = localAgentFolder + relativeFolderPath + localEntry.getName();
sftpClient.uploadFile(localFilePath, remoteFilePath);
}
}
}
}
/**
* Make script files executable
*
* @param agentInfo
* agent information
* @throws AtsManagerException
*/
private void makeScriptsExecutable(AgentInfo agentInfo) throws AtsManagerException {
// set executable privileges to the script files
if (agentInfo.isUnix()) {
log.info("Set executable priviledges on all 'sh' files in " + agentInfo.getHome());
JschSshClient sshClient = createNewSshClient();
try {
sshClient.connect(agentInfo.getSystemUser(), agentInfo.getSystemPassword(), agentInfo.getHost(),
agentInfo.getSSHPort(), agentInfo.getSSHPrivateKey(), agentInfo.getSSHPrivateKeyPassword());
int exitCode = sshClient.execute("chmod a+x " + agentInfo.getHome() + "/*.sh", true);
if (exitCode != 0) {
throw new AtsManagerException("Unable to set execute privileges to the shell script files in '"
+ agentInfo.getHome() + "'");
}
} finally {
sshClient.disconnect();
}
}
}
/**
* Execute post install/upgrade(full) shell command, if any
*
* @param agentInfo
* agent information
* @throws AtsManagerException
*/
private void executePostActionShellCommand(AgentInfo agentInfo, String actionName, String shellCommand)
throws AtsManagerException {
if (shellCommand != null) {
log.info("Executing post '" + actionName + "' shell command: " + shellCommand);
JschSshClient sshClient = createNewSshClient();
try {
sshClient.connect(agentInfo.getSystemUser(), agentInfo.getSystemPassword(), agentInfo.getHost(),
agentInfo.getSSHPort(), agentInfo.getSSHPrivateKey(), agentInfo.getSSHPrivateKeyPassword());
int exitCode = sshClient.execute(shellCommand, true);
if (exitCode != 0) {
throw new AtsManagerException("Unable to execute the post '" + actionName + "' shell command '"
+ shellCommand + "' on agent '" + agentInfo.getAlias() + "'. The error output is"
+ (StringUtils.isNullOrEmpty(sshClient.getErrorOutput()) ? " empty."
: ":\n" + sshClient.getErrorOutput()));
}
log.info("The output of shell command \"" + shellCommand + "\" is"
+ (StringUtils.isNullOrEmpty(sshClient.getStandardOutput()) ? " empty."
: ":\n" + sshClient.getStandardOutput()));
} finally {
sshClient.disconnect();
}
}
}
/**
* Extract the agent zip file in a temporary directory and return its location
*
* @param agentZipPath
* agent zip file path
* @return the directory where the zip file is unzipped
* @throws AtsManagerException
*/
private String extractAgentZip(String agentZipPath) throws AtsManagerException {
// the temp path contains the thread name to have uniqueness when running action
// on more than
// one agent at same time
final String tempPath = IoUtils.normalizeDirPath(AtsSystemProperties.SYSTEM_USER_TEMP_DIR + "/ats_tmp/")
+ Thread.currentThread().getName() + "_";
if (agentZipPath.toLowerCase().startsWith("http://")) {
// download from HTTP URL
agentZipPath = downloadAgentZip(agentZipPath, tempPath);
}
File agentZip = new File(agentZipPath);
if (!agentZip.exists()) {
throw new AtsManagerException("The agent ZIP file doesn't exist '" + agentZipPath + "'");
}
String agentFolderName = tempPath + "agent_" + String.valueOf(agentZip.lastModified());
File agentFolder = new File(agentFolderName);
if (!agentFolder.exists()) {
try {
log.info("Unzip " + agentZipPath + " into " + agentFolderName);
IoUtils.unzip(agentZipPath, agentFolderName, true);
} catch (IOException ioe) {
throw new AtsManagerException("Unable to unzip the agent ZIP file '" + agentZipPath
+ "' to the temporary created directory '" + agentFolderName + "'", ioe);
}
}
return agentFolderName;
}
private String downloadAgentZip(String agentZipUrl, String tempPath) throws AtsManagerException {
File downloadedFile = new File(tempPath + "agent.zip");
downloadedFile.deleteOnExit();
log.info("Download ATS agent from " + agentZipUrl + " into " + downloadedFile);
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
try {
URL url = new URL(agentZipUrl);
URLConnection conn = url.openConnection();
bis = new BufferedInputStream(conn.getInputStream());
bos = new BufferedOutputStream(new FileOutputStream(downloadedFile));
int inByte;
while ((inByte = bis.read()) != -1) {
bos.write(inByte);
}
return downloadedFile.getPath();
} catch (Exception e) {
throw new AtsManagerException("Error downloading agent ZIP file from " + agentZipUrl, e);
} finally {
IoUtils.closeStream(bis);
IoUtils.closeStream(bos);
}
}
private JschSshClient createNewSshClient() {
JschSshClient sshClient = new JschSshClient();
for (Entry<String, String> entry : sshClientConfigurationProperties.entrySet()) {
sshClient.setConfigurationProperty(entry.getKey(), entry.getValue());
}
return sshClient;
}
private JschSftpClient createNewSftpClient() {
JschSftpClient sftpClient = new JschSftpClient();
for (Entry<String, String> entry : sshClientConfigurationProperties.entrySet()) {
sftpClient.setConfigurationProperty(entry.getKey(), entry.getValue());
}
return sftpClient;
}
}
|
92356d9913db8470022eafa0754e03f3b22bfd49 | 7,056 | java | Java | bundle/src/test/java/com/adobe/acs/commons/httpcache/config/impl/RequestCookieCacheExtensionTest.java | LukeGrover/acs-aem-commons | 84f76f7faccca34062008ea61499e2dd201c7a90 | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | bundle/src/test/java/com/adobe/acs/commons/httpcache/config/impl/RequestCookieCacheExtensionTest.java | LukeGrover/acs-aem-commons | 84f76f7faccca34062008ea61499e2dd201c7a90 | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | bundle/src/test/java/com/adobe/acs/commons/httpcache/config/impl/RequestCookieCacheExtensionTest.java | LukeGrover/acs-aem-commons | 84f76f7faccca34062008ea61499e2dd201c7a90 | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | 34.419512 | 147 | 0.713719 | 997,295 | /*
* #%L
* ACS AEM Commons Bundle
* %%
* Copyright (C) 2015 Adobe
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
package com.adobe.acs.commons.httpcache.config.impl;
import com.adobe.acs.commons.httpcache.config.HttpCacheConfig;
import com.adobe.acs.commons.httpcache.config.impl.keys.KeyValueHttpCacheKey;
import com.adobe.acs.commons.httpcache.config.impl.keys.helper.KeyValueMapWrapper;
import com.adobe.acs.commons.httpcache.config.impl.keys.helper.RequestCookieKeyValueWrapperBuilder;
import com.adobe.acs.commons.httpcache.exception.HttpCacheKeyCreationException;
import com.adobe.acs.commons.httpcache.exception.HttpCacheRepositoryAccessException;
import com.google.common.collect.ImmutableSet;
import org.apache.commons.lang3.StringUtils;
import org.apache.sling.api.SlingHttpServletRequest;
import org.apache.sling.api.resource.Resource;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import javax.servlet.http.Cookie;
import java.lang.annotation.Annotation;
import java.util.HashMap;
import java.util.Map;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.when;
@RunWith(MockitoJUnitRunner.class)
public class RequestCookieCacheExtensionTest {
public static final String REQUEST_URI = "/check-in.html";
private static final String REQUEST_RESOURCE_PATH = "/content/eurowings/de/check-in";
@Mock
private SlingHttpServletRequest request;
@Mock
private SlingHttpServletRequest emptyRequest;
@Mock
private Cookie presentCookie;
@Mock
private Cookie irrelevantCookie;
private Cookie[] cookies;
private Cookie[] emptyCookies;
KeyValueConfig configA = new KeyValueConfig(){
@Override
public Class<? extends Annotation> annotationType() {
return null;
}
@Override
public String configName() {
return "unique-config2";
}
@Override
public String[] allowedKeys() {
return new String[]{"present-cookie-key", "non-present-cookie"};
}
@Override
public String[] allowedValues() {
return new String[0];
}
@Override
public boolean emptyAllowed() {
return false;
}
};
KeyValueConfig configB = new KeyValueConfig(){
@Override
public Class<? extends Annotation> annotationType() {
return null;
}
@Override
public String configName() {
return "unique-config";
}
@Override
public String[] allowedKeys() {
return new String[]{"present-cookie-key"};
}
@Override
public String[] allowedValues() {
return new String[]{"present-cookie-key=present-cookie-value|value2"};
}
@Override
public boolean emptyAllowed() {
return true;
}
};
@Mock
private HttpCacheConfig validCacheKeyConfig;
@Mock
private Resource requestResource;
private final RequestCookieHttpCacheConfigExtension systemUnderTest = new RequestCookieHttpCacheConfigExtension();
@Before
public void setUp(){
cookies = new Cookie[]{presentCookie};
emptyCookies = new Cookie[]{irrelevantCookie};
when(emptyRequest.getCookies()).thenReturn(emptyCookies);
when(request.getCookies()).thenReturn(cookies);
when(irrelevantCookie.getName()).thenReturn("bla");
when(presentCookie.getName()).thenReturn("present-cookie-key");
when(presentCookie.getValue()).thenReturn("present-cookie-value");
when(validCacheKeyConfig.getAuthenticationRequirement()).thenReturn("anonymous");
when(request.getRequestURI()).thenReturn(REQUEST_URI);
when(request.getResource()).thenReturn(requestResource);
when(requestResource.getPath()).thenReturn(REQUEST_RESOURCE_PATH);
}
@Test
public void test() throws HttpCacheRepositoryAccessException, HttpCacheKeyCreationException {
systemUnderTest.activate(configA);
assertTrue(systemUnderTest.accepts(request, null));
assertFalse(systemUnderTest.accepts(emptyRequest, null));
KeyValueHttpCacheKey cacheKey = (KeyValueHttpCacheKey) systemUnderTest.build(request, validCacheKeyConfig);
KeyValueMapWrapper map = cacheKey.getKeyValueMap();
assertTrue(map.containsKey("present-cookie-key"));
assertEquals(StringUtils.EMPTY, map.get("present-cookie-key"));
assertFalse(map.containsKey("non-present-cookie"));
assertEquals("/check-in.html[CookieKeyValues:present-cookie-key][AUTH_REQ:anonymous]", cacheKey.toString());
}
@Test
public void test_with_specific_values() throws HttpCacheRepositoryAccessException, HttpCacheKeyCreationException {
systemUnderTest.activate(configB);
assertTrue(systemUnderTest.accepts(request, null));
KeyValueHttpCacheKey cacheKey = (KeyValueHttpCacheKey) systemUnderTest.build(request, validCacheKeyConfig);
KeyValueMapWrapper map = cacheKey.getKeyValueMap();
assertTrue(map.containsKey("present-cookie-key"));
assertEquals("present-cookie-value", map.get("present-cookie-key"));
assertFalse(map.containsKey("non-present-cookie"));
assertEquals("/check-in.html[CookieKeyValues:present-cookie-key=present-cookie-value][AUTH_REQ:anonymous]", cacheKey.toString());
}
@Test
public void testKey() throws HttpCacheRepositoryAccessException, HttpCacheKeyCreationException {
systemUnderTest.activate(configA);
assertTrue(systemUnderTest.accepts(request, null));
assertFalse(systemUnderTest.accepts(emptyRequest, null));
ImmutableSet<String> allowedKeys = ImmutableSet.of("present-cookie-key", "non-present-cookie-key");
ImmutableSet<Cookie> presentValues = ImmutableSet.of(presentCookie);
Map<String, String> cookieKeyValues = new HashMap<>();
KeyValueMapWrapper requestCookieKeyValueMap = new RequestCookieKeyValueWrapperBuilder(allowedKeys, cookieKeyValues, presentValues).build();
KeyValueHttpCacheKey cookieCacheKey = new KeyValueHttpCacheKey(REQUEST_URI, validCacheKeyConfig, requestCookieKeyValueMap);
assertTrue(systemUnderTest.doesKeyMatchConfig(cookieCacheKey, validCacheKeyConfig));
}
}
|
92356e16f1fadb154ff276f2d13a643fb90b7c6f | 1,932 | java | Java | web-common/src/main/java/pl/edu/icm/unity/webui/common/EnumComboBox.java | WillemElbers/unity-idm | bdd318cb2379429bee3a3d2c2feb14a3251a291e | [
"BSD-3-Clause"
] | null | null | null | web-common/src/main/java/pl/edu/icm/unity/webui/common/EnumComboBox.java | WillemElbers/unity-idm | bdd318cb2379429bee3a3d2c2feb14a3251a291e | [
"BSD-3-Clause"
] | 6 | 2016-10-13T13:31:44.000Z | 2016-10-18T16:29:49.000Z | web-common/src/main/java/pl/edu/icm/unity/webui/common/EnumComboBox.java | WillemElbers/unity-idm | bdd318cb2379429bee3a3d2c2feb14a3251a291e | [
"BSD-3-Clause"
] | 1 | 2019-11-19T10:47:34.000Z | 2019-11-19T10:47:34.000Z | 28 | 99 | 0.735507 | 997,296 | /*
* Copyright (c) 2013 ICM Uniwersytet Warszawski All rights reserved.
* See LICENCE.txt file for licensing information.
*/
package pl.edu.icm.unity.webui.common;
import java.util.HashSet;
import java.util.Set;
import java.util.TreeMap;
import pl.edu.icm.unity.server.utils.UnityMessageSource;
import com.vaadin.data.Property;
import com.vaadin.ui.ComboBox;
/**
* {@link ComboBox} allowing to simply select from enum constatnts.
*
* @author K. Benedyczak
* @param <T>
*/
public class EnumComboBox<T extends Enum<?>> extends MapComboBox<T>
{
private UnityMessageSource msg;
private String msgPrefix;
public EnumComboBox(UnityMessageSource msg, String msgPrefix, Class<T> enumClass, T initialValue)
{
init(msg, msgPrefix, enumClass, initialValue, new HashSet<T>());
}
public EnumComboBox(String caption, UnityMessageSource msg, String msgPrefix, Class<T> enumClass,
T initialValue)
{
this(caption, msg, msgPrefix, enumClass, initialValue, new HashSet<T>());
}
public EnumComboBox(String caption, UnityMessageSource msg, String msgPrefix, Class<T> enumClass,
T initialValue, Set<T> hidden)
{
super(caption);
init(msg, msgPrefix, enumClass, initialValue, hidden);
}
private void init(UnityMessageSource msg, String msgPrefix, Class<T> enumClass, T initialValue,
Set<T> hidden)
{
this.msg = msg;
this.msgPrefix = msgPrefix;
TreeMap<String, T> values = new TreeMap<String, T>();
T[] consts = enumClass.getEnumConstants();
for (T constant: consts)
if (!hidden.contains(constant))
values.put(msg.getMessage(msgPrefix+constant.toString()), constant);
super.init(values, msg.getMessage(msgPrefix+initialValue.toString()));
}
/**
* In case of i18n the value might be different
*/
public void setEnumValue(T newValue) throws Property.ReadOnlyException
{
String realValue = msg.getMessage(msgPrefix+newValue.toString());
super.setValue(realValue);
}
}
|
92356e3edfafc6cd44d5f037768e52de55f3664c | 716 | java | Java | backstage-manage-api/src/main/java/com/ak47007/model/vo/main/StatisticsVO.java | ChinaDragonNB/blog-open | 8b630280fa1b209da89110f1cc2387878cdb992f | [
"MIT"
] | 4 | 2021-07-13T12:05:30.000Z | 2022-01-08T09:30:56.000Z | backstage-manage-api/src/main/java/com/ak47007/model/vo/main/StatisticsVO.java | ChinaDragonNB/blog-open | 8b630280fa1b209da89110f1cc2387878cdb992f | [
"MIT"
] | null | null | null | backstage-manage-api/src/main/java/com/ak47007/model/vo/main/StatisticsVO.java | ChinaDragonNB/blog-open | 8b630280fa1b209da89110f1cc2387878cdb992f | [
"MIT"
] | null | null | null | 17.047619 | 47 | 0.646648 | 997,297 | package com.ak47007.model.vo.main;
import io.swagger.annotations.ApiModelProperty;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* @author AK47007
* date 2021/4/23 22:39
* describes: 首页统计数量视图对象
*/
@Data
@AllArgsConstructor
@NoArgsConstructor
public class StatisticsVO {
/**
* 文章数量
*/
@ApiModelProperty(value = "文章数量")
private Integer articleNum;
/**
* 访问数量
*/
@ApiModelProperty(value = "访问数量")
private Integer viewsSum;
/**
* 标签数量
*/
@ApiModelProperty(value = "标签数量")
private Integer tagsNum;
/**
* 友情链接数量
*/
@ApiModelProperty(value = "友情链接数量")
private Integer linksNum;
}
|
92356e6f4d1a5fd1073dabbabfe635ab7745a202 | 1,435 | java | Java | activiti-examples/activiti-api-basic-full-example-bean/src/main/java/org/activiti/examples/Content.java | lipc918/Activiti | 1752f45be53d5c76ce4877bb7a760dbadd59dce3 | [
"Apache-2.0"
] | 347 | 2017-07-31T08:38:02.000Z | 2021-06-14T13:43:20.000Z | activiti-examples/activiti-api-basic-full-example-bean/src/main/java/org/activiti/examples/Content.java | lipc918/Activiti | 1752f45be53d5c76ce4877bb7a760dbadd59dce3 | [
"Apache-2.0"
] | 173 | 2017-08-03T11:45:35.000Z | 2019-12-03T12:54:10.000Z | activiti-examples/activiti-api-basic-full-example-bean/src/main/java/org/activiti/examples/Content.java | lipc918/Activiti | 1752f45be53d5c76ce4877bb7a760dbadd59dce3 | [
"Apache-2.0"
] | 310 | 2017-08-04T02:43:21.000Z | 2021-06-11T09:18:06.000Z | 23.916667 | 136 | 0.602091 | 997,298 | package org.activiti.examples;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import java.util.ArrayList;
import java.util.List;
@JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.PROPERTY,property = "@class")
public class Content {
private String body;
private boolean approved;
private List<String> tags;
@JsonCreator
public Content(@JsonProperty("body")String body, @JsonProperty("approved")boolean approved, @JsonProperty("tags")List<String> tags){
this.body = body;
this.approved = approved;
this.tags = tags;
if(this.tags == null){
this.tags = new ArrayList<>();
}
}
public String getBody() {
return body;
}
public void setBody(String body) {
this.body = body;
}
public boolean isApproved() {
return approved;
}
public void setApproved(boolean approved) {
this.approved = approved;
}
public List<String> getTags() {
return tags;
}
public void setTags(List<String> tags) {
this.tags = tags;
}
@Override
public String toString() {
return "Content{" +
"body='" + body + '\'' +
", approved=" + approved +
", tags=" + tags +
'}';
}
}
|
92356ea4b83a3868b175818cd351a261c06cd65b | 5,283 | java | Java | src/main/java/br/uff/ic/archd/db/dao/DataBaseFactory.java | gems-uff/ada | f5377dbbfad28dd2d3237fe4be6896d6c66ce6da | [
"MIT"
] | 2 | 2017-12-02T03:11:07.000Z | 2021-06-02T15:14:12.000Z | src/main/java/br/uff/ic/archd/db/dao/DataBaseFactory.java | gems-uff/ada | f5377dbbfad28dd2d3237fe4be6896d6c66ce6da | [
"MIT"
] | null | null | null | src/main/java/br/uff/ic/archd/db/dao/DataBaseFactory.java | gems-uff/ada | f5377dbbfad28dd2d3237fe4be6896d6c66ce6da | [
"MIT"
] | null | null | null | 31.260355 | 86 | 0.70036 | 997,299 | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package br.uff.ic.archd.db.dao;
import br.uff.ic.archd.db.dao.mysql.MySQLAnomalieDao;
import br.uff.ic.archd.db.dao.mysql.MySQLArtifactBirthDao;
import br.uff.ic.archd.db.dao.mysql.MySQLClassesDao;
import br.uff.ic.archd.db.dao.mysql.MySQLExternalImportsDao;
import br.uff.ic.archd.db.dao.mysql.MySQLImplementedInterfacesDao;
import br.uff.ic.archd.db.dao.mysql.MySQLInterfaceDao;
import br.uff.ic.archd.db.dao.mysql.MySQLInternalImportsDao;
import br.uff.ic.archd.db.dao.mysql.MySQLJavaAttributeDao;
import br.uff.ic.archd.db.dao.mysql.MySQLJavaExternalAttributeAccessDao;
import br.uff.ic.archd.db.dao.mysql.MySQLJavaMethodDao;
import br.uff.ic.archd.db.dao.mysql.MySQLMethodInvocationsDao;
import br.uff.ic.archd.db.dao.mysql.MySQLOriginalNameDao;
import br.uff.ic.archd.db.dao.mysql.MySQLTerminatedDao;
/**
*
* @author wallace
*/
public class DataBaseFactory {
private static DataBaseFactory dataBaseFactory;
private TerminatedDao terminatedDao;
private ClassesDao classesDao;
private InterfaceDao interfaceDao;
private JavaMethodDao javaMethodDao;
private JavaAttributeDao javaAttributeDao;
private ImplementedInterfacesDao implementedInterfacesDao;
private InternalImportsDao internalImportsDao;
private ExternalImportsDao externalImportsDao;
private MethodInvocationsDao methodInvocationsDao;
private JavaExternalAttributeAccessDao javaExternalAttributeAccessDao;
private AnomalieDao anomalieDao;
private ArtifactBirthDao artifactBirthDao;
private OriginalNameDao originalNameDao;
public static DataBaseFactory getInstance(){
if(dataBaseFactory == null){
dataBaseFactory = new DataBaseFactory();
}
return dataBaseFactory;
}
// private DataBaseFactory(){
// terminatedDao = new HsqldbTerminatedDao();
// classesDao = new HsqldbClassesDao();
// interfaceDao = new HsqldbInterfaceDao();
// javaMethodDao = new HsqldbJavaMethodDao();
// javaAttributeDao = new HsqldbJavaAttributeDao();
// implementedInterfacesDao = new HsqldbImplementedInterfacesDao();
// internalImportsDao = new HsqldbInternalImportsDao();
// externalImportsDao = new HsqldbExternalImportsDao();
// methodInvocationsDao = new HsqldbMethodInvocationsDao();
// javaExternalAttributeAccessDao = new HsqldbJavaExternalAttributeAccessDao();
// anomalieDao = new HsqldbAnomalieDao();
// artifactBirthDao = new HsqldbArtifactBirthDao();
// originalNameDao = new HsqldbOriginalNameDao();
//
// }
private DataBaseFactory(){
terminatedDao = new MySQLTerminatedDao();
classesDao = new MySQLClassesDao();
interfaceDao = new MySQLInterfaceDao();
javaMethodDao = new MySQLJavaMethodDao();
javaAttributeDao = new MySQLJavaAttributeDao();
implementedInterfacesDao = new MySQLImplementedInterfacesDao();
internalImportsDao = new MySQLInternalImportsDao();
externalImportsDao = new MySQLExternalImportsDao();
methodInvocationsDao = new MySQLMethodInvocationsDao();
javaExternalAttributeAccessDao = new MySQLJavaExternalAttributeAccessDao();
anomalieDao = new MySQLAnomalieDao();
artifactBirthDao = new MySQLArtifactBirthDao();
originalNameDao = new MySQLOriginalNameDao();
}
public TerminatedDao getTerminatedDao(){
return terminatedDao;
}
/**
* @return the classesDao
*/
public ClassesDao getClassesDao() {
return classesDao;
}
/**
* @return the interfaceDao
*/
public InterfaceDao getInterfaceDao() {
return interfaceDao;
}
/**
* @return the javaMethodDao
*/
public JavaMethodDao getJavaMethodDao() {
return javaMethodDao;
}
/**
* @return the javaAttributeDao
*/
public JavaAttributeDao getJavaAttributeDao() {
return javaAttributeDao;
}
/**
* @return the implementedInterfacesDao
*/
public ImplementedInterfacesDao getImplementedInterfacesDao() {
return implementedInterfacesDao;
}
/**
* @return the internalImportsDao
*/
public InternalImportsDao getInternalImportsDao() {
return internalImportsDao;
}
/**
* @return the externalImportsDao
*/
public ExternalImportsDao getExternalImportsDao() {
return externalImportsDao;
}
/**
* @return the methodInvocationsDao
*/
public MethodInvocationsDao getMethodInvocationsDao() {
return methodInvocationsDao;
}
public JavaExternalAttributeAccessDao getJavaExternalAttributeAccessDao(){
return javaExternalAttributeAccessDao;
}
/**
* @return the anomalieDao
*/
public AnomalieDao getAnomalieDao() {
return anomalieDao;
}
/**
* @return the artifactBirthDao
*/
public ArtifactBirthDao getArtifactBirthDao() {
return artifactBirthDao;
}
/**
* @return the originalNameDao
*/
public OriginalNameDao getOriginalNameDao() {
return originalNameDao;
}
}
|
92356eb1dd6ee171e80835aeac598ec2f3b110cb | 9,160 | java | Java | src/test/java/care/better/platform/web/template/NamedElementsTest.java | better-care/webtemplate-test | 8f3381a37d6d77df8dfa06c35b3308a6933047d5 | [
"Apache-2.0"
] | null | null | null | src/test/java/care/better/platform/web/template/NamedElementsTest.java | better-care/webtemplate-test | 8f3381a37d6d77df8dfa06c35b3308a6933047d5 | [
"Apache-2.0"
] | null | null | null | src/test/java/care/better/platform/web/template/NamedElementsTest.java | better-care/webtemplate-test | 8f3381a37d6d77df8dfa06c35b3308a6933047d5 | [
"Apache-2.0"
] | null | null | null | 60.263158 | 159 | 0.730895 | 997,300 | /* Copyright 2020-2021 Better Ltd (www.better.care)
*
* 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 care.better.platform.web.template;
import care.better.platform.web.template.extension.WebTemplateTestExtension;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.datatype.joda.JodaModule;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import java.util.Collections;
import java.util.Map;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.entry;
/**
* @author Marko Narat
*/
@SuppressWarnings("AnonymousInnerClassMayBeStatic")
@ExtendWith(WebTemplateTestExtension.class)
public class NamedElementsTest extends AbstractWebTemplateTest {
private ObjectMapper objectMapper;
@Override
@BeforeEach
public void setUp() {
super.setUp();
objectMapper = new ObjectMapper();
objectMapper.registerModule(new JodaModule());
objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
}
@Test
public void customNames() throws Exception {
String template = getFileContent("/res/IDCR_-_Laboratory_Test_Report.v0.opt");
Map<String, Object> flatComposition = objectMapper.readValue(getFileContent("/res/NamedElements1.json"), new TypeReference<Map<String, Object>>() {});
JsonNode rawComposition = getCompositionConverter().convertFlatToRaw(
template,
"en",
objectMapper.writeValueAsString(flatComposition),
Collections.emptyMap(),
objectMapper);
Map<String, Object> retrieve = getCompositionConverter().convertRawToFlat(template, "en", rawComposition.toString(), objectMapper);
assertThat(retrieve).contains(
entry("laboratory_test_report/laboratory_test:0/laboratory_test_panel/laboratory_result:0/result_value/_name|value", "Urea"));
assertThat(retrieve).contains(
entry("laboratory_test_report/laboratory_test:0/laboratory_test_panel/laboratory_result:0/result_value/_name|code", "365755003"));
assertThat(retrieve).contains(
entry("laboratory_test_report/laboratory_test:0/laboratory_test_panel/laboratory_result:0/result_value/_name|terminology",
"SNOMED-CT"));
assertThat(retrieve).contains(
entry("laboratory_test_report/laboratory_test:0/laboratory_test_panel/laboratory_result:1/result_value/_name|value", "Creatinine"));
assertThat(retrieve).contains(
entry("laboratory_test_report/laboratory_test:0/laboratory_test_panel/laboratory_result:1/result_value/_name|code", "70901006"));
assertThat(retrieve).contains(
entry("laboratory_test_report/laboratory_test:0/laboratory_test_panel/laboratory_result:1/result_value/_name|terminology",
"SNOMED-CT"));
assertThat(retrieve).contains(
entry("laboratory_test_report/laboratory_test:0/laboratory_test_panel/laboratory_result:2/result_value/_name|value", "Sodium"));
assertThat(retrieve).contains(
entry("laboratory_test_report/laboratory_test:0/laboratory_test_panel/laboratory_result:2/result_value/_name|code", "365761000"));
assertThat(retrieve).contains(
entry("laboratory_test_report/laboratory_test:0/laboratory_test_panel/laboratory_result:2/result_value/_name|terminology",
"SNOMED-CT"));
assertThat(retrieve).contains(
entry("laboratory_test_report/laboratory_test:0/laboratory_test_panel/laboratory_result:3/result_value/_name|value", "Potassium"));
assertThat(retrieve).contains(
entry("laboratory_test_report/laboratory_test:0/laboratory_test_panel/laboratory_result:3/result_value/_name|code", "365760004"));
assertThat(retrieve).contains(
entry("laboratory_test_report/laboratory_test:0/laboratory_test_panel/laboratory_result:3/result_value/_name|terminology",
"SNOMED-CT"));
}
@Test
public void customNamesAsDvText() throws Exception {
String template = getFileContent("/res/IDCR_-_Laboratory_Test_Report.v0.opt");
Map<String, Object> flatComposition = objectMapper.readValue(getFileContent("/res/NamedElements2.json"), new TypeReference<Map<String, Object>>() {});
JsonNode rawComposition = getCompositionConverter().convertFlatToRaw(
template,
"en",
objectMapper.writeValueAsString(flatComposition),
Collections.emptyMap(),
objectMapper);
Map<String, Object> retrieve = getCompositionConverter().convertRawToFlat(template, "en", rawComposition.toString(), objectMapper);
assertThat(retrieve).contains(
entry("laboratory_test_report/laboratory_test:0/laboratory_test_panel/laboratory_result:0/result_value/_name", "Urea"),
entry("laboratory_test_report/laboratory_test:0/laboratory_test_panel/laboratory_result:1/result_value/_name", "New name"));
assertThat(retrieve.keySet()).doesNotContain(
"laboratory_test_report/laboratory_test:0/laboratory_test_panel/laboratory_result:0/result_value/_name|code",
"laboratory_test_report/laboratory_test:0/laboratory_test_panel/laboratory_result:0/result_value/_name|terminology",
"laboratory_test_report/laboratory_test:0/laboratory_test_panel/laboratory_result:1/result_value/_name|code",
"laboratory_test_report/laboratory_test:0/laboratory_test_panel/laboratory_result:1/result_value/_name|terminology");
}
@Test
public void regularNames() throws Exception {
String template = getFileContent("/res/IDCR_-_Laboratory_Test_Report.v0.opt");
Map<String, Object> flatComposition = objectMapper.readValue(getFileContent("/res/NamedElements3.json"), new TypeReference<Map<String, Object>>() {});
JsonNode rawComposition = getCompositionConverter().convertFlatToRaw(
template,
"en",
objectMapper.writeValueAsString(flatComposition),
Collections.emptyMap(),
objectMapper);
Map<String, Object> retrieve = getCompositionConverter().convertRawToFlat(template, "en", rawComposition.toString(), objectMapper);
assertThat(
retrieve.containsKey("laboratory_test_report/laboratory_test:0/laboratory_test_panel/laboratory_result:0/result_value/_name|value")).isFalse();
assertThat(retrieve.containsKey("laboratory_test_report/laboratory_test:0/laboratory_test_panel/laboratory_result:0/result_value|magnitude")).isTrue();
assertThat(
retrieve.containsKey("laboratory_test_report/laboratory_test:0/laboratory_test_panel/laboratory_result:1/result_value/_name|value")).isFalse();
assertThat(retrieve.containsKey("laboratory_test_report/laboratory_test:0/laboratory_test_panel/laboratory_result:1/result_value|magnitude")).isTrue();
assertThat(
retrieve.containsKey("laboratory_test_report/laboratory_test:1/laboratory_test_panel/laboratory_result:0/result_value/_name|value")).isFalse();
assertThat(retrieve.containsKey("laboratory_test_report/laboratory_test:1/laboratory_test_panel/laboratory_result:0/result_value|magnitude")).isTrue();
assertThat(
retrieve.containsKey("laboratory_test_report/laboratory_test:1/laboratory_test_panel/laboratory_result:1/result_value/_name|value")).isFalse();
assertThat(retrieve.containsKey("laboratory_test_report/laboratory_test:1/laboratory_test_panel/laboratory_result:1/result_value|magnitude")).isTrue();
assertThat(retrieve).doesNotContain(
entry("laboratory_test_report/laboratory_test:1/laboratory_test_panel/laboratory_result:1/result_value/_name|value", "Potassium"),
entry("laboratory_test_report/laboratory_test:1/laboratory_test_panel/laboratory_result:1/result_value/_name|code", "365760004"),
entry("laboratory_test_report/laboratory_test:1/laboratory_test_panel/laboratory_result:1/result_value/_name|terminology",
"SNOMED-CT"));
assertThat(retrieve.keySet().stream().anyMatch(input -> input.contains("/_name"))).isFalse();
}
} |
92356fe593f1f29cb330878142671f0c16339f76 | 1,478 | java | Java | eap74-rhel8-payg-multivm/src/test/coffee-app/src/main/java/cafe/model/CafeRepository.java | edburns/rhel-jboss-templates | c38723be24cd89219204f79270425aff5ba086a4 | [
"MIT"
] | 7 | 2020-07-07T06:01:59.000Z | 2022-01-05T16:37:58.000Z | eap74-rhel8-payg-multivm/src/test/coffee-app/src/main/java/cafe/model/CafeRepository.java | edburns/rhel-jboss-templates | c38723be24cd89219204f79270425aff5ba086a4 | [
"MIT"
] | 3 | 2021-04-21T03:15:34.000Z | 2022-02-16T01:18:14.000Z | eap74-rhel8-payg-multivm/src/test/coffee-app/src/main/java/cafe/model/CafeRepository.java | edburns/rhel-jboss-templates | c38723be24cd89219204f79270425aff5ba086a4 | [
"MIT"
] | 9 | 2021-01-02T14:13:14.000Z | 2022-02-01T02:29:51.000Z | 26.872727 | 103 | 0.731394 | 997,301 | package cafe.model;
import java.lang.invoke.MethodHandles;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicLong;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.enterprise.context.ApplicationScoped;
import cafe.model.entity.Coffee;
@ApplicationScoped
public class CafeRepository {
private static final Logger logger = Logger.getLogger(MethodHandles.lookup().lookupClass().getName());
private List<Coffee> coffeeList = null;
private AtomicLong counter;
public CafeRepository() {
coffeeList = new ArrayList<Coffee>();
counter = new AtomicLong();
persistCoffee(new Coffee("Coffee 1", 10.0));
persistCoffee(new Coffee("Coffee 2", 20.0));
}
public List<Coffee> getAllCoffees() {
logger.log(Level.INFO, "Finding all coffees.");
return coffeeList;
}
public Coffee persistCoffee(Coffee coffee) {
logger.log(Level.INFO, "Persisting the new coffee {0}.", coffee);
coffee.setId(counter.incrementAndGet());
coffeeList.add(coffee);
return coffee;
}
public void removeCoffeeById(Long coffeeId) {
logger.log(Level.INFO, "Removing a coffee {0}.", coffeeId);
coffeeList.removeIf(coffee -> coffee.getId().equals(coffeeId));
}
public Coffee findCoffeeById(Long coffeeId) {
logger.log(Level.INFO, "Finding the coffee with id {0}.", coffeeId);
return coffeeList.stream().filter(coffee -> coffee.getId().equals(coffeeId)).findFirst().get();
}
}
|
9235702c5d60b6b5bc62993648e0731f6725ef82 | 4,845 | java | Java | domain/src/main/java/com/chilitech/domain/features/home/HomePresenter.java | chilitech/ChiliTech | 6a2a94d237b8baf56854e5709efd69d4e0c7febc | [
"Apache-2.0"
] | null | null | null | domain/src/main/java/com/chilitech/domain/features/home/HomePresenter.java | chilitech/ChiliTech | 6a2a94d237b8baf56854e5709efd69d4e0c7febc | [
"Apache-2.0"
] | null | null | null | domain/src/main/java/com/chilitech/domain/features/home/HomePresenter.java | chilitech/ChiliTech | 6a2a94d237b8baf56854e5709efd69d4e0c7febc | [
"Apache-2.0"
] | null | null | null | 29.363636 | 131 | 0.597523 | 997,302 | package com.chilitech.domain.features.home;
import com.chilitech.domain.base.BaseUseCase;
import com.chilitech.domain.usecase.RequestBannerTask;
import com.chilitech.domain.usecase.RequestCategoryDetailTask;
import com.chilitech.domain.usecase.RequestCategoryTask;
import com.chilitech.domain.usecase.RequestUpdateStrategyTask;
import javax.inject.Inject;
public class HomePresenter implements HomeContract.Presenter {
HomeContract.View mView;
@Inject
RequestBannerTask mRequestBannerTask;
@Inject
RequestCategoryDetailTask mRequestCategoryDetailTask;
@Inject
RequestCategoryTask mRequestCategoryTask;
@Inject
RequestUpdateStrategyTask mRequestUpdateStrategyTask;
@Inject
public HomePresenter() {
}
@Override
public void setView(HomeContract.View view) {
this.mView = view;
}
@Override
public void resume() {
}
@Override
public void pause() {
}
@Override
public void destroy() {
this.mView = null;
if (mRequestBannerTask != null) {
mRequestBannerTask.cancel();
}
if (mRequestCategoryDetailTask != null) {
mRequestCategoryDetailTask.cancel();
}
if (mRequestCategoryTask != null) {
mRequestCategoryTask.cancel();
}
if (mRequestUpdateStrategyTask != null) {
mRequestUpdateStrategyTask.cancel();
}
}
@Override
public void requestCategory(String token) {
mRequestCategoryTask.setRequestValues(new RequestCategoryTask.RequestValues(token));
mRequestCategoryTask.setUseCaseCallback(new BaseUseCase.UseCaseCallback<RequestCategoryTask.ResponseValues>() {
@Override
public void onSuccess(RequestCategoryTask.ResponseValues response) {
if (mView == null) {
return;
}
mView.requestCategorySuccess(response.getList());
}
@Override
public void onError() {
if (mView == null) {
return;
}
mView.requestCategoryFail();
}
});
mRequestCategoryTask.run();
}
@Override
public void requestCategoryDetail(String id) {
mRequestCategoryDetailTask.setRequestValues(new RequestCategoryDetailTask.RequestValues(id));
mRequestCategoryDetailTask.setUseCaseCallback(new BaseUseCase.UseCaseCallback<RequestCategoryDetailTask.ResponseValues>() {
@Override
public void onSuccess(RequestCategoryDetailTask.ResponseValues response) {
if (mView == null) {
return;
}
mView.requestCategoryDetailSuccess(response.getList());
}
@Override
public void onError() {
if (mView == null) {
return;
}
mView.requestCategoryDetailFail();
}
});
mRequestCategoryDetailTask.run();
}
@Override
public void requestBanner(String token) {
mRequestBannerTask.setRequestValues(new RequestBannerTask.RequestValues(token));
mRequestBannerTask.setUseCaseCallback(new BaseUseCase.UseCaseCallback<RequestBannerTask.ResponseValues>() {
@Override
public void onSuccess(RequestBannerTask.ResponseValues response) {
if (mView == null) {
return;
}
mView.requestBannerSuccess(response.getUrl());
}
@Override
public void onError() {
if (mView == null) {
return;
}
mView.requestBannerFail();
}
});
mRequestBannerTask.run();
}
@Override
public void requestUpdateStrategy(String token) {
mRequestUpdateStrategyTask.setRequestValues(new RequestUpdateStrategyTask.RequestValues(token));
mRequestUpdateStrategyTask.setUseCaseCallback(new BaseUseCase.UseCaseCallback<RequestUpdateStrategyTask.ResponseValues>() {
@Override
public void onSuccess(RequestUpdateStrategyTask.ResponseValues response) {
if (mView == null) {
return;
}
mView.requestUpdateStrategySuccess(response.isNeedToBeUpdated());
}
@Override
public void onError() {
if (mView == null) {
return;
}
mView.requestUpdateStrategyFail();
}
});
mRequestUpdateStrategyTask.run();
}
@Override
public void gotoAddCategoryActivity() {
}
@Override
public void gotoSearchActivity() {
}
}
|
92357090f1be7c4e80ec54f447191bcf3f01c0a7 | 2,316 | java | Java | wechat-server/src/main/java/top/erzhiqian/weixin/account/app/WeixinAppManagerApp.java | erzhiqianyi/LeaningMicroservice | c4f5a4812994ac6436fbfaf884e98e16902913d5 | [
"Apache-2.0"
] | null | null | null | wechat-server/src/main/java/top/erzhiqian/weixin/account/app/WeixinAppManagerApp.java | erzhiqianyi/LeaningMicroservice | c4f5a4812994ac6436fbfaf884e98e16902913d5 | [
"Apache-2.0"
] | 4 | 2020-09-27T14:33:18.000Z | 2020-10-10T00:50:55.000Z | wechat-server/src/main/java/top/erzhiqian/weixin/account/app/WeixinAppManagerApp.java | erzhiqianyi/LeaningMicroservice | c4f5a4812994ac6436fbfaf884e98e16902913d5 | [
"Apache-2.0"
] | null | null | null | 40.631579 | 103 | 0.71114 | 997,303 | package top.erzhiqian.weixin.account.app;
import org.springframework.stereotype.Component;
import top.erzhiqian.weixin.account.client.cmd.WeixinAppRegisterCmd;
import top.erzhiqian.weixin.account.domain.entity.WeixinApp;
import top.erzhiqian.weixin.account.domain.entity.AppHost;
import top.erzhiqian.weixin.account.domain.repository.WeixinAppHostRepository;
import top.erzhiqian.weixin.account.domain.repository.WeixinAppRepository;
import top.erzhiqian.weixin.account.domain.valueobject.HostAccountId;
import top.erzhiqian.weixin.account.domain.valueobject.WeixinAppAccount;
import top.erzhiqian.weixin.lang.WeixinAppId;
import java.util.Optional;
@Component
public class WeixinAppManagerApp {
private WeixinAppRepository weixinAppRepository;
private WeixinAppHostRepository hostRepository;
public WeixinAppManagerApp(WeixinAppRepository weixinAppRepository,
WeixinAppHostRepository hostRepository) {
this.weixinAppRepository = weixinAppRepository;
this.hostRepository = hostRepository;
}
public void registerWeixinApp(HostAccountId hostId, WeixinAppRegisterCmd cmd) {
WeixinAppId appId = WeixinAppId.app(cmd.getAppId());
WeixinApp app = weixinAppRepository.findWeixinApp(appId);
/**
//todo 判断app是否已经存在
Optional<AppHost> optional = hostRepository.findWeixinAppHost(WeixinAppId.app(cmd.getAppId()));
if (optional.isPresent()) {
throw new IllegalArgumentException("app already register.");
}
host.registerApp();
Optional<WeixinApp> optional = weixinAppRepository.findWeixinApp(appId);
if (optional.isPresent()) {
throw new IllegalArgumentException("weixin app already exists.");
}
WeixinAppAccount weixinAccount = new WeixinAppAccount
.Builder(cmd.getAppId(), cmd.getAppName(), cmd.getAppType())
.originalId(cmd.getOriginalId())
.weixinId(cmd.getWeixinId())
.state(cmd.getCertifiedStatus())
.hostType(cmd.getHostType())
.build();
AppHost appHost = null;
// AppHost.registerAccount(host, weixinAccount);
hostRepository.save(appHost);
weixinAppRepository.save(weixinAccount);
*/
}
}
|
9235709e809bcf65a2e4bddfffaa4e50a47608c9 | 178 | java | Java | vertx-pin/zero-jet/src/main/java/io/vertx/tp/jet/cv/em/WorkerType.java | evgreenhua/vertx-zero | e4fd363516427a13dd9664a06d8a49ed16be1e9f | [
"Apache-2.0"
] | 454 | 2017-11-12T09:00:21.000Z | 2022-03-10T14:26:04.000Z | vertx-pin/zero-jet/src/main/java/io/vertx/tp/jet/cv/em/WorkerType.java | evgreenhua/vertx-zero | e4fd363516427a13dd9664a06d8a49ed16be1e9f | [
"Apache-2.0"
] | 56 | 2017-11-28T05:36:25.000Z | 2022-03-26T14:19:57.000Z | vertx-pin/zero-jet/src/main/java/io/vertx/tp/jet/cv/em/WorkerType.java | evgreenhua/vertx-zero | e4fd363516427a13dd9664a06d8a49ed16be1e9f | [
"Apache-2.0"
] | 103 | 2017-11-07T00:49:59.000Z | 2022-03-31T10:22:59.000Z | 16.181818 | 33 | 0.483146 | 997,304 | package io.vertx.tp.jet.cv.em;
/*
* Worker Type
*/
public enum WorkerType {
STD, // Standard
PLUG, // Plug-in
JS, // JavaScript
}
|
9235710d4d4903f0bb191820608c95dd353656a5 | 664 | java | Java | back-end/src/main/java/eu/acclimatize/unison/HourlyWeather.java | conormuldoon/unison | 7dc520b98fff5e8352b178735706e04e4f9516b9 | [
"MIT"
] | null | null | null | back-end/src/main/java/eu/acclimatize/unison/HourlyWeather.java | conormuldoon/unison | 7dc520b98fff5e8352b178735706e04e4f9516b9 | [
"MIT"
] | null | null | null | back-end/src/main/java/eu/acclimatize/unison/HourlyWeather.java | conormuldoon/unison | 7dc520b98fff5e8352b178735706e04e4f9516b9 | [
"MIT"
] | null | null | null | 15.090909 | 61 | 0.706325 | 997,305 | package eu.acclimatize.unison;
import javax.persistence.Embedded;
import javax.persistence.EmbeddedId;
import javax.persistence.Entity;
/**
*
* A JPA entity class for storing hourly weather data.
*
*/
@Entity
public class HourlyWeather {
@EmbeddedId
private ItemKey key;
@Embedded
private WeatherValue value;
/**
* Creates an instance of HourlyWeather.
*
* @param k The entities primary key.
* @param weatherValue The weather value for the hour.
*/
public HourlyWeather(ItemKey k, WeatherValue weatherValue) {
key = k;
value = weatherValue;
}
/**
* A zero argument constructor for JPA.
*/
public HourlyWeather() {
}
}
|
923572307a27c48eff019d0f65d72940244f3791 | 2,035 | java | Java | src/main/java/org/rulelearn/rules/UnknownRuleSemanticsException.java | ruleLearn/rulelearn | b1eaf7375bb586da4a7a70ed31e3983dbc40ac7f | [
"Apache-2.0"
] | 6 | 2018-04-17T08:36:26.000Z | 2020-11-28T21:22:27.000Z | src/main/java/org/rulelearn/rules/UnknownRuleSemanticsException.java | ruleLearn/rulelearn | b1eaf7375bb586da4a7a70ed31e3983dbc40ac7f | [
"Apache-2.0"
] | null | null | null | src/main/java/org/rulelearn/rules/UnknownRuleSemanticsException.java | ruleLearn/rulelearn | b1eaf7375bb586da4a7a70ed31e3983dbc40ac7f | [
"Apache-2.0"
] | 8 | 2019-04-09T20:37:40.000Z | 2019-12-10T12:26:30.000Z | 33.349206 | 166 | 0.708234 | 997,306 | /**
* Copyright (C) Jerzy Błaszczyński, Marcin Szeląg
*
* 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.rulelearn.rules;
/**
* Exception occurring when the semantics of a decision rule is different than expected (i.e., it might be correct but is not concordant with the expected semantics).
*
* @author Jerzy Błaszczyński (<a href="mailto:envkt@example.com@cs.put.poznan.pl</a>)
* @author Marcin Szeląg (<a href="mailto:ychag@example.com@cs.put.poznan.pl</a>)
*
*/
public class UnknownRuleSemanticsException extends RuntimeException {
private static final long serialVersionUID = 5034172542445366932L;
public UnknownRuleSemanticsException() {
super();
}
/**
* Creates an exception with a message.
*
* @param message exception message
*/
public UnknownRuleSemanticsException(String message) {
super(message);
}
/**
* Creates an exception without a message but with a pointer to a cause.
*
* @param cause a throwable exception, which caused the {@link UnknownRuleSemanticsException}
*/
public UnknownRuleSemanticsException(Throwable cause) {
super(cause);
}
/**
* Creates an exception with a message and a pointer to a cause.
*
* @param message exception message
* @param cause a throwable exception, which caused the {@link UnknownRuleSemanticsException}
*/
public UnknownRuleSemanticsException(String message, Throwable cause) {
super(message, cause);
}
}
|
923572895b23c3e9b2e0f48459a3fc632c0b13d2 | 3,081 | java | Java | presto-spark-base/src/main/java/com/facebook/presto/spark/PrestoSparkServiceFactory.java | ahouzheng/presto | c2ac1469eea9da9c6e29c8c4d43e00b851400c8b | [
"Apache-2.0"
] | 9,782 | 2016-03-18T15:16:19.000Z | 2022-03-31T07:49:41.000Z | presto-spark-base/src/main/java/com/facebook/presto/spark/PrestoSparkServiceFactory.java | ahouzheng/presto | c2ac1469eea9da9c6e29c8c4d43e00b851400c8b | [
"Apache-2.0"
] | 10,310 | 2016-03-18T01:03:00.000Z | 2022-03-31T23:54:08.000Z | presto-spark-base/src/main/java/com/facebook/presto/spark/PrestoSparkServiceFactory.java | ahouzheng/presto | c2ac1469eea9da9c6e29c8c4d43e00b851400c8b | [
"Apache-2.0"
] | 3,803 | 2016-03-18T22:54:24.000Z | 2022-03-31T07:49:46.000Z | 42.791667 | 136 | 0.753002 | 997,307 | /*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.presto.spark;
import com.facebook.airlift.log.Logger;
import com.facebook.presto.spark.classloader_interface.IPrestoSparkService;
import com.facebook.presto.spark.classloader_interface.IPrestoSparkServiceFactory;
import com.facebook.presto.spark.classloader_interface.PrestoSparkConfiguration;
import com.facebook.presto.spark.classloader_interface.SparkProcessType;
import com.facebook.presto.sql.parser.SqlParserOptions;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.inject.Injector;
import com.google.inject.Module;
import java.util.List;
import static com.google.common.base.Preconditions.checkArgument;
public class PrestoSparkServiceFactory
implements IPrestoSparkServiceFactory
{
private final Logger log = Logger.get(PrestoSparkServiceFactory.class);
@Override
public IPrestoSparkService createService(SparkProcessType sparkProcessType, PrestoSparkConfiguration configuration)
{
ImmutableMap.Builder<String, String> properties = ImmutableMap.builder();
properties.putAll(configuration.getConfigProperties());
properties.put("plugin.dir", configuration.getPluginsDirectoryPath());
PrestoSparkInjectorFactory prestoSparkInjectorFactory = new PrestoSparkInjectorFactory(
sparkProcessType,
properties.build(),
configuration.getCatalogProperties(),
configuration.getEventListenerProperties(),
configuration.getAccessControlProperties(),
configuration.getSessionPropertyConfigurationProperties(),
configuration.getFunctionNamespaceProperties(),
configuration.getTempStorageProperties(),
getSqlParserOptions(),
getAdditionalModules(configuration));
Injector injector = prestoSparkInjectorFactory.create();
PrestoSparkService prestoSparkService = injector.getInstance(PrestoSparkService.class);
log.info("Initialized");
return prestoSparkService;
}
protected List<Module> getAdditionalModules(PrestoSparkConfiguration configuration)
{
checkArgument("LOCAL".equals(configuration.getMetadataStorageType().toUpperCase()), "only local metadata storage is supported");
return ImmutableList.of(new PrestoSparkLocalMetadataStorageModule());
}
protected SqlParserOptions getSqlParserOptions()
{
return new SqlParserOptions();
}
}
|
923572b6491b08e224df5856eb68d01da2e4cf35 | 10,757 | java | Java | src/main/java/com/microsoft/graph/requests/ScheduleRequestBuilder.java | GotanDev/msgraph-sdk-java | a8d54844f82989f172ea8585202f2c403f9a0be7 | [
"MIT"
] | 260 | 2018-02-27T22:36:10.000Z | 2022-03-30T14:36:25.000Z | src/main/java/com/microsoft/graph/requests/ScheduleRequestBuilder.java | GotanDev/msgraph-sdk-java | a8d54844f82989f172ea8585202f2c403f9a0be7 | [
"MIT"
] | 561 | 2018-02-28T02:37:38.000Z | 2022-03-31T08:01:19.000Z | src/main/java/com/microsoft/graph/requests/ScheduleRequestBuilder.java | GotanDev/msgraph-sdk-java | a8d54844f82989f172ea8585202f2c403f9a0be7 | [
"MIT"
] | 130 | 2018-02-27T23:24:41.000Z | 2022-02-23T15:14:42.000Z | 39.988848 | 200 | 0.723529 | 997,308 | // Template Source: BaseEntityRequestBuilder.java.tt
// ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
// ------------------------------------------------------------------------------
package com.microsoft.graph.requests;
import com.microsoft.graph.http.IRequestBuilder;
import com.microsoft.graph.core.ClientException;
import com.microsoft.graph.models.Schedule;
import com.microsoft.graph.requests.OfferShiftRequestCollectionRequestBuilder;
import com.microsoft.graph.requests.OfferShiftRequestRequestBuilder;
import com.microsoft.graph.requests.OpenShiftChangeRequestCollectionRequestBuilder;
import com.microsoft.graph.requests.OpenShiftChangeRequestRequestBuilder;
import com.microsoft.graph.requests.OpenShiftCollectionRequestBuilder;
import com.microsoft.graph.requests.OpenShiftRequestBuilder;
import com.microsoft.graph.requests.SchedulingGroupCollectionRequestBuilder;
import com.microsoft.graph.requests.SchedulingGroupRequestBuilder;
import com.microsoft.graph.requests.ShiftCollectionRequestBuilder;
import com.microsoft.graph.requests.ShiftRequestBuilder;
import com.microsoft.graph.requests.SwapShiftsChangeRequestCollectionRequestBuilder;
import com.microsoft.graph.requests.SwapShiftsChangeRequestRequestBuilder;
import com.microsoft.graph.requests.TimeOffReasonCollectionRequestBuilder;
import com.microsoft.graph.requests.TimeOffReasonRequestBuilder;
import com.microsoft.graph.requests.TimeOffRequestCollectionRequestBuilder;
import com.microsoft.graph.requests.TimeOffRequestRequestBuilder;
import com.microsoft.graph.requests.TimeOffCollectionRequestBuilder;
import com.microsoft.graph.requests.TimeOffRequestBuilder;
import java.util.Arrays;
import java.util.EnumSet;
import javax.annotation.Nullable;
import javax.annotation.Nonnull;
import com.microsoft.graph.core.IBaseClient;
import com.microsoft.graph.http.BaseRequestBuilder;
import com.microsoft.graph.models.ScheduleShareParameterSet;
// **NOTE** This file was generated by a tool and any changes will be overwritten.
/**
* The class for the Schedule Request Builder.
*/
public class ScheduleRequestBuilder extends BaseRequestBuilder<Schedule> {
/**
* The request builder for the Schedule
*
* @param requestUrl the request URL
* @param client the service client
* @param requestOptions the options for this request
*/
public ScheduleRequestBuilder(@Nonnull final String requestUrl, @Nonnull final IBaseClient<?> client, @Nullable final java.util.List<? extends com.microsoft.graph.options.Option> requestOptions) {
super(requestUrl, client, requestOptions);
}
/**
* Creates the request
*
* @param requestOptions the options for this request
* @return the ScheduleRequest instance
*/
@Nonnull
public ScheduleRequest buildRequest(@Nullable final com.microsoft.graph.options.Option... requestOptions) {
return buildRequest(getOptions(requestOptions));
}
/**
* Creates the request with specific requestOptions instead of the existing requestOptions
*
* @param requestOptions the options for this request
* @return the ScheduleRequest instance
*/
@Nonnull
public ScheduleRequest buildRequest(@Nonnull final java.util.List<? extends com.microsoft.graph.options.Option> requestOptions) {
return new com.microsoft.graph.requests.ScheduleRequest(getRequestUrl(), getClient(), requestOptions);
}
/**
* Gets a request builder for the OfferShiftRequest collection
*
* @return the collection request builder
*/
@Nonnull
public OfferShiftRequestCollectionRequestBuilder offerShiftRequests() {
return new OfferShiftRequestCollectionRequestBuilder(getRequestUrlWithAdditionalSegment("offerShiftRequests"), getClient(), null);
}
/**
* Gets a request builder for the OfferShiftRequest item
*
* @return the request builder
* @param id the item identifier
*/
@Nonnull
public OfferShiftRequestRequestBuilder offerShiftRequests(@Nonnull final String id) {
return new OfferShiftRequestRequestBuilder(getRequestUrlWithAdditionalSegment("offerShiftRequests") + "/" + id, getClient(), null);
}
/**
* Gets a request builder for the OpenShiftChangeRequest collection
*
* @return the collection request builder
*/
@Nonnull
public OpenShiftChangeRequestCollectionRequestBuilder openShiftChangeRequests() {
return new OpenShiftChangeRequestCollectionRequestBuilder(getRequestUrlWithAdditionalSegment("openShiftChangeRequests"), getClient(), null);
}
/**
* Gets a request builder for the OpenShiftChangeRequest item
*
* @return the request builder
* @param id the item identifier
*/
@Nonnull
public OpenShiftChangeRequestRequestBuilder openShiftChangeRequests(@Nonnull final String id) {
return new OpenShiftChangeRequestRequestBuilder(getRequestUrlWithAdditionalSegment("openShiftChangeRequests") + "/" + id, getClient(), null);
}
/**
* Gets a request builder for the OpenShift collection
*
* @return the collection request builder
*/
@Nonnull
public OpenShiftCollectionRequestBuilder openShifts() {
return new OpenShiftCollectionRequestBuilder(getRequestUrlWithAdditionalSegment("openShifts"), getClient(), null);
}
/**
* Gets a request builder for the OpenShift item
*
* @return the request builder
* @param id the item identifier
*/
@Nonnull
public OpenShiftRequestBuilder openShifts(@Nonnull final String id) {
return new OpenShiftRequestBuilder(getRequestUrlWithAdditionalSegment("openShifts") + "/" + id, getClient(), null);
}
/**
* Gets a request builder for the SchedulingGroup collection
*
* @return the collection request builder
*/
@Nonnull
public SchedulingGroupCollectionRequestBuilder schedulingGroups() {
return new SchedulingGroupCollectionRequestBuilder(getRequestUrlWithAdditionalSegment("schedulingGroups"), getClient(), null);
}
/**
* Gets a request builder for the SchedulingGroup item
*
* @return the request builder
* @param id the item identifier
*/
@Nonnull
public SchedulingGroupRequestBuilder schedulingGroups(@Nonnull final String id) {
return new SchedulingGroupRequestBuilder(getRequestUrlWithAdditionalSegment("schedulingGroups") + "/" + id, getClient(), null);
}
/**
* Gets a request builder for the Shift collection
*
* @return the collection request builder
*/
@Nonnull
public ShiftCollectionRequestBuilder shifts() {
return new ShiftCollectionRequestBuilder(getRequestUrlWithAdditionalSegment("shifts"), getClient(), null);
}
/**
* Gets a request builder for the Shift item
*
* @return the request builder
* @param id the item identifier
*/
@Nonnull
public ShiftRequestBuilder shifts(@Nonnull final String id) {
return new ShiftRequestBuilder(getRequestUrlWithAdditionalSegment("shifts") + "/" + id, getClient(), null);
}
/**
* Gets a request builder for the SwapShiftsChangeRequest collection
*
* @return the collection request builder
*/
@Nonnull
public SwapShiftsChangeRequestCollectionRequestBuilder swapShiftsChangeRequests() {
return new SwapShiftsChangeRequestCollectionRequestBuilder(getRequestUrlWithAdditionalSegment("swapShiftsChangeRequests"), getClient(), null);
}
/**
* Gets a request builder for the SwapShiftsChangeRequest item
*
* @return the request builder
* @param id the item identifier
*/
@Nonnull
public SwapShiftsChangeRequestRequestBuilder swapShiftsChangeRequests(@Nonnull final String id) {
return new SwapShiftsChangeRequestRequestBuilder(getRequestUrlWithAdditionalSegment("swapShiftsChangeRequests") + "/" + id, getClient(), null);
}
/**
* Gets a request builder for the TimeOffReason collection
*
* @return the collection request builder
*/
@Nonnull
public TimeOffReasonCollectionRequestBuilder timeOffReasons() {
return new TimeOffReasonCollectionRequestBuilder(getRequestUrlWithAdditionalSegment("timeOffReasons"), getClient(), null);
}
/**
* Gets a request builder for the TimeOffReason item
*
* @return the request builder
* @param id the item identifier
*/
@Nonnull
public TimeOffReasonRequestBuilder timeOffReasons(@Nonnull final String id) {
return new TimeOffReasonRequestBuilder(getRequestUrlWithAdditionalSegment("timeOffReasons") + "/" + id, getClient(), null);
}
/**
* Gets a request builder for the TimeOffRequest collection
*
* @return the collection request builder
*/
@Nonnull
public TimeOffRequestCollectionRequestBuilder timeOffRequests() {
return new TimeOffRequestCollectionRequestBuilder(getRequestUrlWithAdditionalSegment("timeOffRequests"), getClient(), null);
}
/**
* Gets a request builder for the TimeOffRequest item
*
* @return the request builder
* @param id the item identifier
*/
@Nonnull
public TimeOffRequestRequestBuilder timeOffRequests(@Nonnull final String id) {
return new TimeOffRequestRequestBuilder(getRequestUrlWithAdditionalSegment("timeOffRequests") + "/" + id, getClient(), null);
}
/**
* Gets a request builder for the TimeOff collection
*
* @return the collection request builder
*/
@Nonnull
public TimeOffCollectionRequestBuilder timesOff() {
return new TimeOffCollectionRequestBuilder(getRequestUrlWithAdditionalSegment("timesOff"), getClient(), null);
}
/**
* Gets a request builder for the TimeOff item
*
* @return the request builder
* @param id the item identifier
*/
@Nonnull
public TimeOffRequestBuilder timesOff(@Nonnull final String id) {
return new TimeOffRequestBuilder(getRequestUrlWithAdditionalSegment("timesOff") + "/" + id, getClient(), null);
}
/**
* Gets a builder to execute the method
* @return the request builder
* @param parameters the parameters for the service method
*/
@Nonnull
public ScheduleShareRequestBuilder share(@Nonnull final ScheduleShareParameterSet parameters) {
return new ScheduleShareRequestBuilder(getRequestUrlWithAdditionalSegment("microsoft.graph.share"), getClient(), null, parameters);
}
}
|
9235733a875fe2b480f4647ed0fc6eafbae3b120 | 680 | java | Java | src/main/java/com/example/socialmedia/config/RequestLoggingFilterConfig.java | basharkhan6/Social_Media | d6556a2a5bfaba271737bbb7ae02c48735a8a2f6 | [
"MIT"
] | 1 | 2021-07-10T21:29:43.000Z | 2021-07-10T21:29:43.000Z | src/main/java/com/example/socialmedia/config/RequestLoggingFilterConfig.java | basharkhan6/Social_Media | d6556a2a5bfaba271737bbb7ae02c48735a8a2f6 | [
"MIT"
] | null | null | null | src/main/java/com/example/socialmedia/config/RequestLoggingFilterConfig.java | basharkhan6/Social_Media | d6556a2a5bfaba271737bbb7ae02c48735a8a2f6 | [
"MIT"
] | null | null | null | 30.909091 | 79 | 0.761765 | 997,309 | package com.example.socialmedia.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.filter.CommonsRequestLoggingFilter;
@Configuration
public class RequestLoggingFilterConfig {
@Bean
public CommonsRequestLoggingFilter logFilter() {
CommonsRequestLoggingFilter filter = new CommonsRequestLoggingFilter();
filter.setIncludeQueryString(true);
filter.setIncludePayload(true);
filter.setMaxPayloadLength(10000);
filter.setIncludeHeaders(false);
filter.setAfterMessagePrefix("REQUEST DATA : ");
return filter;
}
}
|
9235740cc074b9207ffdb4245c7ef4563b09f074 | 208 | java | Java | base/src/main/java/adudecalledleo/tbsquared/icon/Icon.java | Leo40Git/textbox-squared | 315c75cb64a9d945b168f3ae5ac40d388e48097c | [
"MIT"
] | null | null | null | base/src/main/java/adudecalledleo/tbsquared/icon/Icon.java | Leo40Git/textbox-squared | 315c75cb64a9d945b168f3ae5ac40d388e48097c | [
"MIT"
] | null | null | null | base/src/main/java/adudecalledleo/tbsquared/icon/Icon.java | Leo40Git/textbox-squared | 315c75cb64a9d945b168f3ae5ac40d388e48097c | [
"MIT"
] | null | null | null | 26 | 85 | 0.822115 | 997,310 | package adudecalledleo.tbsquared.icon;
import java.awt.image.*;
import adudecalledleo.tbsquared.definition.Definition;
public record Icon(Definition sourceDefinition, String name, BufferedImage image) { }
|
92357662cb22e254665ed9083408a8d4c8b26ce7 | 12,425 | java | Java | ide/editor.lib2/src/org/netbeans/modules/editor/lib2/view/AttributedCharSequence.java | tusharvjoshi/incubator-netbeans | a61bd21f4324f7e73414633712522811cb20ac93 | [
"Apache-2.0"
] | 1,056 | 2019-04-25T20:00:35.000Z | 2022-03-30T04:46:14.000Z | ide/editor.lib2/src/org/netbeans/modules/editor/lib2/view/AttributedCharSequence.java | tusharvjoshi/incubator-netbeans | a61bd21f4324f7e73414633712522811cb20ac93 | [
"Apache-2.0"
] | 1,846 | 2019-04-25T20:50:05.000Z | 2022-03-31T23:40:41.000Z | ide/editor.lib2/src/org/netbeans/modules/editor/lib2/view/AttributedCharSequence.java | tusharvjoshi/incubator-netbeans | a61bd21f4324f7e73414633712522811cb20ac93 | [
"Apache-2.0"
] | 550 | 2019-04-25T20:04:33.000Z | 2022-03-25T17:43:01.000Z | 33.490566 | 115 | 0.608451 | 997,311 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.netbeans.modules.editor.lib2.view;
import java.awt.font.TextAttribute;
import java.text.AttributedCharacterIterator;
import java.text.AttributedCharacterIterator.Attribute;
import java.util.*;
import javax.swing.text.AttributeSet;
import javax.swing.text.StyleConstants;
import org.netbeans.lib.editor.util.ArrayUtilities;
import org.netbeans.lib.editor.util.CharSequenceUtilities;
import org.openide.util.Exceptions;
/**
* Char sequence with additional attributes.
* <br>
* Method operate with javax.swing.text.AttributeSet which they transfer
* to corresponding TextAttribute constants.
* <br>
* After creation the series of addTextRun() is called followed by setText()
* which completes modification and makes the object ready for clients.
*
* @author Miloslav Metelka
*/
public final class AttributedCharSequence implements AttributedCharacterIterator {
private static final Map<Object,AttributeTranslateHandler> attr2Handler
= new HashMap<Object, AttributeTranslateHandler>(20, 0.5f);
static {
attr2Handler.put(StyleConstants.Family, new AttributeTranslateHandler(TextAttribute.FAMILY));
attr2Handler.put(StyleConstants.Italic,
new AttributeTranslateHandler(TextAttribute.POSTURE, TextAttribute.POSTURE_OBLIQUE));
attr2Handler.put(StyleConstants.Bold,
new AttributeTranslateHandler(TextAttribute.WEIGHT, TextAttribute.WEIGHT_BOLD));
attr2Handler.put(StyleConstants.Size, new AttributeTranslateHandler(TextAttribute.SIZE));
attr2Handler.put(StyleConstants.Superscript,
new AttributeTranslateHandler(TextAttribute.SUPERSCRIPT, TextAttribute.SUPERSCRIPT_SUPER));
attr2Handler.put(StyleConstants.Subscript,
new AttributeTranslateHandler(TextAttribute.SUPERSCRIPT, TextAttribute.SUPERSCRIPT_SUB));
attr2Handler.put(StyleConstants.Underline,
new AttributeTranslateHandler(TextAttribute.UNDERLINE, TextAttribute.UNDERLINE_ON));
attr2Handler.put(StyleConstants.StrikeThrough, new AttributeTranslateHandler(TextAttribute.STRIKETHROUGH));
attr2Handler.put(StyleConstants.StrikeThrough, new AttributeTranslateHandler(TextAttribute.STRIKETHROUGH));
attr2Handler.put(StyleConstants.Foreground, new AttributeTranslateHandler(TextAttribute.FOREGROUND));
attr2Handler.put(StyleConstants.Background, new AttributeTranslateHandler(TextAttribute.BACKGROUND));
attr2Handler.put(StyleConstants.Background, new AttributeTranslateHandler(TextAttribute.BACKGROUND));
}
public static Map<Attribute,Object> translate(AttributeSet attrs) {
int attrCount = attrs.getAttributeCount();
Map<Attribute,Object> ret = new HashMap<Attribute, Object>(attrCount);
for (Enumeration<?> attrNames = attrs.getAttributeNames(); attrNames.hasMoreElements();) {
Object attrName = attrNames.nextElement();
AttributeTranslateHandler handler = attr2Handler.get(attrName);
if (handler != null) {
Object textAttrValue = handler.getTextAttrValue(attrs.getAttribute(attrName));
if (textAttrValue != null) {
ret.put(handler.getTextAttr(), textAttrValue);
}
} // Unknown attributes are ignored
}
return ret;
}
/**
* Merge textAttrs0 with textAttrs1 (textAttrs1 contents override textAttrs0 for same attributes).
*
* @param textAttrs0
* @param textAttrs1
* @return merge of two maps.
*/
public static Map<Attribute,Object> merge(Map<Attribute,Object> textAttrs0, Map<Attribute,Object> textAttrs1) {
Map<Attribute,Object> ret = new HashMap<Attribute, Object>(textAttrs0);
ret.putAll(textAttrs1);
return ret;
}
private final List<TextRun> textRuns = new ArrayList<TextRun>(); // 8=super + 4 = 12 bytes
private CharSequence text; // 12 + 4 = 16 bytes
private int charIndex; // 16 + 4 = 20 bytes
private int textRunIndex; // 20 + 4 = 24 bytes
private Set<Attribute> allAttributeKeys; // 24 + 4 = 28 bytes
public AttributedCharSequence() {
}
void addTextRun(int endIndex, Map<Attribute,Object> textAttrs) {
if (endIndex <= endIndex()) {
throw new IllegalArgumentException("endIndex=" + endIndex + ", endIndex()=" + endIndex()); // NOI18N
}
textRuns.add(new TextRun(endIndex, textAttrs));
}
void setText(CharSequence text, Map<Attribute,Object> defaultTextAttrs) {
this.text = text;
int endIndex = endIndex();
int textLen = text.length();
if (endIndex > textLen) {
throw new IllegalStateException("endIndex=" + endIndex + " > text.length()=" + textLen); // NOI18N
}
if (endIndex < textLen) {
addTextRun(textLen, defaultTextAttrs);
}
((ArrayList)textRuns).trimToSize();
}
private int endIndex() {
return (textRuns.size() > 0) ? textRuns.get(textRuns.size() - 1).endIndex : 0;
}
@Override
public int getRunStart() {
return (textRunIndex > 0)
? textRuns.get(textRunIndex - 1).endIndex
: 0;
}
@Override
public int getRunStart(Attribute attribute) {
return getRunStart();
}
@Override
public int getRunStart(Set<? extends Attribute> attributes) {
return getRunStart();
}
@Override
public int getRunLimit() {
return (textRunIndex < textRuns.size())
? textRuns.get(textRunIndex).endIndex
: textRuns.get(textRuns.size() - 1).endIndex;
}
@Override
public int getRunLimit(Attribute attribute) {
return getRunLimit();
}
@Override
public int getRunLimit(Set<? extends Attribute> attributes) {
return getRunLimit();
}
@Override
public Map<Attribute, Object> getAttributes() {
if (textRunIndex >= textRuns.size()) {
return Collections.emptyMap();
}
return textRuns.get(textRunIndex).attrs;
}
@Override
public Object getAttribute(Attribute attribute) {
return getAttributes().get(attribute);
}
@Override
public Set<Attribute> getAllAttributeKeys() {
if (allAttributeKeys == null) {
HashSet<Attribute> allKeys = new HashSet<Attribute>();
for (int i = textRuns.size() - 1; i >= 0; i--) {
allKeys.addAll(textRuns.get(i).attrs.keySet());
}
allAttributeKeys = allKeys;
}
return allAttributeKeys;
}
@Override
public char first() {
setIndex(0);
return current();
}
@Override
public char last() {
setIndex(Math.max(0, text.length() - 1));
return current();
}
@Override
public char current() {
return (charIndex < text.length()) ? text.charAt(charIndex) : DONE;
}
@Override
public char next() {
if (charIndex == text.length()) {
return DONE;
}
charIndex++;
if (charIndex == textRuns.get(textRunIndex).endIndex) {
textRunIndex++;
}
return current();
}
@Override
public char previous() {
if (charIndex == 0) {
return DONE;
}
charIndex--;
if (textRunIndex > 0 && charIndex < textRuns.get(textRunIndex - 1).endIndex) {
textRunIndex--;
}
return current();
}
@Override
public char setIndex(int position) {
if (position < 0 || position > text.length()) {
throw new IllegalArgumentException("position=" + position + " not within <0," + // NOI18N
text.length() + ">"); // NOI18N
}
return setIndexImpl(position);
}
private char setIndexImpl(int position) {
charIndex = position;
// Find text run
if (position == 0) {
textRunIndex = 0;
} else {
int last = textRuns.size() - 1;
int low = 0;
int high = last;
while (low <= high) {
int mid = (low + high) >>> 1; // mid in the binary search
TextRun textRun = textRuns.get(mid);
if (textRun.endIndex < position) {
low = mid + 1;
} else if (textRun.endIndex > position) {
high = mid - 1;
} else { // textRun.endIndex == position
low = mid + 1;
break;
}
}
textRunIndex = Math.min(low, last); // Make sure last item is returned for relOffset above end
}
return current();
}
@Override
public int getBeginIndex() {
return 0;
}
@Override
public int getEndIndex() {
return text.length();
}
@Override
public int getIndex() {
return charIndex;
}
@Override
public Object clone() {
try {
return super.clone();
} catch (CloneNotSupportedException ex) {
Exceptions.printStackTrace(ex); // Should never happen
return null;
}
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder(100);
sb.append("text(").append(text.length()).append(")=\"").append( // NOI18N
CharSequenceUtilities.debugText(text)).append("\"; "). // NOI18N
append(textRuns.size()).append(" text runs:\n"); // NOI18N
int textRunsSize = textRuns.size();
int maxDigitCount = ArrayUtilities.digitCount(textRunsSize);
for (int i = 0; i < textRunsSize; i++) {
ArrayUtilities.appendBracketedIndex(sb, i, maxDigitCount);
sb.append(": "); // NOI18N
textRuns.get(i).appendInfo(sb);
sb.append("\n"); // NOI18N
}
return sb.toString();
}
private static final class TextRun {
final int endIndex;
final Map<Attribute,Object> attrs;
public TextRun(int endIndex, Map<Attribute, Object> attrs) {
this.endIndex = endIndex;
this.attrs = attrs;
}
StringBuilder appendInfo(StringBuilder sb) {
sb.append("endIndex=").append(endIndex).append(", attrs=").append(attrs); // NOI18N
return sb;
}
@Override
public String toString() {
return appendInfo(new StringBuilder()).toString();
}
}
private static final class AttributeTranslateHandler {
AttributeTranslateHandler(Attribute textAttr) {
this(textAttr, null);
}
AttributeTranslateHandler(Attribute textAttr, Object textAttrValue) {
this.textAttr = textAttr;
this.textAttrValue = textAttrValue;
}
private final Attribute textAttr;
private final Object textAttrValue;
Attribute getTextAttr() {
return textAttr;
}
Object getTextAttrValue(Object attrValue) {
Object ret;
if (textAttrValue == null) { // Use passed value
ret = attrValue;
} else { // Translate if Boolean.TRUE
if (Boolean.TRUE.equals(attrValue)) {
ret = textAttrValue;
} else {
ret = null;
}
}
return ret;
}
}
}
|
923576aed85ef8c4a473733acbaa3f1504f5e784 | 1,059 | java | Java | Deprecated/SoarPre8.6/Eclipse-Soar/src/edu/rosehulman/soar/perspective/SoarPerspectiveFactory.java | sleyzerzon/soar | 74a6f32ba1be3a7b3ed4eac0b44b0f4b2e981f71 | [
"Unlicense"
] | 1 | 2016-04-01T04:02:28.000Z | 2016-04-01T04:02:28.000Z | Deprecated/SoarPre8.6/Eclipse-Soar/src/edu/rosehulman/soar/perspective/SoarPerspectiveFactory.java | sleyzerzon/soar | 74a6f32ba1be3a7b3ed4eac0b44b0f4b2e981f71 | [
"Unlicense"
] | null | null | null | Deprecated/SoarPre8.6/Eclipse-Soar/src/edu/rosehulman/soar/perspective/SoarPerspectiveFactory.java | sleyzerzon/soar | 74a6f32ba1be3a7b3ed4eac0b44b0f4b2e981f71 | [
"Unlicense"
] | null | null | null | 25.214286 | 89 | 0.744098 | 997,312 | /**
*
* @file SoarPerspectiveFactory.java
* @date Mar 23, 2004
*/
package edu.rosehulman.soar.perspective;
import edu.rosehulman.soar.*;
import org.eclipse.ui.*;
/**
* Creates the Soar perspective, with all of our pretty views.
*
* @author Tim Jasko <tj9582@yahoo.com>
*/
public class SoarPerspectiveFactory implements IPerspectiveFactory {
public void createInitialLayout(IPageLayout layout) {
// Get the editor area.
String editorArea = layout.getEditorArea();
// Top left: Resource Navigator view
IFolderLayout topLeft = layout.createFolder("topLeft", IPageLayout.LEFT, 0.25f,
editorArea);
topLeft.addView(SoarPlugin.ID_NAVIGATOR);
// Bottom left: Outline view and Property Sheet view
IFolderLayout bottomLeft = layout.createFolder("bottomLeft", IPageLayout.BOTTOM, 0.70f,
"topLeft");
bottomLeft.addView(IPageLayout.ID_OUTLINE);
//bottomLeft.addView(IPageLayout.ID_PROP_SHEET);
// Bottom right: Task List view
layout.addView(IPageLayout.ID_PROBLEM_VIEW, IPageLayout.BOTTOM, 0.75f, editorArea);
}
}
|
9235772b459d811ff87d172ad5bbc85f1c5c3678 | 2,972 | java | Java | src/main/java/org/amity/simulator/language/StateMachine.java | BandedHawk/system-simulator | 2d5b2453ea29b79ab7471079ef5238802eee231a | [
"Apache-2.0"
] | null | null | null | src/main/java/org/amity/simulator/language/StateMachine.java | BandedHawk/system-simulator | 2d5b2453ea29b79ab7471079ef5238802eee231a | [
"Apache-2.0"
] | null | null | null | src/main/java/org/amity/simulator/language/StateMachine.java | BandedHawk/system-simulator | 2d5b2453ea29b79ab7471079ef5238802eee231a | [
"Apache-2.0"
] | null | null | null | 31.242105 | 79 | 0.544137 | 997,313 | /*
* StateMachine.java
*
* (C) Copyright 2017 Jon Barnett.
*
* 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.
*
* Created on November 13, 2017
*/
package org.amity.simulator.language;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Defines valid state traversals for the parsing of the system definition file
* for modeling.
*
* @author <a href="mailto:ychag@example.com">Jon Barnett</a>
*/
public class StateMachine
{
private final static Map<Syntax, List<Syntax>> MACHINE;
static
{
MACHINE = new HashMap<>();
for (Syntax grammar : Syntax.values())
{
final List<Syntax> options = new ArrayList<>();
switch (grammar)
{
case START:
options.add(Syntax.LABEL);
options.add(Syntax.COMMENT);
MACHINE.put(grammar, options);
break;
case OPEN:
options.add(Syntax.CLOSE);
options.add(Syntax.LABEL);
options.add(Syntax.COMMENT);
MACHINE.put(grammar, options);
break;
case CLOSE:
options.add(Syntax.LABEL);
options.add(Syntax.COMMENT);
MACHINE.put(grammar, options);
break;
case LABEL:
options.add(Syntax.ASSIGN);
options.add(Syntax.OPEN);
options.add(Syntax.COMMENT);
MACHINE.put(grammar, options);
break;
case ASSIGN:
options.add(Syntax.VALUE);
options.add(Syntax.COMMENT);
MACHINE.put(grammar, options);
break;
case VALUE:
options.add(Syntax.LABEL);
options.add(Syntax.CLOSE);
options.add(Syntax.COMMENT);
MACHINE.put(grammar, options);
break;
default:
}
}
}
/**
* Retrieve possible next states, given current state
*
* @param state current condition of the parsing system
* @return valid states to traverse
*/
public static List<Syntax> getOptions(final Syntax state)
{
return MACHINE.get(state);
}
}
|
923578a7da36cdd56dc76911a2aa84f8c7b860da | 1,029 | java | Java | gradle/wrapper/dists/gradle-1.12-all/4ff8jj5a73a7zgj5nnzv1ubq0/gradle-1.12/src/core/org/gradle/api/internal/resource/ResourceNotFoundException.java | bit-man/pushfish-android | 5f4fcf56adf5a8cdb6f31d91c315bcd3b3dc93bc | [
"BSD-2-Clause"
] | 158 | 2015-04-18T23:39:02.000Z | 2021-07-01T18:28:29.000Z | gradle/wrapper/dists/gradle-1.12-all/4ff8jj5a73a7zgj5nnzv1ubq0/gradle-1.12/src/core/org/gradle/api/internal/resource/ResourceNotFoundException.java | bit-man/pushfish-android | 5f4fcf56adf5a8cdb6f31d91c315bcd3b3dc93bc | [
"BSD-2-Clause"
] | 31 | 2015-04-29T18:52:40.000Z | 2020-06-29T19:25:24.000Z | gradle/wrapper/dists/gradle-1.12-all/4ff8jj5a73a7zgj5nnzv1ubq0/gradle-1.12/src/core/org/gradle/api/internal/resource/ResourceNotFoundException.java | bit-man/pushfish-android | 5f4fcf56adf5a8cdb6f31d91c315bcd3b3dc93bc | [
"BSD-2-Clause"
] | 32 | 2016-01-05T21:58:24.000Z | 2021-06-21T21:56:34.000Z | 33.193548 | 104 | 0.73275 | 997,314 | /*
* Copyright 2010 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gradle.api.internal.resource;
/**
* An exception thrown when attempting to access the content of a {@link Resource} which does not exist.
*/
public class ResourceNotFoundException extends ResourceException {
public ResourceNotFoundException(String message) {
super(message);
}
public ResourceNotFoundException(String message, Throwable t) {
super(message, t);
}
}
|
92357aabb2d6daad6db376f47bdaa2cd71bdc597 | 456 | java | Java | app/src/main/java/com/buftas/myPasswords/Password.java | buftas/MyPasswords | e7b2f02dc5b8db733480ccac6ed72160f999f573 | [
"MIT"
] | 5 | 2020-07-22T20:47:39.000Z | 2022-01-12T00:41:05.000Z | app/src/main/java/com/buftas/myPasswords/Password.java | buftas/MyPasswords | e7b2f02dc5b8db733480ccac6ed72160f999f573 | [
"MIT"
] | null | null | null | app/src/main/java/com/buftas/myPasswords/Password.java | buftas/MyPasswords | e7b2f02dc5b8db733480ccac6ed72160f999f573 | [
"MIT"
] | 1 | 2022-01-12T00:41:11.000Z | 2022-01-12T00:41:11.000Z | 21.714286 | 103 | 0.662281 | 997,315 | //Nikolaos Katsiopis
//icsd13076
package com.buftas.myPasswords;
public class Password extends DataObject {//This class creates a password instance with tis description
private String pass;
public Password(String name, String username, String pass) {
super(name, username);
this.pass = pass;
}
public String getPass() {
return pass;
}
public void setPass(String pass) {
this.pass = pass;
}
}
|
92357b4f876da31a3890e6921c7b1392e7f22623 | 1,819 | java | Java | ode-core/src/main/java/com/leidos/ode/core/controllers/topics/PublishVDOTSpdVolOccDataController.java | OSADP/P-ODE | 105b6e2db4c48bcfeb6b89a2b3e159fef15c3a9c | [
"Apache-2.0"
] | null | null | null | ode-core/src/main/java/com/leidos/ode/core/controllers/topics/PublishVDOTSpdVolOccDataController.java | OSADP/P-ODE | 105b6e2db4c48bcfeb6b89a2b3e159fef15c3a9c | [
"Apache-2.0"
] | 7 | 2020-03-04T22:25:30.000Z | 2021-06-04T02:14:05.000Z | ode-core/src/main/java/com/leidos/ode/core/controllers/topics/PublishVDOTSpdVolOccDataController.java | OSADP/P-ODE | 105b6e2db4c48bcfeb6b89a2b3e159fef15c3a9c | [
"Apache-2.0"
] | 1 | 2020-02-02T18:19:07.000Z | 2020-02-02T18:19:07.000Z | 30.316667 | 91 | 0.738868 | 997,316 | package com.leidos.ode.core.controllers.topics;
import com.leidos.ode.agent.data.ODEAgentMessage;
import com.leidos.ode.core.controllers.PublishDataController;
import com.leidos.ode.logging.ODELogger;
import javax.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
/**
* Created with IntelliJ IDEA.
* User: LAMDE
* Date: 9/5/14
* Time: 4:00 PM
* To change this template use File | Settings | File Templates.
*/
@Controller
public class PublishVDOTSpdVolOccDataController extends PublishDataController {
@Value("${leidos.ode.publisher.topic.vdotspdvolocc}")
private String topicName;
@Autowired
@Qualifier("odeLogger")
private ODELogger odeLogger;
@Override
public String getTopicName() {
return topicName;
}
@Override
@RequestMapping(value = PublishEndpoints.VDOT_SPD_VOL_OCC, method = RequestMethod.POST)
public @ResponseBody String publishData(@RequestBody ODEAgentMessage odeAgentMessage) {
System.out.println("VDOT Speed message received");
return publish(odeAgentMessage);
}
/**
* @return the odeLogger
*/
public ODELogger getOdeLogger() {
return odeLogger;
}
/**
* @param odeLogger the odeLogger to set
*/
public void setOdeLogger(ODELogger odeLogger) {
this.odeLogger = odeLogger;
}
}
|
92357c01f62568efcb8216097658de09ce6f0544 | 1,346 | java | Java | core/src/main/java/org/jfantasy/framework/log/interceptor/LogOperationSourcePointcut.java | limaofeng/jfantasy-framework | 781246acef1b32ba3a20dc0d988dcd31df7e3e21 | [
"MIT"
] | 1 | 2021-08-13T15:25:01.000Z | 2021-08-13T15:25:01.000Z | core/src/main/java/org/jfantasy/framework/log/interceptor/LogOperationSourcePointcut.java | limaofeng/jfantasy-framework | 781246acef1b32ba3a20dc0d988dcd31df7e3e21 | [
"MIT"
] | 1 | 2021-09-11T01:28:09.000Z | 2021-09-11T13:33:40.000Z | core/src/main/java/org/jfantasy/framework/log/interceptor/LogOperationSourcePointcut.java | limaofeng/jfantasy-framework | 781246acef1b32ba3a20dc0d988dcd31df7e3e21 | [
"MIT"
] | null | null | null | 30.590909 | 96 | 0.763744 | 997,317 | package org.jfantasy.framework.log.interceptor;
import java.io.Serializable;
import java.lang.reflect.Method;
import org.jfantasy.framework.log.annotation.LogOperationSource;
import org.springframework.aop.support.StaticMethodMatcherPointcut;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
@SuppressWarnings("serial")
abstract class LogOperationSourcePointcut extends StaticMethodMatcherPointcut
implements Serializable {
@Override
public boolean matches(Method method, Class<?> targetClass) {
LogOperationSource cas = getLogOperationSource();
return cas != null && !CollectionUtils.isEmpty(cas.getOperations(method, targetClass));
}
@Override
public boolean equals(Object other) {
if (this == other) {
return true;
}
if (!(other instanceof LogOperationSourcePointcut)) {
return false;
}
LogOperationSourcePointcut otherPc = (LogOperationSourcePointcut) other;
return ObjectUtils.nullSafeEquals(getLogOperationSource(), otherPc.getLogOperationSource());
}
@Override
public int hashCode() {
return LogOperationSourcePointcut.class.hashCode();
}
@Override
public String toString() {
return getClass().getName() + ": " + getLogOperationSource();
}
protected abstract LogOperationSource getLogOperationSource();
}
|
92357dec5e8924035996e7d9a2c1e73d9eb15aaa | 682 | java | Java | src/main/java/com/storycraft/core/chat/ColoredChat.java | story-network/story-plugin | cb6bb2c3433c2860a2beb9d52211e5078f37f787 | [
"MIT"
] | 1 | 2018-03-20T23:21:51.000Z | 2018-03-20T23:21:51.000Z | src/main/java/com/storycraft/core/chat/ColoredChat.java | storycraft/story-plugin | cb6bb2c3433c2860a2beb9d52211e5078f37f787 | [
"MIT"
] | 8 | 2019-06-17T09:25:12.000Z | 2019-12-13T08:07:41.000Z | src/main/java/com/storycraft/core/chat/ColoredChat.java | storycraft/story-plugin | cb6bb2c3433c2860a2beb9d52211e5078f37f787 | [
"MIT"
] | 1 | 2019-07-27T08:42:27.000Z | 2019-07-27T08:42:27.000Z | 28.416667 | 86 | 0.717009 | 997,318 | package com.storycraft.core.chat;
import com.storycraft.StoryMiniPlugin;
import org.bukkit.ChatColor;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.AsyncPlayerChatEvent;
public class ColoredChat extends StoryMiniPlugin implements Listener {
@Override
public void onEnable() {
getPlugin().getServer().getPluginManager().registerEvents(this, getPlugin());
}
@EventHandler
public void onChat(AsyncPlayerChatEvent e) {
if (e.getPlayer().hasPermission("server.chat.color")) {
e.setMessage(ChatColor.translateAlternateColorCodes('&', e.getMessage()));
}
}
} |
92357ff37a558cd64f08239b02089d0b29d8e578 | 2,793 | java | Java | mysql/src/main/java/com/github/sandor_balazs/nosql_java/domain/Employee.java | sandor-balazs/nosql-java | 417c04477a61cd1517091ce8b6b7c2aae3c329c4 | [
"BSD-2-Clause"
] | 2 | 2016-12-11T04:35:00.000Z | 2016-12-12T22:29:30.000Z | mysql/src/main/java/com/github/sandor_balazs/nosql_java/domain/Employee.java | sandor-balazs/nosql-java | 417c04477a61cd1517091ce8b6b7c2aae3c329c4 | [
"BSD-2-Clause"
] | null | null | null | mysql/src/main/java/com/github/sandor_balazs/nosql_java/domain/Employee.java | sandor-balazs/nosql-java | 417c04477a61cd1517091ce8b6b7c2aae3c329c4 | [
"BSD-2-Clause"
] | null | null | null | 21.320611 | 65 | 0.588256 | 997,319 | package com.github.sandor_balazs.nosql_java.domain;
import com.fasterxml.jackson.annotation.JsonIgnore;
import org.hibernate.annotations.Cache;
import org.hibernate.annotations.CacheConcurrencyStrategy;
import javax.persistence.*;
import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;
import java.util.Objects;
/**
* A Employee.
*/
@Entity
@Table(name = "employee")
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
public class Employee implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@Column(name = "first_name")
private String firstName;
@Column(name = "last_name")
private String lastName;
@Column(name = "uid")
private String uid;
@Column(name = "phone")
private String phone;
@Column(name = "email")
private String email;
@OneToMany(mappedBy = "employee")
@JsonIgnore
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
private Set<Employment> employments = new HashSet<>();
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getUid() {
return uid;
}
public void setUid(String uid) {
this.uid = uid;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public Set<Employment> getEmployments() {
return employments;
}
public void setEmployments(Set<Employment> employments) {
this.employments = employments;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Employee employee = (Employee) o;
return Objects.equals(id, employee.id);
}
@Override
public int hashCode() {
return Objects.hashCode(id);
}
@Override
public String toString() {
return "Employee{" +
"id=" + id +
", firstName='" + firstName + "'" +
", lastName='" + lastName + "'" +
", uid='" + uid + "'" +
", phone='" + phone + "'" +
", email='" + email + "'" +
'}';
}
}
|
9235801e97ff09c3ac44d82c4a76e2228d6afb82 | 2,823 | java | Java | drools-workbench-models/drools-workbench-models-guided-dtable/src/main/java/org/drools/workbench/models/guided/dtable/shared/model/MetadataCol52.java | cuijulian/drools | 31b4dacd07ad962592dfb5ae6eee5cb825acce14 | [
"Apache-2.0"
] | 5 | 2016-07-31T17:00:18.000Z | 2022-01-11T04:34:29.000Z | drools-workbench-models/drools-workbench-models-guided-dtable/src/main/java/org/drools/workbench/models/guided/dtable/shared/model/MetadataCol52.java | cuijulian/drools | 31b4dacd07ad962592dfb5ae6eee5cb825acce14 | [
"Apache-2.0"
] | 5 | 2017-11-08T14:08:38.000Z | 2018-07-02T14:49:23.000Z | drools-workbench-models/drools-workbench-models-guided-dtable/src/main/java/org/drools/workbench/models/guided/dtable/shared/model/MetadataCol52.java | cuijulian/drools | 31b4dacd07ad962592dfb5ae6eee5cb825acce14 | [
"Apache-2.0"
] | 1 | 2019-10-18T09:35:54.000Z | 2019-10-18T09:35:54.000Z | 28.806122 | 77 | 0.601134 | 997,320 | /*
* Copyright 2011 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.drools.workbench.models.guided.dtable.shared.model;
import java.util.List;
import java.util.Objects;
/**
* This is a rule metadata - eg @foo(bar) etc.
*/
public class MetadataCol52 extends DTColumnConfig52 {
private static final long serialVersionUID = 729l;
private String metadata;
/**
* Available fields for this type of column.
*/
public static final String FIELD_METADATA = "metadata";
public String getMetadata() {
return metadata;
}
public void setMetadata( String metadata ) {
this.metadata = metadata;
}
@Override
public List<BaseColumnFieldDiff> diff( BaseColumn otherColumn ) {
if ( otherColumn == null ) {
return null;
}
List<BaseColumnFieldDiff> result = super.diff( otherColumn );
MetadataCol52 other = (MetadataCol52) otherColumn;
// Field: metadata.
if ( !isEqualOrNull( this.getMetadata(),
other.getMetadata() ) ) {
result.add( new BaseColumnFieldDiffImpl( FIELD_METADATA,
this.getMetadata(),
other.getMetadata() ) );
}
return result;
}
/**
* Clones this metadata column instance.
* @return The cloned instance.
*/
public MetadataCol52 cloneColumn() {
MetadataCol52 cloned = new MetadataCol52();
cloned.setMetadata( getMetadata() );
cloned.cloneCommonColumnConfigFrom( this );
return cloned;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof MetadataCol52)) {
return false;
}
if (!super.equals(o)) {
return false;
}
MetadataCol52 that = (MetadataCol52) o;
return Objects.equals(metadata, that.metadata);
}
@Override
public int hashCode() {
int result = super.hashCode();
result=~~result;
result = 31 * result + (metadata != null ? metadata.hashCode() : 0);
result=~~result;
return result;
}
}
|
9235803596f398cee38454b45351e352450e5422 | 943 | java | Java | springBootCrudApi/src/main/java/com/springboot/workers/crudapi/model/Title.java | Mrafe/Spring | e75606c980bef00e8f15e51f91e450597155280a | [
"Apache-2.0"
] | null | null | null | springBootCrudApi/src/main/java/com/springboot/workers/crudapi/model/Title.java | Mrafe/Spring | e75606c980bef00e8f15e51f91e450597155280a | [
"Apache-2.0"
] | null | null | null | springBootCrudApi/src/main/java/com/springboot/workers/crudapi/model/Title.java | Mrafe/Spring | e75606c980bef00e8f15e51f91e450597155280a | [
"Apache-2.0"
] | null | null | null | 21.431818 | 112 | 0.732768 | 997,321 | package com.springboot.workers.crudapi.model;
import java.util.Date;
public class Title {
int workerRefId;
String workerTitle;
Date affectedFrom;
public Title(int workerRefId, String workerTitle, Date affectedFrom) {
this.workerRefId = workerRefId;
this.workerTitle = workerTitle;
this.affectedFrom = affectedFrom;
}
public int getWorkerRefId() {
return workerRefId;
}
public void setWorkerRefId(int workerRefId) {
this.workerRefId = workerRefId;
}
public String getWorkerTitle() {
return workerTitle;
}
public void setWorkerTitle(String workerTitle) {
this.workerTitle = workerTitle;
}
public Date getAffectedFrom() {
return affectedFrom;
}
public void setAffectedFrom(Date affectedFrom) {
this.affectedFrom = affectedFrom;
}
@Override
public String toString() {
return "Title [workerRefId=" + workerRefId + ", workerTitle=" + workerTitle + ", affectedFrom=" + affectedFrom
+ "]";
}
}
|
9235805b48621e0ca85ce6f8c7772a8675ab9da2 | 1,829 | java | Java | examples/src/main/java/org/rajawali3d/examples/wallpaper/PreviewActivity.java | gormanb/Rajawali | a37eb07cfe01cf7c5a049d71699c781439c2369c | [
"Apache-2.0"
] | 1,845 | 2015-03-17T17:24:58.000Z | 2022-03-30T02:53:17.000Z | examples/src/main/java/org/rajawali3d/examples/wallpaper/PreviewActivity.java | lxholding/Rajawali | a66ca651517cc789d79b50c34e4b31acfc39b26c | [
"Apache-2.0"
] | 934 | 2015-03-17T15:34:16.000Z | 2022-02-11T20:04:57.000Z | examples/src/main/java/org/rajawali3d/examples/wallpaper/PreviewActivity.java | lxholding/Rajawali | a66ca651517cc789d79b50c34e4b31acfc39b26c | [
"Apache-2.0"
] | 566 | 2015-03-18T01:08:03.000Z | 2022-03-25T13:09:32.000Z | 32.192982 | 106 | 0.677929 | 997,322 | package org.rajawali3d.examples.wallpaper;
import android.app.Activity;
import android.app.Service;
import android.app.WallpaperManager;
import android.content.ComponentName;
import android.content.Intent;
import android.content.res.Resources;
import android.os.Build;
import android.os.Bundle;
import android.widget.Toast;
import org.rajawali3d.examples.R;
/**
* @author Jared Woolston (efpyi@example.com)
*/
public class PreviewActivity extends Activity {
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
Intent intent = new Intent();
if (Build.VERSION.SDK_INT >= 16) {
/*
* Open live wallpaper preview (API Level 16 or greater).
*/
intent.setAction(WallpaperManager.ACTION_CHANGE_LIVE_WALLPAPER);
String pkg = Service.class.getPackage().getName();
String cls = Service.class.getCanonicalName();
intent.putExtra(WallpaperManager.EXTRA_LIVE_WALLPAPER_COMPONENT, new ComponentName(pkg, cls));
} else {
/*
* Open live wallpaper picker (API Level 15 or lower).
*
* Display a quick little message (toast) with instructions.
*/
intent.setAction(WallpaperManager.ACTION_LIVE_WALLPAPER_CHOOSER);
Resources res = getResources();
String hint = res.getString(R.string.picker_toast_prefix)
+ res.getString(R.string.lwp_name)
+ res.getString(R.string.picker_toast_suffix);
Toast toast = Toast.makeText(this, hint, Toast.LENGTH_LONG);
toast.show();
}
startActivityForResult(intent, 0);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
finish();
}
}
|
92358080d2c3f8f6c8ce172a8bb1dc1f98139cfc | 2,515 | java | Java | src-nds/ndsNormalizer/ElementRepositoryBase.java | lta-disco-unimib-it/KLFA | 7bbf0b31846239c849a307a48f820e28b62c874e | [
"Apache-2.0"
] | 1 | 2021-06-06T01:36:32.000Z | 2021-06-06T01:36:32.000Z | src-nds/ndsNormalizer/ElementRepositoryBase.java | lta-disco-unimib-it/KLFA | 7bbf0b31846239c849a307a48f820e28b62c874e | [
"Apache-2.0"
] | null | null | null | src-nds/ndsNormalizer/ElementRepositoryBase.java | lta-disco-unimib-it/KLFA | 7bbf0b31846239c849a307a48f820e28b62c874e | [
"Apache-2.0"
] | null | null | null | 28.258427 | 87 | 0.637376 | 997,323 | /*******************************************************************************
* Copyright 2019 Fabrizio Pastore, Leonardo Mariani
*
* 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 ndsNormalizer;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;
import java.util.Stack;
import java.util.TreeSet;
import javax.sound.sampled.LineEvent;
public class ElementRepositoryBase<T extends LineData> implements ElementRepository<T>{
protected HashMap<String,T> elements = new HashMap<String,T>();
protected HashMap<String,Integer> counters = new HashMap<String, Integer>();
protected Integer startLevel;
private static final int keySize = 20;
protected boolean[] keys = new boolean[keySize];
private int reservedKeys;
ElementRepositoryBase( Integer startLevel, int reservedKeys ){
this.reservedKeys = reservedKeys;
this.startLevel = startLevel;
for ( int x = 0; x < keySize; x++ )
keys[x]=false;
}
public void nextCycle(){
Set set = new TreeSet ( counters.keySet() );
Iterator<String> it = set.iterator();
while ( it.hasNext() ){
String elementName = it.next();
Integer count = counters.get( elementName );
if ( count > 1 ){
--count;
counters.put(elementName, count);
} else{
counters.remove(elementName);
T el = elements.remove(elementName);
int pos = Integer.valueOf( el.getData() )-reservedKeys;
keys[pos] = false;
}
}
}
public T get(String value) {
if ( elements.containsKey(value) ){
//counters.put(value, startLevel);
return elements.get(value);
}
return null;
}
public void put(String key, T data) {
counters.put(key, startLevel);
elements.put(key, data);
}
public String nextKey(){
for ( int i = 0; i < keySize; ++i ){
if ( ! keys[i] ){
String res = ""+(i+reservedKeys);
keys[i] = true;
return res;
}
}
return "-1";
}
}
|
9235827e0fef888e11716efa7941ae1d2acf5aae | 2,362 | java | Java | mall-modules/mall-coupon/src/main/java/com/ruoyi/coupon/domain/MemberPrice.java | 437595587/Mall | 0cdddd4fab21dd685bf85cad8b86fa7707746fa6 | [
"MIT"
] | 3 | 2021-09-09T12:08:08.000Z | 2021-09-19T09:49:44.000Z | mall-modules/mall-coupon/src/main/java/com/ruoyi/coupon/domain/MemberPrice.java | 437595587/Mall | 0cdddd4fab21dd685bf85cad8b86fa7707746fa6 | [
"MIT"
] | null | null | null | mall-modules/mall-coupon/src/main/java/com/ruoyi/coupon/domain/MemberPrice.java | 437595587/Mall | 0cdddd4fab21dd685bf85cad8b86fa7707746fa6 | [
"MIT"
] | 2 | 2021-09-10T06:13:29.000Z | 2022-02-14T09:34:06.000Z | 21.472727 | 71 | 0.617697 | 997,324 | package com.ruoyi.coupon.domain;
import com.ruoyi.common.core.annotation.Excel;
import com.ruoyi.common.core.web.domain.BaseEntity;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import java.math.BigDecimal;
/**
* 商品会员价格对象 sms_member_price
*
* @author xuxing
* @date 2021-08-23
*/
public class MemberPrice extends BaseEntity
{
private static final long serialVersionUID = 1L;
/** id */
private Long id;
/** sku_id */
@Excel(name = "sku_id")
private Long skuId;
/** 会员等级id */
@Excel(name = "会员等级id")
private Long memberLevelId;
/** 会员等级名 */
@Excel(name = "会员等级名")
private String memberLevelName;
/** 会员对应价格 */
@Excel(name = "会员对应价格")
private BigDecimal memberPrice;
/** 可否叠加其他优惠[0-不可叠加优惠,1-可叠加] */
@Excel(name = "可否叠加其他优惠[0-不可叠加优惠,1-可叠加]")
private Integer addOther;
public void setId(Long id)
{
this.id = id;
}
public Long getId()
{
return id;
}
public void setSkuId(Long skuId)
{
this.skuId = skuId;
}
public Long getSkuId()
{
return skuId;
}
public void setMemberLevelId(Long memberLevelId)
{
this.memberLevelId = memberLevelId;
}
public Long getMemberLevelId()
{
return memberLevelId;
}
public void setMemberLevelName(String memberLevelName)
{
this.memberLevelName = memberLevelName;
}
public String getMemberLevelName()
{
return memberLevelName;
}
public void setMemberPrice(BigDecimal memberPrice)
{
this.memberPrice = memberPrice;
}
public BigDecimal getMemberPrice()
{
return memberPrice;
}
public void setAddOther(Integer addOther)
{
this.addOther = addOther;
}
public Integer getAddOther()
{
return addOther;
}
@Override
public String toString() {
return new ToStringBuilder(this,ToStringStyle.MULTI_LINE_STYLE)
.append("id", getId())
.append("skuId", getSkuId())
.append("memberLevelId", getMemberLevelId())
.append("memberLevelName", getMemberLevelName())
.append("memberPrice", getMemberPrice())
.append("addOther", getAddOther())
.toString();
}
}
|
923582e14f970a51ec7887d485691242159f3ae8 | 183 | java | Java | src/main/java/com/github/whalerain/javatool/core/ReflectTool.java | whalerain/java-tool | fea046f9ca183875191cf581c15238b47896c932 | [
"Apache-2.0"
] | null | null | null | src/main/java/com/github/whalerain/javatool/core/ReflectTool.java | whalerain/java-tool | fea046f9ca183875191cf581c15238b47896c932 | [
"Apache-2.0"
] | 5 | 2020-04-25T05:08:29.000Z | 2022-01-04T16:36:06.000Z | src/main/java/com/github/whalerain/javatool/core/ReflectTool.java | whalerain/java-tool | fea046f9ca183875191cf581c15238b47896c932 | [
"Apache-2.0"
] | null | null | null | 8.714286 | 46 | 0.699454 | 997,325 | package com.github.whalerain.javatool.core;
import cn.hutool.core.util.ReflectUtil;
/**
* 反射工具类
*
* @author ZhangXi
*/
public class ReflectTool extends ReflectUtil {
}
|
92358430cba787bad330cf3cc1cc03cd04ebb681 | 539 | java | Java | base-framework-starter/base-framework-starter-exception/src/main/java/empty/base/starter/exception/exception/AuthorizationException.java | zhenming98/base-framework | dc8fda6253d71ccb650441553daa8834bb59edfd | [
"Apache-2.0"
] | 1 | 2022-01-25T13:05:17.000Z | 2022-01-25T13:05:17.000Z | base-framework-starter/base-framework-starter-exception/src/main/java/empty/base/starter/exception/exception/AuthorizationException.java | zhenming98/base-framework | dc8fda6253d71ccb650441553daa8834bb59edfd | [
"Apache-2.0"
] | null | null | null | base-framework-starter/base-framework-starter-exception/src/main/java/empty/base/starter/exception/exception/AuthorizationException.java | zhenming98/base-framework | dc8fda6253d71ccb650441553daa8834bb59edfd | [
"Apache-2.0"
] | null | null | null | 23.434783 | 87 | 0.693878 | 997,326 | package empty.base.starter.exception.exception;
/**
* @author yzm
* @date 2021/9/26 - 21:44
*/
public class AuthorizationException extends BaseException{
public static final String CODE = "E1000";
public AuthorizationException(String message) {
this(CODE, message);
}
public AuthorizationException(String errCode, String message) {
super(errCode, message);
}
protected AuthorizationException(String errCode, String message, Throwable cause) {
super(errCode, message, cause);
}
}
|
92358469889bb6b3b5981b7d625df87c70e5ad72 | 1,966 | java | Java | src/main/java/org/efaps/ui/wicket/models/objects/grid/GridRow.java | eFaps/eFaps-WebApp | d30eb05c7f231839ce764757ec3d1961af44ef52 | [
"Apache-2.0"
] | 1 | 2020-07-18T16:57:14.000Z | 2020-07-18T16:57:14.000Z | src/main/java/org/efaps/ui/wicket/models/objects/grid/GridRow.java | eFaps/eFaps-WebApp | d30eb05c7f231839ce764757ec3d1961af44ef52 | [
"Apache-2.0"
] | 142 | 2015-07-16T03:55:07.000Z | 2020-05-03T05:14:06.000Z | src/main/java/org/efaps/ui/wicket/models/objects/grid/GridRow.java | eFaps/eFaps-WebApp | d30eb05c7f231839ce764757ec3d1961af44ef52 | [
"Apache-2.0"
] | 2 | 2017-08-11T06:56:08.000Z | 2019-01-17T15:34:17.000Z | 22.860465 | 75 | 0.645473 | 997,327 | /*
* Copyright 2003 - 2018 The eFaps Team
*
* 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.efaps.ui.wicket.models.objects.grid;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.efaps.db.Instance;
public class GridRow
extends ArrayList<GridCell>
{
/** The Constant serialVersionUID. */
private static final long serialVersionUID = 1L;
/** The instance. */
private final Instance instance;
/** The children. */
private final List<GridRow> children = new ArrayList<>();
/**
* Instantiates a new row.
*
* @param _instance the instance
*/
public GridRow(final Instance _instance)
{
this.instance = _instance;
}
/**
* Gets the single instance of Row.
*
* @return single instance of Row
*/
public Instance getInstance()
{
return this.instance;
}
/**
* Adds the child.
*
* @param _gridRow the grid row
* @return the grid row
*/
public GridRow addChild(final GridRow _gridRow)
{
this.children.add(_gridRow);
return this;
}
/**
* Gets the children.
*
* @return the children
*/
public List<GridRow> getChildren()
{
return this.children;
}
@Override
public String toString() {
return ToStringBuilder.reflectionToString(this);
}
}
|
9235847c2d36ee783a66a0d53fad4263657859f9 | 2,692 | java | Java | unitils-mock/src/main/java/org/unitils/mock/core/PartialMockObject.java | Silvermedia/unitils | ed11af302a968b7a9f5666911160139f8994c2d7 | [
"Apache-2.0"
] | null | null | null | unitils-mock/src/main/java/org/unitils/mock/core/PartialMockObject.java | Silvermedia/unitils | ed11af302a968b7a9f5666911160139f8994c2d7 | [
"Apache-2.0"
] | null | null | null | unitils-mock/src/main/java/org/unitils/mock/core/PartialMockObject.java | Silvermedia/unitils | ed11af302a968b7a9f5666911160139f8994c2d7 | [
"Apache-2.0"
] | null | null | null | 43.419355 | 382 | 0.733655 | 997,328 | /*
* Copyright 2013, Unitils.org
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.unitils.mock.core;
import org.unitils.mock.PartialMock;
import org.unitils.mock.annotation.MatchStatement;
import org.unitils.mock.core.matching.MatchingInvocationHandlerFactory;
import org.unitils.mock.core.proxy.impl.MatchingProxyInvocationHandler;
import org.unitils.mock.mockbehavior.MockBehavior;
import org.unitils.mock.mockbehavior.MockBehaviorFactory;
/**
* Implementation of a PartialMock.
* For a partial mock, if a method is called that is not mocked, the original behavior will be called.
*
* @author Tim Ducheyne
* @author Filip Neven
* @author Kenny Claes
*/
public class PartialMockObject<T> extends MockObject<T> implements PartialMock<T> {
public PartialMockObject(String name, Class<T> type, T proxy, T matchingProxy, boolean chained, BehaviorDefiningInvocations behaviorDefiningInvocations, MatchingProxyInvocationHandler matchingProxyInvocationHandler, MockBehaviorFactory mockBehaviorFactory, MatchingInvocationHandlerFactory matchingInvocationHandlerFactory, MockService mockService, DummyFactory dummyFactory) {
super(name, type, proxy, matchingProxy, chained, behaviorDefiningInvocations, matchingProxyInvocationHandler, mockBehaviorFactory, matchingInvocationHandlerFactory, mockService, dummyFactory);
}
/**
* Stubs out (removes) the behavior of the method when the invocation following
* this call matches the observed behavior. E.g.
* <p/>
* mock.stub().method1();
* <p/>
* will not invoke the actual behavior of method1.
* <p/>
* If the method has a return type, a default value will be returned.
* <p/>
* Note: stubbed methods can still be asserted afterwards: e.g.
* <p/>
* mock.assertInvoked().method1();
*
* @return The proxy instance that will record the method call, not null
*/
@MatchStatement
public T stub() {
MockBehavior mockBehavior = mockBehaviorFactory.createStubMockBehavior();
return startBehaviorMatchingInvocation(mockBehavior, false);
}
} |
9235862d0727a1b538946c5760a3b41e6c3718ca | 2,975 | java | Java | eventmesh-emesher/src/main/java/com/webank/emesher/core/consumergroup/ConsumerGroupTopicConf.java | lrhkobe/EventMesh | cd225439895396590e3d59d7e0d3156fec05acb4 | [
"Apache-2.0"
] | 1 | 2020-11-10T14:05:17.000Z | 2020-11-10T14:05:17.000Z | eventmesh-emesher/src/main/java/com/webank/emesher/core/consumergroup/ConsumerGroupTopicConf.java | Candimy/EventMesh | 24a89ee4ba7f00847604a51b72655e3db0fb8f76 | [
"Apache-2.0"
] | null | null | null | eventmesh-emesher/src/main/java/com/webank/emesher/core/consumergroup/ConsumerGroupTopicConf.java | Candimy/EventMesh | 24a89ee4ba7f00847604a51b72655e3db0fb8f76 | [
"Apache-2.0"
] | 1 | 2020-10-26T11:44:35.000Z | 2020-10-26T11:44:35.000Z | 28.605769 | 98 | 0.664874 | 997,329 | /*
* 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.webank.emesher.core.consumergroup;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
public class ConsumerGroupTopicConf {
public static Logger logger = LoggerFactory.getLogger(ConsumerGroupTopicConf.class);
private String consumerGroup;
private String topic;
/**
* PUSH URL
*/
private Map<String /** IDC*/, List<String> /** IDC内URL列表*/> idcUrls = Maps.newConcurrentMap();
/**
* ALL IDC URLs
*/
private Set<String> urls = Sets.newConcurrentHashSet();
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
ConsumerGroupTopicConf that = (ConsumerGroupTopicConf) o;
return consumerGroup.equals(that.consumerGroup) &&
Objects.equals(topic, that.topic) &&
Objects.equals(idcUrls, that.idcUrls);
}
@Override
public int hashCode() {
return Objects.hash(consumerGroup, topic, idcUrls);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("consumeTopicConfig={consumerGroup=").append(consumerGroup)
.append(",topic=").append(topic)
.append(",idcUrls=").append(idcUrls).append("}");
return sb.toString();
}
public String getConsumerGroup() {
return consumerGroup;
}
public void setConsumerGroup(String consumerGroup) {
this.consumerGroup = consumerGroup;
}
public String getTopic() {
return topic;
}
public void setTopic(String topic) {
this.topic = topic;
}
public Map<String, List<String>> getIdcUrls() {
return idcUrls;
}
public void setIdcUrls(Map<String, List<String>> idcUrls) {
this.idcUrls = idcUrls;
}
public Set<String> getUrls() {
return urls;
}
public void setUrls(Set<String> urls) {
this.urls = urls;
}
}
|
9235862dcbffd828b04927e9017b07481d47d5a5 | 1,263 | java | Java | ex/WeekendPlanner/Server/src/example/web/utils/DateUtils.java | zzj19931010/Android_concurrency_hw | a049b12f77018104a927754604e118c3ee563e93 | [
"MIT"
] | null | null | null | ex/WeekendPlanner/Server/src/example/web/utils/DateUtils.java | zzj19931010/Android_concurrency_hw | a049b12f77018104a927754604e118c3ee563e93 | [
"MIT"
] | null | null | null | ex/WeekendPlanner/Server/src/example/web/utils/DateUtils.java | zzj19931010/Android_concurrency_hw | a049b12f77018104a927754604e118c3ee563e93 | [
"MIT"
] | null | null | null | 28.066667 | 69 | 0.756928 | 997,330 | package example.web.utils;
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.Period;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAdjusters;
import example.web.model.Flight;
/**
* A utility class to compute appropriate times and time ranges
*/
public class DateUtils {
public static String getFormattedDateOfNext(DayOfWeek day) {
return getDateOfNext(day)
.format(DateTimeFormatter.ISO_LOCAL_DATE);
}
private static LocalDate getDateOfNext(DayOfWeek day) {
LocalDate today = LocalDate.now();
return day == DayOfWeek.FRIDAY ?
today.with(TemporalAdjusters.nextOrSame(day)) :
today.plusDays(1).with(TemporalAdjusters.next(day));
}
public static String makeDateTimeRange(Flight flight) {
return removeSeconds(flight.getDepartingArrivalDateTime())
+ " TO "
+ removeSeconds(flight.getReturningDepartureDateTime());
}
public static Integer getNumDaysUntilNext(DayOfWeek day) {
LocalDate today = LocalDate.now();
return Period.between(today, getDateOfNext(day)).getDays()
+ (today.getDayOfWeek().compareTo(DayOfWeek.FRIDAY) > 0 ? 7 : 0);
}
private static String removeSeconds(String dateTime) {
return dateTime.substring(0, dateTime.lastIndexOf(":"));
}
}
|
92358797059d84fda7f9fccf53779dfae254a1eb | 202 | java | Java | example/src/com/lambda/Greeter.java | TinaDelli/java-example | b21e3637e73e146dd92080200010ae64a5412c86 | [
"MIT"
] | null | null | null | example/src/com/lambda/Greeter.java | TinaDelli/java-example | b21e3637e73e146dd92080200010ae64a5412c86 | [
"MIT"
] | null | null | null | example/src/com/lambda/Greeter.java | TinaDelli/java-example | b21e3637e73e146dd92080200010ae64a5412c86 | [
"MIT"
] | null | null | null | 14.428571 | 39 | 0.569307 | 997,331 | package com.lambda;
public class Greeter
{
public String sayHello()
{
return "Hello World";
}
public String sayHello(String name)
{
return "Hello, " + name;
}
}
|
9235896ab2e6da625781887f1f5e8d9f98292a37 | 259 | java | Java | lsq-core/src/test/java/org/aksw/simba/lsq/TestLsqHashId.java | saleem-muhammad/LSQ | 93f860a6e778a9562cc93c42c4f914c09b81cd02 | [
"Apache-1.1"
] | 22 | 2015-04-30T21:47:52.000Z | 2021-12-07T21:34:14.000Z | lsq-core/src/test/java/org/aksw/simba/lsq/TestLsqHashId.java | saleem-muhammad/LSQ | 93f860a6e778a9562cc93c42c4f914c09b81cd02 | [
"Apache-1.1"
] | 24 | 2015-06-21T16:08:41.000Z | 2022-03-28T13:40:34.000Z | lsq-core/src/test/java/org/aksw/simba/lsq/TestLsqHashId.java | saleem-muhammad/LSQ | 93f860a6e778a9562cc93c42c4f914c09b81cd02 | [
"Apache-1.1"
] | 10 | 2015-06-21T00:41:33.000Z | 2022-03-09T09:30:41.000Z | 18.5 | 48 | 0.698842 | 997,332 | package org.aksw.simba.lsq;
import org.junit.Test;
public class TestLsqHashId {
@Test
public void testHashId() {
// Model m = ModelFactory.createDefaultModel();
// m.createResource().as(LocalExecution.class)
// .setQueryExec(queryExec)
}
}
|
92358992bfd51edf0a0b1892755d33d6114a788d | 3,345 | java | Java | jib-cli/src/test/java/com/google/cloud/tools/jib/cli/jar/SpringBootPackagedProcessorTest.java | musebc/jib | 2de13f585482bdbc5f4b3cc5f5cbffc13ab9ed3e | [
"Apache-2.0"
] | 11,775 | 2018-04-26T15:42:11.000Z | 2022-03-31T17:08:44.000Z | jib-cli/src/test/java/com/google/cloud/tools/jib/cli/jar/SpringBootPackagedProcessorTest.java | musebc/jib | 2de13f585482bdbc5f4b3cc5f5cbffc13ab9ed3e | [
"Apache-2.0"
] | 2,284 | 2018-04-26T17:03:16.000Z | 2022-03-31T15:36:08.000Z | jib-cli/src/test/java/com/google/cloud/tools/jib/cli/jar/SpringBootPackagedProcessorTest.java | musebc/jib | 2de13f585482bdbc5f4b3cc5f5cbffc13ab9ed3e | [
"Apache-2.0"
] | 1,336 | 2018-05-11T21:54:27.000Z | 2022-03-31T15:23:16.000Z | 38.011364 | 96 | 0.761136 | 997,333 | /*
* Copyright 2020 Google LLC.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.cloud.tools.jib.cli.jar;
import static com.google.common.truth.Truth.assertThat;
import com.google.cloud.tools.jib.api.buildplan.AbsoluteUnixPath;
import com.google.cloud.tools.jib.api.buildplan.FileEntriesLayer;
import com.google.common.collect.ImmutableList;
import com.google.common.io.Resources;
import java.net.URISyntaxException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import org.junit.Test;
/** Tests for {@link SpringBootPackagedProcessor}. */
public class SpringBootPackagedProcessorTest {
private static final String SPRING_BOOT_JAR = "jar/spring-boot/springboot_sample.jar";
private static final Integer JAR_JAVA_VERSION = 0; // any value
@Test
public void testCreateLayers() throws URISyntaxException {
Path springBootJar = Paths.get(Resources.getResource(SPRING_BOOT_JAR).toURI());
SpringBootPackagedProcessor springBootProcessor =
new SpringBootPackagedProcessor(springBootJar, JAR_JAVA_VERSION);
List<FileEntriesLayer> layers = springBootProcessor.createLayers();
assertThat(layers.size()).isEqualTo(1);
FileEntriesLayer jarLayer = layers.get(0);
assertThat(jarLayer.getName()).isEqualTo("jar");
assertThat(jarLayer.getEntries().size()).isEqualTo(1);
assertThat(jarLayer.getEntries().get(0).getExtractionPath())
.isEqualTo(AbsoluteUnixPath.get("/app/springboot_sample.jar"));
}
@Test
public void testComputeEntrypoint() throws URISyntaxException {
Path springBootJar = Paths.get(Resources.getResource(SPRING_BOOT_JAR).toURI());
SpringBootPackagedProcessor springBootProcessor =
new SpringBootPackagedProcessor(springBootJar, JAR_JAVA_VERSION);
ImmutableList<String> actualEntrypoint =
springBootProcessor.computeEntrypoint(ImmutableList.of());
assertThat(actualEntrypoint)
.isEqualTo(ImmutableList.of("java", "-jar", "/app/springboot_sample.jar"));
}
@Test
public void testComputeEntrypoint_jvmFlag() throws URISyntaxException {
Path springBootJar = Paths.get(Resources.getResource(SPRING_BOOT_JAR).toURI());
SpringBootPackagedProcessor springBootProcessor =
new SpringBootPackagedProcessor(springBootJar, JAR_JAVA_VERSION);
ImmutableList<String> actualEntrypoint =
springBootProcessor.computeEntrypoint(ImmutableList.of("-jvm-flag"));
assertThat(actualEntrypoint)
.isEqualTo(ImmutableList.of("java", "-jvm-flag", "-jar", "/app/springboot_sample.jar"));
}
@Test
public void testGetJavaVersion() {
SpringBootPackagedProcessor springBootPackagedProcessor =
new SpringBootPackagedProcessor(Paths.get("ignore"), 8);
assertThat(springBootPackagedProcessor.getJavaVersion()).isEqualTo(8);
}
}
|
92358b0ad5ca7b40c38ae48211b53922f6e312c7 | 398 | java | Java | app/src/main/java/date/liyin/vly/MainApplication.java | cubesky/Vly | 33facf1356968cb227a45fbdf67e40f4df623467 | [
"MIT"
] | 4 | 2020-06-07T18:05:18.000Z | 2020-06-09T11:12:18.000Z | app/src/main/java/date/liyin/vly/MainApplication.java | cubesky/Vly | 33facf1356968cb227a45fbdf67e40f4df623467 | [
"MIT"
] | null | null | null | app/src/main/java/date/liyin/vly/MainApplication.java | cubesky/Vly | 33facf1356968cb227a45fbdf67e40f4df623467 | [
"MIT"
] | 1 | 2020-07-10T12:18:24.000Z | 2020-07-10T12:18:24.000Z | 24.875 | 103 | 0.718593 | 997,334 | package date.liyin.vly;
import android.app.Application;
import android.content.pm.ApplicationInfo;
import com.lzf.easyfloat.EasyFloat;
public class MainApplication extends Application {
@Override
public void onCreate() {
super.onCreate();
EasyFloat.init(this, 0 != (this.getApplicationInfo().flags & ApplicationInfo.FLAG_DEBUGGABLE));
// Enable EasyFloat
}
}
|
92358bcb193d88cff0789e8a9d079dc7e51166ab | 5,527 | java | Java | src/main/java/com/myblog/controller/LogController.java | prayjourney/newblog-in-java | ab8228aac197e2c181150d2cb80b8ce313657ec2 | [
"Apache-2.0"
] | 1 | 2018-04-16T06:38:11.000Z | 2018-04-16T06:38:11.000Z | src/main/java/com/myblog/controller/LogController.java | DanielDcool/newblog | b27d1e06c4dacd009a6ab98c77a4320bef04b3b1 | [
"Apache-2.0"
] | null | null | null | src/main/java/com/myblog/controller/LogController.java | DanielDcool/newblog | b27d1e06c4dacd009a6ab98c77a4320bef04b3b1 | [
"Apache-2.0"
] | 1 | 2020-09-29T14:21:35.000Z | 2020-09-29T14:21:35.000Z | 40.050725 | 109 | 0.644292 | 997,335 | package com.myblog.controller;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
import com.myblog.jmx.JMXClient;
import com.myblog.model.FanPie;
import com.myblog.model.TopTen;
import com.myblog.util.IPUtils;
import com.myblog.util.JedisUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Zephery on 2017/6/23.
*/
@Controller
public class LogController {
private final static Logger logger = LoggerFactory.getLogger(LogController.class);
@RequestMapping("/log")
public ModelAndView log(HttpServletRequest request) {
JedisUtil jedis = JedisUtil.getInstance(); //remember not to close
String temp = jedis.get("daterange");
String pv_count = jedis.get("pv_count");
String visitor_count = jedis.get("visitor_count");
String bounce_ratio = jedis.get("bounce_ratio");
String avg_visit_time = jedis.get("avg_visit_time");
String top_ten = jedis.get("top_ten");
String source = jedis.get("source");
String rukou_str = jedis.get("rukouyemian");
String diyu_str = jedis.get("diyu");
String pv_sum = jedis.get("pv_sum");
String uv_sum = jedis.get("uv_sum");
Gson gson = new Gson();
JsonParser parser = new JsonParser();
//前十访问页面
JsonArray array = parser.parse(top_ten).getAsJsonArray();
List<TopTen> topTens = new ArrayList<>();
for (JsonElement element : array) {
TopTen topTen = gson.fromJson(element, TopTen.class);
topTens.add(topTen);
}
//来源统计
JsonArray sourcearray = parser.parse(source).getAsJsonArray();
List<FanPie> sourcelist = new ArrayList<>();
for (JsonElement element : sourcearray) {
FanPie fanPie = gson.fromJson(element, FanPie.class);
sourcelist.add(fanPie);
}
//前十入口页面
JsonArray rukouarray = parser.parse(rukou_str).getAsJsonArray();
List<TopTen> rukou = new ArrayList<>();
for (JsonElement element : rukouarray) {
TopTen topTen = gson.fromJson(element, TopTen.class);
rukou.add(topTen);
}
//地域地图
JsonArray diyuarray = parser.parse(diyu_str).getAsJsonArray();
List<TopTen> diyu = new ArrayList<>();
for (JsonElement element : diyuarray) {
TopTen topTen = gson.fromJson(element, TopTen.class);
diyu.add(topTen);
}
rukou.sort((o1, o2) -> {
if (o1.getPv_count() > o2.getPv_count()) {
return -1;
} else {
return 1;
}
});
diyu.sort((o1, o2) -> {
if (o1.getPv_count() > o2.getPv_count()) {
return -1;
} else {
return 1;
}
});
List<String> jmx_memory_use = JedisUtil.getInstance().lrange("jmx_memory_use");
List<String> cpu_usage = JedisUtil.getInstance().lrange("cpu_usage");
Integer jmx_memory_committed = Integer.parseInt(JedisUtil.getInstance().get("jmx_memory_committed"));
JsonArray memoryPoolJson = JMXClient.getInstance().getMemoryPoolDetail();
ModelAndView mv = new ModelAndView();
String ip = IPUtils.getIpAddr(request);
String yourcity = IPUtils.getAddressByIP(ip);
mv.addObject("ip", ip);
mv.addObject("yourcity", yourcity);
mv.addObject("daterange", parser.parse(temp).getAsJsonArray());
mv.addObject("topTens", topTens);
mv.addObject("pv_count", pv_count);
mv.addObject("visitor_count", visitor_count);
mv.addObject("bounce_ratio", bounce_ratio);
mv.addObject("sourcelist", sourcelist);
mv.addObject("rukou", rukou.subList(0, rukou.size() > 5 ? 5 : rukou.size()));
mv.addObject("avg_visit_time", avg_visit_time);
mv.addObject("diyu", diyu);
mv.addObject("diyumax", diyu.get(0).getPv_count());
mv.addObject("pv_sum", pv_sum);
mv.addObject("uv_sum", uv_sum);
mv.addObject("jmx_memory_use", jmx_memory_use);
mv.addObject("cpu_usage", cpu_usage);
mv.addObject("jmx_memory_committed", jmx_memory_committed);
mv.addObject("memoryPoolJson", memoryPoolJson);
mv.setViewName("log");
return mv;
}
@RequestMapping("/jmx")
@ResponseBody
public void jmx(HttpServletResponse response) throws IOException {
int aa = Integer.parseInt(JMXClient.getInstance().getJVMUsage().toString());
Integer bb = aa / 1048576;
response.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=UTF-8");
response.getWriter().write(bb.toString());
}
@RequestMapping("/cpu")
@ResponseBody
public void cpu(HttpServletResponse response) throws IOException {
String aa = JMXClient.getInstance().getCpuUsage();
response.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=UTF-8");
response.getWriter().write(aa);
}
}
|
92358c133ed90c1838f80e70e86ccf7008875424 | 1,035 | java | Java | TeamCode/src/main/java/org/firstinspires/ftc/teamcode/greengirls/newchallenge/GGLibrary.java | GG7190/gg_16-17 | fb489982e0df05b1eb0804ec74fb206629040642 | [
"MIT"
] | null | null | null | TeamCode/src/main/java/org/firstinspires/ftc/teamcode/greengirls/newchallenge/GGLibrary.java | GG7190/gg_16-17 | fb489982e0df05b1eb0804ec74fb206629040642 | [
"MIT"
] | null | null | null | TeamCode/src/main/java/org/firstinspires/ftc/teamcode/greengirls/newchallenge/GGLibrary.java | GG7190/gg_16-17 | fb489982e0df05b1eb0804ec74fb206629040642 | [
"MIT"
] | null | null | null | 20.294118 | 63 | 0.603865 | 997,336 | package org.firstinspires.ftc.teamcode.greengirls.newchallenge;
import org.firstinspires.ftc.teamcode.greengirls.GGCore;
/**
* Created by User on 8/2/2016.
*/
public class GGLibrary extends GGCore {
//Set positions for button pushers
public void buttonPushOut(){
servo1.setPosition(SERVO1_MIN_RANGE);
servo2.setPosition(SERVO2_MIN_RANGE);
}
public void buttonPushIn(){
servo1.setPosition(SERVO1_MAX_RANGE);
servo2.setPosition(SERVO2_MAX_RANGE);
}
//lift up
public void liftUp() {
motor1.setPower(-1);
motor2.setPower(1);
}
//lift down
public void liftDown() {
motor1.setPower(1);
motor2.setPower(-1);
}
//stop lift motor
public void stopLift() {
motor1.setPower(0);
motor2.setPower(0);
}
//Start Funnel
public void startFunnel(){
motor3.setPower(1);
}
//Stop Funnel
public void stopFunnel(){
motor3.setPower(0);
}
} |
92358e4713c27c6fa7dab0bc217a36309bb44ab5 | 551 | java | Java | yudao-module-pay/yudao-module-pay-impl/src/main/java/cn/iocoder/yudao/module/pay/service/notify/PayNotifyService.java | orangerman/ruoyi-vue-pro | cc87bce3cbbfe5ca394734c30ef265fccbe13f18 | [
"MIT"
] | 1 | 2022-03-23T06:22:12.000Z | 2022-03-23T06:22:12.000Z | yudao-module-pay/yudao-module-pay-impl/src/main/java/cn/iocoder/yudao/module/pay/service/notify/PayNotifyService.java | rongzhida/ruoyi-vue-pro | bf370952590ff7a4c9d010753f528aa5096e247d | [
"MIT"
] | 1 | 2022-02-09T04:00:44.000Z | 2022-02-09T04:00:44.000Z | yudao-module-pay/yudao-module-pay-impl/src/main/java/cn/iocoder/yudao/module/pay/service/notify/PayNotifyService.java | rongzhida/ruoyi-vue-pro | bf370952590ff7a4c9d010753f528aa5096e247d | [
"MIT"
] | 1 | 2022-02-12T00:26:52.000Z | 2022-02-12T00:26:52.000Z | 18.366667 | 80 | 0.671506 | 997,337 | package cn.iocoder.yudao.module.pay.service.notify;
import cn.iocoder.yudao.module.pay.service.notify.dto.PayNotifyTaskCreateReqDTO;
import javax.validation.Valid;
/**
* 支付通知 Service 接口
*
* @author 芋道源码
*/
public interface PayNotifyService {
/**
* 创建支付通知任务
*
* @param reqDTO 任务信息
*/
void createPayNotifyTask(@Valid PayNotifyTaskCreateReqDTO reqDTO);
/**
* 执行支付通知
*
* 注意,该方法提供给定时任务调用。目前是 yudao-admin-server 进行调用
* @return 通知数量
*/
int executeNotify() throws InterruptedException;
}
|
92358f675f2235b9aa006954db4e00408cfcb2e9 | 11,385 | java | Java | src/main/java/com/synopsys/integration/alert/component/settings/SettingsUIConfig.java | mphammer/blackduck-alert | c61015597c52ad7388ebe03d7dfc117c8be5e788 | [
"Apache-2.0"
] | null | null | null | src/main/java/com/synopsys/integration/alert/component/settings/SettingsUIConfig.java | mphammer/blackduck-alert | c61015597c52ad7388ebe03d7dfc117c8be5e788 | [
"Apache-2.0"
] | null | null | null | src/main/java/com/synopsys/integration/alert/component/settings/SettingsUIConfig.java | mphammer/blackduck-alert | c61015597c52ad7388ebe03d7dfc117c8be5e788 | [
"Apache-2.0"
] | null | null | null | 65.431034 | 236 | 0.770224 | 997,338 | /**
* blackduck-alert
*
* Copyright (C) 2019 Black Duck Software, Inc.
* http://www.blackducksoftware.com/
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package com.synopsys.integration.alert.component.settings;
import java.util.Collection;
import java.util.List;
import java.util.Optional;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import com.synopsys.integration.alert.common.rest.model.FieldModel;
import com.synopsys.integration.alert.common.rest.model.FieldValueModel;
import com.synopsys.integration.alert.common.descriptor.config.field.CheckboxConfigField;
import com.synopsys.integration.alert.common.descriptor.config.field.ConfigField;
import com.synopsys.integration.alert.common.descriptor.config.field.NumberConfigField;
import com.synopsys.integration.alert.common.descriptor.config.field.PasswordConfigField;
import com.synopsys.integration.alert.common.descriptor.config.field.SelectConfigField;
import com.synopsys.integration.alert.common.descriptor.config.field.TextInputConfigField;
import com.synopsys.integration.alert.common.descriptor.config.ui.UIConfig;
@Component
public class SettingsUIConfig extends UIConfig {
public SettingsUIConfig() {
super(SettingsDescriptor.SETTINGS_LABEL, SettingsDescriptor.SETTINGS_URL, SettingsDescriptor.SETTINGS_ICON);
}
@Override
public List<ConfigField> createFields() {
final ConfigField sysAdminEmail = PasswordConfigField.createRequired(SettingsDescriptor.KEY_DEFAULT_SYSTEM_ADMIN_EMAIL, "Default System Administrator Email");
final ConfigField defaultUserPassword = PasswordConfigField.createRequired(SettingsDescriptor.KEY_DEFAULT_SYSTEM_ADMIN_PWD, "Default System Administrator Password");
final ConfigField encryptionPassword = PasswordConfigField.createRequired(SettingsDescriptor.KEY_ENCRYPTION_PWD, "Encryption Password");
final ConfigField encryptionSalt = PasswordConfigField.createRequired(SettingsDescriptor.KEY_ENCRYPTION_GLOBAL_SALT, "Encryption Global Salt");
final ConfigField environmentVariableOverride = CheckboxConfigField.create(SettingsDescriptor.KEY_STARTUP_ENVIRONMENT_VARIABLE_OVERRIDE, "Startup Environment Variable Override");
final ConfigField proxyHost = TextInputConfigField.create(SettingsDescriptor.KEY_PROXY_HOST, "Proxy Host", this::validateProxyHost);
final ConfigField proxyPort = NumberConfigField.create(SettingsDescriptor.KEY_PROXY_PORT, "Proxy Port", this::validateProxyPort);
final ConfigField proxyUsername = TextInputConfigField.create(SettingsDescriptor.KEY_PROXY_USERNAME, "Proxy Username", this::validateProxyUserName);
final ConfigField proxyPassword = PasswordConfigField.create(SettingsDescriptor.KEY_PROXY_PWD, "Proxy Password", this::validateProxyPassword);
final ConfigField ldapEnabled = TextInputConfigField.create(SettingsDescriptor.KEY_LDAP_ENABLED, "LDAP Enabled");
final ConfigField ldapServer = TextInputConfigField.create(SettingsDescriptor.KEY_LDAP_SERVER, "LDAP Server", this::validateLDAPServer);
final ConfigField ldapManagerDn = TextInputConfigField.create(SettingsDescriptor.KEY_LDAP_MANAGER_DN, "LDAP Manager DN", this::validateLDAPUsername);
final ConfigField ldapManagerPassword = PasswordConfigField.create(SettingsDescriptor.KEY_LDAP_MANAGER_PWD, "LDAP Manager Password", this::validateLDAPPassword);
final ConfigField ldapAuthenticationType = SelectConfigField.create(SettingsDescriptor.KEY_LDAP_AUTHENTICATION_TYPE, "LDAP Authentication Type", List.of("simple", "none", "digest"));
final ConfigField ldapReferral = SelectConfigField.create(SettingsDescriptor.KEY_LDAP_REFERRAL, "LDAP Referral", List.of("ignore", "follow", "throw"));
final ConfigField ldapUserSearchBase = TextInputConfigField.create(SettingsDescriptor.KEY_LDAP_USER_SEARCH_BASE, "LDAP User Search Base");
final ConfigField ldapUserSearchFilter = TextInputConfigField.create(SettingsDescriptor.KEY_LDAP_USER_SEARCH_FILTER, "LDAP User Search Filter");
final ConfigField ldapUserDNPatterns = TextInputConfigField.create(SettingsDescriptor.KEY_LDAP_USER_DN_PATTERNS, "LDAP User DN Patterns");
final ConfigField ldapUserAttributes = TextInputConfigField.create(SettingsDescriptor.KEY_LDAP_USER_ATTRIBUTES, "LDAP User Attributes");
final ConfigField ldapGroupSearchBase = TextInputConfigField.create(SettingsDescriptor.KEY_LDAP_GROUP_SEARCH_BASE, "LDAP Group Search Base");
final ConfigField ldapGroupSearchFilter = TextInputConfigField.create(SettingsDescriptor.KEY_LDAP_GROUP_SEARCH_FILTER, "LDAP Group Search Filter");
final ConfigField ldapGroupRoleAttribute = TextInputConfigField.create(SettingsDescriptor.KEY_LDAP_GROUP_ROLE_ATTRIBUTE, "LDAP Group Role Attribute");
final ConfigField ldapRolePrefix = TextInputConfigField.create(SettingsDescriptor.KEY_LDAP_ROLE_PREFIX, "LDAP Role Prefix");
return List.of(sysAdminEmail, defaultUserPassword, encryptionPassword, encryptionSalt, environmentVariableOverride, proxyHost, proxyPort, proxyUsername, proxyPassword, ldapEnabled, ldapServer, ldapManagerDn, ldapManagerPassword,
ldapAuthenticationType, ldapReferral, ldapUserSearchBase, ldapUserSearchFilter, ldapUserDNPatterns, ldapUserAttributes, ldapGroupSearchBase, ldapGroupSearchFilter, ldapGroupRoleAttribute, ldapRolePrefix);
}
private Collection<String> validateProxyHost(final FieldValueModel fieldToValidate, final FieldModel fieldModel) {
final boolean hostExists = validateFieldExists(fieldModel, SettingsDescriptor.KEY_PROXY_HOST);
final boolean portExists = validateFieldExists(fieldModel, SettingsDescriptor.KEY_PROXY_PORT);
final boolean userNameExists = validateFieldExists(fieldModel, SettingsDescriptor.KEY_PROXY_USERNAME);
final boolean passwordExists = validateFieldExists(fieldModel, SettingsDescriptor.KEY_PROXY_PWD);
final boolean isHostMissing = (portExists || passwordExists || userNameExists) && !hostExists;
if (isHostMissing) {
return List.of(SettingsDescriptor.FIELD_ERROR_PROXY_HOST_MISSING);
}
return List.of();
}
private Collection<String> validateProxyPort(final FieldValueModel fieldToValidate, final FieldModel fieldModel) {
final boolean hostExists = validateFieldExists(fieldModel, SettingsDescriptor.KEY_PROXY_HOST);
final boolean portExists = validateFieldExists(fieldModel, SettingsDescriptor.KEY_PROXY_PORT);
final boolean userNameExists = validateFieldExists(fieldModel, SettingsDescriptor.KEY_PROXY_USERNAME);
final boolean passwordExists = validateFieldExists(fieldModel, SettingsDescriptor.KEY_PROXY_PWD);
final boolean isPortMissing = (hostExists || passwordExists || userNameExists) && !portExists;
if (isPortMissing) {
return List.of(SettingsDescriptor.FIELD_ERROR_PROXY_PORT_MISSING);
}
return List.of();
}
private Collection<String> validateProxyUserName(final FieldValueModel fieldToValidate, final FieldModel fieldModel) {
Collection<String> result = List.of();
final String proxyPassword = fieldModel.getField(SettingsDescriptor.KEY_PROXY_PWD).flatMap(FieldValueModel::getValue).orElse("");
final boolean fieldHasNoValue = !fieldToValidate.hasValues() || StringUtils.isBlank(fieldToValidate.getValue().orElse(""));
if (fieldHasNoValue && StringUtils.isNotBlank(proxyPassword)) {
result = List.of(SettingsDescriptor.FIELD_ERROR_PROXY_USER_MISSING);
}
return result;
}
private Collection<String> validateProxyPassword(final FieldValueModel fieldToValidate, final FieldModel fieldModel) {
Collection<String> result = List.of();
final boolean userNameExists = validateFieldExists(fieldModel, SettingsDescriptor.KEY_PROXY_USERNAME);
final boolean fieldHasNoValue = !fieldToValidate.isSet() && (!fieldToValidate.hasValues() || StringUtils.isBlank(fieldToValidate.getValue().orElse("")));
if (fieldHasNoValue && userNameExists) {
result = List.of(SettingsDescriptor.FIELD_ERROR_PROXY_PWD_MISSING);
}
return result;
}
private boolean validateFieldExists(final FieldModel fieldModel, final String fieldKey) {
final Optional<String> fieldValue = fieldModel.getFieldValue(fieldKey);
return fieldValue.stream().anyMatch(StringUtils::isNotBlank);
}
private Collection<String> validateLDAPServer(final FieldValueModel fieldToValidate, final FieldModel fieldModel) {
if (isLDAPEnabled(fieldModel)) {
final boolean fieldHasNoValue = !fieldToValidate.hasValues() || StringUtils.isBlank(fieldToValidate.getValue().orElse(""));
if (fieldHasNoValue) {
return List.of(SettingsDescriptor.FIELD_ERROR_LDAP_SERVER_MISSING);
}
}
return List.of();
}
private Collection<String> validateLDAPUsername(final FieldValueModel fieldToValidate, final FieldModel fieldModel) {
if (isLDAPEnabled(fieldModel)) {
final String managerPassword = fieldModel.getField(SettingsDescriptor.KEY_LDAP_MANAGER_PWD).flatMap(FieldValueModel::getValue).orElse("");
final boolean fieldHasNoValue = !fieldToValidate.hasValues() || StringUtils.isBlank(fieldToValidate.getValue().orElse(""));
if (fieldHasNoValue && StringUtils.isNotBlank(managerPassword)) {
return List.of(SettingsDescriptor.FIELD_ERROR_LDAP_USERNAME_MISSING);
}
}
return List.of();
}
private Collection<String> validateLDAPPassword(final FieldValueModel fieldToValidate, final FieldModel fieldModel) {
if (isLDAPEnabled(fieldModel)) {
final String managerDN = fieldModel.getField(SettingsDescriptor.KEY_LDAP_MANAGER_DN).flatMap(FieldValueModel::getValue).orElse("");
final boolean fieldHasNoValue = !fieldToValidate.isSet() && (!fieldToValidate.hasValues() || StringUtils.isBlank(fieldToValidate.getValue().orElse("")));
if (fieldHasNoValue && StringUtils.isNotBlank(managerDN)) {
return List.of(SettingsDescriptor.FIELD_ERROR_LDAP_PWD_MISSING);
}
}
return List.of();
}
private boolean isLDAPEnabled(final FieldModel fieldModel) {
return fieldModel.getField(SettingsDescriptor.KEY_LDAP_ENABLED)
.flatMap(FieldValueModel::getValue)
.map(Boolean::parseBoolean)
.orElse(false);
}
}
|
92358faf1cce45f120e61e8959311afd2fa65c9e | 1,320 | java | Java | src/cn/ieclipse/smartim/views/IMContactDoubleClicker.java | Jamling/SmartQQ4IntelliJ | 9a98b99a97220f7ff191782190a8bddbe07ee3e4 | [
"Apache-2.0"
] | 719 | 2017-07-06T09:19:51.000Z | 2019-03-08T06:05:28.000Z | src/cn/ieclipse/smartim/views/IMContactDoubleClicker.java | Jamling/SmartQQ4IntelliJ | 9a98b99a97220f7ff191782190a8bddbe07ee3e4 | [
"Apache-2.0"
] | 59 | 2017-07-16T13:37:26.000Z | 2019-02-01T08:41:26.000Z | src/cn/ieclipse/smartim/views/IMContactDoubleClicker.java | Jamling/SmartQQ4IntelliJ | 9a98b99a97220f7ff191782190a8bddbe07ee3e4 | [
"Apache-2.0"
] | 72 | 2017-07-10T02:22:37.000Z | 2019-01-25T07:45:22.000Z | 33 | 105 | 0.610606 | 997,339 | package cn.ieclipse.smartim.views;
import javax.swing.*;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.TreePath;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
/**
* Created by Jamling on 2017/11/1.
*/
public class IMContactDoubleClicker extends MouseAdapter {
protected IMPanel imPanel;
public IMContactDoubleClicker(IMPanel imPanel) {
this.imPanel = imPanel;
}
@Override public void mouseClicked(MouseEvent e) {
super.mouseClicked(e);
JTree tree = (JTree)e.getSource();
int selRow = tree.getRowForLocation(e.getX(), e.getY());
TreePath selPath = tree.getPathForLocation(e.getX(), e.getY());
if (selRow != -1 && selPath != null) {
DefaultMutableTreeNode selectedNode = (DefaultMutableTreeNode)selPath.getLastPathComponent();
if (selectedNode.getChildCount() > 0) {
if (tree.isExpanded(selPath)) {
tree.collapsePath(selPath);
} else {
tree.expandPath(selPath);
}
return;
}
if (imPanel != null && e.getClickCount() == 2) {
imPanel.onDoubleClick(((DefaultMutableTreeNode)selectedNode).getUserObject());
}
}
}
}
|
92359099dd4b026fa6a4dbcb8e779fab73681dc6 | 2,048 | java | Java | src/main/java/org/szegedi/spring/web/jsflow/FlowStateStorage.java | szegedi/rhinoInSpring | 1835b20a02e305926edef2ce9bd9a105e54406a2 | [
"Apache-2.0"
] | 2 | 2017-10-06T03:17:50.000Z | 2018-09-10T11:08:29.000Z | src/main/java/org/szegedi/spring/web/jsflow/FlowStateStorage.java | szegedi/rhinoInSpring | 1835b20a02e305926edef2ce9bd9a105e54406a2 | [
"Apache-2.0"
] | 1 | 2019-07-02T17:24:17.000Z | 2019-07-02T17:24:17.000Z | src/main/java/org/szegedi/spring/web/jsflow/FlowStateStorage.java | szegedi/rhinoInSpring | 1835b20a02e305926edef2ce9bd9a105e54406a2 | [
"Apache-2.0"
] | null | null | null | 37.925926 | 84 | 0.685059 | 997,340 | /*
Copyright 2006 Attila Szegedi
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.szegedi.spring.web.jsflow;
import javax.servlet.http.HttpServletRequest;
import org.mozilla.javascript.NativeContinuation;
/**
* A storage for interim flow states. It is sufficient (and recommended) to have
* exactly one flow state storage per application context, although you can have
* exotic scenarios with several controllers, each with a different storage if
* you really have to. If you have a single storage in the application context,
* then all flow controllers that don't have their own storage set will use it.
*
* @author Attila Szegedi
* @version $Id$
*/
public interface FlowStateStorage {
/**
* Stores the state associated with the current request
*
* @param request
* the HTTP request
* @param state
* the state
* @return an identifier for the state. The identifier is unique at least in
* the scope of the current HTTP request's session.
*/
public String storeState(HttpServletRequest request, NativeContinuation state);
/**
* Retrieves the state associated with a request
*
* @param request
* the HTTP request
* @param id
* the unique identifier for the flow state
* @return the flow state, or null if it couldn't be resolved
*/
public NativeContinuation getState(HttpServletRequest request, String id);
} |
923591198efe4818043191e2aa83585360b43c9e | 3,101 | java | Java | municipal-services/mgramseva-ifix-adapter/src/main/java/org/egov/mgramsevaifixadaptor/util/MDMSUtils.java | lakshmisravani-wtt-egov/punjab-mgramseva | 00e64bda9a85e789de45af88e635892439435798 | [
"MIT"
] | 1 | 2021-12-30T13:36:16.000Z | 2021-12-30T13:36:16.000Z | municipal-services/mgramseva-ifix-adapter/src/main/java/org/egov/mgramsevaifixadaptor/util/MDMSUtils.java | lakshmisravani-wtt-egov/punjab-mgramseva | 00e64bda9a85e789de45af88e635892439435798 | [
"MIT"
] | 18 | 2021-07-26T05:19:46.000Z | 2021-09-27T12:01:32.000Z | municipal-services/mgramseva-ifix-adapter/src/main/java/org/egov/mgramsevaifixadaptor/util/MDMSUtils.java | egovernments/punjab-mgramseva | 00e64bda9a85e789de45af88e635892439435798 | [
"MIT"
] | 1 | 2021-10-13T06:19:01.000Z | 2021-10-13T06:19:01.000Z | 31.969072 | 133 | 0.72525 | 997,341 | package org.egov.mgramsevaifixadaptor.util;
import org.egov.common.contract.request.RequestInfo;
import org.egov.mdms.model.MasterDetail;
import org.egov.mdms.model.MdmsCriteria;
import org.egov.mdms.model.MdmsCriteriaReq;
import org.egov.mdms.model.ModuleDetail;
import org.egov.mgramsevaifixadaptor.config.PropertyConfiguration;
import org.egov.mgramsevaifixadaptor.repository.ServiceRequestRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
@Component
public class MDMSUtils {
@Autowired
PropertyConfiguration propertyConfiguration;
@Autowired
ServiceRequestRepository serviceRequestRepository;
/**
* Calls MDMS service to fetch pgr master data
* @param requestInfo
* @param tenantId
* @return
*/
public Object mDMSCall(RequestInfo requestInfo, String tenantId){
MdmsCriteriaReq mdmsCriteriaReq = getMDMSRequest(requestInfo,tenantId);
Object result = serviceRequestRepository.fetchResult(getMdmsSearchUrl().toString(), mdmsCriteriaReq);
return result;
}
/**
* Returns mdms search criteria based on the tenantId
* @param requestInfo
* @param tenantId
* @return
*/
public MdmsCriteriaReq getMDMSRequest(RequestInfo requestInfo,String tenantId){
List<ModuleDetail> pgrModuleRequest = getAdapterModuleRequest(tenantId);
List<ModuleDetail> moduleDetails = new LinkedList<>();
moduleDetails.addAll(pgrModuleRequest);
MdmsCriteria mdmsCriteria = MdmsCriteria.builder().moduleDetails(moduleDetails).tenantId(tenantId)
.build();
MdmsCriteriaReq mdmsCriteriaReq = MdmsCriteriaReq.builder().mdmsCriteria(mdmsCriteria)
.requestInfo(requestInfo).build();
return mdmsCriteriaReq;
}
/**
* Creates request to search projectid from MDMS
* @return request to search projectid from MDMS
*/
private List<ModuleDetail> getAdapterModuleRequest(String tenantId) {
// master details for adaptor module
List<MasterDetail> adapterMasterDetails = new ArrayList<>();
// filter to only get code field from master data
final String filterCode = "$.[?(@.code=='"+tenantId+"')]";
adapterMasterDetails.add(MasterDetail.builder().name(Constants.TENANTS).filter(filterCode).build());
ModuleDetail adaptorModuleDtls = ModuleDetail.builder().masterDetails(adapterMasterDetails)
.moduleName(Constants.TENANT).build();
return Collections.singletonList(adaptorModuleDtls);
}
/**
* Returns the url for mdms search endpoint
*
* @return url for mdms search endpoint
*/
public StringBuilder getMdmsSearchUrl() {
return new StringBuilder().append(propertyConfiguration.getMdmsHost()).append(propertyConfiguration.getMdmsSearchEndpoint());
}
}
|
92359302d5847db15f6ceb95225781f392af29b9 | 6,249 | java | Java | ihmc-interfaces/src/main/generated-java/controller_msgs/msg/dds/FootstepPlanningTimingsMessagePubSubType.java | ihmcrobotics/ihmc-open-robotics-software | 129b261de850e85e1dc78a12e9c075f53c6019a0 | [
"Apache-2.0"
] | 170 | 2016-02-01T18:58:50.000Z | 2022-03-17T05:28:01.000Z | ihmc-interfaces/src/main/generated-java/controller_msgs/msg/dds/FootstepPlanningTimingsMessagePubSubType.java | ihmcrobotics/ihmc-open-robotics-software | 129b261de850e85e1dc78a12e9c075f53c6019a0 | [
"Apache-2.0"
] | 162 | 2016-01-29T17:04:29.000Z | 2022-02-10T16:25:37.000Z | ihmc-interfaces/src/main/generated-java/controller_msgs/msg/dds/FootstepPlanningTimingsMessagePubSubType.java | ihmcrobotics/ihmc-open-robotics-software | 129b261de850e85e1dc78a12e9c075f53c6019a0 | [
"Apache-2.0"
] | 83 | 2016-01-28T22:49:01.000Z | 2022-03-28T03:11:24.000Z | 35.305085 | 177 | 0.754841 | 997,342 | package controller_msgs.msg.dds;
/**
*
* Topic data type of the struct "FootstepPlanningTimingsMessage" defined in "FootstepPlanningTimingsMessage_.idl". Use this class to provide the TopicDataType to a Participant.
*
* This file was automatically generated from FootstepPlanningTimingsMessage_.idl by us.ihmc.idl.generator.IDLGenerator.
* Do not update this file directly, edit FootstepPlanningTimingsMessage_.idl instead.
*
*/
public class FootstepPlanningTimingsMessagePubSubType implements us.ihmc.pubsub.TopicDataType<controller_msgs.msg.dds.FootstepPlanningTimingsMessage>
{
public static final java.lang.String name = "controller_msgs::msg::dds_::FootstepPlanningTimingsMessage_";
private final us.ihmc.idl.CDR serializeCDR = new us.ihmc.idl.CDR();
private final us.ihmc.idl.CDR deserializeCDR = new us.ihmc.idl.CDR();
@Override
public void serialize(controller_msgs.msg.dds.FootstepPlanningTimingsMessage data, us.ihmc.pubsub.common.SerializedPayload serializedPayload) throws java.io.IOException
{
serializeCDR.serialize(serializedPayload);
write(data, serializeCDR);
serializeCDR.finishSerialize();
}
@Override
public void deserialize(us.ihmc.pubsub.common.SerializedPayload serializedPayload, controller_msgs.msg.dds.FootstepPlanningTimingsMessage data) throws java.io.IOException
{
deserializeCDR.deserialize(serializedPayload);
read(data, deserializeCDR);
deserializeCDR.finishDeserialize();
}
public static int getMaxCdrSerializedSize()
{
return getMaxCdrSerializedSize(0);
}
public static int getMaxCdrSerializedSize(int current_alignment)
{
int initial_alignment = current_alignment;
current_alignment += 8 + us.ihmc.idl.CDR.alignment(current_alignment, 8);
current_alignment += 8 + us.ihmc.idl.CDR.alignment(current_alignment, 8);
current_alignment += 8 + us.ihmc.idl.CDR.alignment(current_alignment, 8);
current_alignment += 8 + us.ihmc.idl.CDR.alignment(current_alignment, 8);
current_alignment += 8 + us.ihmc.idl.CDR.alignment(current_alignment, 8);
return current_alignment - initial_alignment;
}
public final static int getCdrSerializedSize(controller_msgs.msg.dds.FootstepPlanningTimingsMessage data)
{
return getCdrSerializedSize(data, 0);
}
public final static int getCdrSerializedSize(controller_msgs.msg.dds.FootstepPlanningTimingsMessage data, int current_alignment)
{
int initial_alignment = current_alignment;
current_alignment += 8 + us.ihmc.idl.CDR.alignment(current_alignment, 8);
current_alignment += 8 + us.ihmc.idl.CDR.alignment(current_alignment, 8);
current_alignment += 8 + us.ihmc.idl.CDR.alignment(current_alignment, 8);
current_alignment += 8 + us.ihmc.idl.CDR.alignment(current_alignment, 8);
current_alignment += 8 + us.ihmc.idl.CDR.alignment(current_alignment, 8);
return current_alignment - initial_alignment;
}
public static void write(controller_msgs.msg.dds.FootstepPlanningTimingsMessage data, us.ihmc.idl.CDR cdr)
{
cdr.write_type_6(data.getTotalElapsedSeconds());
cdr.write_type_6(data.getTimeBeforePlanningSeconds());
cdr.write_type_6(data.getTimePlanningBodyPathSeconds());
cdr.write_type_6(data.getTimePlanningStepsSeconds());
cdr.write_type_11(data.getStepPlanningIterations());
}
public static void read(controller_msgs.msg.dds.FootstepPlanningTimingsMessage data, us.ihmc.idl.CDR cdr)
{
data.setTotalElapsedSeconds(cdr.read_type_6());
data.setTimeBeforePlanningSeconds(cdr.read_type_6());
data.setTimePlanningBodyPathSeconds(cdr.read_type_6());
data.setTimePlanningStepsSeconds(cdr.read_type_6());
data.setStepPlanningIterations(cdr.read_type_11());
}
@Override
public final void serialize(controller_msgs.msg.dds.FootstepPlanningTimingsMessage data, us.ihmc.idl.InterchangeSerializer ser)
{
ser.write_type_6("total_elapsed_seconds", data.getTotalElapsedSeconds());
ser.write_type_6("time_before_planning_seconds", data.getTimeBeforePlanningSeconds());
ser.write_type_6("time_planning_body_path_seconds", data.getTimePlanningBodyPathSeconds());
ser.write_type_6("time_planning_steps_seconds", data.getTimePlanningStepsSeconds());
ser.write_type_11("step_planning_iterations", data.getStepPlanningIterations());
}
@Override
public final void deserialize(us.ihmc.idl.InterchangeSerializer ser, controller_msgs.msg.dds.FootstepPlanningTimingsMessage data)
{
data.setTotalElapsedSeconds(ser.read_type_6("total_elapsed_seconds"));
data.setTimeBeforePlanningSeconds(ser.read_type_6("time_before_planning_seconds"));
data.setTimePlanningBodyPathSeconds(ser.read_type_6("time_planning_body_path_seconds"));
data.setTimePlanningStepsSeconds(ser.read_type_6("time_planning_steps_seconds"));
data.setStepPlanningIterations(ser.read_type_11("step_planning_iterations"));
}
public static void staticCopy(controller_msgs.msg.dds.FootstepPlanningTimingsMessage src, controller_msgs.msg.dds.FootstepPlanningTimingsMessage dest)
{
dest.set(src);
}
@Override
public controller_msgs.msg.dds.FootstepPlanningTimingsMessage createData()
{
return new controller_msgs.msg.dds.FootstepPlanningTimingsMessage();
}
@Override
public int getTypeSize()
{
return us.ihmc.idl.CDR.getTypeSize(getMaxCdrSerializedSize());
}
@Override
public java.lang.String getName()
{
return name;
}
public void serialize(controller_msgs.msg.dds.FootstepPlanningTimingsMessage data, us.ihmc.idl.CDR cdr)
{
write(data, cdr);
}
public void deserialize(controller_msgs.msg.dds.FootstepPlanningTimingsMessage data, us.ihmc.idl.CDR cdr)
{
read(data, cdr);
}
public void copy(controller_msgs.msg.dds.FootstepPlanningTimingsMessage src, controller_msgs.msg.dds.FootstepPlanningTimingsMessage dest)
{
staticCopy(src, dest);
}
@Override
public FootstepPlanningTimingsMessagePubSubType newInstance()
{
return new FootstepPlanningTimingsMessagePubSubType();
}
}
|
92359376ffde0669bbe7edf0372608c0b64993c2 | 15,020 | java | Java | ezsql-orm/src/main/java/com/github/quintans/ezSQL/toolkit/io/BinStore.java | quintans/ezSQL | 5a05d2015db8a2200323943fe2014331297904f4 | [
"Apache-2.0"
] | 5 | 2015-09-21T10:57:48.000Z | 2021-03-26T07:20:28.000Z | ezsql-orm/src/main/java/com/github/quintans/ezSQL/toolkit/io/BinStore.java | quintans/ezSQL | 5a05d2015db8a2200323943fe2014331297904f4 | [
"Apache-2.0"
] | 2 | 2022-01-21T23:21:24.000Z | 2022-02-16T00:55:15.000Z | ezsql-orm/src/main/java/com/github/quintans/ezSQL/toolkit/io/BinStore.java | quintans/ezSQL | 5a05d2015db8a2200323943fe2014331297904f4 | [
"Apache-2.0"
] | null | null | null | 31.291667 | 177 | 0.622037 | 997,343 | /*
* 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.github.quintans.ezSQL.toolkit.io;
import org.apache.commons.io.IOUtils;
import org.apache.commons.io.output.DeferredFileOutputStream;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.Serializable;
/**
* <p>
* This is an adaptation of org.apache.commons.fileupload.disk.DiskFileItem.java
*
* <p>
* After retrieving an instance of this class, you may either request all contents of file at once using
* {@link #get()} or request an {@link java.io.InputStream InputStream} with {@link #getInputStream()}
* and process the file without attempting to load it into memory, which may
* come handy with large files.
*
* <p>
* Temporary files, which are created for file items, should be deleted later on. However, if you do use such a tracker,
* then you must consider the following: Temporary files are automatically deleted as soon as they are no longer needed.
* (More precisely, when the corresponding instance of {@link java.io.File} is garbage collected.)
* </p>
*/
public class BinStore implements Serializable {
// ----------------------------------------------------- Manifest constants
/**
* The UID to use when serializing this instance.
*/
private static final long serialVersionUID = 2237570099615271025L;
public static final int DEFAULT_THRESHOLD = 65535; // 65KB
// ----------------------------------------------------------- Data members
/**
* The size of the item, in bytes. This is used to cache the size when a
* file item is moved from its original location.
*/
private long size = -1;
/**
* The threshold above which uploads will be stored on disk.
*/
private int sizeThreshold = DEFAULT_THRESHOLD;
/**
* Cached contents of the file.
*/
private byte[] cachedContent;
/**
* Output stream for this item.
*/
private transient DeferredFileOutputStream dfos;
/**
* The temporary file to use.
*/
private transient File tempFile;
/**
* File to allow for serialization of the content of this item.
*/
private File dfosFile;
public BinStore() {
}
public BinStore(byte[] data) {
set(data);
}
public static BinStore of(byte[] data) {
return new BinStore(data);
}
public static BinStore ofFile(String pathname) throws IOException {
BinStore bs = new BinStore();
bs.set(new File(pathname));
return bs;
}
public static BinStore ofInputStream(InputStream inputStream) throws IOException {
BinStore bs = new BinStore();
bs.set(inputStream);
return bs;
}
public BinStore(int sizeThreshold, byte[] data) {
this(sizeThreshold);
set(data);
}
/**
* Constructs a new <code>BinStore</code> instance.
*
* @param sizeThreshold The threshold, in bytes, below which items will be
* retained in memory and above which they will be
* stored as a file.
*/
public BinStore(int sizeThreshold) {
this.sizeThreshold = sizeThreshold;
}
/**
* Returns an {@link java.io.InputStream InputStream} that can be
* used to retrieve the contents of the file.
*
* @return An {@link java.io.InputStream InputStream} that can be
* used to retrieve the contents of the file.
* @throws IOException if an error occurs.
*/
public InputStream getInputStream() throws IOException {
if (!isInMemory()) {
return new FileInputStream(this.dfos.getFile());
}
if (this.cachedContent == null) {
this.cachedContent = this.dfos.getData();
}
return new ByteArrayInputStream(this.cachedContent);
}
/**
* Provides a hint as to whether or not the file contents will be read
* from memory.
*
* @return <code>true</code> if the file contents will be read
* from memory; <code>false</code> otherwise.
*/
public boolean isInMemory() {
if (this.cachedContent != null) {
return true;
}
return this.dfos.isInMemory();
}
/**
* Returns the size of the file.
*
* @return The size of the file, in bytes.
*/
public long getSize() {
if (this.size >= 0) {
return this.size;
} else if (this.cachedContent != null) {
return this.cachedContent.length;
} else if (this.dfos.isInMemory()) {
return this.dfos.getData().length;
} else {
return this.dfos.getFile().length();
}
}
/**
* Returns the contents of the file as an array of bytes. If the
* contents of the file were not yet cached in memory, they will be
* loaded from the disk storage and cached.
*
* @return The contents of the file as an array of bytes.
*/
public byte[] get() {
if (isInMemory()) {
if (this.cachedContent == null) {
this.cachedContent = this.dfos.getData();
}
return this.cachedContent;
}
byte[] fileData = new byte[(int) getSize()];
FileInputStream fis = null;
try {
fis = new FileInputStream(this.dfos.getFile());
fis.read(fileData);
} catch (IOException e) {
fileData = null;
} finally {
IOUtils.closeQuietly(fis);
}
return fileData;
}
/**
* Sets the contents using an array of bytes as a source
*
* @param data The array of bytes with the data
*/
public void set(byte[] data) {
try {
this.cachedContent = null;
copyAndClose(new ByteArrayInputStream(data), getOutputStream());
} catch (IOException e) {
// ignore
}
}
/**
* Sets the contents using a File as a source
*
* @param source The file with the data
* @throws IOException
*/
public void set(File source) throws IOException {
set(new FileInputStream(source));
}
/**
* Sets the contents using a InputStream as a source
*
* @param source The InputStream with the data
* @throws IOException if something went wrong
*/
public void set(InputStream source) throws IOException {
OutputStream out = null;
try {
out = getOutputStream();
IOUtils.copy(source, out);
} finally {
IOUtils.closeQuietly(out);
}
}
/**
* A convenience method to write an uploaded item to disk. The client code
* is not concerned with whether or not the item is stored in memory, or on
* disk in a temporary location. They just want to write the uploaded item
* to a file.
* <p>
* This implementation first attempts to rename the uploaded item to the specified destination file, if the item was originally written to disk. Otherwise, the data will be
* copied to the specified file.
* <p>
* This method is only guaranteed to work <em>once</em>, the first time it is invoked for a particular item. This is because, in the event that the method renames a temporary
* file, that file will no longer be available to copy or rename again at a later time.
*
* @param file The <code>File</code> into which the uploaded item should
* be stored.
* @throws Exception if an error occurs.
*/
public void write(File file) throws Exception {
if (isInMemory()) {
FileOutputStream fout = null;
try {
fout = new FileOutputStream(file);
fout.write(get());
} finally {
if (fout != null) {
fout.close();
}
}
} else {
File outputFile = getStoreLocation();
if (outputFile != null) {
// Save the length of the file
this.size = outputFile.length();
/*
* The uploaded file is being stored on disk
* in a temporary location so move it to the
* desired file.
*/
if (!outputFile.renameTo(file)) {
BufferedInputStream in = null;
BufferedOutputStream out = null;
try {
in = new BufferedInputStream(
new FileInputStream(outputFile));
out = new BufferedOutputStream(
new FileOutputStream(file));
IOUtils.copy(in, out);
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
// ignore
}
}
if (out != null) {
try {
out.close();
} catch (IOException e) {
// ignore
}
}
}
}
} else {
/*
* For whatever reason we cannot write the
* file to disk.
*/
throw new IOException("Cannot write to disk!");
}
}
}
/**
* Deletes the underlying storage for a file item, including deleting any
* associated temporary disk file. Although this storage will be deleted
* automatically when the <code>FileItem</code> instance is garbage
* collected, this method can be used to ensure that this is done at an
* earlier time, thus preserving system resources.
*/
public void delete() {
this.cachedContent = null;
File outputFile = getStoreLocation();
if (outputFile != null && outputFile.exists()) {
outputFile.delete();
}
}
public OutputStream getOutputStream() throws IOException {
return getOutputStream(null);
}
/**
* Returns an {@link java.io.OutputStream OutputStream} that can
* be used for storing the contents of the file.
*
* @param directory The directory where the temporary file is created.<br>
* If <code>null</code> it's created in the default directory.
* @return An {@link java.io.OutputStream OutputStream} that can be used
* for storing the contents of the file.
* @throws IOException if an error occurs.
*/
public OutputStream getOutputStream(File directory) throws IOException {
this.dfos = new DeferredFileOutputStream(this.sizeThreshold, getTempFile(directory));
return this.dfos;
}
/**
* Returns the {@link java.io.File} object for the <code>FileItem</code>'s
* data's temporary location on the disk. Note that for <code>FileItem</code>s that have their data stored in memory,
* this method will return <code>null</code>. When handling large
* files, you can use {@link java.io.File#renameTo(java.io.File)} to
* move the file to new location without copying the data, if the
* source and destination locations reside within the same logical
* volume.
*
* @return The data file, or <code>null</code> if the data is stored in
* memory.
*/
public File getStoreLocation() {
return this.dfos == null ? null : this.dfos.getFile();
}
/**
* Removes the file contents from the temporary storage.
*/
@Override
protected void finalize() {
File outputFile = this.dfos.getFile();
if (outputFile != null && outputFile.exists()) {
outputFile.delete();
}
}
/**
* Creates and returns a {@link java.io.File File} representing a uniquely
* named temporary file in the configured repository path. The lifetime of
* the file is tied to the lifetime of the <code>FileItem</code> instance;
* the file will be deleted when the instance is garbage collected.
*
* @param directory The directory where this temporary file is created
* @return The {@link java.io.File File} to be used for temporary storage.
*/
protected File getTempFile(File directory) {
if (this.tempFile == null) {
try {
if (directory != null && directory.isDirectory())
this.tempFile = File.createTempFile("byteCache_", null, directory);
else
this.tempFile = File.createTempFile("byteCache_", null);
this.tempFile.deleteOnExit();
} catch (IOException e) {
}
}
return this.tempFile;
}
private void copyAndClose(InputStream in, OutputStream out) throws IOException {
try {
IOUtils.copy(in, out);
} finally {
IOUtils.closeQuietly(in);
IOUtils.closeQuietly(out);
}
}
/**
* Returns a string representation of this object.
*
* @return a string representation of this object.
*/
@Override
public String toString() {
return "StoreLocation="
+ (isInMemory() ? "IN MEMORY" : String.valueOf(getStoreLocation()))
+ ", size="
+ getSize()
+ "bytes";
}
/**
* Writes the state of this object during serialization.
*
* @param out The stream to which the state should be written.
* @throws IOException if an error occurs.
*/
private void writeObject(ObjectOutputStream out) throws IOException {
// Read the data
if (this.dfos.isInMemory()) {
this.cachedContent = get();
} else {
this.cachedContent = null;
this.dfosFile = this.dfos.getFile();
}
// write out values
out.defaultWriteObject();
}
/**
* Reads the state of this object during deserialization.
*
* @param in The stream from which the state should be read.
* @throws IOException if an error occurs.
* @throws ClassNotFoundException if class cannot be found.
*/
private void readObject(ObjectInputStream in)
throws IOException, ClassNotFoundException {
// read values
in.defaultReadObject();
OutputStream output = getOutputStream();
if (this.cachedContent != null) {
output.write(this.cachedContent);
} else {
FileInputStream input = new FileInputStream(this.dfosFile);
IOUtils.copy(input, output);
this.dfosFile.delete();
this.dfosFile = null;
}
output.close();
this.cachedContent = null;
}
}
|
9235943a5f8c8b6b5fd71a45ab4a8f78014d16c9 | 697 | java | Java | src/main/java/com/watercup/concurrency/ReadWriteLock.java | zhengyd2014/java-knowledge | 12cca3635c244170c0f8d9e18d131abe0a2c8617 | [
"Apache-2.0"
] | null | null | null | src/main/java/com/watercup/concurrency/ReadWriteLock.java | zhengyd2014/java-knowledge | 12cca3635c244170c0f8d9e18d131abe0a2c8617 | [
"Apache-2.0"
] | null | null | null | src/main/java/com/watercup/concurrency/ReadWriteLock.java | zhengyd2014/java-knowledge | 12cca3635c244170c0f8d9e18d131abe0a2c8617 | [
"Apache-2.0"
] | null | null | null | 20.5 | 77 | 0.599713 | 997,344 | package com.watercup.concurrency;
public class ReadWriteLock {
private boolean isWriteLocked = false;
private int readers = 0;
public synchronized void acquireReadLock() throws InterruptedException {
while (isWriteLocked) {
wait();
}
readers++;
}
public synchronized void releaseReadLock() {
readers--;
notify();
}
public synchronized void acquireWriteLock() throws InterruptedException {
while (isWriteLocked || readers > 0) {
wait();
}
isWriteLocked = true;
}
public synchronized void releaseWriteLock() {
isWriteLocked = false;
notify();
}
}
|
923595c347d1e61a09f930dafa19d05d5f7e7f65 | 694 | java | Java | src/main/java/com/dtone/dvs/dto/AccountBalance.java | selvakumar-suyambulingam/dtone-dvs-api-java-client | 4622745850511c8b1abef2a157419b15f67a8f47 | [
"MIT"
] | 1 | 2021-09-09T02:41:44.000Z | 2021-09-09T02:41:44.000Z | src/main/java/com/dtone/dvs/dto/AccountBalance.java | selvakumar-suyambulingam/dtone-dvs-api-java-client | 4622745850511c8b1abef2a157419b15f67a8f47 | [
"MIT"
] | 2 | 2020-01-09T09:52:56.000Z | 2022-01-10T02:29:13.000Z | src/main/java/com/dtone/dvs/dto/AccountBalance.java | selvakumar-suyambulingam/dtone-dvs-api-java-client | 4622745850511c8b1abef2a157419b15f67a8f47 | [
"MIT"
] | 3 | 2021-05-16T06:28:13.000Z | 2021-09-09T02:43:45.000Z | 16.926829 | 53 | 0.727666 | 997,345 | package com.dtone.dvs.dto;
import java.math.BigDecimal;
import com.fasterxml.jackson.annotation.JsonProperty;
public class AccountBalance {
@JsonProperty(value = "unit_type")
private UnitTypes unitType;
@JsonProperty(value = "unit")
private String unit;
@JsonProperty(value = "amount")
private BigDecimal amount;
public UnitTypes getUnitType() {
return unitType;
}
public void setUnitType(UnitTypes unitType) {
this.unitType = unitType;
}
public String getUnit() {
return unit;
}
public void setUnit(String unit) {
this.unit = unit;
}
public BigDecimal getAmount() {
return amount;
}
public void setAmount(BigDecimal amount) {
this.amount = amount;
}
}
|
923596ab21b485f49bf6c1da60314239760786cc | 825 | java | Java | keanu-project/src/main/java/io/improbable/keanu/vertices/intgr/nonprobabilistic/CastIntegerVertex.java | Sahanduiuc/keanu | f0f1fb5454538f6422d99cb8e24f5e98d27ca29b | [
"MIT"
] | 1 | 2018-08-14T18:51:01.000Z | 2018-08-14T18:51:01.000Z | keanu-project/src/main/java/io/improbable/keanu/vertices/intgr/nonprobabilistic/CastIntegerVertex.java | Sahanduiuc/keanu | f0f1fb5454538f6422d99cb8e24f5e98d27ca29b | [
"MIT"
] | null | null | null | keanu-project/src/main/java/io/improbable/keanu/vertices/intgr/nonprobabilistic/CastIntegerVertex.java | Sahanduiuc/keanu | f0f1fb5454538f6422d99cb8e24f5e98d27ca29b | [
"MIT"
] | null | null | null | 33 | 103 | 0.774545 | 997,346 | package io.improbable.keanu.vertices.intgr.nonprobabilistic;
import io.improbable.keanu.tensor.intgr.IntegerTensor;
import io.improbable.keanu.vertices.Vertex;
import io.improbable.keanu.vertices.dbl.KeanuRandom;
import io.improbable.keanu.vertices.intgr.IntegerVertex;
import io.improbable.keanu.vertices.update.NonProbabilisticValueUpdater;
public class CastIntegerVertex extends IntegerVertex {
private final Vertex<IntegerTensor> inputVertex;
public CastIntegerVertex(Vertex<IntegerTensor> inputVertex) {
super(new NonProbabilisticValueUpdater<>(v -> ((CastIntegerVertex) v).inputVertex.getValue()));
this.inputVertex = inputVertex;
setParents(inputVertex);
}
@Override
public IntegerTensor sample(KeanuRandom random) {
return inputVertex.sample(random);
}
}
|
923596c1d74033e6e1c50b4062596d4fd3ad9682 | 6,251 | java | Java | src/com/yahoo/ycsb/generator/ScrambledZipfianGenerator.java | af83/YCSB | eb1597f712aaeae794e7c786b87cbde1ff0f2c7c | [
"Apache-2.0"
] | 1 | 2015-07-21T07:31:34.000Z | 2015-07-21T07:31:34.000Z | src/com/yahoo/ycsb/generator/ScrambledZipfianGenerator.java | rsumbaly/YCSB | 1acf1d0444177a86813d1807bb1910041c14ce75 | [
"Apache-2.0"
] | null | null | null | src/com/yahoo/ycsb/generator/ScrambledZipfianGenerator.java | rsumbaly/YCSB | 1acf1d0444177a86813d1807bb1910041c14ce75 | [
"Apache-2.0"
] | null | null | null | 52.091667 | 180 | 0.462646 | 997,347 | /**
* Copyright (c) 2010 Yahoo! Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you
* may not use this file except in compliance with the License. You
* may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License. See accompanying
* LICENSE file.
*/
package com.yahoo.ycsb.generator;
import com.yahoo.ycsb.Utils;
/**
* A generator of a zipfian distribution. It produces a sequence of items, such that some items are more popular than others, according
* to a zipfian distribution. When you construct an instance of this class, you specify the number of items in the set to draw from, either
* by specifying an itemcount (so that the sequence is of items from 0 to itemcount-1) or by specifying a min and a max (so that the sequence is of
* items from min to max inclusive). After you construct the instance, you can change the number of items by calling nextInt(itemcount) or nextLong(itemcount).
*
* Unlike @ZipfianGenerator, this class scatters the "popular" items across the itemspace. Use this, instead of @ZipfianGenerator, if you
* don't want the head of the distribution (the popular items) clustered together.
*/
public class ScrambledZipfianGenerator extends IntegerGenerator
{
public static final double ZETAN=52.93805640344461;
public static final long ITEM_COUNT=10000000000L;
ZipfianGenerator gen;
long _min,_max,_itemcount;
/******************************* Constructors **************************************/
/**
* Create a zipfian generator for the specified number of items.
* @param _items The number of items in the distribution.
*/
public ScrambledZipfianGenerator(long _items)
{
this(0,_items-1);
}
/**
* Create a zipfian generator for items between min and max.
* @param _min The smallest integer to generate in the sequence.
* @param _max The largest integer to generate in the sequence.
*/
public ScrambledZipfianGenerator(long _min, long _max)
{
this(_min,_max,ZipfianGenerator.ZIPFIAN_CONSTANT);
}
/**
* Create a zipfian generator for the specified number of items using the specified zipfian constant.
*
* @param _items The number of items in the distribution.
* @param _zipfianconstant The zipfian constant to use.
*/
/*
// not supported, as the value of zeta depends on the zipfian constant, and we have only precomputed zeta for one zipfian constant
public ScrambledZipfianGenerator(long _items, double _zipfianconstant)
{
this(0,_items-1,_zipfianconstant);
}
*/
/**
* Create a zipfian generator for items between min and max (inclusive) for the specified zipfian constant.
* @param min The smallest integer to generate in the sequence.
* @param max The largest integer to generate in the sequence.
* @param _zipfianconstant The zipfian constant to use.
*/
ScrambledZipfianGenerator(long min, long max, double _zipfianconstant)
{
//not public as we only support one value of zipfianconstant for which we have precomputed zeta
_min=min;
_max=max;
_itemcount=_max-_min+1;
gen=new ZipfianGenerator(0,ITEM_COUNT,_zipfianconstant,ZETAN);
}
/**************************************************************************************************/
/**
* Return the next int in the sequence.
*/
@Override
public int nextInt() {
return (int)nextLong();
}
/**
* Return the next long in the sequence.
*/
public long nextLong()
{
long ret=gen.nextLong();
ret=_min+Utils.FNVhash64(ret)%_itemcount;
setLastInt((int)ret);
return ret;
}
public static void main(String[] args)
{
ScrambledZipfianGenerator gen=new ScrambledZipfianGenerator(10000);
for (int i=0; i<1000000; i++)
{
System.out.println(""+gen.nextInt());
}
}
}
|
92359835ac58cf20364eaf47eb4d7ab61dff6dc3 | 2,160 | java | Java | TasksToJunior/src/main/java/ru/Zlatopolskiy/Task01_017.java | andrewnnov/andreybannikov | 982bbeb55de2694f88563e8bb7a50e2f924e8f48 | [
"Apache-2.0"
] | null | null | null | TasksToJunior/src/main/java/ru/Zlatopolskiy/Task01_017.java | andrewnnov/andreybannikov | 982bbeb55de2694f88563e8bb7a50e2f924e8f48 | [
"Apache-2.0"
] | null | null | null | TasksToJunior/src/main/java/ru/Zlatopolskiy/Task01_017.java | andrewnnov/andreybannikov | 982bbeb55de2694f88563e8bb7a50e2f924e8f48 | [
"Apache-2.0"
] | null | null | null | 20.970874 | 95 | 0.549074 | 997,348 | package ru.Zlatopolskiy;
import java.lang.Math;
import static java.lang.Math.PI;
import static java.lang.Math.pow;
import static java.lang.Math.sin;
import static java.lang.StrictMath.cos;
public class Task01_017 {
private static double x1;
private static double x2;
private static double x3;
private static double m;
private static double v;
private static double h;
private static double g;
private static double R1;
private static double R2;
private static double a;
private static double R;
private static double b;
private static double c;
private static double I;
private static double d;
private static double x;
private static double v0;
private static double t;
private static double gamma;
private static double m1;
private static double m2;
private static double r;
public static void main(String[] args) {
//a
double result1 = Math.sqrt(x1*x1 + x2*x2);
//б
double result2 = x1*x2 + x1*x3 + x2*x3;
//в
double result3 = v0 + (a*Math.pow(t, 2))/2;
//г
double result4 = (m * Math.pow(v, 2))/2 + m*g*h;
//д
double result5 = 1/R1 + 1/R2;
//е
double result6 = m * g * cos(a);
//ж
double result7 = 2 * PI * R;
//з
double result8 = Math.pow(b, 2) + 4 * a * c;
//и
double result9 = gamma*m1*m2/Math.pow(r, 2);
//к
double result10 = Math.pow(I, 2) * R;
//л
double result12 = a * b * Math.sin(c);
//м
double result13 = Math.sqrt(Math.pow(a, 2) + Math.pow(b, 2) + 2 * a * b * Math.cos(c));
//н
double result14 = (a*d + b*c)/a*d;
//о (неуверен)
double result15 = Math.sqrt(1 - pow(sin(x), 2));
//п
double result16 = 1/ ((Math.sqrt(a * pow(x, 2)) + b*x + c));
// р
double result17 = (Math.sqrt(x + 1) + Math.sqrt(x - 1))/2* Math.sqrt(x);
//c
double result18 = Math.abs(x) + Math.abs(x + 1);
//т
double result19 = Math.abs(1 - Math.abs(x));
}
}
|
92359842acc9f5a8e21597588ddce9b3a091f3e0 | 9,521 | java | Java | backend/de.metas.handlingunits.base/src/main/java-gen/de/metas/handlingunits/model/I_PP_Order_Qty.java | dram/metasfresh | a1b881a5b7df8b108d4c4ac03082b72c323873eb | [
"RSA-MD"
] | 1,144 | 2016-02-14T10:29:35.000Z | 2022-03-30T09:50:41.000Z | backend/de.metas.handlingunits.base/src/main/java-gen/de/metas/handlingunits/model/I_PP_Order_Qty.java | dram/metasfresh | a1b881a5b7df8b108d4c4ac03082b72c323873eb | [
"RSA-MD"
] | 8,283 | 2016-04-28T17:41:34.000Z | 2022-03-30T13:30:12.000Z | backend/de.metas.handlingunits.base/src/main/java-gen/de/metas/handlingunits/model/I_PP_Order_Qty.java | dram/metasfresh | a1b881a5b7df8b108d4c4ac03082b72c323873eb | [
"RSA-MD"
] | 441 | 2016-04-29T08:06:07.000Z | 2022-03-28T06:09:56.000Z | 23.335784 | 237 | 0.703603 | 997,349 | package de.metas.handlingunits.model;
import java.math.BigDecimal;
import javax.annotation.Nullable;
import org.adempiere.model.ModelColumn;
/** Generated Interface for PP_Order_Qty
* @author metasfresh (generated)
*/
@SuppressWarnings("unused")
public interface I_PP_Order_Qty
{
String Table_Name = "PP_Order_Qty";
// /** AD_Table_ID=540807 */
// int Table_ID = org.compiere.model.MTable.getTable_ID(Table_Name);
/**
* Get Client.
* Client/Tenant for this installation.
*
* <br>Type: TableDir
* <br>Mandatory: true
* <br>Virtual Column: false
*/
int getAD_Client_ID();
String COLUMNNAME_AD_Client_ID = "AD_Client_ID";
/**
* Set Organisation.
* Organisational entity within client
*
* <br>Type: Search
* <br>Mandatory: true
* <br>Virtual Column: false
*/
void setAD_Org_ID (int AD_Org_ID);
/**
* Get Organisation.
* Organisational entity within client
*
* <br>Type: Search
* <br>Mandatory: true
* <br>Virtual Column: false
*/
int getAD_Org_ID();
String COLUMNNAME_AD_Org_ID = "AD_Org_ID";
/**
* Set UOM.
* Unit of Measure
*
* <br>Type: TableDir
* <br>Mandatory: true
* <br>Virtual Column: false
*/
void setC_UOM_ID (int C_UOM_ID);
/**
* Get UOM.
* Unit of Measure
*
* <br>Type: TableDir
* <br>Mandatory: true
* <br>Virtual Column: false
*/
int getC_UOM_ID();
String COLUMNNAME_C_UOM_ID = "C_UOM_ID";
/**
* Get Created.
* Date this record was created
*
* <br>Type: DateTime
* <br>Mandatory: true
* <br>Virtual Column: false
*/
java.sql.Timestamp getCreated();
ModelColumn<I_PP_Order_Qty, Object> COLUMN_Created = new ModelColumn<>(I_PP_Order_Qty.class, "Created", null);
String COLUMNNAME_Created = "Created";
/**
* Get Created By.
* User who created this records
*
* <br>Type: Table
* <br>Mandatory: true
* <br>Virtual Column: false
*/
int getCreatedBy();
String COLUMNNAME_CreatedBy = "CreatedBy";
/**
* Set Active.
* The record is active in the system
*
* <br>Type: YesNo
* <br>Mandatory: true
* <br>Virtual Column: false
*/
void setIsActive (boolean IsActive);
/**
* Get Active.
* The record is active in the system
*
* <br>Type: YesNo
* <br>Mandatory: true
* <br>Virtual Column: false
*/
boolean isActive();
ModelColumn<I_PP_Order_Qty, Object> COLUMN_IsActive = new ModelColumn<>(I_PP_Order_Qty.class, "IsActive", null);
String COLUMNNAME_IsActive = "IsActive";
/**
* Set Handling Unit.
*
* <br>Type: Search
* <br>Mandatory: true
* <br>Virtual Column: false
*/
void setM_HU_ID (int M_HU_ID);
/**
* Get Handling Unit.
*
* <br>Type: Search
* <br>Mandatory: true
* <br>Virtual Column: false
*/
int getM_HU_ID();
de.metas.handlingunits.model.I_M_HU getM_HU();
void setM_HU(de.metas.handlingunits.model.I_M_HU M_HU);
ModelColumn<I_PP_Order_Qty, de.metas.handlingunits.model.I_M_HU> COLUMN_M_HU_ID = new ModelColumn<>(I_PP_Order_Qty.class, "M_HU_ID", de.metas.handlingunits.model.I_M_HU.class);
String COLUMNNAME_M_HU_ID = "M_HU_ID";
/**
* Set Locator.
* Warehouse Locator
*
* <br>Type: Locator
* <br>Mandatory: false
* <br>Virtual Column: false
*/
void setM_Locator_ID (int M_Locator_ID);
/**
* Get Locator.
* Warehouse Locator
*
* <br>Type: Locator
* <br>Mandatory: false
* <br>Virtual Column: false
*/
int getM_Locator_ID();
String COLUMNNAME_M_Locator_ID = "M_Locator_ID";
/**
* Set Picking candidate.
*
* <br>Type: Search
* <br>Mandatory: false
* <br>Virtual Column: false
*/
void setM_Picking_Candidate_ID (int M_Picking_Candidate_ID);
/**
* Get Picking candidate.
*
* <br>Type: Search
* <br>Mandatory: false
* <br>Virtual Column: false
*/
int getM_Picking_Candidate_ID();
@Nullable de.metas.handlingunits.model.I_M_Picking_Candidate getM_Picking_Candidate();
void setM_Picking_Candidate(@Nullable de.metas.handlingunits.model.I_M_Picking_Candidate M_Picking_Candidate);
ModelColumn<I_PP_Order_Qty, de.metas.handlingunits.model.I_M_Picking_Candidate> COLUMN_M_Picking_Candidate_ID = new ModelColumn<>(I_PP_Order_Qty.class, "M_Picking_Candidate_ID", de.metas.handlingunits.model.I_M_Picking_Candidate.class);
String COLUMNNAME_M_Picking_Candidate_ID = "M_Picking_Candidate_ID";
/**
* Set Product.
* Product, Service, Item
*
* <br>Type: Search
* <br>Mandatory: true
* <br>Virtual Column: false
*/
void setM_Product_ID (int M_Product_ID);
/**
* Get Product.
* Product, Service, Item
*
* <br>Type: Search
* <br>Mandatory: true
* <br>Virtual Column: false
*/
int getM_Product_ID();
String COLUMNNAME_M_Product_ID = "M_Product_ID";
/**
* Set Bewegungs-Datum.
* Datum, an dem eine Produkt in oder aus dem Bestand bewegt wurde
*
* <br>Type: Date
* <br>Mandatory: true
* <br>Virtual Column: false
*/
void setMovementDate (java.sql.Timestamp MovementDate);
/**
* Get Bewegungs-Datum.
* Datum, an dem eine Produkt in oder aus dem Bestand bewegt wurde
*
* <br>Type: Date
* <br>Mandatory: true
* <br>Virtual Column: false
*/
java.sql.Timestamp getMovementDate();
ModelColumn<I_PP_Order_Qty, Object> COLUMN_MovementDate = new ModelColumn<>(I_PP_Order_Qty.class, "MovementDate", null);
String COLUMNNAME_MovementDate = "MovementDate";
/**
* Set Manufacturing Cost Collector.
*
* <br>Type: Search
* <br>Mandatory: false
* <br>Virtual Column: false
*/
void setPP_Cost_Collector_ID (int PP_Cost_Collector_ID);
/**
* Get Manufacturing Cost Collector.
*
* <br>Type: Search
* <br>Mandatory: false
* <br>Virtual Column: false
*/
int getPP_Cost_Collector_ID();
@Nullable org.eevolution.model.I_PP_Cost_Collector getPP_Cost_Collector();
void setPP_Cost_Collector(@Nullable org.eevolution.model.I_PP_Cost_Collector PP_Cost_Collector);
ModelColumn<I_PP_Order_Qty, org.eevolution.model.I_PP_Cost_Collector> COLUMN_PP_Cost_Collector_ID = new ModelColumn<>(I_PP_Order_Qty.class, "PP_Cost_Collector_ID", org.eevolution.model.I_PP_Cost_Collector.class);
String COLUMNNAME_PP_Cost_Collector_ID = "PP_Cost_Collector_ID";
/**
* Set Manufacturing Order BOM Line.
*
* <br>Type: Search
* <br>Mandatory: false
* <br>Virtual Column: false
*/
void setPP_Order_BOMLine_ID (int PP_Order_BOMLine_ID);
/**
* Get Manufacturing Order BOM Line.
*
* <br>Type: Search
* <br>Mandatory: false
* <br>Virtual Column: false
*/
int getPP_Order_BOMLine_ID();
@Nullable org.eevolution.model.I_PP_Order_BOMLine getPP_Order_BOMLine();
void setPP_Order_BOMLine(@Nullable org.eevolution.model.I_PP_Order_BOMLine PP_Order_BOMLine);
ModelColumn<I_PP_Order_Qty, org.eevolution.model.I_PP_Order_BOMLine> COLUMN_PP_Order_BOMLine_ID = new ModelColumn<>(I_PP_Order_Qty.class, "PP_Order_BOMLine_ID", org.eevolution.model.I_PP_Order_BOMLine.class);
String COLUMNNAME_PP_Order_BOMLine_ID = "PP_Order_BOMLine_ID";
/**
* Set Manufacturing Order.
* Manufacturing Order
*
* <br>Type: Search
* <br>Mandatory: true
* <br>Virtual Column: false
*/
void setPP_Order_ID (int PP_Order_ID);
/**
* Get Manufacturing Order.
* Manufacturing Order
*
* <br>Type: Search
* <br>Mandatory: true
* <br>Virtual Column: false
*/
int getPP_Order_ID();
org.eevolution.model.I_PP_Order getPP_Order();
void setPP_Order(org.eevolution.model.I_PP_Order PP_Order);
ModelColumn<I_PP_Order_Qty, org.eevolution.model.I_PP_Order> COLUMN_PP_Order_ID = new ModelColumn<>(I_PP_Order_Qty.class, "PP_Order_ID", org.eevolution.model.I_PP_Order.class);
String COLUMNNAME_PP_Order_ID = "PP_Order_ID";
/**
* Set Manufacturing order Issue/Receipt quantity.
*
* <br>Type: ID
* <br>Mandatory: true
* <br>Virtual Column: false
*/
void setPP_Order_Qty_ID (int PP_Order_Qty_ID);
/**
* Get Manufacturing order Issue/Receipt quantity.
*
* <br>Type: ID
* <br>Mandatory: true
* <br>Virtual Column: false
*/
int getPP_Order_Qty_ID();
ModelColumn<I_PP_Order_Qty, Object> COLUMN_PP_Order_Qty_ID = new ModelColumn<>(I_PP_Order_Qty.class, "PP_Order_Qty_ID", null);
String COLUMNNAME_PP_Order_Qty_ID = "PP_Order_Qty_ID";
/**
* Set Processed.
*
* <br>Type: YesNo
* <br>Mandatory: true
* <br>Virtual Column: false
*/
void setProcessed (boolean Processed);
/**
* Get Processed.
*
* <br>Type: YesNo
* <br>Mandatory: true
* <br>Virtual Column: false
*/
boolean isProcessed();
ModelColumn<I_PP_Order_Qty, Object> COLUMN_Processed = new ModelColumn<>(I_PP_Order_Qty.class, "Processed", null);
String COLUMNNAME_Processed = "Processed";
/**
* Set Quantity.
* Quantity
*
* <br>Type: Quantity
* <br>Mandatory: true
* <br>Virtual Column: false
*/
void setQty (BigDecimal Qty);
/**
* Get Quantity.
* Quantity
*
* <br>Type: Quantity
* <br>Mandatory: true
* <br>Virtual Column: false
*/
BigDecimal getQty();
ModelColumn<I_PP_Order_Qty, Object> COLUMN_Qty = new ModelColumn<>(I_PP_Order_Qty.class, "Qty", null);
String COLUMNNAME_Qty = "Qty";
/**
* Get Updated.
* Date this record was updated
*
* <br>Type: DateTime
* <br>Mandatory: true
* <br>Virtual Column: false
*/
java.sql.Timestamp getUpdated();
ModelColumn<I_PP_Order_Qty, Object> COLUMN_Updated = new ModelColumn<>(I_PP_Order_Qty.class, "Updated", null);
String COLUMNNAME_Updated = "Updated";
/**
* Get Updated By.
* User who updated this records
*
* <br>Type: Table
* <br>Mandatory: true
* <br>Virtual Column: false
*/
int getUpdatedBy();
String COLUMNNAME_UpdatedBy = "UpdatedBy";
}
|
9235995a37b69858f62ed14f35c3c94be15263a8 | 1,303 | java | Java | qs-worker-core/src/main/java/com/blacklocus/qs/realm/QSUnsupportedOperationException.java | chids/queue-slayer | e499497dede988353cbb73484c902ea61edb69dd | [
"Apache-2.0"
] | null | null | null | qs-worker-core/src/main/java/com/blacklocus/qs/realm/QSUnsupportedOperationException.java | chids/queue-slayer | e499497dede988353cbb73484c902ea61edb69dd | [
"Apache-2.0"
] | null | null | null | qs-worker-core/src/main/java/com/blacklocus/qs/realm/QSUnsupportedOperationException.java | chids/queue-slayer | e499497dede988353cbb73484c902ea61edb69dd | [
"Apache-2.0"
] | null | null | null | 31.02381 | 118 | 0.735994 | 997,350 | /**
* Copyright 2013 BlackLocus
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.blacklocus.qs.realm;
/**
* Thrown by {@link QSInfoService} methods that do not (perhaps cannot) be supported by their backing store. The realm
* application should be tolerant of such unsupported methods.
*
* @author Jason Dunkelberger (dirkraft)
*/
public class QSUnsupportedOperationException extends UnsupportedOperationException {
public QSUnsupportedOperationException() {
}
public QSUnsupportedOperationException(String message) {
super(message);
}
public QSUnsupportedOperationException(String message, Throwable cause) {
super(message, cause);
}
public QSUnsupportedOperationException(Throwable cause) {
super(cause);
}
}
|
92359965a2a74cccd1fde2c561f8bf2a094fc14f | 32,697 | java | Java | Android/modules/RTEGame/src/main/java/io/agora/scene/rtegame/ui/room/RoomViewModel.java | AgoraIO-Solutions/BreakOutRoom | e1a4b57890ee1ffd4317e9aac6a308afc72f9d9c | [
"MIT"
] | null | null | null | Android/modules/RTEGame/src/main/java/io/agora/scene/rtegame/ui/room/RoomViewModel.java | AgoraIO-Solutions/BreakOutRoom | e1a4b57890ee1ffd4317e9aac6a308afc72f9d9c | [
"MIT"
] | null | null | null | Android/modules/RTEGame/src/main/java/io/agora/scene/rtegame/ui/room/RoomViewModel.java | AgoraIO-Solutions/BreakOutRoom | e1a4b57890ee1ffd4317e9aac6a308afc72f9d9c | [
"MIT"
] | null | null | null | 38.152859 | 181 | 0.610882 | 997,351 | package io.agora.scene.rtegame.ui.room;
import android.content.Context;
import android.view.TextureView;
import androidx.annotation.Keep;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.ViewModel;
import java.util.List;
import java.util.Objects;
import io.agora.example.base.BaseUtil;
import io.agora.rtc2.ChannelMediaOptions;
import io.agora.rtc2.Constants;
import io.agora.rtc2.IRtcEngineEventHandler;
import io.agora.rtc2.RtcConnection;
import io.agora.rtc2.RtcEngine;
import io.agora.rtc2.RtcEngineConfig;
import io.agora.rtc2.RtcEngineEx;
import io.agora.rtc2.internal.RtcEngineImpl;
import io.agora.rtc2.video.VideoCanvas;
import io.agora.scene.rtegame.GlobalViewModel;
import io.agora.scene.rtegame.R;
import io.agora.scene.rtegame.bean.AgoraGame;
import io.agora.scene.rtegame.bean.AppServerResult;
import io.agora.scene.rtegame.bean.GameApplyInfo;
import io.agora.scene.rtegame.bean.GameInfo;
import io.agora.scene.rtegame.bean.GiftInfo;
import io.agora.scene.rtegame.bean.LocalUser;
import io.agora.scene.rtegame.bean.PKApplyInfo;
import io.agora.scene.rtegame.bean.PKInfo;
import io.agora.scene.rtegame.bean.RoomInfo;
import io.agora.scene.rtegame.repo.GameRepo;
import io.agora.scene.rtegame.util.Event;
import io.agora.scene.rtegame.util.GamSyncEventListener;
import io.agora.scene.rtegame.util.GameConstants;
import io.agora.scene.rtegame.util.ViewStatus;
import io.agora.syncmanager.rtm.IObject;
import io.agora.syncmanager.rtm.SceneReference;
import io.agora.syncmanager.rtm.Sync;
import io.agora.syncmanager.rtm.SyncManagerException;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
/**
* @author lq
*/
@Keep
public class RoomViewModel extends ViewModel {
//<editor-fold desc="Persistent variable">
public final RoomInfo currentRoom;
@Nullable
public AgoraGame roomGame;
@NonNull
public final LocalUser localUser;
public final boolean amHost;
@Nullable
public SceneReference currentSceneRef = null;
@Nullable
private SceneReference targetSceneRef = null;
public boolean isLocalVideoMuted = false;
public boolean isLocalMicMuted = false;
private PKInfo pkInfo = null;
//</editor-fold>
//<editor-fold desc="Live data">
// RTC engine 初始化结果
private final MutableLiveData<RtcEngineEx> _mEngine = new MutableLiveData<>();
@NonNull
public LiveData<RtcEngineEx> mEngine() {
return _mEngine;
}
public final MutableLiveData<List<AgoraGame>> gameList = new MutableLiveData<>();
public final MutableLiveData<Event<String>> gameStartUrl = new MutableLiveData<>();
// UI状态
private final MutableLiveData<ViewStatus> _viewStatus = new MutableLiveData<>();
@NonNull
public LiveData<ViewStatus> viewStatus() {
return _viewStatus;
}
///////////////////// 本房间主播 在 RTC 中的 id /////////////////////////
private final MutableLiveData<Integer> _LocalHostId = new MutableLiveData<>();
@NonNull
public LiveData<Integer> localHostId() {
return _LocalHostId;
}
// 直播间礼物信息
private final MutableLiveData<Event<GiftInfo>> _gift = new MutableLiveData<>(new Event<>(null));
@NonNull
public LiveData<Event<GiftInfo>> gift() {
return _gift;
}
// 连麦房间信息
private final MutableLiveData<RoomInfo> _subRoomInfo = new MutableLiveData<>();
@NonNull
public LiveData<RoomInfo> subRoomInfo() {
return _subRoomInfo;
}
// 当前在玩游戏信息
private final MutableLiveData<GameApplyInfo> _currentGame = new MutableLiveData<>();
@NonNull
public LiveData<GameApplyInfo> currentGame() {
return _currentGame;
}
// 连麦房间信息
private final MutableLiveData<GameInfo> _gameShareInfo = new MutableLiveData<>();
@NonNull
public LiveData<GameInfo> gameShareInfo() {
return _gameShareInfo;
}
private final MutableLiveData<PKApplyInfo> _applyInfo = new MutableLiveData<>();
@NonNull
public LiveData<PKApplyInfo> applyInfo() {
return _applyInfo;
}
private final MutableLiveData<Event<Boolean>> _pkResult = new MutableLiveData<>();
@NonNull
public LiveData<Event<Boolean>> pkResult() {
return _pkResult;
}
//</editor-fold>
//<editor-fold desc="Init and end">
public RoomViewModel(@NonNull Context context, @NonNull RoomInfo roomInfo) {
this.currentRoom = roomInfo;
localUser = GlobalViewModel.localUser == null ? GlobalViewModel.checkLocalOrGenerate(context) : GlobalViewModel.localUser;
this.amHost = Objects.equals(currentRoom.getUserId(), localUser.getUserId());
// Consume at the beginning
Event<String> objectEvent = new Event<>("");
objectEvent.getContentIfNotHandled();
gameStartUrl.setValue(objectEvent);
initRTC(context, new IRtcEngineEventHandler() {
@Override
public void onUserJoined(int uid, int elapsed) {
BaseUtil.logD("onUserJoined:" + uid);
if (String.valueOf(uid).equals(currentRoom.getUserId()))
RoomViewModel.this._LocalHostId.postValue(uid);
}
@Override
public void onError(int err) {
BaseUtil.logD("onError:" + err);
RtcEngine.getErrorDescription(err);
}
});
}
private void onJoinRTMSucceed(@NonNull SceneReference sceneReference) {
BaseUtil.logD("onJoinRTMSucceed");
currentSceneRef = sceneReference;
_viewStatus.postValue(new ViewStatus.Message(localUser.getName() + " 加入RTM成功"));
// 初始化时,监听当前频道属性
if (currentSceneRef != null) {
subscribeAttr(currentSceneRef, currentRoom);
currentSceneRef.subscribe(new Sync.EventListener() {
@Override
public void onCreated(IObject item) {
}
@Override
public void onUpdated(IObject item) {
}
@Override
public void onDeleted(IObject item) {
_viewStatus.postValue(new ViewStatus.Error("主播已下播💔"));
}
@Override
public void onSubscribeError(SyncManagerException ex) {
}
});
}
}
@Override
protected void onCleared() {
super.onCleared();
new Thread(() -> {
// destroy RTE
RtcEngine engine = _mEngine.getValue();
if (engine != null) {
engine.leaveChannel();
RtcEngine.destroy();
}
if (amHost) {
// Step 1
// requestExitGame();
// Step 2
endPK();
// Step 3
exitGame();
}
// destroy RTM
if (currentSceneRef != null) {
if (amHost)
currentSceneRef.delete(new Sync.Callback() {
@Override
public void onSuccess() {
BaseUtil.logD("delete onSuccess");
}
@Override
public void onFail(SyncManagerException exception) {
BaseUtil.logD("delete onFail");
}
});
else currentSceneRef.unsubscribe(null);
}
if (targetSceneRef != null) {
currentSceneRef.unsubscribe(null);
currentSceneRef = null;
}
}).start();
}
//</editor-fold>
//<editor-fold desc="SyncManager related">
public void subscribeAttr(@NonNull SceneReference sceneRef, @NonNull RoomInfo targetRoom) {
if (Objects.equals(targetRoom.getId(), currentRoom.getId())) {
BaseUtil.logD("subscribe current room attr");
sceneRef.get(GameConstants.GIFT_INFO, (GetAttrCallback) this::tryHandleGetGiftInfo);
sceneRef.get(GameConstants.PK_INFO, (GetAttrCallback) this::tryHandlePKInfo);
sceneRef.subscribe(GameConstants.PK_INFO, new GamSyncEventListener(GameConstants.PK_INFO, this::tryHandlePKInfo));
sceneRef.subscribe(GameConstants.GIFT_INFO, new GamSyncEventListener(GameConstants.GIFT_INFO, this::tryHandleGiftInfo));
if (amHost) {
sceneRef.get(GameConstants.PK_APPLY_INFO, (GetAttrCallback) this::tryHandleApplyPKInfo);
sceneRef.subscribe(GameConstants.PK_APPLY_INFO, new GamSyncEventListener(GameConstants.PK_APPLY_INFO, this::tryHandleApplyPKInfo));
sceneRef.get(GameConstants.GAME_APPLY_INFO, (GetAttrCallback) RoomViewModel.this::tryHandleGameApplyInfo);
sceneRef.subscribe(GameConstants.GAME_APPLY_INFO, new GamSyncEventListener(GameConstants.GAME_APPLY_INFO, this::tryHandleGameApplyInfo));
} else {
sceneRef.get(GameConstants.PK_APPLY_INFO, (GetAttrCallback) this::justFetchValue);
sceneRef.subscribe(GameConstants.PK_APPLY_INFO, new GamSyncEventListener(GameConstants.PK_APPLY_INFO, this::justFetchValue));
sceneRef.get(GameConstants.GAME_INFO, (GetAttrCallback) this::tryHandleGameInfo);
sceneRef.subscribe(GameConstants.GAME_INFO, new GamSyncEventListener(GameConstants.GAME_INFO, this::tryHandleGameInfo));
}
} else {
BaseUtil.logD("subscribe other room attr");
sceneRef.subscribe(GameConstants.PK_APPLY_INFO, new GamSyncEventListener(GameConstants.PK_APPLY_INFO, this::tryHandleApplyPKInfo));
sceneRef.subscribe(GameConstants.GAME_APPLY_INFO, new GamSyncEventListener(GameConstants.GAME_APPLY_INFO, this::tryHandleGameApplyInfo));
}
}
//<editor-fold desc="Gift related">
private void tryHandleGiftInfo(IObject item) {
BaseUtil.logD("tryHandleGiftInfo->" + System.currentTimeMillis());
GiftInfo giftInfo = handleIObject(item, GiftInfo.class);
if (giftInfo != null) {
_gift.postValue(new Event<>(giftInfo));
}
}
/**
* 加入房间先获取当前 Gift
*/
private void tryHandleGetGiftInfo(IObject item) {
GiftInfo giftInfo = handleIObject(item, GiftInfo.class);
if (giftInfo != null) {
Event<GiftInfo> giftInfoEvent = new Event<>(giftInfo);
giftInfoEvent.getContentIfNotHandled(); // consume this time
_gift.postValue(giftInfoEvent);
}
}
public void donateGift(@NonNull GiftInfo gift) {
if (currentSceneRef != null && _gift.getValue() != null) {
GiftInfo currentGift = _gift.getValue().peekContent();
if (currentGift != null) {
gift.setCoin(currentGift.getCoin() + gift.getCoin());
}
currentSceneRef.update(GameConstants.GIFT_INFO, gift, null);
}
// Currently in game mode, report it
if (!amHost) {
GameInfo gameInfo = _gameShareInfo.getValue();
if (gameInfo != null && gameInfo.getStatus() == GameInfo.START) {
GameRepo.sendGift(gameInfo.getGameId(), localUser, gameInfo.getRoomId(), gift.getGiftType(), currentRoom.getUserId());
}
}
}
//</editor-fold>
//<editor-fold desc="PKApplyInfo related">
private void tryHandleApplyPKInfo(IObject item) {
PKApplyInfo pkApplyInfo = handleIObject(item, PKApplyInfo.class);
if (pkApplyInfo != null) {
if (_applyInfo.getValue() == null || !Objects.equals(_applyInfo.getValue().toString(), pkApplyInfo.toString()))
onPKApplyInfoChanged(pkApplyInfo);
}
}
private void justFetchValue(IObject item) {
PKApplyInfo pkApplyInfo = handleIObject(item, PKApplyInfo.class);
if (pkApplyInfo != null) {
_applyInfo.postValue(pkApplyInfo);
}
}
/**
* 仅主播调用
*/
private void onPKApplyInfoChanged(@NonNull PKApplyInfo pkApplyInfo) {
BaseUtil.logD("onPKApplyInfoChanged:" + pkApplyInfo.toString());
_applyInfo.postValue(pkApplyInfo);
switch (pkApplyInfo.getStatus()) {
case PKApplyInfo.APPLYING: {
// 当前不在PK && 收到其他主播的游戏邀请《==》加入对方RTM频道(同时监听对方频道的属性, 支持退出游戏后可以再次邀请进入游戏。)
if (targetSceneRef == null && Objects.equals(pkApplyInfo.getTargetRoomId(), currentRoom.getId()))
Sync.Instance().joinScene(pkApplyInfo.getRoomId(), new Sync.JoinSceneCallback() {
@Override
public void onSuccess(SceneReference sceneReference) {
if (targetSceneRef == null)
targetSceneRef = sceneReference;
subscribeAttr(targetSceneRef, new RoomInfo(pkApplyInfo.getRoomId(), "", pkApplyInfo.getUserId()));
// targetSceneRef.subscribe(GameConstants.PK_APPLY_INFO, new GamSyncEventListener(GameConstants.PK_APPLY_INFO, RoomViewModel.this::tryHandleApplyPKInfo));
}
@Override
public void onFail(SyncManagerException exception) {
}
});
break;
}
case PKApplyInfo.AGREED: {
startApplyPK(pkApplyInfo);
break;
}
case PKApplyInfo.REFUSED:
case PKApplyInfo.END: {
// ensure game end
if (currentSceneRef != null)
currentSceneRef.update(GameConstants.GAME_INFO, new GameInfo(GameInfo.END, "",""), null);
endPK();
break;
}
}
}
public void acceptApplyPK(@NonNull PKApplyInfo pkApplyInfo) {
PKApplyInfo pkApplyInfo1 = pkApplyInfo.clone();
pkApplyInfo1.setStatus(PKApplyInfo.AGREED);
if (currentSceneRef != null)
currentSceneRef.update(GameConstants.PK_APPLY_INFO, pkApplyInfo1, null);
}
public void cancelApplyPK(@NonNull PKApplyInfo pkApplyInfo) {
PKApplyInfo desiredPK = pkApplyInfo.clone();
desiredPK.setStatus(PKApplyInfo.REFUSED);
boolean startedByMe = Objects.equals(localUser.getUserId(), desiredPK.getUserId());
if (startedByMe) {
if (targetSceneRef != null)
targetSceneRef.update(GameConstants.PK_APPLY_INFO, desiredPK, null);
} else {
if (currentSceneRef != null)
currentSceneRef.update(GameConstants.PK_APPLY_INFO, desiredPK, null);
}
}
/**
* 仅主播调用
* 主播开始PK,为接收方接受发起方PK请求后的调用
* Step 1. 根据当前角色生成 PKInfo
* Step 2. 更新频道内{@link GameConstants#PK_INFO} 参数
* Step 3. 更新频道内{@link GameConstants#GAME_APPLY_INFO} 参数
*/
public void startApplyPK(@NonNull PKApplyInfo pkApplyInfo) {
PKInfo pkInfo;
GameApplyInfo gameApplyInfo = new GameApplyInfo(GameApplyInfo.PLAYING, pkApplyInfo.getGameId());
if (Objects.equals(localUser.getUserId(), pkApplyInfo.getUserId())) {// 客户端为发起方
BaseUtil.logD("发起方");
pkInfo = new PKInfo(PKInfo.AGREED, pkApplyInfo.getTargetRoomId(), pkApplyInfo.getTargetUserId());
if (targetSceneRef != null) {
BaseUtil.logD("targetSceneRef");
targetSceneRef.update(GameConstants.GAME_APPLY_INFO, gameApplyInfo, (GetAttrCallback) result -> BaseUtil.logD("onSuccess(:" + result.toString()));
}
} else {// 客户端为接收方,当前房间内所有人需要知道发起方的 roomId 和 UserId
BaseUtil.logD("接收方");
pkInfo = new PKInfo(PKInfo.AGREED, pkApplyInfo.getRoomId(), pkApplyInfo.getUserId());
}
if (currentSceneRef != null) {
currentSceneRef.update(GameConstants.PK_INFO, pkInfo, null);
}
}
/**
* 向其他主播(不同的频道)发送PK邀请
* <p>
* **RTM 限制订阅只能在加入频道的情况下发生**
* <p>
* 1. 加入对方频道
* 2. 监听对方频道属性
* 3. 往对方频道添加属性 pkApplyInfo
*
* @param roomViewModel We want to separate the logic with different UI, but a RoomViewModel is still needed.
* @param targetRoom 对方的 RoomInfo
* @param gameId Currently only have one game. Ignore this.
*/
public void sendApplyPKInvite(@NonNull RoomViewModel roomViewModel, @NonNull RoomInfo targetRoom, @NonNull String gameId) {
if (targetSceneRef != null)
doSendApplyPKInvite(roomViewModel, targetSceneRef, targetRoom, gameId);
else
Sync.Instance().joinScene(targetRoom.getId(), new Sync.JoinSceneCallback() {
@Override
public void onSuccess(SceneReference sceneReference) {
targetSceneRef = sceneReference;
// 发起邀请,监听对方频道
roomViewModel.subscribeAttr(sceneReference, targetRoom);
doSendApplyPKInvite(roomViewModel, targetSceneRef, targetRoom, gameId);
}
@Override
public void onFail(SyncManagerException exception) {
_pkResult.postValue(new Event<>(false));
}
});
}
private void doSendApplyPKInvite(@NonNull RoomViewModel roomViewModel, @NonNull SceneReference sceneReference, RoomInfo targetRoom, @NonNull String gameId) {
PKApplyInfo pkApplyInfo = new PKApplyInfo(roomViewModel.currentRoom.getUserId(), targetRoom.getUserId(), localUser.getName(), PKApplyInfo.APPLYING, gameId,
roomViewModel.currentRoom.getId(), targetRoom.getId());
sceneReference.update(GameConstants.PK_APPLY_INFO, pkApplyInfo, new Sync.DataItemCallback() {
@Override
public void onSuccess(IObject result) {
BaseUtil.logD("success update:" + result.getId() + "->" + result.toString());
_pkResult.postValue(new Event<>(true));
}
@Override
public void onFail(SyncManagerException exception) {
_pkResult.postValue(new Event<>(false));
}
});
}
//</editor-fold>
//<editor-fold desc="GameInfo">
private void tryHandleGameInfo(IObject item) {
GameInfo gameInfo = handleIObject(item, GameInfo.class);
if (gameInfo != null) {
if (_gameShareInfo.getValue() == null || !Objects.equals(_gameShareInfo.getValue().toString(), gameInfo.toString()))
onGameInfoChanged(gameInfo);
}
}
/**
* 只在当前频道
* 观众:{@link GameInfo#START} 订阅视频流 ,{@link GameInfo#END} 取消订阅
*/
private void onGameInfoChanged(@NonNull GameInfo gameInfo) {
BaseUtil.logD("onGameShareInfoChanged");
if (gameInfo.getStatus() == GameInfo.START)
roomGame = new AgoraGame(gameInfo.getGameId(), "");
else
roomGame = null;
_gameShareInfo.postValue(gameInfo);
}
//</editor-fold>
//<editor-fold desc="GameApplyInfo">
private void tryHandleGameApplyInfo(IObject item) {
BaseUtil.logD("tryHandleGameApplyInfo->" + item.toString());
GameApplyInfo currentGame = handleIObject(item, GameApplyInfo.class);
if (currentGame != null) {
onGameApplyInfoChanged(currentGame);
}
}
private void onGameApplyInfoChanged(@NonNull GameApplyInfo currentGame) {
BaseUtil.logD("onGameApplyInfoChanged:" + currentGame.toString());
if (currentGame.getStatus() == GameApplyInfo.PLAYING) {
roomGame = new AgoraGame(currentGame.getGameId(), "");
PKApplyInfo applyInfo = _applyInfo.getValue();
if (currentSceneRef != null && applyInfo != null) {
String targetRoomId = applyInfo.getRoomId().equals(currentRoom.getId()) ? applyInfo.getTargetRoomId() : currentRoom.getId();
currentSceneRef.update(GameConstants.GAME_INFO, new GameInfo(GameInfo.START, targetRoomId, currentGame.getGameId()), null);
}
} else if (currentGame.getStatus() == GameApplyInfo.END) {
exitGame();
if (currentSceneRef != null)
currentSceneRef.update(GameConstants.GAME_INFO, new GameInfo(GameInfo.END, "", currentGame.getGameId()), null);
}
_currentGame.postValue(currentGame);
}
/**
* 只更新监听的{@link GameConstants#GAME_APPLY_INFO} 字段
*/
public void requestExitGame() {
GameApplyInfo gameApplyInfo = _currentGame.getValue();
if (gameApplyInfo == null) return;
GameApplyInfo desiredGameApplyInfo = new GameApplyInfo(GameApplyInfo.END, gameApplyInfo.getGameId());
PKApplyInfo pkApplyInfo = _applyInfo.getValue();
if (pkApplyInfo != null) {
boolean startedByMe = Objects.equals(localUser.getUserId(), pkApplyInfo.getUserId());
if (!startedByMe) {
if (currentSceneRef != null)
currentSceneRef.update(GameConstants.GAME_APPLY_INFO, desiredGameApplyInfo, null);
} else {
if (targetSceneRef != null)
targetSceneRef.update(GameConstants.GAME_APPLY_INFO, desiredGameApplyInfo, null);
}
}
}
//</editor-fold>
//<editor-fold desc="PKInfo">
private void tryHandlePKInfo(IObject item) {
PKInfo pkInfo = handleIObject(item, PKInfo.class);
if (pkInfo != null)
onPKInfoChanged(pkInfo);
}
/**
* {@link PKInfo#AGREED} 加入对方频道,拉流 | {@link PKInfo#END} 退出频道
*/
private void onPKInfoChanged(@NonNull PKInfo pkInfo) {
BaseUtil.logD("onPKInfoChanged:" + pkInfo.toString());
this.pkInfo = pkInfo;
if (pkInfo.getStatus() == PKInfo.AGREED) {
// 只用来加入频道,只使用 roomId 字段
// this variable will only for join channel so room name doesn't matter.
RoomInfo subRoom = new RoomInfo(pkInfo.getRoomId(), "", pkInfo.getUserId());
joinSubRoom(subRoom);
} else if (pkInfo.getStatus() == PKInfo.END) {
leaveSubRoom();
}
}
/**
* 仅主播调用
*/
public void endPK() {
PKInfo pkInfo = new PKInfo(PKInfo.END, "", "");
PKApplyInfo pkApplyInfo = applyInfo().getValue();
boolean startedByMe = false;
if (pkApplyInfo != null) {
pkApplyInfo = pkApplyInfo.clone();
pkApplyInfo.setStatus(PKApplyInfo.END);
startedByMe = Objects.equals(localUser.getUserId(), pkApplyInfo.getUserId());
}
if (currentSceneRef != null) {
currentSceneRef.update(GameConstants.PK_INFO, pkInfo, null);
if (pkApplyInfo != null && !startedByMe) {
currentSceneRef.update(GameConstants.PK_APPLY_INFO, pkApplyInfo, null);
}
}
if (targetSceneRef != null) {
if (pkApplyInfo != null && startedByMe)
targetSceneRef.update(GameConstants.PK_APPLY_INFO, pkApplyInfo, null);
BaseUtil.logD("targetSceneRef unsubscribe");
targetSceneRef.unsubscribe(null);
targetSceneRef = null;
}
}
//</editor-fold>
@Nullable
private <T> T handleIObject(IObject obj, Class<T> clazz) {
T res = null;
try {
res = obj.toObject(clazz);
} catch (Exception e) {
e.printStackTrace();
BaseUtil.logD(e.getMessage());
}
return res;
}
//</editor-fold>
//<editor-fold desc="RTC related">
public void muteLocalVideoStream(boolean mute) {
isLocalVideoMuted = mute;
RtcEngineEx engine = _mEngine.getValue();
if (engine != null) {
engine.muteLocalVideoStream(isLocalVideoMuted);
}
}
public void muteLocalAudioStream(boolean mute) {
isLocalMicMuted = mute;
RtcEngineEx engine = _mEngine.getValue();
if (engine != null) {
engine.muteLocalAudioStream(isLocalMicMuted);
}
}
public void flipCamera() {
RtcEngineEx engine = _mEngine.getValue();
if (engine != null) {
engine.switchCamera();
}
}
/**
* 加入当前房间
*/
public void joinRoom(@NonNull LocalUser localUser) {
new Thread(() -> {
RtcEngineEx engine = _mEngine.getValue();
if (engine != null) {
ChannelMediaOptions options = new ChannelMediaOptions();
options.autoSubscribeAudio = true;
options.autoSubscribeVideo = true;
options.publishCameraTrack = amHost;
options.publishAudioTrack = amHost;
options.clientRoleType = amHost ? Constants.CLIENT_ROLE_BROADCASTER : Constants.CLIENT_ROLE_AUDIENCE;
engine.joinChannel(((RtcEngineImpl) engine).getContext().getString(R.string.rtc_app_token), currentRoom.getId(), Integer.parseInt(localUser.getUserId()), options);
}
}).start();
}
/**
* 加入其他主播房间前先退出当前已加入的其他主播房间
* 加入成功监听到对方主播上线《==》UI更新
*/
public void joinSubRoom(@NonNull RoomInfo subRoomInfo) {
leaveSubRoom();
RtcEngineEx engine = _mEngine.getValue();
if (engine != null) {
RtcConnection connection = new RtcConnection();
connection.channelId = subRoomInfo.getId();
connection.localUid = -Integer.parseInt(localUser.getUserId());
ChannelMediaOptions options = new ChannelMediaOptions();
// public abstract int joinChannelEx(String token, RtcConnection connection, ChannelMediaOptions options, IRtcEngineEventHandler eventHandler);
engine.joinChannelEx(((RtcEngineImpl) engine).getContext().getString(R.string.rtc_app_token), connection, options, new IRtcEngineEventHandler() {
@Override
public void onJoinChannelSuccess(String channel, int uid, int elapsed) {
BaseUtil.logD("onJoinChannelSuccess:" + channel + uid);
_subRoomInfo.postValue(subRoomInfo);
}
});
}
}
public void leaveSubRoom() {
RoomInfo tempRoom = _subRoomInfo.getValue();
if (tempRoom == null) return;
String roomId = tempRoom.getId();
BaseUtil.logD("leaveSubRoom:" + roomId);
_subRoomInfo.postValue(null);
RtcEngineEx engine = _mEngine.getValue();
if (engine != null) {
RtcConnection connection = new RtcConnection();
connection.channelId = roomId;
connection.localUid = -Integer.parseInt(localUser.getUserId());
engine.leaveChannelEx(connection);
}
}
public void initRTC(@NonNull Context mContext, @NonNull IRtcEngineEventHandler mEventHandler) {
new Thread(() -> {
String appID = mContext.getString(R.string.rtc_app_id);
if (appID.isEmpty() || appID.codePointCount(0, appID.length()) != 32) {
_viewStatus.postValue(new ViewStatus.Message("APP ID is not valid"));
_mEngine.postValue(null);
} else {
RtcEngineConfig config = new RtcEngineConfig();
config.mContext = mContext;
config.mAppId = appID;
config.mEventHandler = mEventHandler;
RtcEngineConfig.LogConfig logConfig = new RtcEngineConfig.LogConfig();
logConfig.filePath = mContext.getExternalCacheDir().getAbsolutePath();
config.mLogConfig = logConfig;
try {
RtcEngineEx engineEx = (RtcEngineEx) RtcEngine.create(config);
configRTC(engineEx);
_mEngine.postValue(engineEx);
} catch (Exception e) {
e.printStackTrace();
_mEngine.postValue(null);
}
// 监听当前房间数据 <==> 礼物、PK、
Sync.Instance().joinScene(currentRoom.getId(), new Sync.JoinSceneCallback() {
@Override
public void onSuccess(SceneReference sceneReference) {
onJoinRTMSucceed(sceneReference);
}
@Override
public void onFail(SyncManagerException e) {
_viewStatus.postValue(new ViewStatus.Message("加入RTM失败"));
}
});
}
}).start();
}
private void configRTC(@NonNull RtcEngineEx engine) {
if (amHost) {
engine.enableAudio();
engine.enableVideo();
engine.startPreview();
}
}
public void setupLocalView(@NonNull TextureView view) {
RtcEngineEx engine = _mEngine.getValue();
if (engine != null) {
BaseUtil.logD("id:" + localUser.getUserId());
engine.setupLocalVideo(new VideoCanvas(view, Constants.RENDER_MODE_HIDDEN, Integer.parseInt(localUser.getUserId())));
}
}
/**
* @param view 用来构造 videoCanvas
* @param roomInfo isLocalHost => current RoomInfo,!isLocalHost => 对方的 RoomInfo
* @param isLocalHost 是否是当前房间主播
*/
public void setupRemoteView(@NonNull TextureView view, @NonNull RoomInfo roomInfo, boolean isLocalHost) {
RtcEngineEx engine = _mEngine.getValue();
if (engine != null) {
VideoCanvas videoCanvas = new VideoCanvas(view, Constants.RENDER_MODE_HIDDEN, Integer.parseInt(roomInfo.getUserId()));
if (isLocalHost) {
engine.setupRemoteVideo(videoCanvas);
} else {
RtcConnection connection = new RtcConnection();
connection.channelId = roomInfo.getId();
connection.localUid = -Integer.parseInt(localUser.getUserId());
engine.setupRemoteVideoEx(videoCanvas, connection);
}
}
}
//</editor-fold>
//<editor-fold desc="YuanQi Game">
public void startGame() {
if (roomGame == null) return;
String roomId = null;
if (amHost) {
PKApplyInfo pkApplyInfo = _applyInfo.getValue();
if (pkApplyInfo != null)
roomId = pkApplyInfo.getRoomId().equals(currentRoom.getId()) ? pkApplyInfo.getTargetRoomId() : currentRoom.getId();
} else {
GameInfo gameShareInfo = _gameShareInfo.getValue();
if (gameShareInfo != null)
roomId = gameShareInfo.getRoomId();
}
if (roomId != null)
GameRepo.getJoinUrl(roomGame.getGameId(), localUser, currentRoom, roomId, getIdentification(roomId), new Callback<AppServerResult<String>>() {
@Override
public void onResponse(@NonNull Call<AppServerResult<String>> call, @NonNull Response<AppServerResult<String>> response) {
AppServerResult<String> body = response.body();
if (body != null)
gameStartUrl.postValue(new Event<>(body.getResult()));
}
@Override
public void onFailure(@NonNull Call<AppServerResult<String>> call, Throwable t) {
}
});
}
private String getIdentification(String gameRoomId) {
if (amHost) {
if (Objects.equals(currentRoom.getId(), gameRoomId))
return "2";
else return "1";
} else {
return "3";
}
}
/**
* 监听到修改成功,退出游戏
*/
public void exitGame() {
if (roomGame == null) return;
PKApplyInfo applyInfo = _applyInfo.getValue();
if (applyInfo != null) {
GameRepo.leaveGame(roomGame.getGameId(), localUser, applyInfo.getTargetRoomId(), getIdentification(applyInfo.getTargetRoomId()));
}
}
public void fetchGameList() {
GameRepo.getGameList("3", gameList);
}
public void sendBarrage(@NonNull String barrage) {
if (roomGame != null)
GameRepo.sendBarrage(barrage, roomGame.getGameId(), localUser, currentRoom.getId(), getIdentification(currentRoom.getId()), currentRoom.getId());
}
public void setRole(int oldRole, int newRole) {
if (roomGame != null)
GameRepo.changeRole(roomGame.getGameId(), localUser, currentRoom.getId(), oldRole, newRole);
}
//</editor-fold>
private interface GetAttrCallback extends Sync.DataItemCallback {
@Override
default void onFail(SyncManagerException exception) {
}
}
}
|
92359a12ac0fea6f07fdf4fe2bbaf1325a149f53 | 3,574 | java | Java | src/main/java/org/jfrog/hudson/pipeline/declarative/steps/distribution/DeleteReleaseBundleStep.java | matthewbednarski/jenkins-artifactory-plugin | 310974b2b1b2fcbc2c6f00571950bf32dc49af00 | [
"Apache-2.0"
] | 85 | 2015-01-15T03:22:20.000Z | 2022-03-29T18:14:56.000Z | src/main/java/org/jfrog/hudson/pipeline/declarative/steps/distribution/DeleteReleaseBundleStep.java | matthewbednarski/jenkins-artifactory-plugin | 310974b2b1b2fcbc2c6f00571950bf32dc49af00 | [
"Apache-2.0"
] | 415 | 2018-07-02T16:29:18.000Z | 2022-03-29T19:05:41.000Z | src/main/java/org/jfrog/hudson/pipeline/declarative/steps/distribution/DeleteReleaseBundleStep.java | matthewbednarski/jenkins-artifactory-plugin | 310974b2b1b2fcbc2c6f00571950bf32dc49af00 | [
"Apache-2.0"
] | 127 | 2015-02-02T14:48:24.000Z | 2022-03-27T13:13:04.000Z | 29.783333 | 123 | 0.692781 | 997,352 | package org.jfrog.hudson.pipeline.declarative.steps.distribution;
import com.google.inject.Inject;
import hudson.Extension;
import org.jenkinsci.plugins.workflow.steps.AbstractStepDescriptorImpl;
import org.jenkinsci.plugins.workflow.steps.StepContext;
import org.jfrog.hudson.pipeline.ArtifactorySynchronousStepExecution;
import org.jfrog.hudson.pipeline.common.executors.ReleaseBundleDeleteExecutor;
import org.jfrog.hudson.pipeline.common.types.DistributionServer;
import org.jfrog.hudson.pipeline.declarative.utils.DeclarativePipelineUtils;
import org.kohsuke.stapler.DataBoundConstructor;
import org.kohsuke.stapler.DataBoundSetter;
import javax.annotation.Nonnull;
import java.io.IOException;
import java.util.List;
/**
* @author yahavi
**/
@SuppressWarnings("unused")
public class DeleteReleaseBundleStep extends RemoteReleaseBundleStep {
public static final String STEP_NAME = "dsDeleteReleaseBundle";
private boolean deleteFromDist;
@DataBoundConstructor
public DeleteReleaseBundleStep(String serverId, String name, String version) {
super(serverId, name, version);
}
@DataBoundSetter
public void setCountryCodes(List<String> countryCodes) {
this.countryCodes = countryCodes;
}
@DataBoundSetter
public void setDeleteFromDist(boolean deleteFromDist) {
this.deleteFromDist = deleteFromDist;
}
@DataBoundSetter
public void setDistRules(String distRules) {
this.distRules = distRules;
}
@DataBoundSetter
public void setSiteName(String siteName) {
this.siteName = siteName;
}
@DataBoundSetter
public void setCityName(String cityName) {
this.cityName = cityName;
}
@DataBoundSetter
public void setDryRun(boolean dryRun) {
this.dryRun = dryRun;
}
@DataBoundSetter
public void setSync(boolean sync) {
this.sync = sync;
}
public static class Execution extends ArtifactorySynchronousStepExecution<Void> {
private final transient DeleteReleaseBundleStep step;
@Inject
public Execution(DeleteReleaseBundleStep step, StepContext context) throws IOException, InterruptedException {
super(context);
this.step = step;
}
@SuppressWarnings("ConstantConditions")
@Override
protected Void runStep() throws Exception {
DistributionServer server = DeclarativePipelineUtils.getDistributionServer(build, rootWs, step.serverId, true);
new ReleaseBundleDeleteExecutor(server, step.name, step.version, step.dryRun, step.sync, step.deleteFromDist,
step.distRules, step.countryCodes, step.siteName, step.cityName, listener, build, ws).execute();
return null;
}
@Override
public org.jfrog.hudson.ArtifactoryServer getUsageReportServer() throws Exception {
return null;
}
@Override
public String getUsageReportFeatureName() {
return STEP_NAME;
}
}
@Extension
public static final class DescriptorImpl extends AbstractStepDescriptorImpl {
public DescriptorImpl() {
super(DeleteReleaseBundleStep.Execution.class);
}
@Override
public String getFunctionName() {
return STEP_NAME;
}
@Nonnull
@Override
public String getDisplayName() {
return "Delete a release bundle";
}
@Override
public boolean isAdvanced() {
return true;
}
}
}
|
92359abfa4757cbb36fc9a36550101021233e69c | 1,287 | java | Java | investor/src/test/java/pl/ws/investor/domain/TestFoundsProvider.java | Scoobie02/investor | b5009619979bd64ec65cc20a6fbd77fdf9b186e5 | [
"Apache-2.0"
] | null | null | null | investor/src/test/java/pl/ws/investor/domain/TestFoundsProvider.java | Scoobie02/investor | b5009619979bd64ec65cc20a6fbd77fdf9b186e5 | [
"Apache-2.0"
] | null | null | null | investor/src/test/java/pl/ws/investor/domain/TestFoundsProvider.java | Scoobie02/investor | b5009619979bd64ec65cc20a6fbd77fdf9b186e5 | [
"Apache-2.0"
] | null | null | null | 42.9 | 78 | 0.66589 | 997,353 | package pl.ws.investor.domain;
import java.util.ArrayList;
import java.util.List;
public class TestFoundsProvider {
public static List<Found> caseOneAndTwoFounds() {
List<Found> founds = new ArrayList<>();
founds.add(new Found(1L, FoundKind.POLISH, "Fundusz Polski 1"));
founds.add(new Found(2L, FoundKind.POLISH, "Fundusz Polski 2"));
founds.add(new Found(3L, FoundKind.FOREIGN, "Fundusz Zagraniczny 1"));
founds.add(new Found(4L, FoundKind.FOREIGN, "Fundusz Zagraniczny 2"));
founds.add(new Found(5L, FoundKind.FOREIGN, "Fundusz Zagraniczny 3"));
founds.add(new Found(6L, FoundKind.CASH, "Fundusz Pieniężny 1"));
return founds;
}
public static List<Found> caseThreeFounds(){
List<Found> founds = new ArrayList<>();
founds.add(new Found(1L, FoundKind.POLISH, "Fundusz Polski 1"));
founds.add(new Found(2L, FoundKind.POLISH, "Fundusz Polski 2"));
founds.add(new Found(3L, FoundKind.POLISH, "Fundusz Polski 3"));
founds.add(new Found(4L, FoundKind.FOREIGN, "Fundusz Zagraniczny 1"));
founds.add(new Found(5L, FoundKind.FOREIGN, "Fundusz Zagraniczny 2"));
founds.add(new Found(6L, FoundKind.CASH, "Fundusz Pieniężny 1"));
return founds;
}
}
|
92359b11ca1e4a88d2c3582933171d62bfb1452f | 292 | java | Java | src/main/java/com/github/kbnt/java14/records/Person.java | knowledge-base-and-tutorials/java14-features | 9d55ea293f5883d3f777c0ac929e14dfeff973d8 | [
"Apache-2.0"
] | 7 | 2020-01-31T23:12:08.000Z | 2020-12-26T09:41:36.000Z | src/main/java/com/github/kbnt/java14/records/Person.java | knowledge-base-and-tutorials/java14-features | 9d55ea293f5883d3f777c0ac929e14dfeff973d8 | [
"Apache-2.0"
] | null | null | null | src/main/java/com/github/kbnt/java14/records/Person.java | knowledge-base-and-tutorials/java14-features | 9d55ea293f5883d3f777c0ac929e14dfeff973d8 | [
"Apache-2.0"
] | 7 | 2020-03-15T15:27:25.000Z | 2020-11-24T04:25:59.000Z | 18.5625 | 70 | 0.673401 | 997,354 | package com.github.kbnt.java14.records;
/**
* A simple person (we can get his/her first name, last name and age).
*
* @author <a href="mailto:dycjh@example.com">Chris T</a>
*
*/
public interface Person {
public String firstName();
public String lastName();
public int age();
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.