hexsha
stringlengths 40
40
| size
int64 8
1.04M
| content
stringlengths 8
1.04M
| avg_line_length
float64 2.24
100
| max_line_length
int64 4
1k
| alphanum_fraction
float64 0.25
0.97
|
---|---|---|---|---|---|
138c91d341ee80a279ef6721d608cb0f50c26d32
| 27,459 |
/*
* Copyright 2018 Key Bridge.
*
* 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.broadbandforum.tr181.device.ip.diagnostics;
import java.util.ArrayList;
import java.util.Collection;
import javax.validation.constraints.Size;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlList;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
import org.broadbandforum.annotation.CWMPObject;
import org.broadbandforum.annotation.CWMPParameter;
import org.broadbandforum.common.IPAddress;
/**
* This object provides access to a diagnostics test that performs either an ICMP Ping or UDP Echo ping against multiple hosts determining which one has the smallest average response time. There MUST be a ping response to the transmitted ping, or timeout, before the next ping is sent out.
*
* @since TR181 v2.9
*/
@CWMPObject(name = "Device.IP.Diagnostics.ServerSelectionDiagnostics.")
@XmlRootElement(name = "Device.IP.Diagnostics.ServerSelectionDiagnostics")
@XmlType(name = "Device.IP.Diagnostics.ServerSelectionDiagnostics")
@XmlAccessorType(XmlAccessType.FIELD)
public class ServerSelectionDiagnostics {
/**
* Indicates availability of diagnostic data. {{enum}}
If the ACS sets the value of this parameter to {{enum|Requested}}, the CPE MUST initiate the corresponding diagnostic test. When writing, the only allowed value is {{enum|Requested}}. To ensure the use of the proper test parameters (the writable parameters in this object), the test parameters MUST be set either prior to or at the same time as (in the same SetParameterValues) setting the {{param}} to {{enum|Requested}}.
When requested, the CPE SHOULD wait until after completion of the communication session with the ACS before starting the diagnostic.
When the test is completed, the value of this parameter MUST be either {{enum|Completed}} (if the test completed successfully), or one of the ''Error'' values listed above.
If the value of this parameter is anything other than {{enum|Completed}}, the values of the results parameters for this test are indeterminate.
When the diagnostic initiated by the ACS is completed (successfully or not), the CPE MUST establish a new connection to the ACS to allow the ACS to view the results, indicating the Event code ''8 DIAGNOSTICS COMPLETE'' in the Inform message.
After the diagnostic is complete, the value of all result parameters (all read-only parameters in this object) MUST be retained by the CPE until either this diagnostic is run again, or the CPE reboots. After a reboot, if the CPE has not retained the result parameters from the most recent test, it MUST set the value of this parameter to {{enum|None}}.
Modifying any of the writable parameters in this object except for this one MUST result in the value of this parameter being set to {{enum|None}}.
While the test is in progress, modifying any of the writable parameters in this object except for this one MUST result in the test being terminated and the value of this parameter being set to {{enum|None}}.
While the test is in progress, setting this parameter to {{enum|Requested}} (and possibly modifying other writable parameters in this object) MUST result in the test being terminated and then restarted using the current values of the test parameters.
*
* @since 2.9
*/
@XmlElement(name = "DiagnosticsState")
@CWMPParameter(access = "readWrite", activeNotify = "canDeny")
public String diagnosticsState;
/**
* {{reference|the IP-layer interface over which the test is to be performed|ignore}} Example: Device.IP.Interface.1
If {{empty}} is specified, the CPE MUST use the interface as directed by its routing policy (''Forwarding'' table entries) to determine the appropriate interface.
*
* @since 2.9
*/
@XmlElement(name = "Interface")
@CWMPParameter(access = "readWrite")
@Size(max = 256)
public String _interface;
/**
* Indicates the IP protocol version to be used.
*
* @since 2.9
*/
@XmlElement(name = "ProtocolVersion")
@CWMPParameter(access = "readWrite")
public String protocolVersion;
/**
* The protocol over which the test is to be performed.
*
* @since 2.9
*/
@XmlElement(name = "Protocol")
@CWMPParameter(access = "readWrite")
public String protocol;
/**
* Each entry is a Host name or address of a host to ping.
*
* @since 2.9
*/
@XmlElement(name = "HostList")
@CWMPParameter(access = "readWrite")
@Size
@XmlList
public Collection<String> hostList;
/**
* Number of repetitions of the ping test to perform for each {{param|HostList}} entry before reporting the results.
*
* @since 2.9
*/
@XmlElement(name = "NumberOfRepetitions")
@CWMPParameter(access = "readWrite")
@Size(min = 1)
public Long numberOfRepetitions;
/**
* Timeout in milliseconds for each iteration of the ping test where the total number of iterations is the value of {{param|NumberOfRepetitions}} times the number of entities in the {{param|HostList}} Parameter.
*
* @since 2.9
*/
@XmlElement(name = "Timeout")
@CWMPParameter(access = "readWrite", units = "milliseconds")
@Size(min = 1)
public Long timeout;
/**
* Result parameter indicating the Host (one of the items within the {{param|HostList}} Parameter) with the smallest average response time.
*
* @since 2.9
*/
@XmlElement(name = "FastestHost")
@CWMPParameter(activeNotify = "canDeny")
public String fastestHost;
/**
* Result parameter indicating the minimum response time in microseconds over all repetitions with successful responses of the most recent ping test for the Host identified in {{param|FastestHost}}. Success is defined by the underlying protocol used. If there were no successful responses across all Hosts, this value MUST be zero.
*
* @since 2.9
*/
@XmlElement(name = "MinimumResponseTime")
@CWMPParameter(activeNotify = "canDeny", units = "microseconds")
public Long minimumResponseTime;
/**
* Result parameter indicating the average response time in microseconds over all repetitions with successful responses of the most recent ping test for the Host identified in {{param|FastestHost}}. Success is defined by the underlying protocol used. If there were no successful responses across all Hosts, this value MUST be zero.
*
* @since 2.9
*/
@XmlElement(name = "AverageResponseTime")
@CWMPParameter(activeNotify = "canDeny", units = "microseconds")
public Long averageResponseTime;
/**
* Result parameter indicating the maximum response time in microseconds over all repetitions with successful responses of the most recent ping test for the Host identified in {{param|FastestHost}}. Success is defined by the underlying protocol used. If there were no successful responses across all Hosts, this value MUST be zero.
*
* @since 2.9
*/
@XmlElement(name = "MaximumResponseTime")
@CWMPParameter(activeNotify = "canDeny", units = "microseconds")
public Long maximumResponseTime;
/**
* Indicates which IP address was used to send the request to the host identified in {{param|FastestHost}}.
*
* @since 2.9
*/
@XmlElement(name = "IPAddressUsed")
public IPAddress ipaddressUsed;
public ServerSelectionDiagnostics() {
}
//<editor-fold defaultstate="collapsed" desc="Getter and Setter">
/**
* Get the indicates availability of diagnostic data. {{enum}}
If the ACS sets the value of this parameter to {{enum|Requested}}, the CPE MUST initiate the corresponding diagnostic test. When writing, the only allowed value is {{enum|Requested}}. To ensure the use of the proper test parameters (the writable parameters in this object), the test parameters MUST be set either prior to or at the same time as (in the same SetParameterValues) setting the {{param}} to {{enum|Requested}}.
When requested, the CPE SHOULD wait until after completion of the communication session with the ACS before starting the diagnostic.
When the test is completed, the value of this parameter MUST be either {{enum|Completed}} (if the test completed successfully), or one of the ''Error'' values listed above.
If the value of this parameter is anything other than {{enum|Completed}}, the values of the results parameters for this test are indeterminate.
When the diagnostic initiated by the ACS is completed (successfully or not), the CPE MUST establish a new connection to the ACS to allow the ACS to view the results, indicating the Event code ''8 DIAGNOSTICS COMPLETE'' in the Inform message.
After the diagnostic is complete, the value of all result parameters (all read-only parameters in this object) MUST be retained by the CPE until either this diagnostic is run again, or the CPE reboots. After a reboot, if the CPE has not retained the result parameters from the most recent test, it MUST set the value of this parameter to {{enum|None}}.
Modifying any of the writable parameters in this object except for this one MUST result in the value of this parameter being set to {{enum|None}}.
While the test is in progress, modifying any of the writable parameters in this object except for this one MUST result in the test being terminated and the value of this parameter being set to {{enum|None}}.
While the test is in progress, setting this parameter to {{enum|Requested}} (and possibly modifying other writable parameters in this object) MUST result in the test being terminated and then restarted using the current values of the test parameters.
*
* @since 2.9
* @return the value
*/
public String getDiagnosticsState() {
return diagnosticsState;
}
/**
* Set the indicates availability of diagnostic data. {{enum}}
If the ACS sets the value of this parameter to {{enum|Requested}}, the CPE MUST initiate the corresponding diagnostic test. When writing, the only allowed value is {{enum|Requested}}. To ensure the use of the proper test parameters (the writable parameters in this object), the test parameters MUST be set either prior to or at the same time as (in the same SetParameterValues) setting the {{param}} to {{enum|Requested}}.
When requested, the CPE SHOULD wait until after completion of the communication session with the ACS before starting the diagnostic.
When the test is completed, the value of this parameter MUST be either {{enum|Completed}} (if the test completed successfully), or one of the ''Error'' values listed above.
If the value of this parameter is anything other than {{enum|Completed}}, the values of the results parameters for this test are indeterminate.
When the diagnostic initiated by the ACS is completed (successfully or not), the CPE MUST establish a new connection to the ACS to allow the ACS to view the results, indicating the Event code ''8 DIAGNOSTICS COMPLETE'' in the Inform message.
After the diagnostic is complete, the value of all result parameters (all read-only parameters in this object) MUST be retained by the CPE until either this diagnostic is run again, or the CPE reboots. After a reboot, if the CPE has not retained the result parameters from the most recent test, it MUST set the value of this parameter to {{enum|None}}.
Modifying any of the writable parameters in this object except for this one MUST result in the value of this parameter being set to {{enum|None}}.
While the test is in progress, modifying any of the writable parameters in this object except for this one MUST result in the test being terminated and the value of this parameter being set to {{enum|None}}.
While the test is in progress, setting this parameter to {{enum|Requested}} (and possibly modifying other writable parameters in this object) MUST result in the test being terminated and then restarted using the current values of the test parameters.
*
* @since 2.9
* @param diagnosticsState the input value
*/
public void setDiagnosticsState(String diagnosticsState) {
this.diagnosticsState = diagnosticsState;
}
/**
* Set the indicates availability of diagnostic data. {{enum}}
If the ACS sets the value of this parameter to {{enum|Requested}}, the CPE MUST initiate the corresponding diagnostic test. When writing, the only allowed value is {{enum|Requested}}. To ensure the use of the proper test parameters (the writable parameters in this object), the test parameters MUST be set either prior to or at the same time as (in the same SetParameterValues) setting the {{param}} to {{enum|Requested}}.
When requested, the CPE SHOULD wait until after completion of the communication session with the ACS before starting the diagnostic.
When the test is completed, the value of this parameter MUST be either {{enum|Completed}} (if the test completed successfully), or one of the ''Error'' values listed above.
If the value of this parameter is anything other than {{enum|Completed}}, the values of the results parameters for this test are indeterminate.
When the diagnostic initiated by the ACS is completed (successfully or not), the CPE MUST establish a new connection to the ACS to allow the ACS to view the results, indicating the Event code ''8 DIAGNOSTICS COMPLETE'' in the Inform message.
After the diagnostic is complete, the value of all result parameters (all read-only parameters in this object) MUST be retained by the CPE until either this diagnostic is run again, or the CPE reboots. After a reboot, if the CPE has not retained the result parameters from the most recent test, it MUST set the value of this parameter to {{enum|None}}.
Modifying any of the writable parameters in this object except for this one MUST result in the value of this parameter being set to {{enum|None}}.
While the test is in progress, modifying any of the writable parameters in this object except for this one MUST result in the test being terminated and the value of this parameter being set to {{enum|None}}.
While the test is in progress, setting this parameter to {{enum|Requested}} (and possibly modifying other writable parameters in this object) MUST result in the test being terminated and then restarted using the current values of the test parameters.
*
* @since 2.9
* @param diagnosticsState the input value
* @return this instance
*/
public ServerSelectionDiagnostics withDiagnosticsState(String diagnosticsState) {
this.diagnosticsState = diagnosticsState;
return this;
}
/**
* Get the {{reference|the IP-layer interface over which the test is to be performed|ignore}} Example: Device.IP.Interface.1
If {{empty}} is specified, the CPE MUST use the interface as directed by its routing policy (''Forwarding'' table entries) to determine the appropriate interface.
*
* @since 2.9
* @return the value
*/
public String get_interface() {
return _interface;
}
/**
* Set the {{reference|the IP-layer interface over which the test is to be performed|ignore}} Example: Device.IP.Interface.1
If {{empty}} is specified, the CPE MUST use the interface as directed by its routing policy (''Forwarding'' table entries) to determine the appropriate interface.
*
* @since 2.9
* @param _interface the input value
*/
public void set_interface(String _interface) {
this._interface = _interface;
}
/**
* Set the {{reference|the IP-layer interface over which the test is to be performed|ignore}} Example: Device.IP.Interface.1
If {{empty}} is specified, the CPE MUST use the interface as directed by its routing policy (''Forwarding'' table entries) to determine the appropriate interface.
*
* @since 2.9
* @param _interface the input value
* @return this instance
*/
public ServerSelectionDiagnostics with_interface(String _interface) {
this._interface = _interface;
return this;
}
/**
* Get the indicates the IP protocol version to be used.
*
* @since 2.9
* @return the value
*/
public String getProtocolVersion() {
return protocolVersion;
}
/**
* Set the indicates the IP protocol version to be used.
*
* @since 2.9
* @param protocolVersion the input value
*/
public void setProtocolVersion(String protocolVersion) {
this.protocolVersion = protocolVersion;
}
/**
* Set the indicates the IP protocol version to be used.
*
* @since 2.9
* @param protocolVersion the input value
* @return this instance
*/
public ServerSelectionDiagnostics withProtocolVersion(String protocolVersion) {
this.protocolVersion = protocolVersion;
return this;
}
/**
* Get the protocol over which the test is to be performed.
*
* @since 2.9
* @return the value
*/
public String getProtocol() {
return protocol;
}
/**
* Set the protocol over which the test is to be performed.
*
* @since 2.9
* @param protocol the input value
*/
public void setProtocol(String protocol) {
this.protocol = protocol;
}
/**
* Set the protocol over which the test is to be performed.
*
* @since 2.9
* @param protocol the input value
* @return this instance
*/
public ServerSelectionDiagnostics withProtocol(String protocol) {
this.protocol = protocol;
return this;
}
/**
* Get the each entry is a Host name or address of a host to ping.
*
* @since 2.9
* @return the value
*/
public Collection<String> getHostList() {
if (this.hostList == null){ this.hostList=new ArrayList<>();}
return hostList;
}
/**
* Set the each entry is a Host name or address of a host to ping.
*
* @since 2.9
* @param hostList the input value
*/
public void setHostList(Collection<String> hostList) {
this.hostList = hostList;
}
/**
* Set the each entry is a Host name or address of a host to ping.
*
* @since 2.9
* @param string the input value
* @return this instance
*/
public ServerSelectionDiagnostics withHostList(String string) {
getHostList().add(string);
return this;
}
/**
* Get the number of repetitions of the ping test to perform for each {{param|HostList}} entry before reporting the results.
*
* @since 2.9
* @return the value
*/
public Long getNumberOfRepetitions() {
return numberOfRepetitions;
}
/**
* Set the number of repetitions of the ping test to perform for each {{param|HostList}} entry before reporting the results.
*
* @since 2.9
* @param numberOfRepetitions the input value
*/
public void setNumberOfRepetitions(Long numberOfRepetitions) {
this.numberOfRepetitions = numberOfRepetitions;
}
/**
* Set the number of repetitions of the ping test to perform for each {{param|HostList}} entry before reporting the results.
*
* @since 2.9
* @param numberOfRepetitions the input value
* @return this instance
*/
public ServerSelectionDiagnostics withNumberOfRepetitions(Long numberOfRepetitions) {
this.numberOfRepetitions = numberOfRepetitions;
return this;
}
/**
* Get the timeout in milliseconds for each iteration of the ping test where the total number of iterations is the value of {{param|NumberOfRepetitions}} times the number of entities in the {{param|HostList}} Parameter.
*
* @since 2.9
* @return the value
*/
public Long getTimeout() {
return timeout;
}
/**
* Set the timeout in milliseconds for each iteration of the ping test where the total number of iterations is the value of {{param|NumberOfRepetitions}} times the number of entities in the {{param|HostList}} Parameter.
*
* @since 2.9
* @param timeout the input value
*/
public void setTimeout(Long timeout) {
this.timeout = timeout;
}
/**
* Set the timeout in milliseconds for each iteration of the ping test where the total number of iterations is the value of {{param|NumberOfRepetitions}} times the number of entities in the {{param|HostList}} Parameter.
*
* @since 2.9
* @param timeout the input value
* @return this instance
*/
public ServerSelectionDiagnostics withTimeout(Long timeout) {
this.timeout = timeout;
return this;
}
/**
* Get the result parameter indicating the Host (one of the items within the {{param|HostList}} Parameter) with the smallest average response time.
*
* @since 2.9
* @return the value
*/
public String getFastestHost() {
return fastestHost;
}
/**
* Set the result parameter indicating the Host (one of the items within the {{param|HostList}} Parameter) with the smallest average response time.
*
* @since 2.9
* @param fastestHost the input value
*/
public void setFastestHost(String fastestHost) {
this.fastestHost = fastestHost;
}
/**
* Set the result parameter indicating the Host (one of the items within the {{param|HostList}} Parameter) with the smallest average response time.
*
* @since 2.9
* @param fastestHost the input value
* @return this instance
*/
public ServerSelectionDiagnostics withFastestHost(String fastestHost) {
this.fastestHost = fastestHost;
return this;
}
/**
* Get the result parameter indicating the minimum response time in microseconds over all repetitions with successful responses of the most recent ping test for the Host identified in {{param|FastestHost}}. Success is defined by the underlying protocol used. If there were no successful responses across all Hosts, this value MUST be zero.
*
* @since 2.9
* @return the value
*/
public Long getMinimumResponseTime() {
return minimumResponseTime;
}
/**
* Set the result parameter indicating the minimum response time in microseconds over all repetitions with successful responses of the most recent ping test for the Host identified in {{param|FastestHost}}. Success is defined by the underlying protocol used. If there were no successful responses across all Hosts, this value MUST be zero.
*
* @since 2.9
* @param minimumResponseTime the input value
*/
public void setMinimumResponseTime(Long minimumResponseTime) {
this.minimumResponseTime = minimumResponseTime;
}
/**
* Set the result parameter indicating the minimum response time in microseconds over all repetitions with successful responses of the most recent ping test for the Host identified in {{param|FastestHost}}. Success is defined by the underlying protocol used. If there were no successful responses across all Hosts, this value MUST be zero.
*
* @since 2.9
* @param minimumResponseTime the input value
* @return this instance
*/
public ServerSelectionDiagnostics withMinimumResponseTime(Long minimumResponseTime) {
this.minimumResponseTime = minimumResponseTime;
return this;
}
/**
* Get the result parameter indicating the average response time in microseconds over all repetitions with successful responses of the most recent ping test for the Host identified in {{param|FastestHost}}. Success is defined by the underlying protocol used. If there were no successful responses across all Hosts, this value MUST be zero.
*
* @since 2.9
* @return the value
*/
public Long getAverageResponseTime() {
return averageResponseTime;
}
/**
* Set the result parameter indicating the average response time in microseconds over all repetitions with successful responses of the most recent ping test for the Host identified in {{param|FastestHost}}. Success is defined by the underlying protocol used. If there were no successful responses across all Hosts, this value MUST be zero.
*
* @since 2.9
* @param averageResponseTime the input value
*/
public void setAverageResponseTime(Long averageResponseTime) {
this.averageResponseTime = averageResponseTime;
}
/**
* Set the result parameter indicating the average response time in microseconds over all repetitions with successful responses of the most recent ping test for the Host identified in {{param|FastestHost}}. Success is defined by the underlying protocol used. If there were no successful responses across all Hosts, this value MUST be zero.
*
* @since 2.9
* @param averageResponseTime the input value
* @return this instance
*/
public ServerSelectionDiagnostics withAverageResponseTime(Long averageResponseTime) {
this.averageResponseTime = averageResponseTime;
return this;
}
/**
* Get the result parameter indicating the maximum response time in microseconds over all repetitions with successful responses of the most recent ping test for the Host identified in {{param|FastestHost}}. Success is defined by the underlying protocol used. If there were no successful responses across all Hosts, this value MUST be zero.
*
* @since 2.9
* @return the value
*/
public Long getMaximumResponseTime() {
return maximumResponseTime;
}
/**
* Set the result parameter indicating the maximum response time in microseconds over all repetitions with successful responses of the most recent ping test for the Host identified in {{param|FastestHost}}. Success is defined by the underlying protocol used. If there were no successful responses across all Hosts, this value MUST be zero.
*
* @since 2.9
* @param maximumResponseTime the input value
*/
public void setMaximumResponseTime(Long maximumResponseTime) {
this.maximumResponseTime = maximumResponseTime;
}
/**
* Set the result parameter indicating the maximum response time in microseconds over all repetitions with successful responses of the most recent ping test for the Host identified in {{param|FastestHost}}. Success is defined by the underlying protocol used. If there were no successful responses across all Hosts, this value MUST be zero.
*
* @since 2.9
* @param maximumResponseTime the input value
* @return this instance
*/
public ServerSelectionDiagnostics withMaximumResponseTime(Long maximumResponseTime) {
this.maximumResponseTime = maximumResponseTime;
return this;
}
/**
* Get the indicates which IP address was used to send the request to the host identified in {{param|FastestHost}}.
*
* @since 2.9
* @return the value
*/
public IPAddress getIpaddressUsed() {
return ipaddressUsed;
}
/**
* Set the indicates which IP address was used to send the request to the host identified in {{param|FastestHost}}.
*
* @since 2.9
* @param ipaddressUsed the input value
*/
public void setIpaddressUsed(IPAddress ipaddressUsed) {
this.ipaddressUsed = ipaddressUsed;
}
/**
* Set the indicates which IP address was used to send the request to the host identified in {{param|FastestHost}}.
*
* @since 2.9
* @param ipaddressUsed the input value
* @return this instance
*/
public ServerSelectionDiagnostics withIpaddressUsed(IPAddress ipaddressUsed) {
this.ipaddressUsed = ipaddressUsed;
return this;
}
//</editor-fold>
}
| 44.721498 | 437 | 0.739685 |
8ca6fe6d426eae20c50b97c4842925c61bc93227
| 1,811 |
import edu.princeton.cs.introcs.StdRandom;
import java.security.Key;
/**
* Created by hug.
*/
public class ExperimentHelper {
/** Returns the internal path length for an optimum binary search tree of
* size N. Examples:
* N = 1, OIPL: 0
* N = 2, OIPL: 1
* N = 3, OIPL: 2
* N = 4, OIPL: 4
* N = 5, OIPL: 6
* N = 6, OIPL: 8
* N = 7, OIPL: 10
* N = 8, OIPL: 13
*/
public static int optimalIPL(int N) {
int result = 0;
for (int i = 1; i <= N; i++) {
int depth = (int) Math.floor(Math.log(i) / Math.log(2));
result += depth;
}
return result;
}
/** Returns the average depth for nodes in an optimal BST of
* size N.
* Examples:
* N = 1, OAD: 0
* N = 5, OAD: 1.2
* N = 8, OAD: 1.625
* @return
*/
public static double optimalAverageDepth(int N) {
return (double) optimalIPL(N) / (double) N;
}
public static double deleteAndInsert(BST bst, int M) {
bst.deleteTakingSuccessor(bst.getRandomKey());
int item = StdRandom.uniform(M);
if (!bst.contains(item)) {
bst.add(item);
}
return bst.averageDepth();
}
public static double deleteAndInsertEx3(BST bst, int M) {
bst.deleteTakingRandom(bst.getRandomKey());
int item = StdRandom.uniform(M);
if (!bst.contains(item)) {
bst.add(item);
}
return bst.averageDepth();
}
// public static void main(String[] args) {
//// System.out.println(Math.floor(Math.log(4) / Math.log(2)));
// System.out.println(optimalIPL(8));
// System.out.println(optimalAverageDepth(8));
// }
}
| 27.029851 | 78 | 0.515737 |
3124d18c2b28cd86d312976015a676f6eb74207c
| 980 |
package cn.linter.learning.auth.controller;
import cn.linter.learning.auth.client.UserClient;
import cn.linter.learning.auth.entity.User;
import cn.linter.learning.common.entity.Result;
import cn.linter.learning.common.utils.JwtUtil;
import org.springframework.web.bind.annotation.*;
/**
* 用户控制器
*
* @author wangxiaoyang
* @since 2021/1/21
*/
@RestController
@RequestMapping("oauth/user")
public class UserController {
private final UserClient userClient;
public UserController(UserClient userClient) {
this.userClient = userClient;
}
@GetMapping
public Result<User> getUser(@RequestHeader("Authorization") String token) {
String username = JwtUtil.getUsername(token);
Result<User> result = userClient.queryUser(username);
result.getData().setPassword(null);
return result;
}
@PostMapping
public Result<?> registerUser(@RequestBody User user) {
return userClient.createUser(user);
}
}
| 25.789474 | 79 | 0.717347 |
8d7a4c21097c961a2d9431d991dabbd685686b61
| 592 |
package com.javase.gui.listen;
import java.awt.Frame;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
public class WindowAdapterListen extends Frame {
/**
*
*/
private static final long serialVersionUID = 1L;
WindowAdapterListen() {
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent arg0) {
// TODO Auto-generated method stub
// 用户试图从窗口的系统菜单中关闭窗口时调用。
System.exit(0);
}
});
setBounds(350, 100, 500, 500);
setVisible(true);
}
public static void main(String[] args) {
new WindowAdapterListen();
}
}
| 19.733333 | 49 | 0.709459 |
4cb58f7066ea270bc516cf805fcaf6677a31ee77
| 10,424 |
/*
* Copyright (c) 2002-2021, City of Paris
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright notice
* and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice
* and the following disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* 3. Neither the name of 'Mairie de Paris' nor 'Lutece' nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* License 1.0
*/
package fr.paris.lutece.plugins.appointment.business.form;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import fr.paris.lutece.portal.service.plugin.Plugin;
import fr.paris.lutece.util.sql.DAOUtil;
/**
* This class provides Data Access methods for Form objects
*
* @author Laurent Payen
*
*/
public final class FormDAO implements IFormDAO
{
private static final String SQL_QUERY_INSERT = "INSERT INTO appointment_form ( title, description, reference, id_category, starting_validity_date, ending_validity_date, is_active, id_workflow, workgroup,is_multislot_appointment, role_fo, capacity_per_slot ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
private static final String SQL_QUERY_UPDATE = "UPDATE appointment_form SET title = ?, description = ?, reference = ?, id_category = ?, starting_validity_date = ?, ending_validity_date = ?, is_active = ?, id_workflow = ?, workgroup = ?, is_multislot_appointment = ?, role_fo = ?, capacity_per_slot= ? WHERE id_form = ?";
private static final String SQL_QUERY_DELETE = "DELETE FROM appointment_form WHERE id_form = ? ";
private static final String SQL_QUERY_SELECT_COLUMNS = "SELECT form.id_form, form.title, form.description, form.reference, form.id_category, form.starting_validity_date, form.ending_validity_date, form.is_active, form.id_workflow, form.workgroup, form.is_multislot_appointment, form.role_fo, form.capacity_per_slot FROM appointment_form form";
private static final String SQL_QUERY_SELECT_BY_TITLE = SQL_QUERY_SELECT_COLUMNS + " WHERE title = ?";
private static final String SQL_QUERY_SELECT_ALL = SQL_QUERY_SELECT_COLUMNS;
private static final String SQL_QUERY_SELECT = SQL_QUERY_SELECT_COLUMNS + " WHERE id_form = ?";
private static final String SQL_QUERY_SELECT_ACTIVE_FORMS = SQL_QUERY_SELECT_COLUMNS + " WHERE is_active = 1";
private static final String SQL_QUERY_SELECT_ACTIVE_AND_DISPLAYED_ON_PORTLET_FORMS = SQL_QUERY_SELECT_COLUMNS
+ " INNER JOIN appointment_display display ON form.id_form = display.id_form WHERE form.is_active = 1 AND display.is_displayed_on_portlet = 1";
private static final String SQL_QUERY_SELECT_BY_CATEGORY = SQL_QUERY_SELECT_COLUMNS + " WHERE id_category = ?";
@Override
public void insert( Form form, Plugin plugin )
{
try ( DAOUtil daoUtil = buildDaoUtil( SQL_QUERY_INSERT, form, plugin, true ) )
{
daoUtil.executeUpdate( );
if ( daoUtil.nextGeneratedKey( ) )
{
form.setIdForm( daoUtil.getGeneratedKeyInt( 1 ) );
}
}
}
@Override
public void update( Form form, Plugin plugin )
{
try ( DAOUtil daoUtil = buildDaoUtil( SQL_QUERY_UPDATE, form, plugin, false ) )
{
daoUtil.executeUpdate( );
}
}
@Override
public void delete( int nIdForm, Plugin plugin )
{
try ( DAOUtil daoUtil = new DAOUtil( SQL_QUERY_DELETE, plugin ) )
{
daoUtil.setInt( 1, nIdForm );
daoUtil.executeUpdate( );
}
}
@Override
public Form select( int nIdForm, Plugin plugin )
{
Form form = null;
try ( DAOUtil daoUtil = new DAOUtil( SQL_QUERY_SELECT, plugin ) )
{
daoUtil.setInt( 1, nIdForm );
daoUtil.executeQuery( );
if ( daoUtil.next( ) )
{
form = buildForm( daoUtil );
}
}
return form;
}
@Override
public List<Form> selectByCategory( int nIdCategory, Plugin plugin )
{
List<Form> listForms = new ArrayList<>( );
try ( DAOUtil daoUtil = new DAOUtil( SQL_QUERY_SELECT_BY_CATEGORY, plugin ) )
{
daoUtil.setInt( 1, nIdCategory );
daoUtil.executeQuery( );
while ( daoUtil.next( ) )
{
listForms.add( buildForm( daoUtil ) );
}
}
return listForms;
}
@Override
public List<Form> findActiveForms( Plugin plugin )
{
List<Form> listForms = new ArrayList<>( );
try ( DAOUtil daoUtil = new DAOUtil( SQL_QUERY_SELECT_ACTIVE_FORMS, plugin ) )
{
daoUtil.executeQuery( );
while ( daoUtil.next( ) )
{
listForms.add( buildForm( daoUtil ) );
}
}
return listForms;
}
@Override
public List<Form> findActiveAndDisplayedOnPortletForms( Plugin plugin )
{
List<Form> listForms = new ArrayList<>( );
try ( DAOUtil daoUtil = new DAOUtil( SQL_QUERY_SELECT_ACTIVE_AND_DISPLAYED_ON_PORTLET_FORMS, plugin ) )
{
daoUtil.executeQuery( );
while ( daoUtil.next( ) )
{
listForms.add( buildForm( daoUtil ) );
}
}
return listForms;
}
@Override
public List<Form> findByTitle( String strTitle, Plugin plugin )
{
List<Form> listForms = new ArrayList<>( );
try ( DAOUtil daoUtil = new DAOUtil( SQL_QUERY_SELECT_BY_TITLE, plugin ) )
{
daoUtil.setString( 1, strTitle );
daoUtil.executeQuery( );
while ( daoUtil.next( ) )
{
listForms.add( buildForm( daoUtil ) );
}
}
return listForms;
}
@Override
public List<Form> findAllForms( Plugin plugin )
{
List<Form> listForms = new ArrayList<>( );
try ( DAOUtil daoUtil = new DAOUtil( SQL_QUERY_SELECT_ALL, plugin ) )
{
daoUtil.executeQuery( );
while ( daoUtil.next( ) )
{
listForms.add( buildForm( daoUtil ) );
}
}
return listForms;
}
/**
* Build a Form business object from the resultset
*
* @param daoUtil
* the prepare statement util object
* @return a new Form with all its attributes assigned
*/
private Form buildForm( DAOUtil daoUtil )
{
int nIndex = 1;
Form form = new Form( );
form.setIdForm( daoUtil.getInt( nIndex++ ) );
form.setTitle( daoUtil.getString( nIndex++ ) );
form.setDescription( daoUtil.getString( nIndex++ ) );
form.setReference( daoUtil.getString( nIndex++ ) );
form.setIdCategory( daoUtil.getInt( nIndex++ ) );
form.setStartingValiditySqlDate( daoUtil.getDate( nIndex++ ) );
form.setEndingValiditySqlDate( daoUtil.getDate( nIndex++ ) );
form.setIsActive( daoUtil.getBoolean( nIndex++ ) );
form.setIdWorkflow( daoUtil.getInt( nIndex++ ) );
form.setWorkgroup( daoUtil.getString( nIndex++ ) );
form.setIsMultislotAppointment( daoUtil.getBoolean( nIndex++ ) );
form.setRole( daoUtil.getString( nIndex++ ) );
form.setCapacityPerSlot( daoUtil.getInt( nIndex ) );
return form;
}
/**
* Build a daoUtil object with the form
*
* @param query
* the query
* @param form
* the form
* @param plugin
* the plugin
* @param isInsert
* true if it is an insert query (in this case, need to set the id). If false, it is an update, in this case, there is a where parameter id to
* set
* @return a new daoUtil with all its values assigned
*/
private DAOUtil buildDaoUtil( String query, Form form, Plugin plugin, boolean isInsert )
{
int nIndex = 1;
DAOUtil daoUtil = null;
if ( isInsert )
{
daoUtil = new DAOUtil( query, Statement.RETURN_GENERATED_KEYS, plugin );
}
else
{
daoUtil = new DAOUtil( query, plugin );
}
daoUtil.setString( nIndex++, form.getTitle( ) );
daoUtil.setString( nIndex++, form.getDescription( ) );
daoUtil.setString( nIndex++, form.getReference( ) );
if ( form.getIdCategory( ) == null || form.getIdCategory( ) == 0 )
{
daoUtil.setIntNull( nIndex++ );
}
else
{
daoUtil.setInt( nIndex++, form.getIdCategory( ) );
}
daoUtil.setDate( nIndex++, form.getStartingValiditySqlDate( ) );
daoUtil.setDate( nIndex++, form.getEndingValiditySqlDate( ) );
daoUtil.setBoolean( nIndex++, form.getIsActive( ) );
daoUtil.setInt( nIndex++, form.getIdWorkflow( ) );
daoUtil.setString( nIndex++, form.getWorkgroup( ) );
daoUtil.setBoolean( nIndex++, form.getIsMultislotAppointment( ) );
daoUtil.setString( nIndex++, form.getRole( ) );
daoUtil.setInt( nIndex++, form.getCapacityPerSlot( ) );
if ( !isInsert )
{
daoUtil.setInt( nIndex, form.getIdForm( ) );
}
return daoUtil;
}
}
| 38.464945 | 347 | 0.626727 |
62a8977d6984991ff63cb0393f4a43bf2dbdc875
| 518 |
package com.free.zhou.newsinfo.model;
import com.free.zhou.api.Api;
import com.free.zhou.newsinfo.bean.NewsInfo;
import com.free.zhou.newsinfo.contract.NewsInfoContract;
import com.jaydenxiao.common.baserx.RxSchedulers;
import rx.Observable;
/**
* Created by zskzh on 2017/5/13.
*/
public class NewsModel implements NewsInfoContract.Model {
@Override
public Observable<NewsInfo> getNewsInfo(String id) {
return Api.getDefault().getNewsInfo(id).compose(RxSchedulers.<NewsInfo>io_main());
}
}
| 24.666667 | 90 | 0.756757 |
bbe833d72f8953524d37266ed4a5cdd8ab809deb
| 2,273 |
package com.dsa.maths;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
/**
* Fibonacci Series using Linear approach
*
* @author sumitkumar
*
*/
public class Fibonacci {
private static Map<Integer, Integer> memory = new HashMap<Integer, Integer>();
static {
memory.put(0, 0);
memory.put(1, 1);
}
/**
* Linear approach of generating fibonacci series
*
* @param limit
*/
private static void fibLinear(int limit) {
int a = 0;
int b = 1;
int next;
System.out.print("0 1" + " ");
for (int i = 2; i <= limit; i++) {
next = (a + b);
System.out.print(next + " ");
a = b;
b = next;
}
}
/**
* Recursive approach of generating fibonacci series.
*
* @param limit
* @return
*/
private static int fibRec(int limit) {
int next;
if (memory.get(limit) != null) {
next = memory.get(limit);
} else {
next = fibRec(limit - 1) + fibRec(limit - 2);
// Optimization step: store the result of previously executed steps in a map
memory.put(limit, next);
System.out.print(next + " ");
}
return next;
}
public static void main(String[] args) {
System.out.println("Enter the limit for the series...");
Scanner scan = new Scanner(System.in);
final int limit = scan.nextInt();
if (limit <= 1) {
System.out.print("0" + " ");
} else if (limit == 2) {
System.out.print("0 1" + " ");
} else {
final Thread t1 = new Thread(new Runnable() {
public void run() {
fibLinear(limit);
}
}, "linearThread");
Thread t2 = new Thread(new Runnable() {
public void run() {
System.out.print("0 1" + " ");
fibRec(limit);
}
}, "recursiveThread");
System.out.print(t1.getName() + " => ");
t1.start();
try {
// This will actually make the Thread run sequentially.
// Thread t1 will join to the Main Thread.
t1.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
try {
// Currently executing thread i.e. Main Thread in this example will Sleep here.
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("");
System.out.print(t2.getName() + " => ");
// Main thread now start the thread t2
t2.start();
}
}
}
| 19.765217 | 83 | 0.598328 |
9d0d39458abc5499c96379158fce394f2457f573
| 141 |
package game.Town.villagers;
public enum VILLAGER_ROLES {
BUILDER, GATHERER, FOODGATHERER, WOODGATHERER, STONEGATHERER, WATERGATHERER
}
| 23.5 | 79 | 0.801418 |
63ab7a3682293db01c2e00bd8c16d625e83b366a
| 1,919 |
package io.sentry.environment;
import io.sentry.BaseTest;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.Test;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
public class SentryEnvironmentTest extends BaseTest {
@AfterMethod
public void tearDown() throws Exception {
SentryEnvironment.SENTRY_THREAD.remove();
}
@Test
public void testThreadNotManagedByDefault() throws Exception {
assertThat(SentryEnvironment.isManagingThread(), is(false));
}
@Test
public void testStartManagingThreadWorks() throws Exception {
SentryEnvironment.startManagingThread();
assertThat(SentryEnvironment.isManagingThread(), is(true));
}
@Test
public void testStartManagingAlreadyManagedThreadWorks() throws Exception {
SentryEnvironment.startManagingThread();
SentryEnvironment.startManagingThread();
assertThat(SentryEnvironment.isManagingThread(), is(true));
}
@Test
public void testStopManagingThreadWorks() throws Exception {
SentryEnvironment.startManagingThread();
SentryEnvironment.stopManagingThread();
assertThat(SentryEnvironment.isManagingThread(), is(false));
}
@Test
public void testStopManagingNonManagedThreadWorks() throws Exception {
SentryEnvironment.stopManagingThread();
assertThat(SentryEnvironment.isManagingThread(), is(false));
}
@Test
public void testThreadManagedTwiceNeedsToBeUnmanagedTwice() throws Exception {
SentryEnvironment.startManagingThread();
SentryEnvironment.startManagingThread();
SentryEnvironment.stopManagingThread();
assertThat(SentryEnvironment.isManagingThread(), is(true));
SentryEnvironment.stopManagingThread();
assertThat(SentryEnvironment.isManagingThread(), is(false));
}
}
| 29.984375 | 82 | 0.732673 |
409ff68f08ee8212dd8357135ac7b68753e500c3
| 1,367 |
package com.jackvanlightly.rabbittesttool.model;
import com.jackvanlightly.rabbittesttool.clients.MessagePayload;
public class Violation {
private ViolationType violationType;
private MessagePayload messagePayload;
private MessagePayload priorMessagePayload;
public Violation(ViolationType violationType, MessagePayload messagePayload) {
this.violationType = violationType;
this.messagePayload = messagePayload;
}
public Violation(ViolationType violationType, MessagePayload messagePayload, MessagePayload priorMessagePayload) {
this.violationType = violationType;
this.messagePayload = messagePayload;
this.priorMessagePayload = priorMessagePayload;
}
public ViolationType getViolationType() {
return violationType;
}
public void setViolationType(ViolationType violationType) {
this.violationType = violationType;
}
public MessagePayload getMessagePayload() {
return messagePayload;
}
public void setMessagePayload(MessagePayload messagePayload) {
this.messagePayload = messagePayload;
}
public MessagePayload getPriorMessagePayload() {
return priorMessagePayload;
}
public void setPriorMessagePayload(MessagePayload priorMessagePayload) {
this.priorMessagePayload = priorMessagePayload;
}
}
| 30.377778 | 118 | 0.746159 |
fa6b717232aa16a5f1ef43ac781488b9293e5d78
| 856 |
package test;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.LinkedList;
public class Test {
public static void main(String[] args) {
String s = "Hello World";
byte[] b = null;
String csn;
csn = "US-ASCII";
try {
b = s.getBytes(csn);
System.out.println(new String(b, csn));
} catch (UnsupportedEncodingException e) {
throw new InternalError("internal error " + e);
}
Hashtable<String, String> ht = new Hashtable<String, String>();
ht.put("one", "1");
ht.put("two", "2");
Enumeration<String> enm = ht.elements();
ArrayList<String> al = Collections.list(enm);
LinkedList<String> ll = new LinkedList<String>(al);
System.out.println("al = " + al);
System.out.println("ll = " + ll);
}
}
| 26.75 | 65 | 0.682243 |
53712b002b4369da1992266cdcff5788d9debf04
| 1,851 |
/*
* Copyright © Yan Zhenjie. All Rights Reserved
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.yanzhenjie.coolhttp.http;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* Created by Yan Zhenjie on 2017/1/8.
*/
public enum AsyncExecutor {
INSTANCE;
private ExecutorService mExecutorService = Executors.newSingleThreadExecutor();
AsyncExecutor() {
mExecutorService = Executors.newSingleThreadExecutor();
}
public <T> void execute(Request<T> request, HttpListener<T> httpListener) {
mExecutorService.execute(() -> {
Response<T> tResponse = SyncExecutor.INSTANCE.execute(request);
ResultMessage<T> tResultMessage = new ResultMessage<>();
tResultMessage.tResponse = tResponse;
tResultMessage.tHttpListener = httpListener;
Poster.getInstance().post(tResultMessage);
});
}
private static class ResultMessage<T> implements Runnable {
private Response<T> tResponse;
private HttpListener<T> tHttpListener;
@Override
public void run() {
if (tResponse.isSucceed()) {
tHttpListener.onSucceed(tResponse);
} else {
tHttpListener.onFailed(tResponse);
}
}
}
}
| 30.344262 | 83 | 0.670989 |
bfa0679fedc64d55ed7496ef787a8df18837debf
| 3,382 |
package team.hollow.neutronia.client.entity.render.model.model;
import net.minecraft.client.model.Cuboid;
import net.minecraft.client.render.entity.model.EntityModel;
import net.minecraft.entity.LivingEntity;
/**
* ModelOlDiggy - Undefined
* Created using Tabula 7.0.0
*/
public class ModelOlDiggy<T extends LivingEntity> extends EntityModel<T> {
public Cuboid Head;
public Cuboid HeadLayer;
public Cuboid RightLeg;
public Cuboid LeftLeg;
public Cuboid Body;
public Cuboid BodyLayer;
public Cuboid RightArm;
public Cuboid LeftArm;
public Cuboid Hat1;
public Cuboid Hat2;
public Cuboid Hat3;
public ModelOlDiggy() {
this.textureWidth = 64;
this.textureHeight = 64;
this.Hat3 = new Cuboid(this, 30, 57);
this.Hat3.setRotationPoint(0.0F, 0.0F, 0.0F);
this.Hat3.addBox(-2.0F, -11.0F, -5.0F, 4, 4, 2, 0.0F);
this.BodyLayer = new Cuboid(this, 16, 34);
this.BodyLayer.setRotationPoint(0.0F, 0.0F, 0.0F);
this.BodyLayer.addBox(-4.0F, 0.0F, -2.0F, 8, 12, 4, 0.5F);
this.Head = new Cuboid(this, 0, 0);
this.Head.setRotationPoint(0.0F, 0.0F, 0.0F);
this.Head.addBox(-4.0F, -8.0F, -4.0F, 8, 8, 8, 0.0F);
this.LeftArm = new Cuboid(this, 40, 34);
this.LeftArm.setRotationPoint(5.0F, 2.0F, 0.0F);
this.LeftArm.addBox(-1.0F, -2.0F, -2.0F, 4, 12, 4, 0.0F);
this.RightArm = new Cuboid(this, 40, 18);
this.RightArm.setRotationPoint(-5.0F, 2.0F, 0.0F);
this.RightArm.addBox(-3.0F, -2.0F, -2.0F, 4, 12, 4, 0.0F);
this.Body = new Cuboid(this, 16, 18);
this.Body.setRotationPoint(0.0F, 0.0F, 0.0F);
this.Body.addBox(-4.0F, 0.0F, -2.0F, 8, 12, 4, 0.0F);
this.Hat1 = new Cuboid(this, 0, 53);
this.Hat1.setRotationPoint(0.0F, -4.0F, 0.0F);
this.Hat1.addBox(-5.0F, -1.0F, -5.0F, 10, 1, 10, 0.0F);
this.Hat2 = new Cuboid(this, 0, 54);
this.Hat2.setRotationPoint(0.0F, 0.0F, 0.0F);
this.Hat2.addBox(-1.0F, -10.5F, -4.75F, 2, 6, 3, 0.0F);
this.LeftLeg = new Cuboid(this, 0, 32);
this.LeftLeg.setRotationPoint(2.0F, 12.0F, 0.0F);
this.LeftLeg.addBox(-2.0F, 0.0F, -2.0F, 4, 12, 4, 0.0F);
this.RightLeg = new Cuboid(this, 0, 16);
this.RightLeg.setRotationPoint(-2.0F, 12.0F, 0.0F);
this.RightLeg.addBox(-2.0F, 0.0F, -2.0F, 4, 12, 4, 0.0F);
this.HeadLayer = new Cuboid(this, 32, 0);
this.HeadLayer.setRotationPoint(0.0F, 0.0F, 0.0F);
this.HeadLayer.addBox(-4.0F, -8.0F, -4.0F, 8, 10, 8, 0.25F);
this.Head.addChild(this.Hat3);
this.Head.addChild(this.Hat1);
this.Head.addChild(this.Hat2);
}
@Override
public void render(T entity, float f, float f1, float f2, float f3, float f4, float f5) {
this.BodyLayer.render(f5);
this.Head.render(f5);
this.LeftArm.render(f5);
this.RightArm.render(f5);
this.Body.render(f5);
this.LeftLeg.render(f5);
this.RightLeg.render(f5);
this.HeadLayer.render(f5);
}
/**
* This is a helper function from Tabula to set the rotation of model parts
*/
public void setRotateAngle(Cuboid Cuboid, float x, float y, float z) {
Cuboid.rotationPointX = x;
Cuboid.rotationPointY = y;
Cuboid.rotationPointZ = z;
}
}
| 39.325581 | 93 | 0.604672 |
c95fa4150ea4880729885403b92b67e0e1236ff2
| 382 |
package com.android21buttons.fragmenttestrule.sample;
import android.app.Activity;
import android.os.Bundle;
import android.support.annotation.Nullable;
public class MainActivity extends Activity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
| 25.466667 | 66 | 0.772251 |
080954c2740542d44b2cff8bf570c03b5061004e
| 1,230 |
package com.iddej.gingerbread2.util.floatingpoint;
public class Vector3F {
public double x, y, z;
public Vector3F(final double x, final double y, final double z) {
this.x = x;
this.y = y;
this.z = z;
}
public Vector3F add(final Vector3F other) {
return new Vector3F(this.x + other.x, this.y + other.y, this.z + other.z);
}
public Vector3F subtract(final Vector3F other) {
return new Vector3F(this.x - other.x, this.y - other.y, this.z - other.z);
}
public Vector3F scale(final double scalar) {
return new Vector3F(this.x * scalar, this.y * scalar, this.z * scalar);
}
public double dotProduct(final Vector3F other) {
return (this.x * other.x) + (this.y * other.y) + (this.z * other.z);
}
public Vector3F crossProduct(final Vector3F other) {
final double x = (this.y * other.z) - (this.z * other.y);
final double y = (this.z * other.x) - (this.x * other.z);
final double z = (this.x * other.y) - (this.y * other.x);
return new Vector3F(x, y, z);
}
public double length() {
return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z));
}
public Vector3F normalize() {
return new Vector3F(this.x / this.length(), this.y / this.length(), this.z / this.length());
}
}
| 28.604651 | 94 | 0.649593 |
76503d5950c8230ff676ccda37e80db93d2e086b
| 21,869 |
/*
* Copyright 2012-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
package com.amazonaws.services.ecs.model;
import java.io.Serializable;
import javax.annotation.Generated;
import com.amazonaws.AmazonWebServiceRequest;
/**
*
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/ecs-2014-11-13/ListAttributes" target="_top">AWS API
* Documentation</a>
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class ListAttributesRequest extends com.amazonaws.AmazonWebServiceRequest implements Serializable, Cloneable {
/**
* <p>
* The short name or full Amazon Resource Name (ARN) of the cluster to list attributes. If you do not specify a
* cluster, the default cluster is assumed.
* </p>
*/
private String cluster;
/**
* <p>
* The type of the target with which to list attributes.
* </p>
*/
private String targetType;
/**
* <p>
* The name of the attribute with which to filter the results.
* </p>
*/
private String attributeName;
/**
* <p>
* The value of the attribute with which to filter results. You must also specify an attribute name to use this
* parameter.
* </p>
*/
private String attributeValue;
/**
* <p>
* The <code>nextToken</code> value returned from a previous paginated <code>ListAttributes</code> request where
* <code>maxResults</code> was used and the results exceeded the value of that parameter. Pagination continues from
* the end of the previous results that returned the <code>nextToken</code> value. This value is <code>null</code>
* when there are no more results to return.
* </p>
* <note>
* <p>
* This token should be treated as an opaque identifier that is only used to retrieve the next items in a list and
* not for other programmatic purposes.
* </p>
* </note>
*/
private String nextToken;
/**
* <p>
* The maximum number of cluster results returned by <code>ListAttributes</code> in paginated output. When this
* parameter is used, <code>ListAttributes</code> only returns <code>maxResults</code> results in a single page
* along with a <code>nextToken</code> response element. The remaining results of the initial request can be seen by
* sending another <code>ListAttributes</code> request with the returned <code>nextToken</code> value. This value
* can be between 1 and 100. If this parameter is not used, then <code>ListAttributes</code> returns up to 100
* results and a <code>nextToken</code> value if applicable.
* </p>
*/
private Integer maxResults;
/**
* <p>
* The short name or full Amazon Resource Name (ARN) of the cluster to list attributes. If you do not specify a
* cluster, the default cluster is assumed.
* </p>
*
* @param cluster
* The short name or full Amazon Resource Name (ARN) of the cluster to list attributes. If you do not specify
* a cluster, the default cluster is assumed.
*/
public void setCluster(String cluster) {
this.cluster = cluster;
}
/**
* <p>
* The short name or full Amazon Resource Name (ARN) of the cluster to list attributes. If you do not specify a
* cluster, the default cluster is assumed.
* </p>
*
* @return The short name or full Amazon Resource Name (ARN) of the cluster to list attributes. If you do not
* specify a cluster, the default cluster is assumed.
*/
public String getCluster() {
return this.cluster;
}
/**
* <p>
* The short name or full Amazon Resource Name (ARN) of the cluster to list attributes. If you do not specify a
* cluster, the default cluster is assumed.
* </p>
*
* @param cluster
* The short name or full Amazon Resource Name (ARN) of the cluster to list attributes. If you do not specify
* a cluster, the default cluster is assumed.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public ListAttributesRequest withCluster(String cluster) {
setCluster(cluster);
return this;
}
/**
* <p>
* The type of the target with which to list attributes.
* </p>
*
* @param targetType
* The type of the target with which to list attributes.
* @see TargetType
*/
public void setTargetType(String targetType) {
this.targetType = targetType;
}
/**
* <p>
* The type of the target with which to list attributes.
* </p>
*
* @return The type of the target with which to list attributes.
* @see TargetType
*/
public String getTargetType() {
return this.targetType;
}
/**
* <p>
* The type of the target with which to list attributes.
* </p>
*
* @param targetType
* The type of the target with which to list attributes.
* @return Returns a reference to this object so that method calls can be chained together.
* @see TargetType
*/
public ListAttributesRequest withTargetType(String targetType) {
setTargetType(targetType);
return this;
}
/**
* <p>
* The type of the target with which to list attributes.
* </p>
*
* @param targetType
* The type of the target with which to list attributes.
* @see TargetType
*/
public void setTargetType(TargetType targetType) {
withTargetType(targetType);
}
/**
* <p>
* The type of the target with which to list attributes.
* </p>
*
* @param targetType
* The type of the target with which to list attributes.
* @return Returns a reference to this object so that method calls can be chained together.
* @see TargetType
*/
public ListAttributesRequest withTargetType(TargetType targetType) {
this.targetType = targetType.toString();
return this;
}
/**
* <p>
* The name of the attribute with which to filter the results.
* </p>
*
* @param attributeName
* The name of the attribute with which to filter the results.
*/
public void setAttributeName(String attributeName) {
this.attributeName = attributeName;
}
/**
* <p>
* The name of the attribute with which to filter the results.
* </p>
*
* @return The name of the attribute with which to filter the results.
*/
public String getAttributeName() {
return this.attributeName;
}
/**
* <p>
* The name of the attribute with which to filter the results.
* </p>
*
* @param attributeName
* The name of the attribute with which to filter the results.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public ListAttributesRequest withAttributeName(String attributeName) {
setAttributeName(attributeName);
return this;
}
/**
* <p>
* The value of the attribute with which to filter results. You must also specify an attribute name to use this
* parameter.
* </p>
*
* @param attributeValue
* The value of the attribute with which to filter results. You must also specify an attribute name to use
* this parameter.
*/
public void setAttributeValue(String attributeValue) {
this.attributeValue = attributeValue;
}
/**
* <p>
* The value of the attribute with which to filter results. You must also specify an attribute name to use this
* parameter.
* </p>
*
* @return The value of the attribute with which to filter results. You must also specify an attribute name to use
* this parameter.
*/
public String getAttributeValue() {
return this.attributeValue;
}
/**
* <p>
* The value of the attribute with which to filter results. You must also specify an attribute name to use this
* parameter.
* </p>
*
* @param attributeValue
* The value of the attribute with which to filter results. You must also specify an attribute name to use
* this parameter.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public ListAttributesRequest withAttributeValue(String attributeValue) {
setAttributeValue(attributeValue);
return this;
}
/**
* <p>
* The <code>nextToken</code> value returned from a previous paginated <code>ListAttributes</code> request where
* <code>maxResults</code> was used and the results exceeded the value of that parameter. Pagination continues from
* the end of the previous results that returned the <code>nextToken</code> value. This value is <code>null</code>
* when there are no more results to return.
* </p>
* <note>
* <p>
* This token should be treated as an opaque identifier that is only used to retrieve the next items in a list and
* not for other programmatic purposes.
* </p>
* </note>
*
* @param nextToken
* The <code>nextToken</code> value returned from a previous paginated <code>ListAttributes</code> request
* where <code>maxResults</code> was used and the results exceeded the value of that parameter. Pagination
* continues from the end of the previous results that returned the <code>nextToken</code> value. This value
* is <code>null</code> when there are no more results to return.</p> <note>
* <p>
* This token should be treated as an opaque identifier that is only used to retrieve the next items in a
* list and not for other programmatic purposes.
* </p>
*/
public void setNextToken(String nextToken) {
this.nextToken = nextToken;
}
/**
* <p>
* The <code>nextToken</code> value returned from a previous paginated <code>ListAttributes</code> request where
* <code>maxResults</code> was used and the results exceeded the value of that parameter. Pagination continues from
* the end of the previous results that returned the <code>nextToken</code> value. This value is <code>null</code>
* when there are no more results to return.
* </p>
* <note>
* <p>
* This token should be treated as an opaque identifier that is only used to retrieve the next items in a list and
* not for other programmatic purposes.
* </p>
* </note>
*
* @return The <code>nextToken</code> value returned from a previous paginated <code>ListAttributes</code> request
* where <code>maxResults</code> was used and the results exceeded the value of that parameter. Pagination
* continues from the end of the previous results that returned the <code>nextToken</code> value. This value
* is <code>null</code> when there are no more results to return.</p> <note>
* <p>
* This token should be treated as an opaque identifier that is only used to retrieve the next items in a
* list and not for other programmatic purposes.
* </p>
*/
public String getNextToken() {
return this.nextToken;
}
/**
* <p>
* The <code>nextToken</code> value returned from a previous paginated <code>ListAttributes</code> request where
* <code>maxResults</code> was used and the results exceeded the value of that parameter. Pagination continues from
* the end of the previous results that returned the <code>nextToken</code> value. This value is <code>null</code>
* when there are no more results to return.
* </p>
* <note>
* <p>
* This token should be treated as an opaque identifier that is only used to retrieve the next items in a list and
* not for other programmatic purposes.
* </p>
* </note>
*
* @param nextToken
* The <code>nextToken</code> value returned from a previous paginated <code>ListAttributes</code> request
* where <code>maxResults</code> was used and the results exceeded the value of that parameter. Pagination
* continues from the end of the previous results that returned the <code>nextToken</code> value. This value
* is <code>null</code> when there are no more results to return.</p> <note>
* <p>
* This token should be treated as an opaque identifier that is only used to retrieve the next items in a
* list and not for other programmatic purposes.
* </p>
* @return Returns a reference to this object so that method calls can be chained together.
*/
public ListAttributesRequest withNextToken(String nextToken) {
setNextToken(nextToken);
return this;
}
/**
* <p>
* The maximum number of cluster results returned by <code>ListAttributes</code> in paginated output. When this
* parameter is used, <code>ListAttributes</code> only returns <code>maxResults</code> results in a single page
* along with a <code>nextToken</code> response element. The remaining results of the initial request can be seen by
* sending another <code>ListAttributes</code> request with the returned <code>nextToken</code> value. This value
* can be between 1 and 100. If this parameter is not used, then <code>ListAttributes</code> returns up to 100
* results and a <code>nextToken</code> value if applicable.
* </p>
*
* @param maxResults
* The maximum number of cluster results returned by <code>ListAttributes</code> in paginated output. When
* this parameter is used, <code>ListAttributes</code> only returns <code>maxResults</code> results in a
* single page along with a <code>nextToken</code> response element. The remaining results of the initial
* request can be seen by sending another <code>ListAttributes</code> request with the returned
* <code>nextToken</code> value. This value can be between 1 and 100. If this parameter is not used, then
* <code>ListAttributes</code> returns up to 100 results and a <code>nextToken</code> value if applicable.
*/
public void setMaxResults(Integer maxResults) {
this.maxResults = maxResults;
}
/**
* <p>
* The maximum number of cluster results returned by <code>ListAttributes</code> in paginated output. When this
* parameter is used, <code>ListAttributes</code> only returns <code>maxResults</code> results in a single page
* along with a <code>nextToken</code> response element. The remaining results of the initial request can be seen by
* sending another <code>ListAttributes</code> request with the returned <code>nextToken</code> value. This value
* can be between 1 and 100. If this parameter is not used, then <code>ListAttributes</code> returns up to 100
* results and a <code>nextToken</code> value if applicable.
* </p>
*
* @return The maximum number of cluster results returned by <code>ListAttributes</code> in paginated output. When
* this parameter is used, <code>ListAttributes</code> only returns <code>maxResults</code> results in a
* single page along with a <code>nextToken</code> response element. The remaining results of the initial
* request can be seen by sending another <code>ListAttributes</code> request with the returned
* <code>nextToken</code> value. This value can be between 1 and 100. If this parameter is not used, then
* <code>ListAttributes</code> returns up to 100 results and a <code>nextToken</code> value if applicable.
*/
public Integer getMaxResults() {
return this.maxResults;
}
/**
* <p>
* The maximum number of cluster results returned by <code>ListAttributes</code> in paginated output. When this
* parameter is used, <code>ListAttributes</code> only returns <code>maxResults</code> results in a single page
* along with a <code>nextToken</code> response element. The remaining results of the initial request can be seen by
* sending another <code>ListAttributes</code> request with the returned <code>nextToken</code> value. This value
* can be between 1 and 100. If this parameter is not used, then <code>ListAttributes</code> returns up to 100
* results and a <code>nextToken</code> value if applicable.
* </p>
*
* @param maxResults
* The maximum number of cluster results returned by <code>ListAttributes</code> in paginated output. When
* this parameter is used, <code>ListAttributes</code> only returns <code>maxResults</code> results in a
* single page along with a <code>nextToken</code> response element. The remaining results of the initial
* request can be seen by sending another <code>ListAttributes</code> request with the returned
* <code>nextToken</code> value. This value can be between 1 and 100. If this parameter is not used, then
* <code>ListAttributes</code> returns up to 100 results and a <code>nextToken</code> value if applicable.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public ListAttributesRequest withMaxResults(Integer maxResults) {
setMaxResults(maxResults);
return this;
}
/**
* Returns a string representation of this object; useful for testing and debugging.
*
* @return A string representation of this object.
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{");
if (getCluster() != null)
sb.append("Cluster: ").append(getCluster()).append(",");
if (getTargetType() != null)
sb.append("TargetType: ").append(getTargetType()).append(",");
if (getAttributeName() != null)
sb.append("AttributeName: ").append(getAttributeName()).append(",");
if (getAttributeValue() != null)
sb.append("AttributeValue: ").append(getAttributeValue()).append(",");
if (getNextToken() != null)
sb.append("NextToken: ").append(getNextToken()).append(",");
if (getMaxResults() != null)
sb.append("MaxResults: ").append(getMaxResults());
sb.append("}");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof ListAttributesRequest == false)
return false;
ListAttributesRequest other = (ListAttributesRequest) obj;
if (other.getCluster() == null ^ this.getCluster() == null)
return false;
if (other.getCluster() != null && other.getCluster().equals(this.getCluster()) == false)
return false;
if (other.getTargetType() == null ^ this.getTargetType() == null)
return false;
if (other.getTargetType() != null && other.getTargetType().equals(this.getTargetType()) == false)
return false;
if (other.getAttributeName() == null ^ this.getAttributeName() == null)
return false;
if (other.getAttributeName() != null && other.getAttributeName().equals(this.getAttributeName()) == false)
return false;
if (other.getAttributeValue() == null ^ this.getAttributeValue() == null)
return false;
if (other.getAttributeValue() != null && other.getAttributeValue().equals(this.getAttributeValue()) == false)
return false;
if (other.getNextToken() == null ^ this.getNextToken() == null)
return false;
if (other.getNextToken() != null && other.getNextToken().equals(this.getNextToken()) == false)
return false;
if (other.getMaxResults() == null ^ this.getMaxResults() == null)
return false;
if (other.getMaxResults() != null && other.getMaxResults().equals(this.getMaxResults()) == false)
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
hashCode = prime * hashCode + ((getCluster() == null) ? 0 : getCluster().hashCode());
hashCode = prime * hashCode + ((getTargetType() == null) ? 0 : getTargetType().hashCode());
hashCode = prime * hashCode + ((getAttributeName() == null) ? 0 : getAttributeName().hashCode());
hashCode = prime * hashCode + ((getAttributeValue() == null) ? 0 : getAttributeValue().hashCode());
hashCode = prime * hashCode + ((getNextToken() == null) ? 0 : getNextToken().hashCode());
hashCode = prime * hashCode + ((getMaxResults() == null) ? 0 : getMaxResults().hashCode());
return hashCode;
}
@Override
public ListAttributesRequest clone() {
return (ListAttributesRequest) super.clone();
}
}
| 41.418561 | 120 | 0.64205 |
ae3fdd26db39ceb1047d79a43883f4b41ea2ef85
| 3,923 |
package llc.ufwa.widget;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import android.content.Context;
import android.view.GestureDetector;
import android.view.GestureDetector.SimpleOnGestureListener;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
/**
* Taken from: http://stackoverflow.com/questions/4139288/android-how-to-handle-right-to-left-swipe-gestures
*
* @author Sean Wagner
*
*/
public abstract class OnSwipeTouchListener implements OnTouchListener {
private static final Logger logger = LoggerFactory.getLogger(OnSwipeTouchListener.class);
private final GestureDetector gestureDetector;
private MotionEvent downAction;
public OnSwipeTouchListener(final Context context) {
this.gestureDetector = new GestureDetector(context, new GestureListener());
}
@Override
public boolean onTouch(final View view, final MotionEvent motionEvent) {
final boolean returnVal = gestureDetector.onTouchEvent(motionEvent);
if(motionEvent.getAction() == MotionEvent.ACTION_UP) {
if(downAction != null) {
downAction = null;
logger.debug("not fling");
onNotFling();
}
}
else if(motionEvent.getAction() == MotionEvent.ACTION_DOWN) {
downAction = motionEvent;
}
return returnVal;
}
private final class GestureListener extends SimpleOnGestureListener {
private static final int SWIPE_THRESHOLD = 50;
private static final int SWIPE_VELOCITY_THRESHOLD = 50;
@Override
public boolean onDown(MotionEvent e) {
return true;
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
final boolean result;
float diffY = e2.getY() - e1.getY();
float diffX = e2.getX() - e1.getX();
if(Math.abs(diffX) > Math.abs(diffY)) {
if(Math.abs(diffX) > SWIPE_THRESHOLD && Math.abs(velocityX) > SWIPE_VELOCITY_THRESHOLD) {
if (diffX > 0) {
result = onSwipeRight();
downAction = null;
}
else {
result = onSwipeLeft();
downAction = null;
}
}
else {
result = false;
}
}
else {
if(Math.abs(diffY) > SWIPE_THRESHOLD && Math.abs(velocityY) > SWIPE_VELOCITY_THRESHOLD) {
if (diffY > 0) {
result = onSwipeBottom();
downAction = null;
}
else {
result = onSwipeTop();
downAction = null;
}
}
else {
result = false;
}
}
return result;
}
}
public abstract boolean onNotFling();
public abstract boolean onSwipeRight();
public abstract boolean onSwipeLeft();
public abstract boolean onSwipeTop();
public abstract boolean onSwipeBottom();
}
| 28.427536 | 108 | 0.474127 |
6bbd84076e427562279052995ae41e4df503e79d
| 3,337 |
/*
* Copyright (C) 2017 Stormpath, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.juiser.servlet;
import io.jsonwebtoken.lang.Assert;
import org.juiser.model.User;
import org.juiser.model.UserBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.servlet.http.HttpServletRequest;
import java.util.function.Function;
/**
* A function that delegates user creation to a <code>Function<HttpServletRequest,User></code> function. If
* that function returns null or throws an exception, a fallback guest factory function will be invoked to create
* a 'guest' User instance. Finally, if the fallback guest factory function itself fails or returns null, a suitable
* simple guest {@code User} instance will be returned.
* <p>This implementation never returns null or propagates exceptions to ensure that a User account instance is
* always accessible to the caller to help eliminate null-pointer exceptions in user/security-related code.</p>
* <p>Any exceptions thrown when invoking the delegate/fallback functions will be logged as {@code warn} statements
* to help with troubleshooting.</p>
*
* @since 0.1.0
*/
public class GuestFallbackUserFactory implements Function<HttpServletRequest, User> {
private static final Logger log = LoggerFactory.getLogger(GuestFallbackUserFactory.class);
private final Function<HttpServletRequest, User> delegate;
private final Function<HttpServletRequest, User> guestFallback;
public GuestFallbackUserFactory(Function<HttpServletRequest, User> delegate,
Function<HttpServletRequest, User> guestFallback) {
Assert.notNull(delegate, "delegate function cannot be null");
Assert.notNull(guestFallback, "guestFallback function cannot be null");
this.delegate = delegate;
this.guestFallback = guestFallback;
}
@Override
public User apply(HttpServletRequest request) {
User user = null;
try {
user = delegate.apply(request);
} catch (Exception e) {
log.warn("Could not create a User instance based on the inbound HttpServletRequest via delegate " +
"function. Attempting to acquire a guest user instance instead...", e);
}
if (user == null) {
try {
user = guestFallback.apply(request);
} catch (Exception e) {
log.warn("Could not create a guest User instance via fallback guest creation function. " +
"Defaulting to a simple guest User instance...", e);
}
}
if (user == null) {
user = new UserBuilder().setGivenName("Guest").setAuthenticated(false).build();
}
assert user != null;
return user;
}
}
| 39.258824 | 117 | 0.691639 |
84fec1675e1a900ba6e9f08cdde7b0f03ce04b6f
| 16,607 |
// -*- mode: java; c-basic-offset: 2; -*-
// Copyright 2018 MIT, All rights reserved
// Released under the Apache License, Version 2.0
// http://www.apache.org/licenses/LICENSE-2.0
package com.google.appinventor.components.runtime.util;
import android.content.Context;
import android.util.Log;
import com.google.appinventor.components.common.YaVersion;
import com.google.appinventor.components.runtime.ReplForm;
import com.google.appinventor.components.runtime.util.AsynchUtil;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
import java.nio.charset.CharacterCodingException;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;
import java.util.TreeSet;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.webrtc.DataChannel.Buffer;
import org.webrtc.DataChannel;
import org.webrtc.IceCandidate;
import org.webrtc.MediaConstraints;
import org.webrtc.MediaStream;
import org.webrtc.PeerConnection.ContinualGatheringPolicy;
import org.webrtc.PeerConnection.IceConnectionState;
import org.webrtc.PeerConnection.IceGatheringState;
import org.webrtc.PeerConnection.Observer;
import org.webrtc.PeerConnection.RTCConfiguration;
import org.webrtc.PeerConnection.SignalingState;
import org.webrtc.PeerConnection;
import org.webrtc.PeerConnectionFactory;
import org.webrtc.RtpReceiver;
import org.webrtc.SdpObserver;
import org.webrtc.SessionDescription;
public class WebRTCNativeMgr {
private static final boolean DEBUG = true;
private static final String LOG_TAG = "AppInvWebRTC";
private static final CharsetDecoder utf8Decoder = Charset.forName("UTF-8").newDecoder();
private ReplForm form;
private PeerConnection peerConnection;
/* We need to keep track of whether or not we have processed an element */
/* Received from the rendezvous server. */
private TreeSet<String> seenNonces = new TreeSet();
private boolean haveOffer = false;
private String rCode;
private volatile boolean keepPolling = true;
private volatile boolean haveLocalDescription = false;
private boolean first = true; // This is used for logging in the Rendezvous server
private Random random = new Random();
private DataChannel dataChannel = null;
private String rendezvousServer = null; // Primary (first level) Rendezvous server
private String rendezvousServer2 = null; // Second level (webrtc rendezvous) Rendezvous server
private List<PeerConnection.IceServer> iceServers = new ArrayList();
Timer timer = new Timer();
/* Callback that handles sdp offer/answers */
SdpObserver sdpObserver = new SdpObserver() {
public void onCreateFailure(String str) {
if (DEBUG) {
Log.d(LOG_TAG, "onCreateFailure: " + str);
}
}
public void onCreateSuccess(SessionDescription sessionDescription) {
try {
if (DEBUG) {
Log.d(LOG_TAG, "sdp.type = " + sessionDescription.type.canonicalForm());
Log.d(LOG_TAG, "sdp.description = " + sessionDescription.description);
}
DataChannel.Init init = new DataChannel.Init();
if (sessionDescription.type == SessionDescription.Type.OFFER) {
if (DEBUG) {
Log.d(LOG_TAG, "Got offer, about to set remote description (again?)");
}
peerConnection.setRemoteDescription(sdpObserver, sessionDescription);
} else if (sessionDescription.type == SessionDescription.Type.ANSWER) {
if (DEBUG) {
Log.d(LOG_TAG, "onCreateSuccess: type = ANSWER");
}
peerConnection.setLocalDescription(sdpObserver, sessionDescription);
haveLocalDescription = true;
/* Send to peer */
JSONObject offer = new JSONObject();
offer.put("type", "answer");
offer.put("sdp", sessionDescription.description);
JSONObject response = new JSONObject();
response.put("offer", offer);
sendRendezvous(response);
}
} catch (Exception e) {
Log.e(LOG_TAG, "Exception during onCreateSuccess", e);
}
}
public void onSetFailure(String str) {
}
public void onSetSuccess() {
}
};
/* callback that handles iceCandidate negotiation */
Observer observer = new Observer() {
public void onAddStream(MediaStream mediaStream) {
}
public void onAddTrack(RtpReceiver rtpReceiver, MediaStream[] mediaStreamArr) {
}
public void onDataChannel(DataChannel dataChannel) {
if (DEBUG) {
Log.d(LOG_TAG, "Have Data Channel!");
Log.d(LOG_TAG, "v5");
}
WebRTCNativeMgr.this.dataChannel = dataChannel;
dataChannel.registerObserver(dataObserver);
keepPolling = false; // Turn off talking to the rendezvous server
timer.cancel();
if (DEBUG) {
Log.d(LOG_TAG, "Poller() Canceled");
}
seenNonces.clear();
}
public void onIceCandidate(IceCandidate iceCandidate) {
try {
if (DEBUG) {
Log.d(LOG_TAG, "IceCandidate = " + iceCandidate.toString());
if (iceCandidate.sdp == null) {
Log.d(LOG_TAG, "IceCandidate is null");
} else {
Log.d(LOG_TAG, "IceCandidateSDP = " + iceCandidate.sdp);
}
}
/* Send to Peer */
JSONObject response = new JSONObject();
response.put("nonce", random.nextInt(100000));
JSONObject jsonCandidate = new JSONObject();
jsonCandidate.put("candidate", iceCandidate.sdp);
jsonCandidate.put("sdpMLineIndex", iceCandidate.sdpMLineIndex);
jsonCandidate.put("sdpMid", iceCandidate.sdpMid);
response.put("candidate", jsonCandidate);
sendRendezvous(response);
} catch (Exception e) {
Log.e(LOG_TAG, "Exception during onIceCandidate", e);
}
}
public void onIceCandidatesRemoved(IceCandidate[] iceCandidateArr) {
}
public void onIceConnectionChange(IceConnectionState iceConnectionState) {
}
public void onIceConnectionReceivingChange(boolean z) {
}
public void onIceGatheringChange(IceGatheringState iceGatheringState) {
if (DEBUG) {
Log.d(LOG_TAG, "onIceGatheringChange: iceGatheringState = " + iceGatheringState);
}
}
public void onRemoveStream(MediaStream mediaStream) {
}
public void onRenegotiationNeeded() {
}
public void onSignalingChange(SignalingState signalingState) {
if (DEBUG) {
Log.d(LOG_TAG, "onSignalingChange: signalingState = " + signalingState);
}
}
};
/* Callback to process incoming data from the browser */
DataChannel.Observer dataObserver = new DataChannel.Observer() {
public void onBufferedAmountChange(long j) {
}
public void onMessage(Buffer buffer) {
String input;
try {
input = utf8Decoder.decode(buffer.data).toString();
} catch (CharacterCodingException e) {
Log.e(LOG_TAG, "onMessage decoder error", e);
return;
}
if (DEBUG) {
Log.d(LOG_TAG, "onMessage: received: " + input);
}
form.evalScheme(input);
}
public void onStateChange() {
}
};
public WebRTCNativeMgr(String rendezvousServer, String rendezvousResult) {
this.rendezvousServer = rendezvousServer;
if (rendezvousResult.isEmpty() || rendezvousResult.startsWith("OK")) {
/* Provide a default when the rendezvous server doesn't provide one */
rendezvousResult = "{\"rendezvous2\" : \"" + YaVersion.RENDEZVOUS_SERVER + "\"," +
"\"iceservers\" : " +
"[{ \"server\" : \"turn:turn.appinventor.mit.edu:3478\"," +
"\"username\" : \"oh\"," +
"\"password\" : \"boy\"}]}";
}
try {
JSONObject resultJson = new JSONObject(rendezvousResult);
this.rendezvousServer2 = resultJson.getString("rendezvous2");
JSONArray iceServerArray = resultJson.getJSONArray("iceservers");
this.iceServers = new ArrayList(iceServerArray.length());
for (int i = 0; i < iceServerArray.length(); i++) {
JSONObject jsonServer = iceServerArray.getJSONObject(i);
PeerConnection.IceServer.Builder builder = PeerConnection.IceServer.builder(jsonServer.getString("server"));
if (DEBUG) {
Log.d(LOG_TAG, "Adding iceServer = " + jsonServer.getString("server"));
}
if (jsonServer.has("username")) {
builder.setUsername(jsonServer.getString("username"));
}
if (jsonServer.has("password")) {
builder.setPassword(jsonServer.getString("password"));
}
this.iceServers.add(builder.createIceServer());
}
} catch (JSONException e) {
Log.e(LOG_TAG, "parsing iceServers:", e);
}
}
public void initiate(ReplForm form, Context context, String code) {
this.form = form;
rCode = code;
/* Initialize WebRTC globally */
PeerConnectionFactory.initializeAndroidGlobals(context, false);
/* Setup factory options */
PeerConnectionFactory.Options options = new PeerConnectionFactory.Options();
/* Create the factory */
PeerConnectionFactory factory = new PeerConnectionFactory(options);
/* Create the peer connection using the iceServers we received in the constructor */
RTCConfiguration rtcConfig = new RTCConfiguration(iceServers);
rtcConfig.continualGatheringPolicy = ContinualGatheringPolicy.GATHER_CONTINUALLY;
peerConnection = factory.createPeerConnection(rtcConfig, new MediaConstraints(),
observer);
timer.schedule(new TimerTask() {
@Override
public void run() {
Poller();
}
}, 0, 1000); // Start the Poller now and then every second
}
/*
* startPolling: poll the Rendezvous server looking for the information via the
* the provided code with "-s" appended (because we are the receiver, replmgr.js
* is in the sender roll.
*/
private void Poller() {
try {
if (!keepPolling) {
return;
}
if (DEBUG) {
Log.d(LOG_TAG, "Poller() Called");
Log.d(LOG_TAG, "Poller: rendezvousServer2 = " + rendezvousServer2);
}
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet("http://" + rendezvousServer2 + "/rendezvous2/" + rCode + "-s");
HttpResponse response = client.execute(request);
StringBuilder sb = new StringBuilder();
BufferedReader rd = null;
try {
rd = new BufferedReader
(new InputStreamReader(
response.getEntity().getContent()));
String line = "";
while ((line = rd.readLine()) != null) {
sb.append(line);
}
} finally {
if (rd != null) {
rd.close();
}
}
if (!keepPolling) {
if (DEBUG) {
Log.d(LOG_TAG, "keepPolling is false, we're done!");
}
return;
}
String responseText = sb.toString();
if (DEBUG) {
Log.d(LOG_TAG, "response = " + responseText);
}
if (responseText.equals("")) {
if (DEBUG) {
Log.d(LOG_TAG, "Received an empty response");
}
// Empty Response
return;
}
JSONArray jsonArray = new JSONArray(responseText);
if (DEBUG) {
Log.d(LOG_TAG, "jsonArray.length() = " + jsonArray.length());
}
int i = 0;
while (i < jsonArray.length()) {
if (DEBUG) {
Log.d(LOG_TAG, "i = " + i);
Log.d(LOG_TAG, "element = " + jsonArray.optString(i));
}
JSONObject element = (JSONObject) jsonArray.get(i);
if (!haveOffer) {
if (!element.has("offer")) {
i++;
continue;
}
JSONObject offer = (JSONObject) element.get("offer");
String sdp = offer.optString("sdp");
String type = offer.optString("type");
haveOffer = true;
if (DEBUG) {
Log.d(LOG_TAG, "sdb = " + sdp);
Log.d(LOG_TAG, "type = " + type);
Log.d(LOG_TAG, "About to set remote offer");
}
if (DEBUG) {
Log.d(LOG_TAG, "Got offer, about to set remote description (maincode)");
}
peerConnection.setRemoteDescription(sdpObserver,
new SessionDescription(SessionDescription.Type.OFFER, sdp));
peerConnection.createAnswer(sdpObserver, new MediaConstraints());
if (DEBUG) {
Log.d(LOG_TAG, "createAnswer returned");
}
i = -1;
} else if (element.has("nonce")) {
if (!haveLocalDescription) {
if (DEBUG) {
Log.d(LOG_TAG, "Incoming candidate before local description set, punting");
}
return;
}
if (element.has("offer")) { // Only take in the offer once!
i++;
if (DEBUG) {
Log.d(LOG_TAG, "skipping offer, already processed");
}
continue;
}
if (element.isNull("candidate")) {
i++;
// do nothing on a received null
continue;
}
String nonce = element.optString("nonce");
JSONObject candidate = (JSONObject) element.get("candidate");
String sdpcandidate = candidate.optString("candidate");
String sdpMid = candidate.optString("sdpMid");
int sdpMLineIndex = candidate.optInt("sdpMLineIndex");
if (!seenNonces.contains(nonce)) {
seenNonces.add(nonce);
if (DEBUG) {
Log.d(LOG_TAG, "new nonce, about to add candidate!");
Log.d(LOG_TAG, "candidate = " + sdpcandidate);
}
IceCandidate iceCandidate = new IceCandidate(sdpMid, sdpMLineIndex, sdpcandidate);
peerConnection.addIceCandidate(iceCandidate);
if (DEBUG) {
Log.d(LOG_TAG, "addIceCandidate returned");
}
}
}
i++;
}
if (DEBUG) {
Log.d(LOG_TAG, "exited loop");
}
} catch (IOException e) {
Log.e(LOG_TAG, "Caught IOException: " + e.toString(), e);
} catch (JSONException e) {
Log.e(LOG_TAG, "Caught JSONException: " + e.toString(), e);
} catch (Exception e) {
Log.e(LOG_TAG, "Caught Exception: " + e.toString(), e);
}
}
private void sendRendezvous(final JSONObject data) {
AsynchUtil.runAsynchronously(new Runnable() {
@Override
public void run() {
try {
data.put("first", first);
data.put("webrtc", true);
data.put("key", rCode + "-r");
if (first) {
first = false;
data.put("apiversion", SdkLevel.getLevel());
}
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost("http://" + rendezvousServer2 + "/rendezvous2/");
try {
if (DEBUG) {
Log.d(LOG_TAG, "About to send = " + data.toString());
}
post.setEntity(new StringEntity(data.toString()));
client.execute(post);
} catch (IOException e) {
Log.e(LOG_TAG, "sendRedezvous IOException", e);
}
} catch (Exception e) {
Log.e(LOG_TAG, "Exception in sendRendezvous", e);
}
}
});
}
public void send(String output) {
try {
if (dataChannel == null) {
Log.w(LOG_TAG, "No Data Channel in Send");
return;
}
ByteBuffer bbuffer = ByteBuffer.wrap(output.getBytes("UTF-8"));
Buffer buffer = new Buffer(bbuffer, false); // false = not binary
dataChannel.send(buffer);
} catch (UnsupportedEncodingException e) {
Log.e(LOG_TAG, "While encoding data to send to companion", e);
}
}
}
| 34.597917 | 116 | 0.615222 |
74f2ec8909038faabe20edb6d8448becc258d3a4
| 4,832 |
/*
* Copyright (C) 2013-2015 RoboVM AB
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.bugvm.apple.corefoundation;
/*<imports>*/
import java.io.*;
import java.nio.*;
import java.util.*;
import com.bugvm.objc.*;
import com.bugvm.objc.annotation.*;
import com.bugvm.objc.block.*;
import com.bugvm.rt.*;
import com.bugvm.rt.annotation.*;
import com.bugvm.rt.bro.*;
import com.bugvm.rt.bro.annotation.*;
import com.bugvm.rt.bro.ptr.*;
import com.bugvm.apple.foundation.*;
import com.bugvm.apple.dispatch.*;
import com.bugvm.apple.coreservices.*;
import com.bugvm.apple.coremedia.*;
import com.bugvm.apple.uikit.*;
import com.bugvm.apple.coretext.*;
/*</imports>*/
/*<javadoc>*/
/*</javadoc>*/
/*<annotations>*/@Library("CoreFoundation")/*</annotations>*/
/*<visibility>*/public/*</visibility>*/ class /*<name>*/CFStringTokenizer/*</name>*/
extends /*<extends>*/CFType/*</extends>*/
/*<implements>*//*</implements>*/ {
/*<ptr>*/public static class CFStringTokenizerPtr extends Ptr<CFStringTokenizer, CFStringTokenizerPtr> {}/*</ptr>*/
/*<bind>*/static { Bro.bind(CFStringTokenizer.class); }/*</bind>*/
/*<constants>*//*</constants>*/
/*<constructors>*/
protected CFStringTokenizer() {}
/*</constructors>*/
/*<properties>*//*</properties>*/
/*<members>*//*</members>*/
/**
* @since Available in iOS 3.0 and later.
*/
public static CFStringTokenizer create(String string, @ByVal CFRange range, CFStringTokenizerUnitOptions options, CFLocale locale) {
return create(null, string, range, options, locale);
}
/**
* @since Available in iOS 3.0 and later.
*/
public CFRange[] getCurrentSubTokens(long maxRanges, List<String> derivedSubTokens) {
CFRange.CFRangePtr ptr = new CFRange.CFRangePtr();
long length = getCurrentSubTokens(ptr, maxRanges, derivedSubTokens);
return ptr.get().toArray((int)length);
}
/*<methods>*/
/**
* @since Available in iOS 3.0 and later.
*/
@Bridge(symbol="CFStringTokenizerCopyBestStringLanguage", optional=true)
public static native @com.bugvm.rt.bro.annotation.Marshaler(CFString.AsStringNoRetainMarshaler.class) String getBestStringLanguage(String string, @ByVal CFRange range);
/**
* @since Available in iOS 3.0 and later.
*/
@Bridge(symbol="CFStringTokenizerGetTypeID", optional=true)
public static native @MachineSizedUInt long getClassTypeID();
/**
* @since Available in iOS 3.0 and later.
*/
@Bridge(symbol="CFStringTokenizerCreate", optional=true)
public static native @com.bugvm.rt.bro.annotation.Marshaler(CFType.NoRetainMarshaler.class) CFStringTokenizer create(CFAllocator alloc, String string, @ByVal CFRange range, CFStringTokenizerUnitOptions options, CFLocale locale);
/**
* @since Available in iOS 3.0 and later.
*/
@Bridge(symbol="CFStringTokenizerSetString", optional=true)
public native void setString(String string, @ByVal CFRange range);
/**
* @since Available in iOS 3.0 and later.
*/
@Bridge(symbol="CFStringTokenizerGoToTokenAtIndex", optional=true)
public native CFStringTokenizerTokenType goToToken(@MachineSizedSInt long index);
/**
* @since Available in iOS 3.0 and later.
*/
@Bridge(symbol="CFStringTokenizerAdvanceToNextToken", optional=true)
public native CFStringTokenizerTokenType advanceToNextToken();
/**
* @since Available in iOS 3.0 and later.
*/
@Bridge(symbol="CFStringTokenizerGetCurrentTokenRange", optional=true)
public native @ByVal CFRange getCurrentTokenRange();
/**
* @since Available in iOS 3.0 and later.
*/
@Bridge(symbol="CFStringTokenizerCopyCurrentTokenAttribute", optional=true)
public native @com.bugvm.rt.bro.annotation.Marshaler(CFType.NoRetainMarshaler.class) CFType getCurrentTokenAttribute(CFStringTokenizerUnitOptions attribute);
/**
* @since Available in iOS 3.0 and later.
*/
@Bridge(symbol="CFStringTokenizerGetCurrentSubTokens", optional=true)
protected native @MachineSizedSInt long getCurrentSubTokens(CFRange.CFRangePtr ranges, @MachineSizedSInt long maxRangeLength, @com.bugvm.rt.bro.annotation.Marshaler(CFArray.AsStringListMarshaler.class) List<String> derivedSubTokens);
/*</methods>*/
}
| 42.017391 | 237 | 0.708609 |
8affcafc78b40b25fd7ba06d688e183aa0bfe4b4
| 31,054 |
/*
* Copyright [2007] [University Corporation for Advanced Internet Development, Inc.]
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.opensaml.xml.security;
import java.math.BigInteger;
import java.security.GeneralSecurityException;
import java.security.Key;
import java.security.KeyException;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.cert.X509Certificate;
import java.security.interfaces.DSAParams;
import java.security.interfaces.DSAPrivateKey;
import java.security.interfaces.RSAPrivateCrtKey;
import java.security.spec.DSAPublicKeySpec;
import java.security.spec.RSAPublicKeySpec;
import java.util.HashSet;
import java.util.Set;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import org.apache.commons.ssl.PKCS8Key;
import org.apache.xml.security.Init;
import org.apache.xml.security.algorithms.JCEMapper;
import org.opensaml.xml.Configuration;
import org.opensaml.xml.encryption.Encrypter;
import org.opensaml.xml.encryption.EncryptionParameters;
import org.opensaml.xml.encryption.KeyEncryptionParameters;
import org.opensaml.xml.security.credential.BasicCredential;
import org.opensaml.xml.security.credential.Credential;
import org.opensaml.xml.security.keyinfo.KeyInfoGenerator;
import org.opensaml.xml.security.keyinfo.KeyInfoGeneratorFactory;
import org.opensaml.xml.security.keyinfo.NamedKeyInfoGeneratorManager;
import org.opensaml.xml.security.x509.BasicX509Credential;
import org.opensaml.xml.signature.KeyInfo;
import org.opensaml.xml.signature.Signature;
import org.opensaml.xml.signature.SignatureConstants;
import org.opensaml.xml.util.DatatypeHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Helper methods for security-related requirements.
*/
public final class SecurityHelper {
/** Class logger. */
private static Logger log = LoggerFactory.getLogger(SecurityHelper.class);
/** Additional algorithm URI's which imply RSA keys. */
private static Set<String> rsaAlgorithmURIs;
/** Additional algorithm URI's which imply DSA keys. */
private static Set<String> dsaAlgorithmURIs;
/** Additional algorithm URI's which imply ECDSA keys. */
private static Set<String> ecdsaAlgorithmURIs;
/** Constructor. */
private SecurityHelper() {
}
/**
* Get the Java security JCA/JCE algorithm identifier associated with an algorithm URI.
*
* @param algorithmURI the algorithm URI to evaluate
* @return the Java algorithm identifier, or null if the mapping is unavailable or indeterminable from the URI
*/
public static String getAlgorithmIDFromURI(String algorithmURI) {
return DatatypeHelper.safeTrimOrNullString(JCEMapper.translateURItoJCEID(algorithmURI));
}
/**
* Check whether the signature method algorithm URI indicates HMAC.
*
* @param signatureAlgorithm the signature method algorithm URI
* @return true if URI indicates HMAC, false otherwise
*/
public static boolean isHMAC(String signatureAlgorithm) {
String algoClass = DatatypeHelper.safeTrimOrNullString(JCEMapper.getAlgorithmClassFromURI(signatureAlgorithm));
return ApacheXMLSecurityConstants.ALGO_CLASS_MAC.equals(algoClass);
}
/**
* Get the Java security JCA/JCE key algorithm specifier associated with an algorithm URI.
*
* @param algorithmURI the algorithm URI to evaluate
* @return the Java key algorithm specifier, or null if the mapping is unavailable or indeterminable from the URI
*/
public static String getKeyAlgorithmFromURI(String algorithmURI) {
// The default Apache config file currently only includes the key algorithm for
// the block ciphers and key wrap URI's. Note: could use a custom config file which contains others.
String apacheValue = DatatypeHelper.safeTrimOrNullString(JCEMapper.getJCEKeyAlgorithmFromURI(algorithmURI));
if (apacheValue != null) {
return apacheValue;
}
// HMAC uses any symmetric key, so there is no implied specific key algorithm
if (isHMAC(algorithmURI)) {
return null;
}
// As a last ditch fallback, check some known common and supported ones.
if (rsaAlgorithmURIs.contains(algorithmURI)) {
return "RSA";
}
if (dsaAlgorithmURIs.contains(algorithmURI)) {
return "DSA";
}
if (ecdsaAlgorithmURIs.contains(algorithmURI)) {
return "ECDSA";
}
return null;
}
/**
* Get the length of the key indicated by the algorithm URI, if applicable and available.
*
* @param algorithmURI the algorithm URI to evaluate
* @return the length of the key indicated by the algorithm URI, or null if the length is either unavailable or
* indeterminable from the URI
*/
public static Integer getKeyLengthFromURI(String algorithmURI) {
String algoClass = DatatypeHelper.safeTrimOrNullString(JCEMapper.getAlgorithmClassFromURI(algorithmURI));
if (ApacheXMLSecurityConstants.ALGO_CLASS_BLOCK_ENCRYPTION.equals(algoClass)
|| ApacheXMLSecurityConstants.ALGO_CLASS_SYMMETRIC_KEY_WRAP.equals(algoClass)) {
try {
int keyLength = JCEMapper.getKeyLengthFromURI(algorithmURI);
return new Integer(keyLength);
} catch (NumberFormatException e) {
log.warn("XML Security config contained invalid key length value for algorithm URI: " + algorithmURI);
}
}
log.info("Mapping from algorithm URI {} to key length not available", algorithmURI);
return null;
}
/**
* Generates a random Java JCE symmetric Key object from the specified XML Encryption algorithm URI.
*
* @param algoURI The XML Encryption algorithm URI
* @return a randomly-generated symmetric Key
* @throws NoSuchAlgorithmException thrown if the specified algorithm is invalid
* @throws KeyException thrown if the length of the key to generate could not be determined
*/
public static SecretKey generateSymmetricKey(String algoURI) throws NoSuchAlgorithmException, KeyException {
String jceAlgorithmName = getKeyAlgorithmFromURI(algoURI);
if (DatatypeHelper.isEmpty(jceAlgorithmName)) {
log.error("Mapping from algorithm URI '" + algoURI
+ "' to key algorithm not available, key generation failed");
throw new NoSuchAlgorithmException("Algorithm URI'" + algoURI + "' is invalid for key generation");
}
Integer keyLength = getKeyLengthFromURI(algoURI);
if (keyLength == null) {
log.error("Key length could not be determined from algorithm URI, can't generate key");
throw new KeyException("Key length not determinable from algorithm URI, could not generate new key");
}
KeyGenerator keyGenerator = KeyGenerator.getInstance(jceAlgorithmName);
keyGenerator.init(keyLength);
return keyGenerator.generateKey();
}
/**
* Extract the encryption key from the credential.
*
* @param credential the credential containing the encryption key
* @return the encryption key (either a public key or a secret (symmetric) key
*/
public static Key extractEncryptionKey(Credential credential) {
if (credential == null) {
return null;
}
if (credential.getPublicKey() != null) {
return credential.getPublicKey();
} else {
return credential.getSecretKey();
}
}
/**
* Extract the decryption key from the credential.
*
* @param credential the credential containing the decryption key
* @return the decryption key (either a private key or a secret (symmetric) key
*/
public static Key extractDecryptionKey(Credential credential) {
if (credential == null) {
return null;
}
if (credential.getPrivateKey() != null) {
return credential.getPrivateKey();
} else {
return credential.getSecretKey();
}
}
/**
* Extract the signing key from the credential.
*
* @param credential the credential containing the signing key
* @return the signing key (either a private key or a secret (symmetric) key
*/
public static Key extractSigningKey(Credential credential) {
if (credential == null) {
return null;
}
if (credential.getPrivateKey() != null) {
return credential.getPrivateKey();
} else {
return credential.getSecretKey();
}
}
/**
* Extract the verification key from the credential.
*
* @param credential the credential containing the verification key
* @return the verification key (either a public key or a secret (symmetric) key
*/
public static Key extractVerificationKey(Credential credential) {
if (credential == null) {
return null;
}
if (credential.getPublicKey() != null) {
return credential.getPublicKey();
} else {
return credential.getSecretKey();
}
}
/**
* Get the key length in bits of the specified key.
*
* @param key the key to evaluate
* @return length of the key in bits, or null if the length can not be determined
*/
public static Integer getKeyLength(Key key) {
// TODO investigate techniques (and use cases) to determine length in other cases,
// e.g. RSA and DSA keys, and non-RAW format symmetric keys
if (key instanceof SecretKey && "RAW".equals(key.getFormat())) {
return key.getEncoded().length * 8;
}
log.debug("Unable to determine length in bits of specified Key instance");
return null;
}
/**
* Get a simple, minimal credential containing a secret (symmetric) key.
*
* @param secretKey the symmetric key to wrap
* @return a credential containing the secret key specified
*/
public static BasicCredential getSimpleCredential(SecretKey secretKey) {
if (secretKey == null) {
throw new IllegalArgumentException("A secret key is required");
}
BasicCredential cred = new BasicCredential();
cred.setSecretKey(secretKey);
return cred;
}
/**
* Get a simple, minimal credential containing a public key, and optionally a private key.
*
* @param publicKey the public key to wrap
* @param privateKey the private key to wrap, which may be null
* @return a credential containing the key(s) specified
*/
public static BasicCredential getSimpleCredential(PublicKey publicKey, PrivateKey privateKey) {
if (publicKey == null) {
throw new IllegalArgumentException("A public key is required");
}
BasicCredential cred = new BasicCredential();
cred.setPublicKey(publicKey);
cred.setPrivateKey(privateKey);
return cred;
}
/**
* Get a simple, minimal credential containing an end-entity X.509 certificate, and optionally a private key.
*
* @param cert the end-entity certificate to wrap
* @param privateKey the private key to wrap, which may be null
* @return a credential containing the certificate and key specified
*/
public static BasicX509Credential getSimpleCredential(X509Certificate cert, PrivateKey privateKey) {
if (cert == null) {
throw new IllegalArgumentException("A certificate is required");
}
BasicX509Credential cred = new BasicX509Credential();
cred.setEntityCertificate(cert);
cred.setPrivateKey(privateKey);
return cred;
}
/**
* Decodes secret keys in DER and PEM format.
*
* This method is not yet implemented.
*
* @param key secret key
* @param password password if the key is encrypted or null if not
*
* @return the decoded key
*
* @throws KeyException thrown if the key can not be decoded
*/
public static SecretKey decodeSecretKey(byte[] key, char[] password) throws KeyException {
// TODO
throw new UnsupportedOperationException("This method is not yet supported");
}
/**
* Decodes RSA/DSA public keys in DER or PEM formats.
*
* @param key encoded key
* @param password password if the key is encrypted or null if not
*
* @return deocded key
*
* @throws KeyException thrown if the key can not be decoded
*/
public static PublicKey decodePublicKey(byte[] key, char[] password) throws KeyException {
// TODO
throw new UnsupportedOperationException("This method is not yet supported");
}
/**
* Derives the public key from either a DSA or RSA private key.
*
* @param key the private key to derive the public key from
*
* @return the derived public key
*
* @throws KeyException thrown if the given private key is not a DSA or RSA key or there is a problem generating the
* public key
*/
public static PublicKey derivePublicKey(PrivateKey key) throws KeyException {
KeyFactory factory;
if (key instanceof DSAPrivateKey) {
DSAPrivateKey dsaKey = (DSAPrivateKey) key;
DSAParams keyParams = dsaKey.getParams();
BigInteger y = keyParams.getQ().modPow(dsaKey.getX(), keyParams.getP());
DSAPublicKeySpec pubKeySpec = new DSAPublicKeySpec(y, keyParams.getP(), keyParams.getQ(), keyParams.getG());
try {
factory = KeyFactory.getInstance("DSA");
return factory.generatePublic(pubKeySpec);
} catch (GeneralSecurityException e) {
throw new KeyException("Unable to derive public key from DSA private key", e);
}
} else if (key instanceof RSAPrivateCrtKey) {
RSAPrivateCrtKey rsaKey = (RSAPrivateCrtKey) key;
RSAPublicKeySpec pubKeySpec = new RSAPublicKeySpec(rsaKey.getModulus(), rsaKey.getPublicExponent());
try {
factory = KeyFactory.getInstance("RSA");
return factory.generatePublic(pubKeySpec);
} catch (GeneralSecurityException e) {
throw new KeyException("Unable to derive public key from RSA private key", e);
}
} else {
throw new KeyException("Private key was not a DSA or RSA key");
}
}
/**
* Decodes RSA/DSA private keys in DER, PEM, or PKCS#8 (encrypted or unencrypted) formats.
*
* @param key encoded key
* @param password decryption password or null if the key is not encrypted
*
* @return deocded private key
*
* @throws KeyException thrown if the key can not be decoded
*/
public static PrivateKey decodePrivateKey(byte[] key, char[] password) throws KeyException {
try {
PKCS8Key deocodedKey = new PKCS8Key(key, password);
return deocodedKey.getPrivateKey();
} catch (GeneralSecurityException e) {
throw new KeyException("Unable to decode private key", e);
}
}
/**
* Prepare a {@link Signature} with necessary additional information prior to signing.
*
* <p>
* <strong>NOTE:</strong>Since this operation modifies the specified Signature object, it should be called
* <strong>prior</strong> to marshalling the Signature object.
* </p>
*
* <p>
* The following Signature values will be added:
* <ul>
* <li>signature algorithm URI</li>
* <li>canonicalization algorithm URI</li>
* <li>HMAC output length (if applicable and a value is configured)</li>
* <li>a {@link KeyInfo} element representing the signing credential</li>
* </ul>
* </p>
*
* <p>Existing (non-null) values of these parameters on the specified signature
* will <strong>NOT</strong> be overwritten, however.</p>
*
* <p>
* All values are determined by the specified {@link SecurityConfiguration}. If a security configuration is not
* supplied, the global security configuration ({@link Configuration#getGlobalSecurityConfiguration()}) will be
* used.
* </p>
*
* <p>
* The signature algorithm URI and optional HMAC output length are derived from the signing credential.
* </p>
*
* <p>
* The KeyInfo to be generated is based on the {@link NamedKeyInfoGeneratorManager} defined in the security
* configuration, and is determined by the type of the signing credential and an optional KeyInfo generator manager
* name. If the latter is ommited, the default manager ({@link NamedKeyInfoGeneratorManager#getDefaultManager()})
* of the security configuration's named generator manager will be used.
* </p>
*
* @param signature the Signature to be updated
* @param signingCredential the credential with which the Signature will be computed
* @param config the SecurityConfiguration to use (may be null)
* @param keyInfoGenName the named KeyInfoGeneratorManager configuration to use (may be null)
* @throws SecurityException thrown if there is an error generating the KeyInfo from the signing credential
*/
public static void prepareSignatureParams(Signature signature, Credential signingCredential,
SecurityConfiguration config, String keyInfoGenName) throws SecurityException {
SecurityConfiguration secConfig;
if (config != null) {
secConfig = config;
} else {
secConfig = Configuration.getGlobalSecurityConfiguration();
}
// The algorithm URI is derived from the credential
String signAlgo = signature.getSignatureAlgorithm();
if (signAlgo == null) {
signAlgo = secConfig.getSignatureAlgorithmURI(signingCredential);
signature.setSignatureAlgorithm(signAlgo);
}
// If we're doing HMAC, set the output length
if (SecurityHelper.isHMAC(signAlgo)) {
if (signature.getHMACOutputLength() == null) {
signature.setHMACOutputLength(secConfig.getSignatureHMACOutputLength());
}
}
if (signature.getCanonicalizationAlgorithm() == null) {
signature.setCanonicalizationAlgorithm(secConfig.getSignatureCanonicalizationAlgorithm());
}
if (signature.getKeyInfo() == null) {
KeyInfoGenerator kiGenerator = getKeyInfoGenerator(signingCredential, secConfig, keyInfoGenName);
if (kiGenerator != null) {
try {
KeyInfo keyInfo = kiGenerator.generate(signingCredential);
signature.setKeyInfo(keyInfo);
} catch (SecurityException e) {
log.error("Error generating KeyInfo from credential", e);
throw e;
}
} else {
log.info("No factory for named KeyInfoGenerator {} was found for credential type {}", keyInfoGenName,
signingCredential.getCredentialType().getName());
log.info("No KeyInfo will be generated for Signature");
}
}
}
/**
* Build an instance of {@link EncryptionParameters} suitable for passing to an {@link Encrypter}.
*
* <p>
* The following parameter values will be added:
* <ul>
* <li>the encryption credential (optional)</li>
* <li>encryption algorithm URI</li>
* <li>an appropriate {@link KeyInfoGenerator} instance which will be used to generate a {@link KeyInfo} element
* from the encryption credential</li>
* </ul>
* </p>
*
* <p>
* All values are determined by the specified {@link SecurityConfiguration}. If a security configuration is not
* supplied, the global security configuration ({@link Configuration#getGlobalSecurityConfiguration()}) will be
* used.
* </p>
*
* <p>
* The encryption algorithm URI is derived from the optional supplied encryption credential. If omitted, the value
* of {@link SecurityConfiguration#getAutoGeneratedDataEncryptionKeyAlgorithmURI()} will be used.
* </p>
*
* <p>
* The KeyInfoGenerator to be used is based on the {@link NamedKeyInfoGeneratorManager} defined in the security
* configuration, and is determined by the type of the signing credential and an optional KeyInfo generator manager
* name. If the latter is ommited, the default manager ({@link NamedKeyInfoGeneratorManager#getDefaultManager()})
* of the security configuration's named generator manager will be used.
* </p>
*
* @param encryptionCredential the credential with which the data will be encrypted (may be null)
* @param config the SecurityConfiguration to use (may be null)
* @param keyInfoGenName the named KeyInfoGeneratorManager configuration to use (may be null)
* @return a new instance of EncryptionParameters
*/
public static EncryptionParameters buildDataEncryptionParams(Credential encryptionCredential,
SecurityConfiguration config, String keyInfoGenName) {
SecurityConfiguration secConfig;
if (config != null) {
secConfig = config;
} else {
secConfig = Configuration.getGlobalSecurityConfiguration();
}
EncryptionParameters encParams = new EncryptionParameters();
encParams.setEncryptionCredential(encryptionCredential);
if (encryptionCredential == null) {
encParams.setAlgorithm(secConfig.getAutoGeneratedDataEncryptionKeyAlgorithmURI());
} else {
encParams.setAlgorithm(secConfig.getDataEncryptionAlgorithmURI(encryptionCredential));
KeyInfoGenerator kiGenerator = getKeyInfoGenerator(encryptionCredential, secConfig, keyInfoGenName);
if (kiGenerator != null) {
encParams.setKeyInfoGenerator(kiGenerator);
} else {
log.info("No factory for named KeyInfoGenerator {} was found for credential type{}", keyInfoGenName,
encryptionCredential.getCredentialType().getName());
log.info("No KeyInfo will be generated for EncryptedData");
}
}
return encParams;
}
/**
* Build an instance of {@link KeyEncryptionParameters} suitable for passing to an {@link Encrypter}.
*
* <p>
* The following parameter values will be added:
* <ul>
* <li>the key encryption credential</li>
* <li>key transport encryption algorithm URI</li>
* <li>an appropriate {@link KeyInfoGenerator} instance which will be used to generate a {@link KeyInfo} element
* from the key encryption credential</li>
* <li>intended recipient of the resultant encrypted key (optional)</li>
* </ul>
* </p>
*
* <p>
* All values are determined by the specified {@link SecurityConfiguration}. If a security configuration is not
* supplied, the global security configuration ({@link Configuration#getGlobalSecurityConfiguration()}) will be
* used.
* </p>
*
* <p>
* The encryption algorithm URI is derived from the optional supplied encryption credential. If omitted, the value
* of {@link SecurityConfiguration#getAutoGeneratedDataEncryptionKeyAlgorithmURI()} will be used.
* </p>
*
* <p>
* The KeyInfoGenerator to be used is based on the {@link NamedKeyInfoGeneratorManager} defined in the security
* configuration, and is determined by the type of the signing credential and an optional KeyInfo generator manager
* name. If the latter is ommited, the default manager ({@link NamedKeyInfoGeneratorManager#getDefaultManager()})
* of the security configuration's named generator manager will be used.
* </p>
*
* @param encryptionCredential the credential with which the key will be encrypted
* @param wrappedKeyAlgorithm the JCA key algorithm name of the key to be encrypted (may be null)
* @param config the SecurityConfiguration to use (may be null)
* @param keyInfoGenName the named KeyInfoGeneratorManager configuration to use (may be null)
* @param recipient the intended recipient of the resultant encrypted key, typically the owner of the key encryption
* key (may be null)
* @return a new instance of KeyEncryptionParameters
* @throws SecurityException if encryption credential is not supplied
*
*/
public static KeyEncryptionParameters buildKeyEncryptionParams(Credential encryptionCredential,
String wrappedKeyAlgorithm, SecurityConfiguration config, String keyInfoGenName, String recipient)
throws SecurityException {
SecurityConfiguration secConfig;
if (config != null) {
secConfig = config;
} else {
secConfig = Configuration.getGlobalSecurityConfiguration();
}
KeyEncryptionParameters kekParams = new KeyEncryptionParameters();
kekParams.setEncryptionCredential(encryptionCredential);
if (encryptionCredential == null) {
throw new SecurityException("Key encryption credential may not be null");
}
kekParams.setAlgorithm(secConfig.getKeyTransportEncryptionAlgorithmURI(encryptionCredential,
wrappedKeyAlgorithm));
KeyInfoGenerator kiGenerator = getKeyInfoGenerator(encryptionCredential, secConfig, keyInfoGenName);
if (kiGenerator != null) {
kekParams.setKeyInfoGenerator(kiGenerator);
} else {
log.info("No factory for named KeyInfoGenerator {} was found for credential type {}", keyInfoGenName,
encryptionCredential.getCredentialType().getName());
log.info("No KeyInfo will be generated for EncryptedKey");
}
kekParams.setRecipient(recipient);
return kekParams;
}
/**
* Obtains a {@link KeyInfoGenerator} for the specified {@link Credential}.
*
* <p>
* The KeyInfoGenerator returned is based on the {@link NamedKeyInfoGeneratorManager} defined by the specified
* security configuration via {@link SecurityConfiguration#getKeyInfoGeneratorManager()}, and is determined by the
* type of the signing credential and an optional KeyInfo generator manager name. If the latter is ommited, the
* default manager ({@link NamedKeyInfoGeneratorManager#getDefaultManager()}) of the security configuration's
* named generator manager will be used.
* </p>
*
* <p>
* The generator is determined by the specified {@link SecurityConfiguration}. If a security configuration is not
* supplied, the global security configuration ({@link Configuration#getGlobalSecurityConfiguration()}) will be
* used.
* </p>
*
* @param credential the credential for which a generator is desired
* @param config the SecurityConfiguration to use (may be null)
* @param keyInfoGenName the named KeyInfoGeneratorManager configuration to use (may be null)
* @return a KeyInfoGenerator appropriate for the specified credential
*/
public static KeyInfoGenerator getKeyInfoGenerator(Credential credential, SecurityConfiguration config,
String keyInfoGenName) {
SecurityConfiguration secConfig;
if (config != null) {
secConfig = config;
} else {
secConfig = Configuration.getGlobalSecurityConfiguration();
}
NamedKeyInfoGeneratorManager kiMgr = secConfig.getKeyInfoGeneratorManager();
if (kiMgr != null) {
KeyInfoGeneratorFactory kiFactory = null;
if (DatatypeHelper.isEmpty(keyInfoGenName)) {
kiFactory = kiMgr.getDefaultManager().getFactory(credential);
} else {
kiFactory = kiMgr.getFactory(keyInfoGenName, credential);
}
if (kiFactory != null) {
return kiFactory.newInstance();
}
}
return null;
}
static {
// We use some Apache XML Security utility functions, so need to make sure library
// is initialized.
if (!Init.isInitialized()) {
Init.init();
}
// Additonal algorithm URI to JCA key algorithm mappins, beyond what is currently
// supplied in the Apache XML Security mapper config.
dsaAlgorithmURIs = new HashSet<String>();
dsaAlgorithmURIs.add(SignatureConstants.ALGO_ID_SIGNATURE_DSA);
ecdsaAlgorithmURIs = new HashSet<String>();
ecdsaAlgorithmURIs.add(SignatureConstants.ALGO_ID_SIGNATURE_ECDSA_SHA1);
rsaAlgorithmURIs = new HashSet<String>();
rsaAlgorithmURIs.add(SignatureConstants.ALGO_ID_SIGNATURE_RSA_SHA1);
rsaAlgorithmURIs.add(SignatureConstants.ALGO_ID_SIGNATURE_RSA_SHA256);
rsaAlgorithmURIs.add(SignatureConstants.ALGO_ID_SIGNATURE_RSA_SHA384);
rsaAlgorithmURIs.add(SignatureConstants.ALGO_ID_SIGNATURE_RSA_SHA512);
rsaAlgorithmURIs.add(SignatureConstants.ALGO_ID_SIGNATURE_RSA_SHA512);
rsaAlgorithmURIs.add(SignatureConstants.ALGO_ID_SIGNATURE_RSA_RIPEMD160);
rsaAlgorithmURIs.add(SignatureConstants.ALGO_ID_SIGNATURE_NOT_RECOMMENDED_RSA_MD5);
}
}
| 43.615169 | 121 | 0.654763 |
b02a70fe5ecc5aa28ceba36c1057249ac816bee3
| 1,890 |
/*
* 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.prestosql.plugin.koralium;
import io.prestosql.plugin.koralium.client.PrestoKoraliumClient;
import io.prestosql.spi.connector.ConnectorIndex;
import io.prestosql.spi.connector.ConnectorPageSource;
import io.prestosql.spi.connector.ConnectorSession;
import io.prestosql.spi.connector.RecordSet;
import java.util.List;
public class KoraliumConnectorIndex
implements ConnectorIndex
{
private final ConnectorSession session;
private final PrestoKoraliumClient client;
private final KoraliumIndexHandle indexHandle;
private final List<KoraliumColumnHandle> lookupSchema;
private final List<KoraliumColumnHandle> outputSchema;
public KoraliumConnectorIndex(
ConnectorSession session,
PrestoKoraliumClient client,
KoraliumIndexHandle indexHandle,
List<KoraliumColumnHandle> lookupSchema,
List<KoraliumColumnHandle> outputSchema)
{
this.session = session;
this.client = client;
this.indexHandle = indexHandle;
this.lookupSchema = lookupSchema;
this.outputSchema = outputSchema;
}
@Override
public ConnectorPageSource lookup(RecordSet recordSet)
{
return new KoraliumIndexPageSource(session, lookupSchema, outputSchema, client, indexHandle, recordSet);
}
}
| 35.660377 | 112 | 0.743915 |
d648c78ffbb513562fd13844571248f188de0472
| 2,320 |
package email.com.gmail.cosmoconsole.forge.photoniccraft.client.network;
import email.com.gmail.cosmoconsole.forge.photoniccraft.common.entity.EntityGammaEffect;
import email.com.gmail.cosmoconsole.forge.photoniccraft.util.PhotonicUtils;
import io.netty.buffer.ByteBuf;
import net.minecraft.client.Minecraft;
import net.minecraft.world.World;
import net.minecraftforge.fml.common.network.simpleimpl.IMessage;
import net.minecraftforge.fml.common.network.simpleimpl.IMessageHandler;
import net.minecraftforge.fml.common.network.simpleimpl.MessageContext;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
public class PhotonicGammaEffectPacket implements IMessage {
public static class Handler implements IMessageHandler<PhotonicGammaEffectPacket, IMessage> {
@Override
public IMessage onMessage(PhotonicGammaEffectPacket message, MessageContext ctx) {
World w = message.world;
if (w == null) {
w = getBackupWorld();
}
final World par2World = w;
final double x = message.x;
final double y = message.y;
final double z = message.z;
Minecraft.getMinecraft().addScheduledTask(new Runnable() {
@Override
public void run() {
EntityGammaEffect e2 = new EntityGammaEffect(par2World);
e2.setPositionAndRotation(x, y, z, 0.0f, 0.0f);
e2.setInitialTicks();
par2World.spawnEntity(e2);
}
});
return null;
}
@SideOnly(value = Side.CLIENT)
private World getBackupWorld() {
return Minecraft.getMinecraft().world;
}
}
private World world;
private double x;
private double y;
private double z;
public PhotonicGammaEffectPacket() {
this.world = null;
this.x = this.y = this.z = 0;
}
public PhotonicGammaEffectPacket(World world, double x, double y, double z) {
this.world = world;
this.x = x;
this.y = y;
this.z = z;
}
@Override
public void fromBytes(ByteBuf buf) {
this.world = PhotonicUtils.convertIntegerToWorld(buf.readInt());
this.x = buf.readDouble();
this.y = buf.readDouble();
this.z = buf.readDouble();
}
@Override
public void toBytes(ByteBuf buf) {
buf.writeInt(PhotonicUtils.convertWorldToInteger(world));
buf.writeDouble(x);
buf.writeDouble(y);
buf.writeDouble(z);
}
}
| 29.74359 | 95 | 0.717672 |
2d6c52cc858dbac3884a901c402535dd3797b4cb
| 1,174 |
package com.ace.security;
import java.util.Collection;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import com.ace.entity.User;
public class AdminUserDetails extends User implements UserDetails{
private String role;
public AdminUserDetails(User user,String role){
super(user);
this.role = role;
}
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
StringBuilder commaBuilder = new StringBuilder();
commaBuilder.append(role);
String authorities = commaBuilder.toString();
return AuthorityUtils.commaSeparatedStringToAuthorityList(authorities);
}
@Override
public String getUsername() {
return super.getLoginName();
}
@Override
public boolean isAccountNonExpired() {
return true;
}
@Override
public boolean isAccountNonLocked() {
return true;
}
@Override
public boolean isCredentialsNonExpired() {
return true;
}
@Override
public boolean isEnabled() {
return true;
}
@Override
public String getPassword() {
return super.getPassword();
}
}
| 19.898305 | 73 | 0.76661 |
56776714e44e59ac6909c0cbfe20ccbad236f448
| 332 |
package dev.liquidnetwork.liquidpractice.util.bootstrap;
import dev.liquidnetwork.liquidpractice.LiquidPractice;
import org.bukkit.event.Listener;
public class BootstrappedListener extends Bootstrapped implements Listener {
public BootstrappedListener(LiquidPractice LiquidPractice) {
super(LiquidPractice);
}
}
| 25.538462 | 76 | 0.810241 |
3f80e8e68dd183552925cbd772aeec255c2e9188
| 7,035 |
/*
* Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* @test
* @bug 6226610 6973030
* @run main/othervm B6226610
* @summary HTTP tunnel connections send user headers to proxy
*/
/* This class includes a proxy server that processes the HTTP CONNECT request,
* and validates that the request does not have the user defined header in it.
* The proxy server always returns 400 Bad Request so that the Http client
* will not try to proceed with the connection as there is no back end http server.
*/
import java.io.*;
import java.net.*;
import sun.net.www.MessageHeader;
public class B6226610 {
static HeaderCheckerProxyTunnelServer proxy;
public static void main(String[] args) throws Exception
{
proxy = new HeaderCheckerProxyTunnelServer();
proxy.start();
String hostname = InetAddress.getLocalHost().getHostName();
try {
URL u = new URL("https://" + hostname + "/");
System.out.println("Connecting to " + u);
InetSocketAddress proxyAddr = new InetSocketAddress(hostname, proxy.getLocalPort());
java.net.URLConnection c = u.openConnection(new Proxy(Proxy.Type.HTTP, proxyAddr));
/* I want this header to go to the destination server only, protected
* by SSL
*/
c.setRequestProperty("X-TestHeader", "value");
c.connect();
} catch (IOException e) {
if ( e.getMessage().equals("Unable to tunnel through proxy. Proxy returns \"HTTP/1.1 400 Bad Request\"") )
{
// OK. Proxy will always return 400 so that the main thread can terminate correctly.
}
else
System.out.println(e);
} finally {
if (proxy != null) proxy.shutdown();
}
if (HeaderCheckerProxyTunnelServer.failed)
throw new RuntimeException("Test failed; see output");
}
}
class HeaderCheckerProxyTunnelServer extends Thread
{
public static boolean failed = false;
private static ServerSocket ss = null;
// client requesting for a tunnel
private Socket clientSocket = null;
/*
* Origin server's address and port that the client
* wants to establish the tunnel for communication.
*/
private InetAddress serverInetAddr;
private int serverPort;
public HeaderCheckerProxyTunnelServer() throws IOException
{
if (ss == null) {
ss = new ServerSocket(0);
}
}
void shutdown() {
try { ss.close(); } catch (IOException e) {}
}
public void run()
{
try {
clientSocket = ss.accept();
processRequests();
} catch (IOException e) {
System.out.println("Proxy Failed: " + e);
e.printStackTrace();
try {
ss.close();
}
catch (IOException excep) {
System.out.println("ProxyServer close error: " + excep);
excep.printStackTrace();
}
}
}
/**
* Returns the port on which the proxy is accepting connections.
*/
public int getLocalPort() {
return ss.getLocalPort();
}
/*
* Processes the CONNECT request
*/
private void processRequests() throws IOException
{
InputStream in = clientSocket.getInputStream();
MessageHeader mheader = new MessageHeader(in);
String statusLine = mheader.getValue(0);
if (statusLine.startsWith("CONNECT")) {
// retrieve the host and port info from the status-line
retrieveConnectInfo(statusLine);
if (mheader.findValue("X-TestHeader") != null) {
System.out.println("Proxy should not receive user defined headers for tunneled requests");
failed = true;
}
// 6973030
String value;
if ((value = mheader.findValue("Proxy-Connection")) == null ||
!value.equals("keep-alive")) {
System.out.println("Proxy-Connection:keep-alive not being sent");
failed = true;
}
//This will allow the main thread to terminate without trying to perform the SSL handshake.
send400();
in.close();
clientSocket.close();
ss.close();
}
else {
System.out.println("proxy server: processes only "
+ "CONNECT method requests, recieved: "
+ statusLine);
}
}
private void send400() throws IOException
{
OutputStream out = clientSocket.getOutputStream();
PrintWriter pout = new PrintWriter(out);
pout.println("HTTP/1.1 400 Bad Request");
pout.println();
pout.flush();
}
private void restart() throws IOException {
(new Thread(this)).start();
}
/*
* This method retrieves the hostname and port of the destination
* that the connect request wants to establish a tunnel for
* communication.
* The input, connectStr is of the form:
* CONNECT server-name:server-port HTTP/1.x
*/
private void retrieveConnectInfo(String connectStr) throws IOException {
int starti;
int endi;
String connectInfo;
String serverName = null;
try {
starti = connectStr.indexOf(' ');
endi = connectStr.lastIndexOf(' ');
connectInfo = connectStr.substring(starti+1, endi).trim();
// retrieve server name and port
endi = connectInfo.indexOf(':');
serverName = connectInfo.substring(0, endi);
serverPort = Integer.parseInt(connectInfo.substring(endi+1));
} catch (Exception e) {
throw new IOException("Proxy recieved a request: "
+ connectStr);
}
serverInetAddr = InetAddress.getByName(serverName);
}
}
| 33.028169 | 118 | 0.604975 |
5a4c87709faa89d55b4716c22cfed87aa53d215f
| 2,404 |
package com.example.herosoft.springclouddemo.product.messages;
import com.alibaba.fastjson.JSONObject;
import com.example.herosoft.springclouddemo.common.domain.model.TxMessage;
import com.example.herosoft.springclouddemo.product.service.StockService;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.annotation.RocketMQTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.stream.annotation.EnableBinding;
import org.springframework.cloud.stream.annotation.StreamListener;
import org.springframework.cloud.stream.messaging.Sink;
import org.springframework.messaging.Message;
import org.springframework.stereotype.Component;
/*RocketMQMessageListener注解版本 - 未调通
@Component
@Slf4j
@RocketMQMessageListener(consumerGroup ="tx-order-consumer-group",topic = "topic-txmsg")
public class StockTxMessageConsumer implements RocketMQListener<Message> {
@Autowired
private StockService stockService;
@Override
public void onMessage(Message message) {
TxMessage txMessage = this.getTxMessage(message);
log.info("商品微服务开始消费消息{}",txMessage);
stockService.decreaseStock(txMessage);
}
private TxMessage getTxMessage(Message message) {
String messageString = new String((byte[]) message.getPayload());
JSONObject jsonObject = JSONObject.parseObject(messageString);
String txStr = jsonObject.getString("txMessage");
return JSONObject.parseObject(txStr,TxMessage.class);
}
}
*/
@EnableBinding(Sink.class)
@Component
@Slf4j
public class StockTxMessageConsumer {
@Autowired
private StockService stockService;
@StreamListener(value=Sink.INPUT)
public void onMessage(Message message) {
TxMessage txMessage = this.getTxMessage(message);
log.info("商品微服务开始消费消息{}",txMessage);
stockService.decreaseStock(txMessage);
log.info("商品微服务完成消费消息{}",txMessage);
}
private TxMessage getTxMessage(Message message) {
String messageString = message.getPayload().toString();
JSONObject jsonObject = JSONObject.parseObject(messageString);
String txStr = jsonObject.getString("txMessage");
return JSONObject.parseObject(txStr,TxMessage.class);
}
}
| 33.859155 | 88 | 0.767471 |
cd9e8d31c11f661ed69d69010f750fe7fd6700bb
| 2,156 |
/*
* JEF - Copyright 2009-2010 Jiyi (mr.jiyi@gmail.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 jef.common.wrapper;
import java.lang.reflect.Field;
import java.util.HashMap;
import jef.common.log.LogUtil;
import jef.tools.reflect.BeanUtils;
import jef.tools.reflect.CloneUtils;
import jef.tools.reflect.FieldEx;
/**
* 利用反射备份一个对象(浅拷贝)
* @author Administrator
*
* @param <T>
*/
public class Backup<T> {
/**
* 备份的对象
*/
private Object obj;
/**
* 备份的域值
*/
private HashMap<Field,Object> fields;
public Backup(T obj, boolean deepCopy){
this.obj=obj;
init(deepCopy);
}
/**
* 构造
* @param obj
*/
public Backup(T obj){
this.obj=obj;
init(false);
}
/*
* 深拷贝:
* 递归复制所有域,直到该域是一个不可变对象为止:
* 目前已知的不可变对象:
* 八原生,八原生包裝类,String,
* java.lang
*/
private void init(boolean deepCopy){
FieldEx[] fs=BeanUtils.getFields(obj.getClass());
fields=new HashMap<Field,Object>(fs.length);
for(FieldEx f: fs){
try {
if(deepCopy){
fields.put(f.getJavaField(), CloneUtils.clone(f.get(obj)));
}else{
fields.put(f.getJavaField(), f.get(obj));
}
} catch (IllegalArgumentException e) {
LogUtil.exception(e);
}
}
}
/**
* 变更目标
* @param obj
*/
public void changeTarget(T obj){
this.obj=obj;
}
/**
* 比较对象
*/
public void compare(){
throw new UnsupportedOperationException();
}
/**
* 恢复对象
*/
public void restore(){
for(Field f: fields.keySet()){
try {
f.set(obj, fields.get(f));
} catch (IllegalArgumentException e) {
LogUtil.exception(e);
} catch (IllegalAccessException e) {
LogUtil.exception(e);
}
}
}
}
| 19.779817 | 75 | 0.658163 |
661547906e465896e7e05f558ea4745c00faf52c
| 3,405 |
package de.hterhors.semanticmr.candidateretrieval.helper;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import de.hterhors.semanticmr.crf.structure.EntityType;
import de.hterhors.semanticmr.crf.structure.annotations.AbstractAnnotation;
import de.hterhors.semanticmr.crf.structure.annotations.AnnotationBuilder;
import de.hterhors.semanticmr.crf.structure.annotations.EntityTemplate;
import de.hterhors.semanticmr.crf.variables.Instance;
public class DictionaryFromInstanceHelper {
public static Set<AbstractAnnotation> getAnnotationsForInstance(Instance instance,
Map<EntityType, Set<String>> trainDictionary) {
Set<AbstractAnnotation> annotations = new HashSet<>();
String doc = instance.getDocument().documentContent;
for (Entry<EntityType, Set<String>> e : trainDictionary.entrySet()) {
for (String s : e.getValue()) {
Matcher m = Pattern.compile(Pattern.quote(s)).matcher(doc);
while (m.find()) {
try {
if (e.getKey().hasNoSlots())
annotations.add(AnnotationBuilder.toAnnotation(instance.getDocument(), e.getKey().name,
m.group(), m.start()));
else
annotations.add(new EntityTemplate(AnnotationBuilder.toAnnotation(instance.getDocument(),
e.getKey().name, m.group(), m.start())));
} catch (RuntimeException e2) {
}
}
}
}
return annotations;
}
/**
* Creates a full recursive property dictionary of all available slots.
*
* @param trainingInstances
* @return
*/
public static Map<EntityType, Set<String>> toDictionary(List<Instance> trainingInstances) {
Map<EntityType, Set<String>> map = new HashMap<>();
for (Instance instance : trainingInstances) {
for (AbstractAnnotation aa : instance.getGoldAnnotations().getAnnotations()) {
recursive(map, aa);
}
}
return map;
}
private static void recursive(Map<EntityType, Set<String>> map, AbstractAnnotation aa) {
if (aa.isInstanceOfEntityTemplate()) {
AbstractAnnotation rootA = aa.asInstanceOfEntityTemplate().getRootAnnotation();
if (rootA.isInstanceOfLiteralAnnotation()) {
map.putIfAbsent(rootA.getEntityType(), new HashSet<>());
String e = rootA.asInstanceOfLiteralAnnotation().getSurfaceForm();
map.get(rootA.getEntityType()).add(e);
}
for (AbstractAnnotation slotFillerValue : Stream
.concat(aa.asInstanceOfEntityTemplate().streamSingleFillerSlotValues(),
aa.asInstanceOfEntityTemplate().flatStreamMultiFillerSlotValues())
.collect(Collectors.toSet())) {
if (slotFillerValue.isInstanceOfEntityTemplate()) {
AbstractAnnotation rootS = slotFillerValue.asInstanceOfEntityTemplate().getRootAnnotation();
if (rootS.isInstanceOfLiteralAnnotation()) {
map.putIfAbsent(rootS.getEntityType(), new HashSet<>());
String e = rootS.asInstanceOfLiteralAnnotation().getSurfaceForm();
map.get(rootS.getEntityType()).add(e);
}
}
recursive(map, slotFillerValue);
}
} else if (aa.isInstanceOfLiteralAnnotation()) {
map.putIfAbsent(aa.getEntityType(), new HashSet<>());
String e = aa.asInstanceOfLiteralAnnotation().getSurfaceForm();
map.get(aa.getEntityType()).add(e);
}
}
}
| 29.353448 | 97 | 0.727166 |
019aa9b9b753ad5690793a83775bd9d20da02985
| 2,966 |
package org.apache.helix.testutil;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import java.io.File;
import java.io.IOException;
import java.net.ServerSocket;
import org.I0Itec.zkclient.IDefaultNameSpace;
import org.I0Itec.zkclient.NetworkUtil;
import org.I0Itec.zkclient.ZkServer;
import org.apache.log4j.Logger;
import com.google.common.io.Files;
public class ZkTestUtil {
static Logger logger = Logger.getLogger(ZkTestUtil.class);
static final int MAX_PORT = 65535;
static final int DEFAULT_ZK_START_PORT = 2183;
public static int availableTcpPort() {
ServerSocket ss = null;
try {
ss = new ServerSocket(0);
ss.setReuseAddress(true);
return ss.getLocalPort();
} catch (IOException e) {
} finally {
if (ss != null) {
try {
ss.close();
} catch (IOException e) {
// should not be thrown
}
}
}
return -1;
}
public static int availableTcpPort(int startPort) {
int port = startPort;
for (; port <= MAX_PORT; port++) {
if (NetworkUtil.isPortFree(port))
break;
}
return port > MAX_PORT ? -1 : port;
}
public static File createAutoDeleteTempDir() {
File tempdir = Files.createTempDir();
tempdir.delete();
tempdir.mkdir();
logger.info("Create temp dir: " + tempdir.getAbsolutePath());
tempdir.deleteOnExit();
return tempdir;
}
public static ZkServer startZkServer() {
File tmpdir = createAutoDeleteTempDir();
File logdir = new File(tmpdir + File.separator + "translog");
File datadir = new File(tmpdir + File.separator + "snapshot");
IDefaultNameSpace defaultNameSpace = new IDefaultNameSpace() {
@Override
public void createDefaultNameSpace(org.I0Itec.zkclient.ZkClient zkClient) {
// init any zk paths if needed
}
};
int port = availableTcpPort(DEFAULT_ZK_START_PORT);
ZkServer zkServer =
new ZkServer(datadir.getAbsolutePath(), logdir.getAbsolutePath(), defaultNameSpace, port);
zkServer.start();
logger.info("Start zookeeper at localhost:" + zkServer.getPort() + " in thread "
+ Thread.currentThread().getName());
return zkServer;
}
}
| 29.66 | 98 | 0.687458 |
62097a2a0517da89df6a42402badd32176392111
| 3,779 |
package com.lambda.essentialism.model;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.*;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
// User is considered the parent entity of all - the Grand Poobah!
@Entity
@Table(name = "users")
@JsonIgnoreProperties("authority")
public class User
extends Auditable {
@GeneratedValue(strategy = GenerationType.AUTO)
@Id
private long userid;
@Column(nullable = false)
private String firstname;
@Column(nullable = false)
private String lastname;
@Column(nullable = false, unique = true)
private String email;
@Column(nullable = false, unique = true)
private String username;
@JsonProperty(access = JsonProperty.Access.WRITE_ONLY)
private String password;
@JsonIgnore
@JsonIgnoreProperties({"user", "userRoles", "role"})
@OneToMany(mappedBy = "user", cascade = CascadeType.ALL)
private List<UserRoles> userRoles = new ArrayList<>();
@JsonIgnoreProperties("user")
@OneToMany(mappedBy = "user", cascade = CascadeType.ALL)
private List<UserValues> userValues = new ArrayList<>();
@OneToMany(mappedBy = "user", cascade = CascadeType.ALL, orphanRemoval = true)
@JsonIgnoreProperties("user")
private List<Project> projects = new ArrayList<>();
public User() {}
public User(String firstname, String lastname, String email, String username, String password, List<UserRoles> userRoles) {
setFirstname(firstname);
setLastname(lastname);
setEmail(email);
setUsername(username);
setPassword(password);
for (UserRoles ur : userRoles) { ur.setUser(this); }
this.userRoles = userRoles;
}
public long getUserid() {
return userid;
}
public void setUserid(long userid) {
this.userid = userid;
}
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 getEmail() { return email; }
public void setEmail(String email) { this.email = email; }
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
this.password = passwordEncoder.encode(password);
}
public void setPasswordNoEncrypt(String password) {
this.password = password;
}
public List<UserRoles> getUserRoles() {
return userRoles;
}
public void setUserRoles(List<UserRoles> userRoles) {
this.userRoles = userRoles;
}
public List<SimpleGrantedAuthority> getAuthority() {
List<SimpleGrantedAuthority> rtnList = new ArrayList<>();
for (UserRoles r : this.userRoles) {
String myRole = "ROLE_" + r.getRole().getName().toUpperCase();
rtnList.add(new SimpleGrantedAuthority(myRole));
}
return rtnList;
}
public List<UserValues> getUserValues() {
return userValues;
}
public void setUserValues(List<UserValues> userValues) {
this.userValues = userValues;
}
public List<Project> getProjects() { return projects; }
public void setProjects(List<Project> projects) { this.projects = projects; }
}
| 27.583942 | 126 | 0.699391 |
0c92ac8320edfb8b9f53ca6f3b2833e84a07b237
| 1,272 |
package dbcache.persist.service;
import dbcache.conf.impl.CacheConfig;
import dbcache.CacheObject;
import dbcache.IEntity;
import dbcache.cache.CacheUnit;
import dbcache.dbaccess.DbAccessService;
import java.util.concurrent.ExecutorService;
/**
* 实体入库服务接口
* @author Jake
* @date 2014年8月13日上午12:24:45
*/
public interface DbPersistService {
/**
* 处理创建
* @param cacheObject 实体缓存对象
* @param dbAccessService 数据库存取服务
* @param cacheConfig TODO
*/
<T extends IEntity<?>> void handleSave(
CacheObject<T> cacheObject,
DbAccessService dbAccessService,
CacheConfig<T> cacheConfig);
/**
* 处理更新
* @param cacheObject 实体缓存对象
* @param dbAccessService 数据库存取服务
*/
<T extends IEntity<?>> void handleUpdate(
CacheObject<T> cacheObject,
DbAccessService dbAccessService,
CacheConfig<T> cacheConfig);
/**
* 处理删除
* @param cacheObject 实体缓存对象
* @param dbAccessService 数据库存取服务
* @param key 缓存key
* @param cacheUnit 缓存容器
*/
void handleDelete(
CacheObject<?> cacheObject,
DbAccessService dbAccessService,
Object key,
CacheUnit cacheUnit);
/**
* 释放并且等待处理完毕
*/
void destroy();
/**
* 打印出未入库对象
*/
void logHadNotPersistEntity();
/**
* 获取入库线程池
* @return ExecutorService
*/
ExecutorService getThreadPool();
}
| 18.434783 | 44 | 0.711478 |
3b1aeeded9ceb30b4276847375ea6a2c0393123e
| 4,135 |
/*
* The MIT License (MIT)
*
* Copyright (c) 2017 Piasy
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.github.piasy.octostars.bridge;
import com.github.piasy.bootstrap.base.model.provider.ProviderModuleExposure;
import com.github.piasy.bootstrap.testbase.TestUtil;
import com.github.piasy.bootstrap.testbase.rules.ThreeTenBPRule;
import com.google.gson.TypeAdapterFactory;
import org.junit.Rule;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnit;
import org.mockito.junit.MockitoRule;
import rx.functions.Action1;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.only;
import static org.mockito.Mockito.verify;
/**
* Created by Piasy{github.com/Piasy} on 5/5/16.
*/
public class RxNetErrorProcessorTest {
@Rule
public ThreeTenBPRule mThreeTenBPRule = ThreeTenBPRule.junitTest();
@Rule
public MockitoRule mMockitoRule = MockitoJUnit.rule();
@Mock
private Action1<ApiError> mApiErrorHandler;
private TypeAdapterFactory mAdapterFactory = ErrorGsonAdapterFactory.create();
@Test
public void testProcessOtherException() {
RxNetErrorProcessor rxNetErrorProcessor =
new RxNetErrorProcessor(ProviderModuleExposure.exposeGson(mAdapterFactory));
Throwable throwable = new IllegalArgumentException();
assertFalse(rxNetErrorProcessor.tryWithApiError(throwable, mApiErrorHandler));
verify(mApiErrorHandler, never()).call(any());
}
@Test
public void testProcessNonApiNetworkError() {
RxNetErrorProcessor rxNetErrorProcessor =
new RxNetErrorProcessor(ProviderModuleExposure.exposeGson(mAdapterFactory));
assertFalse(
rxNetErrorProcessor.tryWithApiError(TestUtil.nonApiError(), mApiErrorHandler));
verify(mApiErrorHandler, never()).call(any());
}
@Test
public void testProcessInvalidApiError() {
RxNetErrorProcessor rxNetErrorProcessor =
new RxNetErrorProcessor(ProviderModuleExposure.exposeGson(mAdapterFactory));
assertFalse(rxNetErrorProcessor.tryWithApiError(TestUtil.invalidApiError(),
mApiErrorHandler));
verify(mApiErrorHandler, never()).call(any());
}
@Test
public void testProcessApiError() {
RxNetErrorProcessor rxNetErrorProcessor =
new RxNetErrorProcessor(ProviderModuleExposure.exposeGson(mAdapterFactory));
assertTrue(rxNetErrorProcessor.tryWithApiError(TestUtil.apiError(), mApiErrorHandler));
ApiError apiError = ProviderModuleExposure.exposeGson(mAdapterFactory)
.fromJson(provideGithubAPIErrorStr(), ApiError.class);
verify(mApiErrorHandler, only()).call(apiError);
}
private String provideGithubAPIErrorStr() {
return "{\"message\":\"Validation Failed\",\"errors\":[{\"resource\":\"Issue\"," +
"\"field\":\"title\",\"code\":\"missing_field\"}]}";
}
}
| 40.539216 | 95 | 0.736155 |
06855bb47578c41d8d7bb224accda799062cf703
| 450 |
package se.arbetsformedlingen.venice.model;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class WebserviceLoad {
private List<WebserviceValue> series = new ArrayList<>();
public WebserviceLoad(WebserviceValue... timeValues) {
Collections.addAll(series, timeValues);
Collections.sort(series);
}
public List<WebserviceValue> getLoadValues() {
return series;
}
}
| 23.684211 | 61 | 0.715556 |
a5a6ee95efe379a6450e95aa387c00a47953d922
| 535 |
package com.jcohy.sample.algorithm.SimpleQuestion;
public class Global {
// tag::code[]
/**
* 题目: 一球从100米高度自由落下,每次落地后反跳回原高度的一半;再落下,
* 求它在 第10次落地时,共经过多少米? 第10次反弹多高?
*
* @param args
*/
public static void main(String[] args) {
double height = 100;
double sum = 0;
for (int i = 1; i <= 10; i++) {
sum += height;
height = height / 2;
sum += height;
}
System.out.println(height + " " + (sum + height));
}
// end::code[]
}
| 22.291667 | 58 | 0.502804 |
1a89855dca0069fcd03c1025a4d999408184cfd1
| 22,262 |
/*! ******************************************************************************
*
* Hop : The Hop Orchestration Platform
*
* http://www.project-hop.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.apache.hop.pipeline.transforms.replacestring;
import org.apache.commons.lang.StringUtils;
import org.apache.hop.core.CheckResult;
import org.apache.hop.core.CheckResultInterface;
import org.apache.hop.core.Const;
import org.apache.hop.core.exception.HopTransformException;
import org.apache.hop.core.exception.HopXmlException;
import org.apache.hop.core.injection.AfterInjection;
import org.apache.hop.core.injection.Injection;
import org.apache.hop.core.injection.InjectionSupported;
import org.apache.hop.core.row.IRowMeta;
import org.apache.hop.core.row.IValueMeta;
import org.apache.hop.core.row.value.ValueMetaString;
import org.apache.hop.core.util.Utils;
import org.apache.hop.core.variables.iVariables;
import org.apache.hop.core.xml.XmlHandler;
import org.apache.hop.i18n.BaseMessages;
import org.apache.hop.metastore.api.IMetaStore;
import org.apache.hop.pipeline.Pipeline;
import org.apache.hop.pipeline.PipelineMeta;
import org.apache.hop.pipeline.transform.BaseTransformMeta;
import org.apache.hop.pipeline.transform.ITransformData;
import org.apache.hop.pipeline.transform.ITransform;
import org.apache.hop.pipeline.transform.TransformMeta;
import org.apache.hop.pipeline.transform.ITransform;
import org.w3c.dom.Node;
import java.util.List;
@InjectionSupported( localizationPrefix = "ReplaceString.Injection.", groups = { "FIELDS" } )
public class ReplaceStringMeta extends BaseTransformMeta implements ITransform {
private static Class<?> PKG = ReplaceStringMeta.class; // for i18n purposes, needed by Translator!!
@Injection( name = "FIELD_IN_STREAM", group = "FIELDS" )
private String[] fieldInStream;
@Injection( name = "FIELD_OUT_STREAM", group = "FIELDS" )
private String[] fieldOutStream;
@Injection( name = "USE_REGEX", group = "FIELDS" )
private int[] useRegEx;
@Injection( name = "REPLACE_STRING", group = "FIELDS" )
private String[] replaceString;
@Injection( name = "REPLACE_BY", group = "FIELDS" )
private String[] replaceByString;
/**
* Flag : set empty string
**/
@Injection( name = "EMPTY_STRING", group = "FIELDS" )
private boolean[] setEmptyString;
@Injection( name = "REPLACE_WITH_FIELD", group = "FIELDS" )
private String[] replaceFieldByString;
@Injection( name = "REPLACE_WHOLE_WORD", group = "FIELDS" )
private int[] wholeWord;
@Injection( name = "CASE_SENSITIVE", group = "FIELDS" )
private int[] caseSensitive;
@Injection( name = "IS_UNICODE", group = "FIELDS" )
private int[] isUnicode;
public static final String[] caseSensitiveCode = { "no", "yes" };
public static final String[] isUnicodeCode = { "no", "yes" };
public static final String[] caseSensitiveDesc = new String[] {
BaseMessages.getString( PKG, "System.Combo.No" ), BaseMessages.getString( PKG, "System.Combo.Yes" ) };
public static final String[] isUnicodeDesc = new String[] {
BaseMessages.getString( PKG, "System.Combo.No" ), BaseMessages.getString( PKG, "System.Combo.Yes" ) };
public static final int CASE_SENSITIVE_NO = 0;
public static final int CASE_SENSITIVE_YES = 1;
public static final int IS_UNICODE_NO = 0;
public static final int IS_UNICODE_YES = 1;
public static final String[] wholeWordDesc = new String[] {
BaseMessages.getString( PKG, "System.Combo.No" ), BaseMessages.getString( PKG, "System.Combo.Yes" ) };
public static final String[] wholeWordCode = { "no", "yes" };
public static final int WHOLE_WORD_NO = 0;
public static final int WHOLE_WORD_YES = 1;
public static final String[] useRegExDesc = new String[] {
BaseMessages.getString( PKG, "System.Combo.No" ), BaseMessages.getString( PKG, "System.Combo.Yes" ) };
public static final String[] useRegExCode = { "no", "yes" };
public static final int USE_REGEX_NO = 0;
public static final int USE_REGEX_YES = 1;
public ReplaceStringMeta() {
super(); // allocate BaseTransformMeta
}
/**
* @return Returns the fieldInStream.
*/
public String[] getFieldInStream() {
return fieldInStream;
}
/**
* @param keyStream The fieldInStream to set.
*/
public void setFieldInStream( String[] keyStream ) {
this.fieldInStream = keyStream;
}
public int[] getCaseSensitive() {
return caseSensitive;
}
public int[] isUnicode() {
return isUnicode;
}
public int[] getWholeWord() {
return wholeWord;
}
public void setWholeWord( int[] wholeWord ) {
this.wholeWord = wholeWord;
}
public int[] getUseRegEx() {
return useRegEx;
}
public void setUseRegEx( int[] useRegEx ) {
this.useRegEx = useRegEx;
}
/**
* @return the setEmptyString
*/
public boolean[] isSetEmptyString() {
return setEmptyString;
}
/**
* @param setEmptyString the setEmptyString to set
*/
public void setEmptyString( boolean[] setEmptyString ) {
this.setEmptyString = setEmptyString;
}
/**
* @return Returns the fieldOutStream.
*/
public String[] getFieldOutStream() {
return fieldOutStream;
}
/**
* @param keyStream The fieldOutStream to set.
*/
public void setFieldOutStream( String[] keyStream ) {
this.fieldOutStream = keyStream;
}
public String[] getReplaceString() {
return replaceString;
}
public void setReplaceString( String[] replaceString ) {
this.replaceString = replaceString;
}
public String[] getReplaceByString() {
return replaceByString;
}
public void setReplaceByString( String[] replaceByString ) {
this.replaceByString = replaceByString;
}
public String[] getFieldReplaceByString() {
return replaceFieldByString;
}
public void setFieldReplaceByString( String[] replaceFieldByString ) {
this.replaceFieldByString = replaceFieldByString;
}
public void setCaseSensitive( int[] caseSensitive ) {
this.caseSensitive = caseSensitive;
}
public void setIsUnicode( int[] isUnicode ) {
this.isUnicode = isUnicode;
}
public void loadXml( Node transformNode, IMetaStore metaStore ) throws HopXmlException {
readData( transformNode, metaStore );
}
public void allocate( int nrkeys ) {
fieldInStream = new String[ nrkeys ];
fieldOutStream = new String[ nrkeys ];
useRegEx = new int[ nrkeys ];
replaceString = new String[ nrkeys ];
replaceByString = new String[ nrkeys ];
setEmptyString = new boolean[ nrkeys ];
replaceFieldByString = new String[ nrkeys ];
wholeWord = new int[ nrkeys ];
caseSensitive = new int[ nrkeys ];
isUnicode = new int[ nrkeys ];
}
public Object clone() {
ReplaceStringMeta retval = (ReplaceStringMeta) super.clone();
int nrkeys = fieldInStream.length;
retval.allocate( nrkeys );
System.arraycopy( fieldInStream, 0, retval.fieldInStream, 0, nrkeys );
System.arraycopy( fieldOutStream, 0, retval.fieldOutStream, 0, nrkeys );
System.arraycopy( useRegEx, 0, retval.useRegEx, 0, nrkeys );
System.arraycopy( replaceString, 0, retval.replaceString, 0, nrkeys );
System.arraycopy( replaceByString, 0, retval.replaceByString, 0, nrkeys );
System.arraycopy( setEmptyString, 0, retval.setEmptyString, 0, nrkeys );
System.arraycopy( replaceFieldByString, 0, retval.replaceFieldByString, 0, nrkeys );
System.arraycopy( wholeWord, 0, retval.wholeWord, 0, nrkeys );
System.arraycopy( caseSensitive, 0, retval.caseSensitive, 0, nrkeys );
System.arraycopy( isUnicode, 0, retval.isUnicode, 0, nrkeys );
return retval;
}
private void readData( Node transformNode, IMetaStore metaStore ) throws HopXmlException {
try {
int nrkeys;
Node lookup = XmlHandler.getSubNode( transformNode, "fields" );
nrkeys = XmlHandler.countNodes( lookup, "field" );
allocate( nrkeys );
for ( int i = 0; i < nrkeys; i++ ) {
Node fnode = XmlHandler.getSubNodeByNr( lookup, "field", i );
fieldInStream[ i ] = Const.NVL( XmlHandler.getTagValue( fnode, "in_stream_name" ), "" );
fieldOutStream[ i ] = Const.NVL( XmlHandler.getTagValue( fnode, "out_stream_name" ), "" );
useRegEx[ i ] = getCaseSensitiveByCode( Const.NVL( XmlHandler.getTagValue( fnode, "use_regex" ), "" ) );
replaceString[ i ] = Const.NVL( XmlHandler.getTagValue( fnode, "replace_string" ), "" );
replaceByString[ i ] = Const.NVL( XmlHandler.getTagValue( fnode, "replace_by_string" ), "" );
String emptyString = XmlHandler.getTagValue( fnode, "set_empty_string" );
setEmptyString[ i ] = !Utils.isEmpty( emptyString ) && "Y".equalsIgnoreCase( emptyString );
replaceFieldByString[ i ] = Const.NVL( XmlHandler.getTagValue( fnode, "replace_field_by_string" ), "" );
wholeWord[ i ] = getWholeWordByCode( Const.NVL( XmlHandler.getTagValue( fnode, "whole_word" ), "" ) );
caseSensitive[ i ] =
getCaseSensitiveByCode( Const.NVL( XmlHandler.getTagValue( fnode, "case_sensitive" ), "" ) );
isUnicode[ i ] =
getIsUniCodeByCode( Const.NVL( XmlHandler.getTagValue( fnode, "is_unicode" ), "" ) );
}
} catch ( Exception e ) {
throw new HopXmlException( BaseMessages.getString(
PKG, "ReplaceStringMeta.Exception.UnableToReadTransformMetaFromXML" ), e );
}
}
private static int getIsUniCodeByCode( String tt ) {
if ( tt == null ) {
return 0;
}
for ( int i = 0; i < isUnicodeCode.length; i++ ) {
if ( isUnicodeCode[ i ].equalsIgnoreCase( tt ) ) {
return i;
}
}
return 0;
}
public void setDefault() {
fieldInStream = null;
fieldOutStream = null;
int nrkeys = 0;
allocate( nrkeys );
}
public String getXml() {
StringBuilder retval = new StringBuilder( 500 );
retval.append( " <fields>" ).append( Const.CR );
for ( int i = 0; i < fieldInStream.length; i++ ) {
retval.append( " <field>" ).append( Const.CR );
retval.append( " " ).append( XmlHandler.addTagValue( "in_stream_name", fieldInStream[ i ] ) );
retval.append( " " ).append( XmlHandler.addTagValue( "out_stream_name", fieldOutStream[ i ] ) );
retval.append( " " ).append( XmlHandler.addTagValue( "use_regex", getUseRegExCode( useRegEx[ i ] ) ) );
retval.append( " " ).append( XmlHandler.addTagValue( "replace_string", replaceString[ i ] ) );
retval.append( " " ).append( XmlHandler.addTagValue( "replace_by_string", replaceByString[ i ] ) );
retval.append( " " ).append( XmlHandler.addTagValue( "set_empty_string", setEmptyString[ i ] ) );
retval.append( " " ).append(
XmlHandler.addTagValue( "replace_field_by_string", replaceFieldByString[ i ] ) );
retval
.append( " " ).append( XmlHandler.addTagValue( "whole_word", getWholeWordCode( wholeWord[ i ] ) ) );
retval.append( " " ).append(
XmlHandler.addTagValue( "case_sensitive", getCaseSensitiveCode( caseSensitive[ i ] ) ) );
retval.append( " " ).append(
XmlHandler.addTagValue( "is_unicode", getIsUniCodeCode( isUnicode[ i ] ) ) );
retval.append( " </field>" ).append( Const.CR );
}
retval.append( " </fields>" ).append( Const.CR );
return retval.toString();
}
private static String getIsUniCodeCode( int i ) {
if ( i < 0 || i >= isUnicodeCode.length ) {
return isUnicodeCode[ 0 ];
}
return isUnicodeCode[ i ];
}
public void getFields( IRowMeta inputRowMeta, String name, IRowMeta[] info, TransformMeta nextTransform,
iVariables variables, IMetaStore metaStore ) throws HopTransformException {
int nrFields = fieldInStream == null ? 0 : fieldInStream.length;
for ( int i = 0; i < nrFields; i++ ) {
String fieldName = variables.environmentSubstitute( fieldOutStream[ i ] );
IValueMeta valueMeta;
if ( !Utils.isEmpty( fieldOutStream[ i ] ) ) {
// We have a new field
valueMeta = new ValueMetaString( fieldName );
valueMeta.setOrigin( name );
//set encoding to new field from source field http://jira.pentaho.com/browse/PDI-11839
IValueMeta sourceField = inputRowMeta.searchValueMeta( fieldInStream[ i ] );
if ( sourceField != null ) {
valueMeta.setStringEncoding( sourceField.getStringEncoding() );
}
inputRowMeta.addValueMeta( valueMeta );
} else {
valueMeta = inputRowMeta.searchValueMeta( fieldInStream[ i ] );
if ( valueMeta == null ) {
continue;
}
valueMeta.setStorageType( IValueMeta.STORAGE_TYPE_NORMAL );
}
}
}
public void check( List<CheckResultInterface> remarks, PipelineMeta pipelineMeta, TransformMeta transforminfo,
IRowMeta prev, String[] input, String[] output, IRowMeta info, iVariables variables,
IMetaStore metaStore ) {
CheckResult cr;
String error_message = "";
boolean first = true;
boolean error_found = false;
if ( prev == null ) {
error_message += BaseMessages.getString( PKG, "ReplaceStringMeta.CheckResult.NoInputReceived" ) + Const.CR;
cr = new CheckResult( CheckResult.TYPE_RESULT_ERROR, error_message, transforminfo );
remarks.add( cr );
} else {
for ( int i = 0; i < fieldInStream.length; i++ ) {
String field = fieldInStream[ i ];
IValueMeta v = prev.searchValueMeta( field );
if ( v == null ) {
if ( first ) {
first = false;
error_message +=
BaseMessages.getString( PKG, "ReplaceStringMeta.CheckResult.MissingInStreamFields" ) + Const.CR;
}
error_found = true;
error_message += "\t\t" + field + Const.CR;
}
}
if ( error_found ) {
cr = new CheckResult( CheckResult.TYPE_RESULT_ERROR, error_message, transforminfo );
} else {
cr =
new CheckResult( CheckResult.TYPE_RESULT_OK, BaseMessages.getString(
PKG, "ReplaceStringMeta.CheckResult.FoundInStreamFields" ), transforminfo );
}
remarks.add( cr );
// Check whether all are strings
first = true;
error_found = false;
for ( int i = 0; i < fieldInStream.length; i++ ) {
String field = fieldInStream[ i ];
IValueMeta v = prev.searchValueMeta( field );
if ( v != null ) {
if ( v.getType() != IValueMeta.TYPE_STRING ) {
if ( first ) {
first = false;
error_message +=
BaseMessages.getString( PKG, "ReplaceStringMeta.CheckResult.OperationOnNonStringFields" )
+ Const.CR;
}
error_found = true;
error_message += "\t\t" + field + Const.CR;
}
}
}
if ( error_found ) {
cr = new CheckResult( CheckResult.TYPE_RESULT_ERROR, error_message, transforminfo );
} else {
cr =
new CheckResult( CheckResult.TYPE_RESULT_OK, BaseMessages.getString(
PKG, "ReplaceStringMeta.CheckResult.AllOperationsOnStringFields" ), transforminfo );
}
remarks.add( cr );
if ( fieldInStream.length > 0 ) {
for ( int idx = 0; idx < fieldInStream.length; idx++ ) {
if ( Utils.isEmpty( fieldInStream[ idx ] ) ) {
cr =
new CheckResult(
CheckResult.TYPE_RESULT_ERROR, BaseMessages.getString(
PKG, "ReplaceStringMeta.CheckResult.InStreamFieldMissing", new Integer( idx + 1 )
.toString() ), transforminfo );
remarks.add( cr );
}
}
}
// Check if all input fields are distinct.
for ( int idx = 0; idx < fieldInStream.length; idx++ ) {
for ( int jdx = 0; jdx < fieldInStream.length; jdx++ ) {
if ( fieldInStream[ idx ].equals( fieldInStream[ jdx ] ) && idx != jdx && idx < jdx ) {
error_message =
BaseMessages.getString( PKG, "ReplaceStringMeta.CheckResult.FieldInputError", fieldInStream[ idx ] );
cr = new CheckResult( CheckResult.TYPE_RESULT_ERROR, error_message, transforminfo );
remarks.add( cr );
}
}
}
}
}
public ITransform getTransform( TransformMeta transformMeta, ITransformData data, int cnr,
PipelineMeta pipelineMeta, Pipeline pipeline ) {
return new ReplaceString( transformMeta, this, data, cnr, pipelineMeta, pipeline );
}
public ITransformData getTransformData() {
return new ReplaceStringData();
}
public boolean supportsErrorHandling() {
return true;
}
private static String getCaseSensitiveCode( int i ) {
if ( i < 0 || i >= caseSensitiveCode.length ) {
return caseSensitiveCode[ 0 ];
}
return caseSensitiveCode[ i ];
}
private static String getWholeWordCode( int i ) {
if ( i < 0 || i >= wholeWordCode.length ) {
return wholeWordCode[ 0 ];
}
return wholeWordCode[ i ];
}
private static String getUseRegExCode( int i ) {
if ( i < 0 || i >= useRegExCode.length ) {
return useRegExCode[ 0 ];
}
return useRegExCode[ i ];
}
public static String getCaseSensitiveDesc( int i ) {
if ( i < 0 || i >= caseSensitiveDesc.length ) {
return caseSensitiveDesc[ 0 ];
}
return caseSensitiveDesc[ i ];
}
public static String getIsUnicodeDesc( int i ) {
if ( i < 0 || i >= isUnicodeDesc.length ) {
return isUnicodeDesc[ 0 ];
}
return isUnicodeDesc[ i ];
}
public static String getWholeWordDesc( int i ) {
if ( i < 0 || i >= wholeWordDesc.length ) {
return wholeWordDesc[ 0 ];
}
return wholeWordDesc[ i ];
}
public static String getUseRegExDesc( int i ) {
if ( i < 0 || i >= useRegExDesc.length ) {
return useRegExDesc[ 0 ];
}
return useRegExDesc[ i ];
}
private static int getCaseSensitiveByCode( String tt ) {
if ( tt == null ) {
return 0;
}
for ( int i = 0; i < caseSensitiveCode.length; i++ ) {
if ( caseSensitiveCode[ i ].equalsIgnoreCase( tt ) ) {
return i;
}
}
return 0;
}
private static int getWholeWordByCode( String tt ) {
if ( tt == null ) {
return 0;
}
for ( int i = 0; i < wholeWordCode.length; i++ ) {
if ( wholeWordCode[ i ].equalsIgnoreCase( tt ) ) {
return i;
}
}
return 0;
}
private static int getRegExByCode( String tt ) {
if ( tt == null ) {
return 0;
}
for ( int i = 0; i < useRegExCode.length; i++ ) {
if ( useRegExCode[ i ].equalsIgnoreCase( tt ) ) {
return i;
}
}
return 0;
}
public static int getCaseSensitiveByDesc( String tt ) {
if ( tt == null ) {
return 0;
}
for ( int i = 0; i < caseSensitiveDesc.length; i++ ) {
if ( caseSensitiveDesc[ i ].equalsIgnoreCase( tt ) ) {
return i;
}
}
// If this fails, try to match using the code.
return getCaseSensitiveByCode( tt );
}
public static int getIsUnicodeByDesc( String tt ) {
if ( tt == null ) {
return 0;
}
for ( int i = 0; i < isUnicodeDesc.length; i++ ) {
if ( isUnicodeDesc[ i ].equalsIgnoreCase( tt ) ) {
return i;
}
}
// If this fails, try to match using the code.
return getIsUniCodeByCode( tt );
}
public static int getWholeWordByDesc( String tt ) {
if ( tt == null ) {
return 0;
}
for ( int i = 0; i < wholeWordDesc.length; i++ ) {
if ( wholeWordDesc[ i ].equalsIgnoreCase( tt ) ) {
return i;
}
}
// If this fails, try to match using the code.
return getWholeWordByCode( tt );
}
public static int getUseRegExByDesc( String tt ) {
if ( tt == null ) {
return 0;
}
for ( int i = 0; i < useRegExDesc.length; i++ ) {
if ( useRegExDesc[ i ].equalsIgnoreCase( tt ) ) {
return i;
}
}
// If this fails, try to match using the code.
return getRegExByCode( tt );
}
private void nullToEmpty( String[] strings ) {
for ( int i = 0; i < strings.length; i++ ) {
if ( strings[ i ] == null ) {
strings[ i ] = StringUtils.EMPTY;
}
}
}
/**
* If we use injection we can have different arrays lengths.
* We need synchronize them for consistency behavior with UI
*/
@AfterInjection
public void afterInjectionSynchronization() {
int nrFields = ( fieldInStream == null ) ? -1 : fieldInStream.length;
if ( nrFields <= 0 ) {
return;
}
String[][] rtnStringArrays = Utils.normalizeArrays( nrFields, fieldOutStream, replaceString, replaceByString, replaceFieldByString );
fieldOutStream = rtnStringArrays[ 0 ];
replaceString = rtnStringArrays[ 1 ];
replaceByString = rtnStringArrays[ 2 ];
replaceFieldByString = rtnStringArrays[ 3 ];
nullToEmpty( fieldOutStream );
nullToEmpty( replaceString );
nullToEmpty( replaceByString );
nullToEmpty( replaceFieldByString );
int[][] rtnIntArrays = Utils.normalizeArrays( nrFields, useRegEx, wholeWord, caseSensitive, isUnicode );
useRegEx = rtnIntArrays[ 0 ];
wholeWord = rtnIntArrays[ 1 ];
caseSensitive = rtnIntArrays[ 2 ];
isUnicode = rtnIntArrays[ 3 ];
boolean[][] rtnBooleanArrays = Utils.normalizeArrays( nrFields, setEmptyString );
setEmptyString = rtnBooleanArrays[ 0 ];
}
}
| 32.786451 | 137 | 0.634983 |
5c57be6333e8a1bb2eb072b4421f931965487be4
| 3,327 |
package com.atguigu.gmall.pms.controller;
import com.atguigu.gmall.common.bean.PageParamVo;
import com.atguigu.gmall.common.bean.PageResultVo;
import com.atguigu.gmall.common.bean.ResponseVo;
import com.atguigu.gmall.pms.entity.AttrGroupEntity;
import com.atguigu.gmall.pms.service.AttrGroupService;
import com.atguigu.gmall.pms.vo.GroupVo;
import com.atguigu.gmall.pms.vo.ItemGroupVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
/**
* 属性分组
*
* @author Cerosg
* @email Cerosg@outlook.com
* @date 2020-07-20 19:34:59
*/
@Api(tags = "属性分组 管理")
@RestController
@RequestMapping("pms/attrgroup")
public class AttrGroupController {
@Autowired
private AttrGroupService attrGroupService;
@GetMapping("withattr/withvalue/{cid}")
@ApiOperation("根据分类id结果spuId/skuId查询组及组下规格参数与值")
public ResponseVo<List<ItemGroupVo>> queryGroupAttrValue(@PathVariable("cid") Long cid,
@RequestParam("spuId") Long spuId,
@RequestParam("skuId") Long skuId) {
return ResponseVo.ok(attrGroupService.queryGroupAttrValue(cid, spuId, skuId));
}
/**
* 属性三级分类分组列表和分组中的属性
*
* @param id 三级分类id
* @return
*/
@GetMapping("/withattrs/{catId}")
@ApiOperation("根据分类id查询属性分组和分组中的属性")
public ResponseVo<List<GroupVo>> queryAttrGroupAndValueByCid(@PathVariable("catId") Long id) {
return ResponseVo.ok(attrGroupService.queryAttrGroupAndValueByCid(id));
}
/**
* 属性三级分类分组列表
*/
@GetMapping("/category/{cid}")
@ApiOperation("根据分类id查询属性分组")
public ResponseVo<List<AttrGroupEntity>> queryAttrGroupByCid(@PathVariable("cid") Long id) {
return ResponseVo.ok(attrGroupService.list(new QueryWrapper<AttrGroupEntity>().eq("category_id", id)));
}
/**
* 列表
*/
@GetMapping
@ApiOperation("分页查询")
public ResponseVo<PageResultVo> queryAttrGroupByPage(PageParamVo paramVo) {
PageResultVo pageResultVo = attrGroupService.queryPage(paramVo);
return ResponseVo.ok(pageResultVo);
}
/**
* 信息
*/
@GetMapping("{id}")
@ApiOperation("详情查询")
public ResponseVo<AttrGroupEntity> queryAttrGroupById(@PathVariable("id") Long id) {
AttrGroupEntity attrGroup = attrGroupService.getById(id);
return ResponseVo.ok(attrGroup);
}
/**
* 保存
*/
@PostMapping
@ApiOperation("保存")
public ResponseVo<Object> save(@RequestBody AttrGroupEntity attrGroup) {
attrGroupService.save(attrGroup);
return ResponseVo.ok();
}
/**
* 修改
*/
@PostMapping("/update")
@ApiOperation("修改")
public ResponseVo update(@RequestBody AttrGroupEntity attrGroup) {
attrGroupService.updateById(attrGroup);
return ResponseVo.ok();
}
/**
* 删除
*/
@PostMapping("/delete")
@ApiOperation("删除")
public ResponseVo delete(@RequestBody List<Long> ids) {
attrGroupService.removeByIds(ids);
return ResponseVo.ok();
}
}
| 27.725 | 111 | 0.665164 |
3745bc2bcda8e29f47672cd1c49fe6d915b21b5b
| 4,042 |
/*
* Copyright 2014, AetherWorks LLC.
*/
package com.aetherworks.example.jersey2.api;
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.when;
import javax.ws.rs.core.Application;
import javax.ws.rs.core.GenericType;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import org.glassfish.jersey.test.JerseyTest;
import org.junit.After;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.mockito.runners.MockitoJUnitRunner;
import com.aetherworks.example.jersey2.SetApplication;
import com.aetherworks.example.jersey2.SetCallHandler;
import com.aetherworks.example.jersey2.exception.InvalidRequestException;
import com.aetherworks.example.jersey2.exception.InvalidRequestExceptionMapper;
@RunWith(MockitoJUnitRunner.class)
public class MockedSetApiTests extends JerseyTest {
/**
* Used to specify the format expected for the return type of the add call.
*/
private final GenericType<Boolean> BOOLEAN_RETURN_TYPE = new GenericType<Boolean>() {
};
/**
* The handler used in the {@link SetResource}. We are going to use {@link Mockito} to mock this handler for some
* tests, to just check the API call itself.
*/
private SetCallHandler setCallHandler;
@Override
protected Application configure() {
setCallHandler = Mockito.mock(SetCallHandler.class);
return new SetApplication(setCallHandler);
}
@Override
@After
public void tearDown() throws Exception {
/*
* The super-class tearDown method takes down the server, so it has to be called.
*/
super.tearDown();
/*
* Reset the mocking on this object so that the field can be safely re-used between tests.
*/
Mockito.reset(setCallHandler);
}
/**
* Makes a call to add, and checks that the expected value is returned. The {@link SetCallHandler} is mocked, so we
* control the return type.
*/
@Test
public void mockedAddCall() throws InvalidRequestException {
/*
* Set up. This code sets up mocking to return true when the SetCallHandler#add() method is called with the
* given value.
*/
final String value = "MyTest1";
final boolean returnValue = true;
when(setCallHandler.add(value)).thenReturn(returnValue);
/*
* Perform call. This is set up as a get request, so the parameter is added to the path of that request.
*/
final String pathToCall = "set/add/" + value;
final Response responseWrapper = target(pathToCall).request(MediaType.APPLICATION_JSON_TYPE).get();
/*
* Manage response. Check that the status code is correct (so we know the call worked), and then check that the
* value returned is as expected.
*/
assertEquals(Response.Status.OK.getStatusCode(), responseWrapper.getStatus());
assertEquals(returnValue, responseWrapper.readEntity(BOOLEAN_RETURN_TYPE));
}
/**
* Mock an exception being thrown and check that the {@link InvalidRequestException} mapper at
* {@link InvalidRequestExceptionMapper} is being used correctly.
*/
@Test
public void exceptionMapping() throws InvalidRequestException {
/*
* Set up. This code sets up mocking to throw an exception when the SetCallHandler#add() method is called with
* the given value.
*/
final String value = "MyTest1";
when(setCallHandler.add(value)).thenThrow(new InvalidRequestException("Mocked StartupException failure."));
/*
* Perform call.
*/
final String pathToCall = "set/add/" + value;
final Response responseWrapper = target(pathToCall).request(MediaType.APPLICATION_JSON_TYPE).get();
/*
* Manage response. We expect an exception to be thrown, so we check that the expected error code is returned.
*/
assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), responseWrapper.getStatus());
final String returnedErrorMessage = responseWrapper.readEntity(String.class);
assertEquals(InvalidRequestExceptionMapper.ERROR_MESSAGE, returnedErrorMessage);
}
}
| 33.966387 | 117 | 0.731569 |
921c086a5bb05ef7e5bcbfad91acdc0f6a4362da
| 4,375 |
package com.gizwits.opensource.appkit.sharingdevice;
import com.gizwits.gizwifisdk.api.GizDeviceSharing;
import com.gizwits.gizwifisdk.enumration.GizDeviceSharingWay;
import com.gizwits.gizwifisdk.enumration.GizUserAccountType;
import com.gizwits.gizwifisdk.enumration.GizWifiErrorCode;
import com.gizwits.gizwifisdk.listener.GizDeviceSharingListener;
import com.gizwits.opensource.appkit.R;
import com.gizwits.opensource.appkit.CommonModule.GosBaseActivity;
import com.gizwits.opensource.appkit.CommonModule.TipsDialog;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class userSharedActivity extends GosBaseActivity {
private String productname;
private EditText username;
private int chooseitem = 0;
private String did;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_gos_user_shared);
setActionBar(true, true, R.string.account_shared);
initData();
initView();
}
private void initView() {
TextView usersharedtext = (TextView) findViewById(R.id.usersharedtext);
username = (EditText) findViewById(R.id.username);
usersharedtext.setText(
getResources().getString(R.string.shared) + productname + getResources().getString(R.string.friends));
}
private void initData() {
Intent tent = getIntent();
productname = tent.getStringExtra("productname");
did = tent.getStringExtra("did");
}
public void usershared(View v) {
final String usernametext = username.getText().toString();
if (TextUtils.isEmpty(usernametext)) {
// Toast.makeText(this,
// getResources().getString(R.string.toast_name_empet), 0).show();
TipsDialog dia = new TipsDialog(this, getResources().getString(R.string.toast_name_empet));
dia.show();
return;
}
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setIcon(R.drawable.friends);
chooseitem = 0;
builder.setTitle(getResources().getString(R.string.chooseusertype));
builder.setSingleChoiceItems(R.array.usertype, 0, new OnClickListener() {
@Override
public void onClick(DialogInterface arg0, int arg1) {
chooseitem = arg1;
}
});
builder.setPositiveButton(getResources().getString(R.string.confirm), new OnClickListener() {
@Override
public void onClick(DialogInterface arg0, int arg1) {
SharedPreferences spf = getSharedPreferences("set", Context.MODE_PRIVATE);
String token = spf.getString("Token", "");
GizUserAccountType gizuser = null;
switch (chooseitem) {
case 0:
gizuser = GizUserAccountType.GizUserNormal;
break;
case 1:
gizuser = GizUserAccountType.GizUserPhone;
break;
case 2:
gizuser = GizUserAccountType.GizUserEmail;
break;
case 3:
gizuser = GizUserAccountType.GizUserOther;
break;
default:
break;
}
GizDeviceSharing.sharingDevice(token, did, GizDeviceSharingWay.GizDeviceSharingByNormal, usernametext,
gizuser);
arg0.dismiss();
}
});
builder.setNegativeButton(getResources().getString(R.string.no), null);
builder.show();
}
@Override
protected void onResume() {
super.onResume();
GizDeviceSharing.setListener(new GizDeviceSharingListener() {
@Override
public void didSharingDevice(GizWifiErrorCode result, String deviceID, int sharingID,
Bitmap QRCodeImage) {
super.didSharingDevice(result, deviceID, sharingID, QRCodeImage);
if (result.ordinal() == 0) {
Toast.makeText(userSharedActivity.this, getResources().getString(R.string.alawyssend), 1).show();
finish();
} else {
Toast.makeText(userSharedActivity.this, getResources().getString(R.string.send_failed1), 2).show();
}
}
});
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
finish();
break;
}
return super.onOptionsItemSelected(item);
}
}
| 26.676829 | 106 | 0.746514 |
e531eac14c1c99544930630b6cf0af241d8cd8c9
| 2,053 |
/*
* Copyright 2019-2020 David MacCormack
*
* 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.jsonurl.stream;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.io.IOException;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
/**
* Unit test for {@link org.jsonurl.stream.JsonUrlCharSequence
* JsonUrlCharSequence}.
*
* @author jsonurl.org
* @author David MacCormack
* @since 2019-11-01
*/
class JsonUrlCharSequenceTest {
@ParameterizedTest
@ValueSource(strings = {
"abcd\r\nabcd"
})
void testText(String text) throws IOException {
CharSequence ncs = text;
JsonUrlCharSequence jcs = new JsonUrlCharSequence(text);
assertEquals(ncs.length(), jcs.length(), text);
assertEquals(ncs.charAt(0), jcs.charAt(0), text);
assertEquals(ncs.subSequence(1, 2), jcs.subSequence(1, 2), text);
assertEquals(ncs.toString(), jcs.toString(), text);
assertEquals("<input>:0", CharIterator.toStringWithOffset(jcs), text);
assertEquals("<input>:1:0", CharIterator.toStringWithLine(jcs), text);
int pos = 0;
for (;;) {
int chr = jcs.nextChar();
if (chr == CharIterator.EOF) {
break;
}
if (ncs.charAt(pos) == '\r') { // NOPMD - AvoidLiteralsInIfCondition
pos++;
}
assertEquals(ncs.charAt(pos), chr, "text");
pos++;
}
}
}
| 29.328571 | 80 | 0.649781 |
7d332308754d5d1a54e9116d40079928026306d2
| 5,042 |
package mediajs.budgetbook.objects.entity;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import mediajs.budgetbook.objects.trans.StoreTO;
/**
* Created by Juergen on 02.03.2015.
*/
public class StoreDAO extends AbstractExpenditureComponentDAO
{
private static final String REAL_TYPE = " REAL";
public static final String SQL_CREATE_ENTRIES =
"CREATE TABLE " + StoreEntry.TABLE_NAME + " (" +
StoreEntry._ID + " INTEGER PRIMARY KEY," +
StoreEntry.COLUMN_VALUE + TEXT_TYPE + COMMA_SEP +
StoreEntry.COLUMN_LATITUDE + REAL_TYPE + COMMA_SEP +
StoreEntry.COLUMN_LONGITUDE + REAL_TYPE + COMMA_SEP +
StoreEntry.COLUMN_SUGGESTED + INTEGER_TYPE + COMMA_SEP +
StoreEntry.COLUMN_FAVORITE + INTEGER_TYPE +
" );";
public static final String SQL_DELETE_ENTRIES = "DROP TABLE IF EXISTS " + StoreEntry.TABLE_NAME;
private String[] allColumns =
{StoreEntry._ID, StoreEntry.COLUMN_VALUE, StoreEntry.COLUMN_SUGGESTED, StoreEntry.COLUMN_FAVORITE, StoreEntry
.COLUMN_LATITUDE, StoreEntry.COLUMN_LONGITUDE};
public StoreDAO( SQLiteDatabase pDatabase )
{
database = pDatabase;
}
public StoreTO createStore( StoreTO StoreTO )
{
ContentValues values = getContentValues( StoreTO );
long insertId = database.insert( StoreEntry.TABLE_NAME, null, values );
StoreTO newStoreTO = getStoreTOByUid( insertId );
return newStoreTO;
}
public StoreTO updateStore( StoreTO StoreTO )
{
ContentValues values = getContentValues( StoreTO );
long updateId = database.update( StoreEntry.TABLE_NAME, values, StoreEntry._ID + "=" + StoreTO.getUid(), null );
StoreTO newStoreTO = getStoreTOByUid( updateId );
return newStoreTO;
}
public void deleteStore( StoreTO StoreTO )
{
deleteStore( StoreTO.getUid() );
}
public void deleteStore( long id )
{
database.delete( StoreEntry.TABLE_NAME, StoreEntry._ID + "=" + id, null );
}
public StoreTO getStoreTOByUid( long uid )
{
Cursor cursor = database.query( StoreEntry.TABLE_NAME,
allColumns, StoreEntry._ID + " = " + uid, null,
null, null, null );
StoreTO result = null;
if( cursor.moveToFirst() )
{
result = cursorToStoreTO( cursor );
}
cursor.close();
return result;
}
public StoreTO getStoreTOByValue( String pValue )
{
Cursor cursor = database.query( StoreEntry.TABLE_NAME,
allColumns, "TRIM(" + StoreEntry.COLUMN_VALUE + ") = '" + pValue.trim() + "'", null,
null, null, null );
StoreTO result = null;
if( cursor.moveToFirst() )
{
result = cursorToStoreTO( cursor );
}
cursor.close();
return result;
}
public Cursor getAllStoreTOsAsCursor()
{
return database.query( StoreEntry.TABLE_NAME, allColumns, null, null, null, null, null );
}
public List<StoreTO> getAllStoreTOs()
{
Cursor cursor;
List<StoreTO> resultList = new LinkedList<StoreTO>();
cursor = getAllStoreTOsAsCursor();
if( cursor != null && cursor.getCount() > 0 && cursor.moveToFirst() )
{
do
{
resultList.add( cursorToStoreTO( cursor ) );
}
while( cursor.moveToNext() );
}
cursor.close();
return resultList;
}
public Map<Long, StoreTO> getAllStoreTOsAsMap()
{
Cursor cursor;
Map<Long, StoreTO> resultMap = new HashMap<Long, StoreTO>();
cursor = getAllStoreTOsAsCursor();
if( cursor != null && cursor.getCount() > 0 && cursor.moveToFirst() )
{
do
{
StoreTO storeTO = cursorToStoreTO( cursor );
resultMap.put( storeTO.getUid(), storeTO );
}
while( cursor.moveToNext() );
}
cursor.close();
return resultMap;
}
private ContentValues getContentValues( StoreTO StoreTO )
{
ContentValues values = new ContentValues();
values.put( StoreEntry.COLUMN_VALUE, StoreTO.getValue() );
values.put( StoreEntry.COLUMN_FAVORITE, StoreTO.isFavorite() ? 1 : 0 );
values.put( StoreEntry.COLUMN_LATITUDE, StoreTO.getLatitude() );
values.put( StoreEntry.COLUMN_LONGITUDE, StoreTO.getLongitude() );
return values;
}
private StoreTO cursorToStoreTO( Cursor cursor )
{
StoreTO StoreTO = new StoreTO();
StoreTO.setUid( cursor.getLong( 0 ) );
StoreTO.setValue( cursor.getString( 1 ) );
StoreTO.setSuggested( cursor.getInt( 2 ) > 0 );
StoreTO.setFavorite( cursor.getInt( 3 ) > 0 );
StoreTO.setLatitude( cursor.getDouble( 4 ) );
StoreTO.setLongitude( cursor.getDouble( 5 ) );
return StoreTO;
}
/* Inner class that defines the table contents */
public static abstract class StoreEntry implements IExpenditureComponentEntry
{
public static final String TABLE_NAME = "t_store";
/**
* The Latitude
* <P>Type: REAL</P>
*/
public static final String COLUMN_LATITUDE = "c_latitude";
/**
* The Longitude
* <P>Type: REAL</P>
*/
public static final String COLUMN_LONGITUDE = "c_longitude";
}
}
| 28.167598 | 118 | 0.687029 |
5ce91b3fd829f8f14418744210e43f6f85cda716
| 1,485 |
package com.linepro.modellbahn.converter.request.transcriber;
import static com.linepro.modellbahn.persistence.util.ProxyUtils.isAvailable;
import java.util.Optional;
import com.linepro.modellbahn.converter.Transcriber;
import com.linepro.modellbahn.entity.DecoderTypCv;
import com.linepro.modellbahn.repository.lookup.DecoderTypLookup;
import com.linepro.modellbahn.request.DecoderTypCvRequest;
import lombok.RequiredArgsConstructor;
@RequiredArgsConstructor
public class DecoderTypCvRequestTranscriber implements Transcriber<DecoderTypCvRequest,DecoderTypCv> {
private final DecoderTypLookup typLookup;
@Override
public DecoderTypCv apply(DecoderTypCvRequest source, DecoderTypCv destination) {
if (isAvailable(source) && isAvailable(destination)) {
if (destination.getDecoderTyp() == null) {
typLookup.find(source.getHersteller(), source.getBestellNr()).ifPresent(t -> destination.setDecoderTyp(t));
}
if (destination.getCv() == null) {
destination.setCv(source.getCv());
}
destination.setBezeichnung(source.getBezeichnung());
destination.setMinimal(source.getMinimal());
destination.setMaximal(source.getMaximal());
destination.setWerkseinstellung(source.getWerkseinstellung());
destination.setDeleted(Optional.ofNullable(source.getDeleted()).orElse(Boolean.FALSE));
}
return destination;
}
}
| 39.078947 | 123 | 0.727273 |
26574e241dada78d101a533959b3cadf4235b747
| 5,441 |
package com.vission.mf.base.util;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.MissingResourceException;
import java.util.ResourceBundle;
import org.springframework.context.i18n.LocaleContextHolder;
import com.vission.mf.base.enums.BaseConstants;
public class DateUtil {
public static String DATE_FORMAT = "yyyy-MM-dd";
public static String DATE_YMD = "yyyyMMdd";
public static String DATE_TIME_FORMAT = "yyyy-MM-dd HH:mm:ss";
/**
* 将Date类型转换为字符串
*/
public static String format(Date date) {
return format(date, "yyyy-MM-dd HH:mm:ss");
}
/**
* 将Date类型转换为字符串
*
* @param date
* 日期类型
* @param pattern
* 字符串格式
* @return 日期字符串
*/
public static String format(Date date, String pattern) {
if (date == null) {
return "null";
}
if (pattern == null || pattern.equals("") || pattern.equals("null")) {
pattern = "yyyy-MM-dd HH:mm:ss";
}
return new java.text.SimpleDateFormat(pattern).format(date);
}
/**
* 将字符串转换为Date类型
*
* @param date
* 字符串类型
* @return 日期类型
*/
public static Date format(String date) {
return format(date, null);
}
/**
* 将字符串转换为Date类型
*
* @param date
* 字符串类型
* @param pattern
* 格式
* @return 日期类型
*/
public static Date format(String date, String pattern) {
if (pattern == null || pattern.equals("") || pattern.equals("null")) {
pattern = "yyyy-MM-dd HH:mm:ss";
}
if (date == null || date.equals("") || date.equals("null")) {
return new Date();
}
// 避免yyyy-MM-dd型返回null
if (date.indexOf(":") < 0) {
date = date + " 00:00:00";
}
Date d = null;
try {
d = new java.text.SimpleDateFormat(pattern).parse(date);
} catch (ParseException pe) {
}
return d;
}
public static Date convertStringToDate(String aMask, String strDate)
throws ParseException {
SimpleDateFormat df;
Date date;
df = new SimpleDateFormat(aMask);
try {
date = df.parse(strDate);
} catch (ParseException pe) {
// log.error("ParseException: " + pe);
throw new ParseException(pe.getMessage(), pe.getErrorOffset());
}
return (date);
}
/**
* 切换字符串的日期格式
*
* @param date
* @param from
* @param to
* @return
*/
public static String changeDataPattern(String date, String from, String to) {
Date d = format(date, from);
if (to == null) {
to = "yyyy-MM-dd";
}
return format(d, to);
}
public static String getDatePattern() {
Locale locale = LocaleContextHolder.getLocale();
String defaultDatePattern;
try {
defaultDatePattern = ResourceBundle.getBundle(
BaseConstants.BUNDLE_KEY, locale).getString("date.format");
} catch (MissingResourceException mse) {
defaultDatePattern = "yyyy-MM-dd";
}
return defaultDatePattern;
}
public static Date getDateofToday() {
Date today = new Date();
SimpleDateFormat df = new SimpleDateFormat(getDatePattern());
String todayAsString = df.format(today);
return convertStringToDate(todayAsString);
}
public static Date convertStringToDate(String strDate) {
Date aDate = null;
try {
aDate = convertStringToDate(getDatePattern(), strDate);
} catch (ParseException pe) {
pe.printStackTrace();
}
return aDate;
}
/**
* @Title: getStrDateTOTimestamp
* @Description: 将yyyy-mm-dd 日期格式转换 Timestamp 类型
* @param @param delegatestarttime
* @param @return
* @return Timestamp
* @throws
*/
public static Timestamp getStrDateTOTimestamp(Object obj) {
if (obj == null) {
return null;
} else {
Date date = stringToDate(obj.toString(), DateUtil.DATE_FORMAT);
return new Timestamp(date.getTime());
}
}
/**
* 字符转化为日期
*
*
* @date 2011-12-14
* @param strDate
* @param pattern
* @return Date
*/
public static Date stringToDate(String strDate, String pattern) {
try {
long ltime = stringToLong(strDate, pattern);
return new Date(ltime);
} catch (Exception ex) {
return null;
}
}
/**
* 字符类型日期转化为长类型
*
*
* @date 2011-12-14
* @param strDate
* @param pattern
* @throws ParseException
* @return long
*/
public static long stringToLong(String strDate, String pattern)
throws ParseException {
Locale locale = Locale.CHINESE;
return stringToLong(strDate, pattern, locale);
}
/**
* 字符类型日期转化为长类型
*
*
* @date 2011-12-14
* @param strDate
* @param pattern
* @param locale
* @throws ParseException
* @return long
*/
public static long stringToLong(String strDate, String pattern,
Locale locale) throws ParseException {
SimpleDateFormat sdf = new SimpleDateFormat(pattern, locale);
Date date = sdf.parse(strDate);
return date.getTime();
}
/**
*
* @Title: getStrDateTOTimestampInTime
* @Description: String 转 Timestamp ,格式为:yyyy-MM-dd HH:mm:ss
* @param @param obj
* @param @return
* @return Timestamp
* @throws
*/
public static Timestamp getStrDateTOTimestampInTime(Object obj) {
if (obj == null) {
return null;
} else {
Date date = stringToDate(obj.toString(), DateUtil.DATE_TIME_FORMAT);
return new Timestamp(date.getTime());
}
}
/**
* @Title: getSystemDate
* @Description: 获取系统日期
* @param @return
* @return Date
* @throws
*/
public static Timestamp getSystemTime(){
Date date = new Date();
Timestamp nousedate = new Timestamp(date.getTime());
return nousedate;
}
}
| 21.677291 | 78 | 0.658151 |
44ba8f5dc660b0d1a0978caeca652871f6fb5785
| 2,955 |
/*******************************************************************************
* Copyright 2012 University of Southern California
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* This code was developed by the Information Integration Group as part
* of the Karma project at the Information Sciences Institute of the
* University of Southern California. For more information, publications,
* and related projects, please see: http://www.isi.edu/integration
******************************************************************************/
package edu.isi.karma.modeling.research;
// TODO this needs to be refactored into a properties file.
public class Params {
public static boolean RESEARCH_MODE = true;
// public static String DATASET_NAME = "museum-saam-crm";
// public static String DATASET_NAME = "museum-29-edm";
// public static String DATASET_NAME = "museum-29-crm";
// public static String DATASET_NAME = "museum-29-crm-lod";
// public static String DATASET_NAME = "museum-29-edm-lod";
public static String DATASET_NAME = "weapon-lod";
// public static String DATASET_NAME = "music";
public static String ROOT_DIR = "/Users/mohsen/Dropbox/__Mohsen__/ISI/source-modeling/datasets/" + DATASET_NAME + "/";
public static String ONTOLOGY_DIR = ROOT_DIR + "preloaded-ontologies/";
public static String OUTPUT_DIR = ROOT_DIR + "output/";
public static String GRAPHS_DIR = ROOT_DIR + "alignment-graph/";
public static String MODEL_DIR = ROOT_DIR + "models-json/";
public static String GRAPHVIS_DIR = ROOT_DIR + "models-graphviz/";
public static String SOURCE_DIR = ROOT_DIR + "sources/";
public static String R2RML_DIR = ROOT_DIR + "models-r2rml/";
public static String RESULTS_DIR = ROOT_DIR + "results/";
public static String GRAPH_JSON_FILE_EXT = ".graph.json";
public static String GRAPH_GRAPHVIZ_FILE_EXT = ".dot";
public static String MODEL_MAIN_FILE_EXT = ".model.json";
public static String GRAPHVIS_MAIN_FILE_EXT = ".model.dot";
public static String GRAPHVIS_OUT_FILE_EXT = ".out.dot";
public static String GRAPHVIS_OUT_DETAILS_FILE_EXT = ".out.details.dot";
public static String LOD_DIR = ROOT_DIR + "lod/";
public static String PATTERNS_INPUT_DIR = "patterns/input/";
public static String PATTERNS_OUTPUT_DIR = "patterns/output/";
public static String LOD_OBJECT_PROPERIES_FILE = "object-properties.csv";
public static String LOD_DATA_PROPERIES_FILE = "data-properties.csv";
}
| 45.461538 | 119 | 0.716751 |
c37056cac1a408a7e1abb17d96b26c04a5ad1d6a
| 10,857 |
begin_unit|revision:0.9.5;language:Java;cregit-version:0.0.1
begin_comment
comment|/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */
end_comment
begin_package
package|package
name|org
operator|.
name|apache
operator|.
name|activemq
operator|.
name|bugs
package|;
end_package
begin_import
import|import static
name|org
operator|.
name|junit
operator|.
name|Assert
operator|.
name|assertNotNull
import|;
end_import
begin_import
import|import
name|java
operator|.
name|util
operator|.
name|UUID
import|;
end_import
begin_import
import|import
name|javax
operator|.
name|jms
operator|.
name|BytesMessage
import|;
end_import
begin_import
import|import
name|javax
operator|.
name|jms
operator|.
name|Connection
import|;
end_import
begin_import
import|import
name|javax
operator|.
name|jms
operator|.
name|Message
import|;
end_import
begin_import
import|import
name|javax
operator|.
name|jms
operator|.
name|MessageConsumer
import|;
end_import
begin_import
import|import
name|javax
operator|.
name|jms
operator|.
name|MessageProducer
import|;
end_import
begin_import
import|import
name|javax
operator|.
name|jms
operator|.
name|Session
import|;
end_import
begin_import
import|import
name|javax
operator|.
name|jms
operator|.
name|Topic
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|activemq
operator|.
name|ActiveMQConnectionFactory
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|activemq
operator|.
name|advisory
operator|.
name|AdvisorySupport
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|activemq
operator|.
name|broker
operator|.
name|BrokerService
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|activemq
operator|.
name|broker
operator|.
name|region
operator|.
name|policy
operator|.
name|PolicyEntry
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|activemq
operator|.
name|broker
operator|.
name|region
operator|.
name|policy
operator|.
name|PolicyMap
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|activemq
operator|.
name|command
operator|.
name|ActiveMQDestination
import|;
end_import
begin_import
import|import
name|org
operator|.
name|junit
operator|.
name|After
import|;
end_import
begin_import
import|import
name|org
operator|.
name|junit
operator|.
name|Before
import|;
end_import
begin_import
import|import
name|org
operator|.
name|junit
operator|.
name|Rule
import|;
end_import
begin_import
import|import
name|org
operator|.
name|junit
operator|.
name|Test
import|;
end_import
begin_import
import|import
name|org
operator|.
name|junit
operator|.
name|rules
operator|.
name|TestName
import|;
end_import
begin_import
import|import
name|org
operator|.
name|slf4j
operator|.
name|Logger
import|;
end_import
begin_import
import|import
name|org
operator|.
name|slf4j
operator|.
name|LoggerFactory
import|;
end_import
begin_class
specifier|public
class|class
name|AMQ6264Test
block|{
specifier|private
specifier|static
specifier|final
name|Logger
name|LOG
init|=
name|LoggerFactory
operator|.
name|getLogger
argument_list|(
name|AMQ6264Test
operator|.
name|class
argument_list|)
decl_stmt|;
annotation|@
name|Rule
specifier|public
specifier|final
name|TestName
name|testName
init|=
operator|new
name|TestName
argument_list|()
decl_stmt|;
specifier|protected
specifier|final
name|int
name|MESSAGE_COUNT
init|=
literal|2000
decl_stmt|;
specifier|private
specifier|final
name|String
name|topicPrefix
init|=
literal|"topic."
decl_stmt|;
specifier|private
specifier|final
name|String
name|topicFilter
init|=
name|topicPrefix
operator|+
literal|">"
decl_stmt|;
specifier|private
specifier|final
name|String
name|topicA
init|=
literal|"topic.A"
decl_stmt|;
specifier|private
name|BrokerService
name|broker
decl_stmt|;
specifier|private
name|Connection
name|connection
decl_stmt|;
specifier|private
name|String
name|connectionURI
decl_stmt|;
annotation|@
name|Test
argument_list|(
name|timeout
operator|=
literal|60000
argument_list|)
specifier|public
name|void
name|testSlowConsumerAdvisory
parameter_list|()
throws|throws
name|Exception
block|{
name|Session
name|session
init|=
name|connection
operator|.
name|createSession
argument_list|(
literal|false
argument_list|,
name|Session
operator|.
name|AUTO_ACKNOWLEDGE
argument_list|)
decl_stmt|;
name|Topic
name|topic
init|=
name|session
operator|.
name|createTopic
argument_list|(
name|topicFilter
argument_list|)
decl_stmt|;
name|MessageConsumer
name|consumer
init|=
name|session
operator|.
name|createDurableSubscriber
argument_list|(
name|topic
argument_list|,
name|testName
operator|.
name|getMethodName
argument_list|()
argument_list|)
decl_stmt|;
name|assertNotNull
argument_list|(
name|consumer
argument_list|)
expr_stmt|;
name|Topic
name|advisoryTopic
init|=
name|AdvisorySupport
operator|.
name|getSlowConsumerAdvisoryTopic
argument_list|(
name|ActiveMQDestination
operator|.
name|createDestination
argument_list|(
name|topicA
argument_list|,
name|ActiveMQDestination
operator|.
name|TOPIC_TYPE
argument_list|)
argument_list|)
decl_stmt|;
name|session
operator|=
name|connection
operator|.
name|createSession
argument_list|(
literal|false
argument_list|,
name|Session
operator|.
name|AUTO_ACKNOWLEDGE
argument_list|)
expr_stmt|;
name|MessageConsumer
name|advisoryConsumer
init|=
name|session
operator|.
name|createConsumer
argument_list|(
name|advisoryTopic
argument_list|)
decl_stmt|;
comment|// start throwing messages at the consumer one for an ongoing series of
comment|// matching topics for the subscription's filter.
name|MessageProducer
name|producer
init|=
name|session
operator|.
name|createProducer
argument_list|(
literal|null
argument_list|)
decl_stmt|;
comment|// Send one to the destination where we want a matching advisory
name|producer
operator|.
name|send
argument_list|(
name|session
operator|.
name|createTopic
argument_list|(
name|topicA
argument_list|)
argument_list|,
name|session
operator|.
name|createMessage
argument_list|()
argument_list|)
expr_stmt|;
for|for
control|(
name|int
name|i
init|=
literal|0
init|;
name|i
operator|<
name|MESSAGE_COUNT
condition|;
name|i
operator|++
control|)
block|{
name|BytesMessage
name|m
init|=
name|session
operator|.
name|createBytesMessage
argument_list|()
decl_stmt|;
name|m
operator|.
name|writeBytes
argument_list|(
operator|new
name|byte
index|[
literal|1024
index|]
argument_list|)
expr_stmt|;
name|Topic
name|newTopic
init|=
name|session
operator|.
name|createTopic
argument_list|(
name|topicPrefix
operator|+
name|UUID
operator|.
name|randomUUID
argument_list|()
operator|.
name|toString
argument_list|()
argument_list|)
decl_stmt|;
name|LOG
operator|.
name|debug
argument_list|(
literal|"Sending message to next topic: {}"
argument_list|,
name|newTopic
argument_list|)
expr_stmt|;
name|producer
operator|.
name|send
argument_list|(
name|newTopic
argument_list|,
name|m
argument_list|)
expr_stmt|;
block|}
name|Message
name|msg
init|=
name|advisoryConsumer
operator|.
name|receive
argument_list|(
literal|1000
argument_list|)
decl_stmt|;
name|assertNotNull
argument_list|(
name|msg
argument_list|)
expr_stmt|;
block|}
annotation|@
name|Before
specifier|public
name|void
name|setUp
parameter_list|()
throws|throws
name|Exception
block|{
name|broker
operator|=
name|createBroker
argument_list|()
expr_stmt|;
name|connectionURI
operator|=
name|broker
operator|.
name|getTransportConnectors
argument_list|()
operator|.
name|get
argument_list|(
literal|0
argument_list|)
operator|.
name|getPublishableConnectString
argument_list|()
expr_stmt|;
name|ActiveMQConnectionFactory
name|factory
init|=
name|createConnectionFactory
argument_list|()
decl_stmt|;
name|connection
operator|=
name|factory
operator|.
name|createConnection
argument_list|()
expr_stmt|;
name|connection
operator|.
name|setClientID
argument_list|(
name|getClass
argument_list|()
operator|.
name|getSimpleName
argument_list|()
argument_list|)
expr_stmt|;
name|connection
operator|.
name|start
argument_list|()
expr_stmt|;
block|}
annotation|@
name|After
specifier|public
name|void
name|tearDown
parameter_list|()
throws|throws
name|Exception
block|{
name|connection
operator|.
name|close
argument_list|()
expr_stmt|;
if|if
condition|(
name|broker
operator|!=
literal|null
condition|)
block|{
name|broker
operator|.
name|stop
argument_list|()
expr_stmt|;
block|}
block|}
specifier|protected
name|ActiveMQConnectionFactory
name|createConnectionFactory
parameter_list|()
throws|throws
name|Exception
block|{
return|return
operator|new
name|ActiveMQConnectionFactory
argument_list|(
name|connectionURI
argument_list|)
return|;
block|}
specifier|protected
name|BrokerService
name|createBroker
parameter_list|()
throws|throws
name|Exception
block|{
name|BrokerService
name|answer
init|=
operator|new
name|BrokerService
argument_list|()
decl_stmt|;
name|answer
operator|.
name|setPersistent
argument_list|(
literal|false
argument_list|)
expr_stmt|;
name|PolicyEntry
name|policy
init|=
operator|new
name|PolicyEntry
argument_list|()
decl_stmt|;
name|policy
operator|.
name|setAdvisoryForSlowConsumers
argument_list|(
literal|true
argument_list|)
expr_stmt|;
name|policy
operator|.
name|setProducerFlowControl
argument_list|(
literal|false
argument_list|)
expr_stmt|;
name|PolicyMap
name|pMap
init|=
operator|new
name|PolicyMap
argument_list|()
decl_stmt|;
name|pMap
operator|.
name|setDefaultEntry
argument_list|(
name|policy
argument_list|)
expr_stmt|;
name|answer
operator|.
name|setUseJmx
argument_list|(
literal|true
argument_list|)
expr_stmt|;
name|answer
operator|.
name|setDestinationPolicy
argument_list|(
name|pMap
argument_list|)
expr_stmt|;
name|answer
operator|.
name|addConnector
argument_list|(
literal|"tcp://0.0.0.0:0"
argument_list|)
expr_stmt|;
name|answer
operator|.
name|setDeleteAllMessagesOnStartup
argument_list|(
literal|true
argument_list|)
expr_stmt|;
name|answer
operator|.
name|start
argument_list|()
expr_stmt|;
return|return
name|answer
return|;
block|}
block|}
end_class
end_unit
| 14.248031 | 810 | 0.80934 |
da368bef56fbd7f91a0845081014ab8a0efad290
| 332 |
package com.ltts.movieapp.service;
import java.util.List;
import org.springframework.stereotype.Service;
import com.ltts.movieapp.model.Customer;
@Service
public interface CustomerService {
void save(Customer email);
public Customer findByEmailAndMobile(String email, String mobile);
public List<Customer> findAll();
}
| 17.473684 | 67 | 0.789157 |
1b05b488253055fda4d98aaf72e6a7c94aa6a8a2
| 4,688 |
package com.jxtech.common;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
import com.jxtech.app.jxvars.JxVars;
import com.jxtech.app.jxvars.JxVarsFactory;
import com.jxtech.util.JsonUtil;
import com.jxtech.util.StrUtil;
/**
* Spring 中的参数配置,可以读取
*
* @author wmzsoft@gmail.com
* @date 2013.09
*/
public class JxParams implements Serializable {
private static final long serialVersionUID = 988179958465814835L;
private String userInfoUrl;// 获得用户信息的URL地址。
private String loginUrl;// 本系统的登录地址。
private String reportUrl;// 报表地址
private String doclink;// 文件访问连接地址
private String docpath;// 文件存储地址
private boolean jndi;
private boolean constantConnection;// 是否采用常连接
private Map<String, String> fileTypes;// 文件类型、缩略图的显示地址,为空代表直接显示
private String authenticate;// 认证实现类
private String permission;// 权限验证实现类
private String obpmUser;// oracle bpm 管理用户
private String obpmPass;// Oracle bpm 管理用户密码
private String obpmJndi;// oracle bpm 访问地址
// private static final Logger LOG = LoggerFactory.getLogger(JxParams.class);
private static class SingletonHolder {
private static final JxParams INSTANCE = new JxParams();
}
private JxParams() {
JxVars vars = JxVarsFactory.getInstance();
this.userInfoUrl = vars.getValue("jx.comtop.userinfourl");
this.loginUrl = vars.getValue("jx.loginurl");
this.reportUrl = vars.getValue("jx.report.url");
this.doclink = vars.getValue("jx.doclink");
this.docpath = vars.getValue("jx.docpath");
this.jndi = "true".equalsIgnoreCase(vars.getValue("jx.db.jndi", "false"));
this.constantConnection = "true".equalsIgnoreCase(vars.getValue("jx.db.constantConnection", "false"));
this.authenticate = vars.getValue("jx.authenticate.class");
this.permission = vars.getValue("jx.permission.class");
this.obpmJndi = vars.getValue("jx.obpm.jndi");
this.obpmUser = vars.getValue("jx.obpm.user");
this.obpmPass = vars.getValue("jx.obpm.pass");
String ftypes = System.getProperty("jx.fileTypes");
if (!StrUtil.isNull(ftypes)) {
this.fileTypes = new HashMap<String, String>();
Map<String, Object> fs = JsonUtil.json2map(ftypes);
for (Map.Entry<String, Object> entry : fs.entrySet()) {
fileTypes.put(entry.getKey(), String.valueOf(entry.getValue()));
}
}
}
public static JxParams getInstance() {
return SingletonHolder.INSTANCE;
}
public boolean isJndi() {
return jndi;
}
public void setJndi(boolean jndi) {
this.jndi = jndi;
}
public String getUserInfoUrl() {
return userInfoUrl;
}
public void setUserInfoUrl(String userInfoUrl) {
this.userInfoUrl = userInfoUrl;
}
public String getLoginUrl() {
return loginUrl;
}
public void setLoginUrl(String loginUrl) {
this.loginUrl = loginUrl;
}
public String getReportUrl() {
return reportUrl;
}
public void setReportUrl(String reportUrl) {
this.reportUrl = reportUrl;
}
public String getDoclink() {
return doclink;
}
public void setDoclink(String doclink) {
this.doclink = doclink;
}
public String getDocpath() {
return docpath;
}
public void setDocpath(String docpath) {
this.docpath = docpath;
}
public boolean isConstantConnection() {
return constantConnection;
}
public void setConstantConnection(boolean constantConnection) {
this.constantConnection = constantConnection;
}
public Map<String, String> getFileTypes() {
return fileTypes;
}
public void setFileTypes(Map<String, String> fileTypes) {
this.fileTypes = fileTypes;
}
public String getAuthenticate() {
return authenticate;
}
public void setAuthenticate(String authenticate) {
this.authenticate = authenticate;
}
public String getObpmUser() {
return obpmUser;
}
public void setObpmUser(String obpmUser) {
this.obpmUser = obpmUser;
}
public String getObpmPass() {
return obpmPass;
}
public void setObpmPass(String obpmPass) {
this.obpmPass = obpmPass;
}
public String getObpmJndi() {
return obpmJndi;
}
public void setObpmJndi(String obpmJndi) {
this.obpmJndi = obpmJndi;
}
public String getPermission() {
return permission;
}
public void setPermission(String permission) {
this.permission = permission;
}
}
| 26.788571 | 110 | 0.650384 |
e8c3c1b7bace263d63a7c43e09adf3ac3cfa942c
| 1,051 |
package terminal;
import java.io.File;
import java.util.Scanner;
public class Terminal {
private File curr;
private CommandSearch commandSearch = new CommandSearch();
public Terminal() {
String os = System.getProperty("os.name");
System.out.println(os);
String message = System.getProperty("user.name");
System.out.println(message);
if (os.toLowerCase().contains("mac")) {
curr = new File("");
message = "command: ";
} else {
curr = new File("/home");
message += "@linux: ";
}
while (true) {
Scanner scanner = new Scanner(System.in);
System.out.print(message);
String command = scanner.nextLine();
try {
curr = commandSearch.findAndExecute(command, curr);
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
}
}
}
}
| 29.194444 | 67 | 0.536632 |
c902f37cc017079781881a078fc41925fe74e352
| 4,838 |
/*
* Copyright (c) CP4J Project
*/
package com.vb.tasks;
import com.vb.datastructure.StringBoard;
import com.vb.datastructure.cell2d.Cell2D;
import com.vb.datastructure.cell2d.CellIterationOrder;
import com.vb.datastructure.cell2d.Direction;
import com.vb.io.FastScanner;
import com.vb.io.FastWriter;
import com.vb.logging.Log;
import com.vb.nd.IntNDArray;
import com.vb.nd.NDShape;
import com.vb.number.DefaultIntArithmetic;
import com.vb.number.IntArithmetic;
import com.vb.task.CPTaskSolver;
import com.vb.utils.MathUtils;
import java.io.IOException;
// Powered by CP4J - https://github.com/duc0/CP4J
public class CF1393_D implements CPTaskSolver {
long solveBruteForce(StringBoard board) {
long result = 0;
Cell2D cell = new Cell2D(0, 0);
do {
int len = 1;
while (true) {
result++;
len++;
if (!isOuterSquare(board, cell.row, cell.col, len)) {
break;
}
}
} while (cell.next(CellIterationOrder.ROW_MAJOR, board.getSize()));
return result;
}
private boolean isOuterSquare(StringBoard board, int row, int col, int len) {
char ch = board.get(row, col);
if (!board.inBoard(row, col - 1) || board.get(row, col - 1) != ch) {
return false;
}
for (int i = 0, curRow = row, curCol = col; i < len; i++) {
if (!board.inBoard(curRow, curCol) || board.get(curRow, curCol) != ch) {
return false;
}
curRow -= 1;
curCol -= 1;
}
for (int i = 0, curRow = row, curCol = col; i < len; i++) {
if (!board.inBoard(curRow, curCol) || board.get(curRow, curCol) != ch) {
return false;
}
curRow += 1;
curCol -= 1;
}
int firstCol = col - 2 * (len - 1);
for (int i = 0, curRow = row, curCol = firstCol; i < len; i++) {
if (!board.inBoard(curRow, curCol) || board.get(curRow, curCol) != ch) {
return false;
}
curRow += 1;
curCol += 1;
}
for (int i = 0, curRow = row, curCol = firstCol; i < len; i++) {
if (!board.inBoard(curRow, curCol) || board.get(curRow, curCol) != ch) {
return false;
}
curRow -= 1;
curCol += 1;
}
return true;
}
long solveDp(StringBoard board) {
IntArithmetic arithmetic = new DefaultIntArithmetic();
NDShape shape = new NDShape(board.numRows(), board.numColumns());
IntNDArray longestDiag1 = new IntNDArray(arithmetic, shape);
IntNDArray longestDiag2 = new IntNDArray(arithmetic, shape);
IntNDArray longestSquare = new IntNDArray(arithmetic, shape);
long result = 0;
Cell2D cur = new Cell2D(0, 0);
do {
char ch = board.get(cur);
Cell2D prevDiag1 = cur.apply(Direction.DOWN_LEFT);
boolean hasDiag1 = false;
if (board.inBoard(prevDiag1) && board.get(prevDiag1) == ch) {
hasDiag1 = true;
longestDiag1.set(cur, longestDiag1.get(prevDiag1) + 1);
} else {
longestDiag1.set(cur, 1);
}
Cell2D prevDiag2 = cur.apply(Direction.UP_LEFT);
boolean hasDiag2 = false;
if (board.inBoard(prevDiag2) && board.get(prevDiag2) == ch) {
hasDiag2 = true;
longestDiag2.set(cur, longestDiag2.get(prevDiag2) + 1);
} else {
longestDiag2.set(cur, 1);
}
Cell2D prevSquare = cur.apply(Direction.LEFT);
if (board.inBoard(prevSquare) && board.get(prevSquare) == ch && hasDiag1 && hasDiag2) {
int candidate =
MathUtils.min(
longestSquare.get(prevSquare),
longestDiag1.get(cur) - 1,
longestDiag2.get(cur) - 1);
if (candidate > 0
&& board.inBoard(cur.row, cur.col - 2 * candidate)
&& longestSquare.get(prevDiag1) >= candidate
&& longestSquare.get(prevDiag2) >= candidate
&& board.get(cur.row, cur.col - 2 * candidate) == ch) {
candidate++;
}
longestSquare.set(cur, candidate);
} else {
longestSquare.set(cur, 1);
}
result += longestSquare.get(cur);
Log.d("Value {0} {1} {2}", cur.row + 1, cur.col + 1, longestSquare.get(cur));
} while (cur.next(CellIterationOrder.DIAG_UP_RIGHT, board.getSize()));
return result;
}
@Override
public void solve(int testNumber, FastScanner in, FastWriter out) throws IOException {
// Log.setDebug(true);
int[] header = in.readTokensAsIntArray();
StringBoard board = new StringBoard(header[0], header[1]);
for (int row = 0; row < board.numRows(); row++) {
board.setRow(row, in.nextLineAsString());
}
long result = solveDp(board);
if (board.getSize().size() <= 100) {
long solveBf = solveBruteForce(board);
if (solveBf != result) {
throw new RuntimeException("Bad bruteforce = " + solveBf);
}
}
out.write(result);
out.flush();
}
}
| 31.828947 | 93 | 0.600661 |
39718047c5fd50dc195ad5e0e601356a45536049
| 3,259 |
package frc.robot.subsystems;
import com.ctre.phoenix.motorcontrol.ControlMode;
import com.ctre.phoenix.motorcontrol.FeedbackDevice;
import com.ctre.phoenix.motorcontrol.NeutralMode;
import com.ctre.phoenix.motorcontrol.can.TalonSRX;
import edu.wpi.first.wpilibj.DigitalInput;
import edu.wpi.first.wpilibj2.command.SubsystemBase;
import frc.robot.RobotMap;
public class ClimberSRXSubsystem extends SubsystemBase{
private final TalonSRX climbMotor;
// Limit switches
private final DigitalInput lowerSwitch, upperSwitch;
private boolean isClimbing, isReleasing;
private int upRevolution, downRevolution;
public ClimberSRXSubsystem() {
climbMotor = new TalonSRX(RobotMap.climbMotor);
climbMotor.configSelectedFeedbackSensor(FeedbackDevice.IntegratedSensor);
lowerSwitch = new DigitalInput(0);
upperSwitch = new DigitalInput(1);
climbMotor.setNeutralMode(NeutralMode.Brake);
}
public void pullUpRobot() {
isClimbing = true;
climbMotor.set(ControlMode.PercentOutput, -1.0);
while (isClimbing) {
if (lowerSwitch.get()) {
downRevolution += 1;
}
if (downRevolution >= 5) {
climbMotor.set(ControlMode.PercentOutput, 0.0);
climbMotor.setNeutralMode(NeutralMode.Brake);
isClimbing = false;
}
}
}
public void climberRelease() {
isReleasing = true;
climbMotor.setNeutralMode(NeutralMode.Coast);
climbMotor.set(ControlMode.PercentOutput, 1.0);
while (isReleasing) {
if (upperSwitch.get()) {
upRevolution += 1;
}
if (upRevolution >= 5) {
climbMotor.set(ControlMode.PercentOutput, 0.0);
climbMotor.setNeutralMode(NeutralMode.Brake);
isReleasing = false;
}
}
// C1encoder.setPosition(0);
// C2encoder.setPosition(0);
// RightClimbMotor.set(ControlMode.Follower, RobotMap.LeftClimbMotor);
// set motors to neutral so spring can expand (coast)
// RightClimbMotor.setNeutralMode(NeutralMode.Coast);
// RightClimbMotor.setIdleMode(IdleMode.kCoast);
// ClimbMotor.setIdleMode(IdleMode.kCoast);
// Climb_encoder = ClimbMotor.getEncoder();
// Right_encoder = RightClimbMotor.getEncoder();
// boolean Latching = true;
// while (Latching) {
// //check encoder value to make sure it doesn't go too far
// // double MotorPos = LeftClimbMotor.getSelectedSensorPosition();
// // double MotorPos = m_encoder.getPosition();
// //stop motors once they reach target distance (or set them to hold position)
// //4096 encoder counts in a single revoloution of CANSpark
// if (Left_encoder.getPosition() >= 2048) {
// Latching = false;
// // LeftClimbMotor.setNeutralMode(NeutralMode.Brake);
// // RightClimbMotor.setNeutralMode(NeutralMode.Brake);
// //RightClimbMotor.setIdleMode(IdleMode.kBrake);
// ClimbMotor.setIdleMode(IdleMode.kBrake);
// }
// }
}
}
| 33.255102 | 87 | 0.629027 |
11c9574da87be6d0f9ad1d8b24131ec21d185493
| 1,158 |
package chapter8;
import javax.management.ValueExp;
import java.util.function.IntPredicate;
import java.util.function.IntUnaryOperator;
import java.util.stream.IntStream;
public class StreamTest {
public static void main(String[] args) {
IntStream build = IntStream.builder()
.add(12)
.add(51)
.add(31)
.build();
// System.out.println("max "+build.max());
// System.out.println("min "+build.min().getAsInt());
// System.out.println("sum"+build.sum());
// System.out.println("count"+build.count());
// System.out.println("average"+build.average());
// System.out.println(build.allMatch(new IntPredicate() {
// @Override
// public boolean test(int value) {
// if (value >10)return true;
// return false;
// }
// }));
IntStream intStream = build.map(new IntUnaryOperator() {
@Override
public int applyAsInt(int operand) {
return 1+operand;
}
});
intStream.forEach(System.out::println);
}
}
| 31.297297 | 64 | 0.549223 |
871c54493a1fb6a2baa16374db15d929f2fc84dd
| 722 |
package com.huaying.hqwmall.order.config;
import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import javax.sql.DataSource;
/**
* mybatis-plus配置
*
* @author Mark sunlightcs@gmail.com
*/
@Configuration
@MapperScan({"com.huaying.hqwmall.order.dao"})
public class MybatisPlusConfig {
/**
* 分页插件
*/
@Bean
public PaginationInterceptor paginationInterceptor() {
return new PaginationInterceptor();
}
}
| 24.066667 | 72 | 0.770083 |
1e6b58ed3fdb1edbbf969b42f13d693329c1db36
| 34,858 |
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is part of dcm4che, an implementation of DICOM(TM) in
* Java(TM), hosted at http://sourceforge.net/projects/dcm4che.
*
* The Initial Developer of the Original Code is
* Gunter Zeilinger, Huetteldorferstr. 24/10, 1150 Vienna/Austria/Europe.
* Portions created by the Initial Developer are Copyright (C) 2002-2005
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Gunter Zeilinger <gunterze@gmail.com>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
package org.dcm4che2.tool.dcmmwl;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.security.GeneralSecurityException;
import java.security.KeyStore;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executor;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.GnuParser;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.OptionBuilder;
import org.apache.commons.cli.OptionGroup;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
import org.dcm4che2.data.BasicDicomObject;
import org.dcm4che2.data.DicomObject;
import org.dcm4che2.data.Tag;
import org.dcm4che2.data.UID;
import org.dcm4che2.net.Association;
import org.dcm4che2.net.CommandUtils;
import org.dcm4che2.net.ConfigurationException;
import org.dcm4che2.net.Device;
import org.dcm4che2.net.DimseRSP;
import org.dcm4che2.net.NetworkApplicationEntity;
import org.dcm4che2.net.NetworkConnection;
import org.dcm4che2.net.NewThreadExecutor;
import org.dcm4che2.net.NoPresentationContextException;
import org.dcm4che2.net.TransferCapability;
import org.dcm4che2.net.UserIdentity;
/**
* @author gunter zeilinger(gunterze@gmail.com)
* @version $Revision: 14419 $ $Date: 2010-11-26 14:22:31 +0100 (Fr, 26 Nov 2010) $
* @since Mar 18, 2006
*
*/
public class DcmMWL {
private static final int KB = 1024;
private static final String USAGE = "dcmmwl <aet>[@<host>[:<port>]] [Options]";
private static final String DESCRIPTION =
"Query specified remote Application Entity (=Modality Worklist SCP) " +
"If <port> is not specified, DICOM default port 104 is assumed. " +
"If also no <host> is specified localhost is assumed.\n" +
"Options:";
private static final String EXAMPLE =
"\nExample: dcmmwl MWLSCP@localhost:11112 -mod CT -date 20060502\n" +
"=> Query Application Entity MWLSCP listening on local port 11112 for " +
"CT procedure steps scheduled for May 2, 2006.";
private static String[] TLS1 = { "TLSv1" };
private static String[] SSL3 = { "SSLv3" };
private static String[] NO_TLS1 = { "SSLv3", "SSLv2Hello" };
private static String[] NO_SSL2 = { "TLSv1", "SSLv3" };
private static String[] NO_SSL3 = { "TLSv1", "SSLv2Hello" };
private static char[] SECRET = { 's', 'e', 'c', 'r', 'e', 't' };
private static final int[] RETURN_KEYS = {
Tag.AccessionNumber,
Tag.ReferringPhysicianName,
Tag.PatientName,
Tag.PatientID,
Tag.PatientBirthDate,
Tag.PatientSex,
Tag.PatientWeight,
Tag.MedicalAlerts,
Tag.Allergies,
Tag.PregnancyStatus,
Tag.StudyInstanceUID,
Tag.RequestingPhysician,
Tag.RequestingService,
Tag.RequestedProcedureDescription,
Tag.AdmissionID,
Tag.SpecialNeeds,
Tag.CurrentPatientLocation,
Tag.PatientState,
Tag.RequestedProcedureID,
Tag.RequestedProcedurePriority,
Tag.PatientTransportArrangements,
Tag.PlacerOrderNumberImagingServiceRequest,
Tag.FillerOrderNumberImagingServiceRequest,
Tag.ConfidentialityConstraintOnPatientDataDescription,
};
private static final int[] SPS_RETURN_KEYS = {
Tag.Modality,
Tag.RequestedContrastAgent,
Tag.ScheduledStationAETitle,
Tag.ScheduledProcedureStepStartDate,
Tag.ScheduledProcedureStepStartTime,
Tag.ScheduledPerformingPhysicianName,
Tag.ScheduledProcedureStepDescription,
Tag.ScheduledProcedureStepID,
Tag.ScheduledStationName,
Tag.ScheduledProcedureStepLocation,
Tag.PreMedication,
Tag.ScheduledProcedureStepStatus
};
private static final String[] IVRLE_TS = {
UID.ImplicitVRLittleEndian };
private static final String[] LE_TS = {
UID.ExplicitVRLittleEndian,
UID.ImplicitVRLittleEndian };
private static final byte[] EXT_NEG_INFO_FUZZY_MATCHING = { 1, 1, 1 };
private final Executor executor;
private final NetworkApplicationEntity remoteAE = new NetworkApplicationEntity();
private final NetworkConnection remoteConn = new NetworkConnection();
private final Device device;
private final NetworkApplicationEntity ae = new NetworkApplicationEntity();
private final NetworkConnection conn = new NetworkConnection();
private Association assoc;
private int priority = 0;
private int cancelAfter = Integer.MAX_VALUE;
private final DicomObject keys = new BasicDicomObject();
private final DicomObject spsKeys = new BasicDicomObject();
private boolean fuzzySemanticPersonNameMatching;
private String keyStoreURL = "resource:tls/test_sys_1.p12";
private char[] keyStorePassword = SECRET;
private char[] keyPassword;
private String trustStoreURL = "resource:tls/mesa_certs.jks";
private char[] trustStorePassword = SECRET;
public DcmMWL(String name) {
device = new Device(name);
executor = new NewThreadExecutor(name);
remoteAE.setInstalled(true);
remoteAE.setAssociationAcceptor(true);
remoteAE.setNetworkConnection(new NetworkConnection[] { remoteConn });
device.setNetworkApplicationEntity(ae);
device.setNetworkConnection(conn);
ae.setNetworkConnection(conn);
ae.setAssociationInitiator(true);
ae.setAETitle(name);
for (int i = 0; i < RETURN_KEYS.length; i++) {
keys.putNull(RETURN_KEYS[i], null);
}
keys.putNestedDicomObject(Tag.RequestedProcedureCodeSequence,
new BasicDicomObject());
keys.putNestedDicomObject(Tag.ScheduledProcedureStepSequence, spsKeys);
for (int i = 0; i < SPS_RETURN_KEYS.length; i++) {
spsKeys.putNull(SPS_RETURN_KEYS[i], null);
}
spsKeys.putNestedDicomObject(Tag.ScheduledProtocolCodeSequence,
new BasicDicomObject());
}
public final void setLocalHost(String hostname) {
conn.setHostname(hostname);
}
public final void setRemoteHost(String hostname) {
remoteConn.setHostname(hostname);
}
public final void setRemotePort(int port) {
remoteConn.setPort(port);
}
public final void setTlsProtocol(String[] tlsProtocol) {
conn.setTlsProtocol(tlsProtocol);
}
public final void setTlsWithoutEncyrption() {
conn.setTlsWithoutEncyrption();
remoteConn.setTlsWithoutEncyrption();
}
public final void setTls3DES_EDE_CBC() {
conn.setTls3DES_EDE_CBC();
remoteConn.setTls3DES_EDE_CBC();
}
public final void setTlsAES_128_CBC() {
conn.setTlsAES_128_CBC();
remoteConn.setTlsAES_128_CBC();
}
public final void setTlsNeedClientAuth(boolean needClientAuth) {
conn.setTlsNeedClientAuth(needClientAuth);
}
public final void setKeyStoreURL(String url) {
keyStoreURL = url;
}
public final void setKeyStorePassword(String pw) {
keyStorePassword = pw.toCharArray();
}
public final void setKeyPassword(String pw) {
keyPassword = pw.toCharArray();
}
public final void setTrustStorePassword(String pw) {
trustStorePassword = pw.toCharArray();
}
public final void setTrustStoreURL(String url) {
trustStoreURL = url;
}
public final void setCalledAET(String called) {
remoteAE.setAETitle(called);
}
public final void setCalling(String calling) {
ae.setAETitle(calling);
}
public final void setUserIdentity(UserIdentity userIdentity) {
ae.setUserIdentity(userIdentity);
}
public final void setPriority(int priority) {
this.priority = priority;
}
public final void setConnectTimeout(int connectTimeout) {
conn.setConnectTimeout(connectTimeout);
}
public final void setMaxPDULengthReceive(int maxPDULength) {
ae.setMaxPDULengthReceive(maxPDULength);
}
public final void setPackPDV(boolean packPDV) {
ae.setPackPDV(packPDV);
}
public final void setAssociationReaperPeriod(int period) {
device.setAssociationReaperPeriod(period);
}
public final void setDimseRspTimeout(int timeout) {
ae.setDimseRspTimeout(timeout);
}
public final void setTcpNoDelay(boolean tcpNoDelay) {
conn.setTcpNoDelay(tcpNoDelay);
}
public final void setAcceptTimeout(int timeout) {
conn.setAcceptTimeout(timeout);
}
public final void setReleaseTimeout(int timeout) {
conn.setReleaseTimeout(timeout);
}
public final void setSocketCloseDelay(int timeout) {
conn.setSocketCloseDelay(timeout);
}
public final void setMaxPDULengthSend(int maxPDULength) {
ae.setMaxPDULengthSend(maxPDULength);
}
public final void setReceiveBufferSize(int bufferSize) {
conn.setReceiveBufferSize(bufferSize);
}
public final void setSendBufferSize(int bufferSize) {
conn.setSendBufferSize(bufferSize);
}
public final void setCancelAfter(int limit) {
this.cancelAfter = limit;
}
public void addMatchingKey(int[] tagPath, String value) {
keys.putString(tagPath, null, value);
}
public void addReturnKey(int[] tagPath) {
keys.putNull(tagPath, null);
}
public void addSpsMatchingKey(int tag, String value) {
spsKeys.putString(tag, null, value);
}
public void setFuzzySemanticPersonNameMatching(boolean b) {
this.fuzzySemanticPersonNameMatching = b;
}
public void setTransferSyntax(String[] ts) {
TransferCapability tc = new TransferCapability(
UID.ModalityWorklistInformationModelFIND, ts,
TransferCapability.SCU);
if (fuzzySemanticPersonNameMatching)
tc.setExtInfo(EXT_NEG_INFO_FUZZY_MATCHING);
ae.setTransferCapability(new TransferCapability[]{tc});
}
public void open() throws IOException, ConfigurationException,
InterruptedException {
assoc = ae.connect(remoteAE, executor);
}
public void close() throws InterruptedException {
assoc.release(true);
}
public List<DicomObject> query() throws IOException, InterruptedException {
TransferCapability tc = assoc.getTransferCapabilityAsSCU(
UID.ModalityWorklistInformationModelFIND);
if (tc == null) {
throw new NoPresentationContextException(
"Modality Worklist not supported by "
+ remoteAE.getAETitle());
}
System.out.println("Send Query Request:");
System.out.println(keys.toString());
DimseRSP rsp = assoc.cfind(UID.ModalityWorklistInformationModelFIND,
priority, keys, tc.getTransferSyntax()[0], cancelAfter);
List<DicomObject> result = new ArrayList<DicomObject>();
while (rsp.next()) {
DicomObject cmd = rsp.getCommand();
if (CommandUtils.isPending(cmd)) {
DicomObject data = rsp.getDataset();
result.add(data);
System.out.println("\nReceived Query Response #"
+ result.size() + ":");
System.out.println(data.toString());
}
}
return result;
}
@SuppressWarnings("unchecked")
public static void main(String[] args) {
CommandLine cl = parse(args);
DcmMWL dcmmwl = new DcmMWL(cl.hasOption("device")
? cl.getOptionValue("device") : "DCMMWL");
final List<String> argList = cl.getArgList();
String remoteAE = argList.get(0);
String[] calledAETAddress = split(remoteAE, '@');
dcmmwl.setCalledAET(calledAETAddress[0]);
if (calledAETAddress[1] == null) {
dcmmwl.setRemoteHost("127.0.0.1");
dcmmwl.setRemotePort(104);
} else {
String[] hostPort = split(calledAETAddress[1], ':');
dcmmwl.setRemoteHost(hostPort[0]);
dcmmwl.setRemotePort(toPort(hostPort[1]));
}
if (cl.hasOption("L")) {
String localAE = cl.getOptionValue("L");
String[] callingAETHost = split(localAE, '@');
dcmmwl.setCalling(callingAETHost[0]);
if (callingAETHost[1] != null) {
dcmmwl.setLocalHost(callingAETHost[1]);
}
}
if (cl.hasOption("username")) {
String username = cl.getOptionValue("username");
UserIdentity userId;
if (cl.hasOption("passcode")) {
String passcode = cl.getOptionValue("passcode");
userId = new UserIdentity.UsernamePasscode(username,
passcode.toCharArray());
} else {
userId = new UserIdentity.Username(username);
}
userId.setPositiveResponseRequested(cl.hasOption("uidnegrsp"));
dcmmwl.setUserIdentity(userId);
}
if (cl.hasOption("connectTO"))
dcmmwl.setConnectTimeout(parseInt(cl.getOptionValue("connectTO"),
"illegal argument of option -connectTO", 1, Integer.MAX_VALUE));
if (cl.hasOption("reaper"))
dcmmwl.setAssociationReaperPeriod(parseInt(cl.getOptionValue("reaper"),
"illegal argument of option -reaper", 1, Integer.MAX_VALUE));
if (cl.hasOption("rspTO"))
dcmmwl.setDimseRspTimeout(parseInt(cl.getOptionValue("rspTO"),
"illegal argument of option -rspTO", 1, Integer.MAX_VALUE));
if (cl.hasOption("acceptTO"))
dcmmwl.setAcceptTimeout(parseInt(cl.getOptionValue("acceptTO"),
"illegal argument of option -acceptTO", 1, Integer.MAX_VALUE));
if (cl.hasOption("releaseTO"))
dcmmwl.setReleaseTimeout(parseInt(cl.getOptionValue("releaseTO"),
"illegal argument of option -releaseTO", 1, Integer.MAX_VALUE));
if (cl.hasOption("soclosedelay"))
dcmmwl.setSocketCloseDelay(parseInt(cl.getOptionValue("soclosedelay"),
"illegal argument of option -soclosedelay", 1, 10000));
if (cl.hasOption("rcvpdulen"))
dcmmwl.setMaxPDULengthReceive(parseInt(cl.getOptionValue("rcvpdulen"),
"illegal argument of option -rcvpdulen", 1, 10000) * KB);
if (cl.hasOption("sndpdulen"))
dcmmwl.setMaxPDULengthSend(parseInt(cl.getOptionValue("sndpdulen"),
"illegal argument of option -sndpdulen", 1, 10000) * KB);
if (cl.hasOption("sosndbuf"))
dcmmwl.setSendBufferSize(parseInt(cl.getOptionValue("sosndbuf"),
"illegal argument of option -sosndbuf", 1, 10000) * KB);
if (cl.hasOption("sorcvbuf"))
dcmmwl.setReceiveBufferSize(parseInt(cl.getOptionValue("sorcvbuf"),
"illegal argument of option -sorcvbuf", 1, 10000) * KB);
dcmmwl.setPackPDV(!cl.hasOption("pdv1"));
dcmmwl.setTcpNoDelay(!cl.hasOption("tcpdelay"));
if (cl.hasOption("C"))
dcmmwl.setCancelAfter(parseInt(cl.getOptionValue("C"),
"illegal argument of option -C", 1, Integer.MAX_VALUE));
if (cl.hasOption("lowprior"))
dcmmwl.setPriority(CommandUtils.LOW);
if (cl.hasOption("highprior"))
dcmmwl.setPriority(CommandUtils.HIGH);
if (cl.hasOption("fuzzy"))
dcmmwl.setFuzzySemanticPersonNameMatching(true);
if (cl.hasOption("q")) {
String[] matchingKeys = cl.getOptionValues("q");
for (int i = 1; i < matchingKeys.length; i++, i++)
dcmmwl.addMatchingKey(Tag.toTagPath(matchingKeys[i - 1]), matchingKeys[i]);
}
if (cl.hasOption("r")) {
String[] returnKeys = cl.getOptionValues("r");
for (int i = 0; i < returnKeys.length; i++)
dcmmwl.addReturnKey(Tag.toTagPath(returnKeys[i]));
}
if (cl.hasOption("date")) {
dcmmwl.addSpsMatchingKey(Tag.ScheduledProcedureStepStartDate,
cl.getOptionValue("date"));
}
if (cl.hasOption("time")) {
dcmmwl.addSpsMatchingKey(Tag.ScheduledProcedureStepStartTime,
cl.getOptionValue("time"));
}
if (cl.hasOption("mod")) {
dcmmwl.addSpsMatchingKey(Tag.Modality, cl.getOptionValue("mod"));
}
if (cl.hasOption("aet")) {
dcmmwl.addSpsMatchingKey(Tag.ScheduledStationAETitle,
cl.getOptionValue("aet"));
}
dcmmwl.setTransferSyntax(cl.hasOption("ivrle") ? IVRLE_TS : LE_TS);
if (cl.hasOption("tls")) {
String cipher = cl.getOptionValue("tls");
if ("NULL".equalsIgnoreCase(cipher)) {
dcmmwl.setTlsWithoutEncyrption();
} else if ("3DES".equalsIgnoreCase(cipher)) {
dcmmwl.setTls3DES_EDE_CBC();
} else if ("AES".equalsIgnoreCase(cipher)) {
dcmmwl.setTlsAES_128_CBC();
} else {
exit("Invalid parameter for option -tls: " + cipher);
}
if (cl.hasOption("tls1")) {
dcmmwl.setTlsProtocol(TLS1);
} else if (cl.hasOption("ssl3")) {
dcmmwl.setTlsProtocol(SSL3);
} else if (cl.hasOption("no_tls1")) {
dcmmwl.setTlsProtocol(NO_TLS1);
} else if (cl.hasOption("no_ssl3")) {
dcmmwl.setTlsProtocol(NO_SSL3);
} else if (cl.hasOption("no_ssl2")) {
dcmmwl.setTlsProtocol(NO_SSL2);
}
dcmmwl.setTlsNeedClientAuth(!cl.hasOption("noclientauth"));
if (cl.hasOption("keystore")) {
dcmmwl.setKeyStoreURL(cl.getOptionValue("keystore"));
}
if (cl.hasOption("keystorepw")) {
dcmmwl.setKeyStorePassword(
cl.getOptionValue("keystorepw"));
}
if (cl.hasOption("keypw")) {
dcmmwl.setKeyPassword(cl.getOptionValue("keypw"));
}
if (cl.hasOption("truststore")) {
dcmmwl.setTrustStoreURL(
cl.getOptionValue("truststore"));
}
if (cl.hasOption("truststorepw")) {
dcmmwl.setTrustStorePassword(
cl.getOptionValue("truststorepw"));
}
long t1 = System.currentTimeMillis();
try {
dcmmwl.initTLS();
} catch (Exception e) {
System.err.println("ERROR: Failed to initialize TLS context:"
+ e.getMessage());
System.exit(2);
}
long t2 = System.currentTimeMillis();
System.out.println("Initialize TLS context in "
+ ((t2 - t1) / 1000F) + "s");
}
long t1 = System.currentTimeMillis();
try {
dcmmwl.open();
} catch (Exception e) {
System.err.println("ERROR: Failed to establish association:");
e.printStackTrace(System.err);
System.exit(2);
}
long t2 = System.currentTimeMillis();
System.out.println("Connected to " + remoteAE + " in "
+ ((t2 - t1) / 1000F) + "s");
try {
List<DicomObject> result = dcmmwl.query();
long t3 = System.currentTimeMillis();
System.out.println("Received " + result.size()
+ " matching entries in " + ((t3 - t2) / 1000F) + "s");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
dcmmwl.close();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("Released connection to " + remoteAE);
}
private static CommandLine parse(String[] args) {
Options opts = new Options();
OptionBuilder.withArgName("name");
OptionBuilder.hasArg();
OptionBuilder.withDescription(
"set device name, use DCMMWL by default");
opts.addOption(OptionBuilder.create("device"));
OptionBuilder.withArgName("aet[@host]");
OptionBuilder.hasArg();
OptionBuilder.withDescription("set AET and local address of local " +
"Application Entity, use device name and pick up any valid " +
"local address to bind the socket by default");
opts.addOption(OptionBuilder.create("L"));
OptionBuilder.withArgName("username");
OptionBuilder.hasArg();
OptionBuilder.withDescription(
"enable User Identity Negotiation with specified username and "
+ " optional passcode");
opts.addOption(OptionBuilder.create("username"));
OptionBuilder.withArgName("passcode");
OptionBuilder.hasArg();
OptionBuilder.withDescription(
"optional passcode for User Identity Negotiation, "
+ "only effective with option -username");
opts.addOption(OptionBuilder.create("passcode"));
opts.addOption("uidnegrsp", false,
"request positive User Identity Negotation response, "
+ "only effective with option -username");
OptionBuilder.withArgName("NULL|3DES|AES");
OptionBuilder.hasArg();
OptionBuilder.withDescription(
"enable TLS connection without, 3DES or AES encryption");
opts.addOption(OptionBuilder.create("tls"));
OptionGroup tlsProtocol = new OptionGroup();
tlsProtocol.addOption(new Option("tls1",
"disable the use of SSLv3 and SSLv2 for TLS connections"));
tlsProtocol.addOption(new Option("ssl3",
"disable the use of TLSv1 and SSLv2 for TLS connections"));
tlsProtocol.addOption(new Option("no_tls1",
"disable the use of TLSv1 for TLS connections"));
tlsProtocol.addOption(new Option("no_ssl3",
"disable the use of SSLv3 for TLS connections"));
tlsProtocol.addOption(new Option("no_ssl2",
"disable the use of SSLv2 for TLS connections"));
opts.addOptionGroup(tlsProtocol);
opts.addOption("noclientauth", false,
"disable client authentification for TLS");
OptionBuilder.withArgName("file|url");
OptionBuilder.hasArg();
OptionBuilder.withDescription(
"file path or URL of P12 or JKS keystore, resource:tls/test_sys_1.p12 by default");
opts.addOption(OptionBuilder.create("keystore"));
OptionBuilder.withArgName("password");
OptionBuilder.hasArg();
OptionBuilder.withDescription(
"password for keystore file, 'secret' by default");
opts.addOption(OptionBuilder.create("keystorepw"));
OptionBuilder.withArgName("password");
OptionBuilder.hasArg();
OptionBuilder.withDescription(
"password for accessing the key in the keystore, keystore password by default");
opts.addOption(OptionBuilder.create("keypw"));
OptionBuilder.withArgName("file|url");
OptionBuilder.hasArg();
OptionBuilder.withDescription(
"file path or URL of JKS truststore, resource:tls/mesa_certs.jks by default");
opts.addOption(OptionBuilder.create("truststore"));
OptionBuilder.withArgName("password");
OptionBuilder.hasArg();
OptionBuilder.withDescription(
"password for truststore file, 'secret' by default");
opts.addOption(OptionBuilder.create("truststorepw"));
opts.addOption("ivrle", false,
"offer only Implicit VR Little Endian Transfer Syntax.");
opts.addOption("fuzzy", false,
"negotiate support of fuzzy semantic person name attribute matching.");
opts.addOption("pdv1", false,
"send only one PDV in one P-Data-TF PDU, pack command and data " +
"PDV in one P-DATA-TF PDU by default.");
opts.addOption("tcpdelay", false,
"set TCP_NODELAY socket option to false, true by default");
OptionBuilder.withArgName("ms");
OptionBuilder.hasArg();
OptionBuilder.withDescription("timeout in ms for TCP connect, no timeout by default");
opts.addOption(OptionBuilder.create("connectTO"));
OptionBuilder.withArgName("ms");
OptionBuilder.hasArg();
OptionBuilder.withDescription("delay in ms for Socket close after sending A-ABORT, 50ms by default");
opts.addOption(OptionBuilder.create("soclosedelay"));
OptionBuilder.withArgName("ms");
OptionBuilder.hasArg();
OptionBuilder.withDescription("period in ms to check for outstanding DIMSE-RSP, 10s by default");
opts.addOption(OptionBuilder.create("reaper"));
OptionBuilder.withArgName("ms");
OptionBuilder.hasArg();
OptionBuilder.withDescription("timeout in ms for receiving DIMSE-RSP, 10s by default");
opts.addOption(OptionBuilder.create("rspTO"));
OptionBuilder.withArgName("ms");
OptionBuilder.hasArg();
OptionBuilder.withDescription("timeout in ms for receiving A-ASSOCIATE-AC, 5s by default");
opts.addOption(OptionBuilder.create("acceptTO"));
OptionBuilder.withArgName("ms");
OptionBuilder.hasArg();
OptionBuilder.withDescription("timeout in ms for receiving A-RELEASE-RP, 5s by default");
opts.addOption(OptionBuilder.create("releaseTO"));
OptionBuilder.withArgName("KB");
OptionBuilder.hasArg();
OptionBuilder.withDescription("maximal length in KB of received P-DATA-TF PDUs, 16KB by default");
opts.addOption(OptionBuilder.create("rcvpdulen"));
OptionBuilder.withArgName("KB");
OptionBuilder.hasArg();
OptionBuilder.withDescription("maximal length in KB of sent P-DATA-TF PDUs, 16KB by default");
opts.addOption(OptionBuilder.create("sndpdulen"));
OptionBuilder.withArgName("KB");
OptionBuilder.hasArg();
OptionBuilder.withDescription("set SO_RCVBUF socket option to specified value in KB");
opts.addOption(OptionBuilder.create("sorcvbuf"));
OptionBuilder.withArgName("KB");
OptionBuilder.hasArg();
OptionBuilder.withDescription("set SO_SNDBUF socket option to specified value in KB");
opts.addOption(OptionBuilder.create("sosndbuf"));
OptionBuilder.withArgName("[seq/]attr=value");
OptionBuilder.hasArgs();
OptionBuilder.withValueSeparator('=');
OptionBuilder.withDescription("specify matching key. attr can be " +
"specified by name or tag value (in hex), e.g. PatientName " +
"or 00100010. Attributes in nested Datasets can " +
"be specified by preceding the name/tag value of " +
"the sequence attribute, e.g. 00400100/00400009 " +
"for Scheduled Procedure Step ID in the Scheduled " +
"Procedure Step Sequence.");
opts.addOption(OptionBuilder.create("q"));
OptionBuilder.withArgName("date");
OptionBuilder.hasArg();
OptionBuilder.withDescription("specify matching SPS start date " +
"(range). Shortcut for -q00400100/00400002=<date>.");
opts.addOption(OptionBuilder.create("date"));
OptionBuilder.withArgName("time");
OptionBuilder.hasArg();
OptionBuilder.withDescription("specify matching SPS start time " +
"(range). Shortcut for -q00400100/00400003=<time>.");
opts.addOption(OptionBuilder.create("time"));
OptionBuilder.withArgName("modality");
OptionBuilder.hasArg();
OptionBuilder.withDescription("specify matching Modality. Shortcut " +
"for -q00400100/00080060=<modality>.");
opts.addOption(OptionBuilder.create("mod"));
OptionBuilder.withArgName("aet");
OptionBuilder.hasArg();
OptionBuilder.withDescription("specify matching Scheduled Station AE " +
"title. Shortcut for -q00400100/00400001=<aet>.");
opts.addOption(OptionBuilder.create("aet"));
OptionBuilder.withArgName("attr");
OptionBuilder.hasArgs();
OptionBuilder.withDescription("specify additional return key. attr can " +
"be specified by name or tag value (in hex).");
opts.addOption(OptionBuilder.create("r"));
OptionBuilder.withArgName("num");
OptionBuilder.hasArg();
OptionBuilder.withDescription("cancel query after receive of specified " +
"number of responses, no cancel by default");
opts.addOption(OptionBuilder.create("C"));
opts.addOption("lowprior", false,
"LOW priority of the C-FIND operation, MEDIUM by default");
opts.addOption("highprior", false,
"HIGH priority of the C-FIND operation, MEDIUM by default");
opts.addOption("h", "help", false, "print this message");
opts.addOption("V", "version", false,
"print the version information and exit");
CommandLine cl = null;
try {
cl = new GnuParser().parse(opts, args);
} catch (ParseException e) {
exit("dcmmwl: " + e.getMessage());
throw new RuntimeException("unreachable");
}
if (cl.hasOption('V')) {
Package p = DcmMWL.class.getPackage();
System.out.println("dcmqr v" + p.getImplementationVersion());
System.exit(0);
}
if (cl.hasOption('h') || cl.getArgList().size() != 1) {
HelpFormatter formatter = new HelpFormatter();
formatter.printHelp(USAGE, DESCRIPTION, opts, EXAMPLE);
System.exit(0);
}
return cl;
}
private static int toPort(String port) {
return port != null ? parseInt(port, "illegal port number", 1, 0xffff)
: 104;
}
private static int parseInt(String s, String errPrompt, int min, int max) {
try {
int i = Integer.parseInt(s);
if (i >= min && i <= max)
return i;
} catch (NumberFormatException e) {
// parameter is not a valid integer; fall through to exit
}
exit(errPrompt);
throw new RuntimeException();
}
private static String[] split(String s, char delim) {
String[] s2 = { s, null };
int pos = s.indexOf(delim);
if (pos != -1) {
s2[0] = s.substring(0, pos);
s2[1] = s.substring(pos + 1);
}
return s2;
}
private static void exit(String msg) {
System.err.println(msg);
System.err.println("Try 'dcmmwl -h' for more information.");
System.exit(1);
}
public void initTLS() throws GeneralSecurityException, IOException {
KeyStore keyStore = loadKeyStore(keyStoreURL, keyStorePassword);
KeyStore trustStore = loadKeyStore(trustStoreURL, trustStorePassword);
device.initTLS(keyStore,
keyPassword != null ? keyPassword : keyStorePassword,
trustStore);
}
private static KeyStore loadKeyStore(String url, char[] password)
throws GeneralSecurityException, IOException {
KeyStore key = KeyStore.getInstance(toKeyStoreType(url));
InputStream in = openFileOrURL(url);
try {
key.load(in, password);
} finally {
in.close();
}
return key;
}
private static InputStream openFileOrURL(String url) throws IOException {
if (url.startsWith("resource:")) {
return DcmMWL.class.getClassLoader().getResourceAsStream(
url.substring(9));
}
try {
return new URL(url).openStream();
} catch (MalformedURLException e) {
return new FileInputStream(url);
}
}
private static String toKeyStoreType(String fname) {
return fname.endsWith(".p12") || fname.endsWith(".P12")
? "PKCS12" : "JKS";
}
}
| 39.656428 | 109 | 0.624907 |
2bc8454dd35d1180ff9e71b6ed30d77203da3ca0
| 1,115 |
package com.wenj91.fastgql.core.sql;
import lombok.Data;
@Data
public class SelectColumn {
private final String tableAlias;
private final Column column;
private final String resultAlias;
private final String func;
SelectColumn(Table table, Column column, String resultAlias, String func) {
this.tableAlias = table.getTableAlias();
this.column = column;
this.resultAlias = resultAlias;
this.func = func;
}
SelectColumn(Table table, Column column, String resultAlias) {
this.tableAlias = table.getTableAlias();
this.column = column;
this.resultAlias = resultAlias;
this.func = null;
}
SelectColumn(String tableAlias, Column column) {
this.tableAlias = tableAlias;
this.column = column;
this.resultAlias = null;
this.func = null;
}
String sqlString() {
String col = String.format("%s.%s", tableAlias, column.getColumnName());
if (func != null) {
col = String.format("%s(%s)", func, col);
}
if (resultAlias == null) {
return col;
} else {
return String.format("%s AS %s", col, resultAlias);
}
}
}
| 23.723404 | 77 | 0.661883 |
8d4e269a522a27a60c460308cc5346916d36f830
| 4,162 |
package cz.xtf.http;
import java.nio.file.Path;
import java.util.concurrent.TimeUnit;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.entity.ContentType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import cz.xtf.TestConfiguration;
public class HttpUtil {
private static final Logger LOGGER = LoggerFactory.getLogger(HttpUtil.class);
public static void waitForHttp(String urlString, int code) throws Exception {
waitForHttp(urlString, TestConfiguration.maxHttpTries(), code);
}
public static void waitForHttp(String urlString, int timeout, int code) throws Exception {
LOGGER.info("Waiting for {} HTTP {}, timeout {} s", urlString, code, timeout);
HttpClient.get(urlString).waitForCode(code, timeout, TimeUnit.SECONDS);
}
public static void waitForAuthHttp(final String urlString, final String username, final String password, final int timeout, final int code) throws Exception {
LOGGER.info("Waiting for {} HTTP {}, timeout {} s", urlString, code, timeout);
HttpClient.get(urlString).basicAuth(username, password).preemptiveAuth().waitForCode(code, timeout, TimeUnit.SECONDS);
}
public static void waitForHttps(String urlString, int code, Path trustStorePath, char[] password) throws Exception {
LOGGER.info("Waiting for {} HTTPS {}", urlString, code);
HttpClient.get(urlString).trustStore(trustStorePath, password).waitForCode(code, TestConfiguration.maxHttpTries(), TimeUnit.SECONDS);
}
public static void waitForHttpOk(String urlString) throws Exception {
waitForHttp(urlString, 200);
}
public static void waitForHttpsOk(String urlString, Path trustStorePath, char[] password) throws Exception {
waitForHttps(urlString, 200, trustStorePath, password);
}
public static String httpGet(String urlString) throws Exception {
LOGGER.debug("HTTP GET {}", urlString);
return HttpClient.get(urlString).response();
}
public static String httpPost(String urlString, String postData) throws Exception {
LOGGER.debug("HTTP POST {}, data: {}", urlString, postData);
return HttpClient.post(urlString).data(postData, null).response();
}
public static String httpPost(String urlString, String postData, ContentType contentType) throws Exception {
LOGGER.debug("HTTP POST {}, data: {}", urlString, postData);
return HttpClient.post(urlString).data(postData, contentType).response();
}
public static String httpGetBasicAuth(String urlString, String username, String password) throws Exception {
LOGGER.debug("HTTP GET with basic auth {}:{} {}", username, password, urlString);
return HttpClient.get(urlString).basicAuth(username, password).response();
}
public static String httpDeleteBasicAuth(String urlString, String username, String password) throws Exception {
LOGGER.debug("HTTP DELETE with basic auth {}:{} {}", username, password, urlString);
return HttpClient.delete(urlString).basicAuth(username, password).response();
}
public static String httpPutBasicAuth(String urlString, String username, String password, String putData, ContentType contentType)
throws Exception {
LOGGER.debug("HTTP PUT with basic auth {}:{} {}, data: {}", username, password, urlString, putData);
return HttpClient.put(urlString).basicAuth(username, password).data(putData, contentType).response();
}
public static String httpsGet(String urlString, Path trustStorePath, char[] password) throws Exception {
LOGGER.debug("HTTP GET {} truststore {} {}", urlString, trustStorePath, password);
return HttpClient.get(urlString).trustStore(trustStorePath, password).response();
}
public static String httpsGetBearerAuth(String urlString, String token, Path trustStorePath, char[] password) throws Exception {
LOGGER.debug("HTTPS GET {} truststore {} {} token {}", urlString, trustStorePath, password, token);
return HttpClient.get(urlString).bearerAuth(token).trustStore(trustStorePath, password).response();
}
public static int codeFromHttpGet(String urlString) throws Exception {
LOGGER.debug("Code from HTTP GET {}", urlString);
try {
return HttpClient.get(urlString).code();
}
catch (ClientProtocolException e) {
return 503;
}
}
}
| 43.354167 | 159 | 0.763335 |
bcdab14961691a1e0f0da0127e10cf738b322a36
| 1,270 |
package carstore.models;
/**
* Model of a car.
*
* @author Evgeny Khodzitskiy (evgeny.hodz@gmail.com)
* @since 25.08.2017
*/
public class Model {
/**
* Id of model.
*/
private int id;
/**
* Car brand. For example, "Skoda".
*/
private Brand brand;
/**
* Car model. For example, "Rapid".
*/
private String model;
/**
* Constructor default.
*/
public Model() {
}
/**
* Id getter.
*
* @return id.
*/
public int getId() {
return id;
}
/**
* Model setter.
*
* @param modelId model.
*/
public void setId(int modelId) {
this.id = modelId;
}
/**
* Brand getter.
*
* @return brand.
*/
public Brand getBrand() {
return brand;
}
/**
* Brand setter.
*
* @param carBrand car brand.
*/
public void setBrand(Brand carBrand) {
this.brand = carBrand;
}
/**
* Model getter.
*
* @return model.
*/
public String getModel() {
return model;
}
/**
* Model setter.
*
* @param carModel car model.
*/
public void setModel(String carModel) {
this.model = carModel;
}
}
| 15.301205 | 53 | 0.474803 |
900b451a50410ed0681d925543dd148b43940a4a
| 491 |
import java.util.Scanner;
public class TheSumOfSetOfNumbers {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
int sum = 0;
int number = 1;
int limit;
System.out.print("Until what? ");
limit = Integer.parseInt(reader.nextLine());
while(number<=limit){
sum = sum + number;
number++;
}
System.out.print("Sum is " + sum);
}
}
| 20.458333 | 52 | 0.511202 |
48a63ad5f0a8ecea0c50c4eefa6d42a8b6fee496
| 715 |
package nl.itz_kiwisap.spigot.fruitlabjoinme.object;
import java.util.UUID;
import net.md_5.bungee.api.connection.ProxiedPlayer;
public class Player {
private ProxiedPlayer player;
private String name;
private UUID uuid;
private int joinme;
public Player(ProxiedPlayer player, int joinme) {
this.player = player;
this.name = player.getName();
this.uuid = player.getUniqueId();
this.joinme = joinme;
}
public void setJoinMe(int joinme) { this.joinme = joinme; }
public ProxiedPlayer getPlayer() { return this.player; }
public String getName() { return this.name; }
public UUID getUniqueId() { return this.uuid; }
public int getJoinMe() { return this.joinme; }
}
| 26.481481 | 61 | 0.71049 |
64f3cf909df7c77c72a5990128c64d94cec7b958
| 1,855 |
//
// $Id$
package client.person;
import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.ui.AbsolutePanel;
import com.threerings.orth.data.MediaDescSize;
import com.threerings.gwt.ui.CenteredBox;
import com.threerings.gwt.ui.InlinePanel;
import com.threerings.msoy.person.gwt.Gallery;
import com.threerings.msoy.person.gwt.GalleryData;
import client.ui.CreatorLabel;
import client.ui.MsoyUI;
import client.util.MediaUtil;
/**
* Displays the Gallery meta data: name, description, thumbnail, yada yada.
*
* @author mjensen
*/
public class GalleryDetailPanel extends AbsolutePanel
{
public GalleryDetailPanel (GalleryData galleryData)
{
Gallery gallery = galleryData.gallery;
setStyleName("galleryDetailPanel");
// Thumbnail centered horizontally & vertically
add(new CenteredBox(MediaUtil.createMediaView(gallery.thumbMedia,
MediaDescSize.THUMBNAIL_SIZE), "GalleryThumbnail",
MediaDescSize.getWidth(MediaDescSize.THUMBNAIL_SIZE),
MediaDescSize.getHeight(MediaDescSize.THUMBNAIL_SIZE)), 10, 10);
String countText = galleryData.photos.size() == 1 ? _pmsgs.galleryOnePhoto()
: _pmsgs.galleryPhotoCount("" + galleryData.photos.size());
add(MsoyUI.createLabel(countText, "Count"), 20, 80);
// Gallery and creator name are inline
InlinePanel nameAndCreator = new InlinePanel("NameAndCreator");
nameAndCreator.add(MsoyUI.createLabel(GalleryPanel.getGalleryLabel(gallery,
galleryData.owner), "Name"));
nameAndCreator.add(new CreatorLabel(galleryData.owner));
add(nameAndCreator, 105, 5);
add(MsoyUI.createLabel(gallery.description, "Description"), 105, 40);
}
protected static final PersonMessages _pmsgs = (PersonMessages)GWT.create(PersonMessages.class);
}
| 33.727273 | 100 | 0.723989 |
d225d53d92fee14133f3e11abf9eb443a17f11ee
| 444 |
/**
* Copyright 2016 West Coast Informatics, LLC
*/
package com.wci.umls.server.model.content;
import com.wci.umls.server.helpers.HasRelationships;
/**
* Represents a terminology component with relationships.
* @param <T> the relationship type
*/
public interface ComponentHasRelationships<T extends Relationship<? extends ComponentHasAttributes, ? extends ComponentHasAttributes>>
extends Component, HasRelationships<T> {
// n/a
}
| 29.6 | 134 | 0.77027 |
491569f2b32d9900253563499e6d7c76ce88cc32
| 2,534 |
/*
* JSimpleToggleButton.java
*
* Created on Aug 28, 2007, 11:46:12 AM
*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package mbarix4j.swing;
import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.Action;
import javax.swing.Icon;
import javax.swing.JToggleButton;
/**
* A ToggleButton that is undecorated except when it has focus.
* @author brian
*/
public class JSimpleToggleButton extends JToggleButton {
// This block will be called be all the constructors
{
initialize();
}
public JSimpleToggleButton() {
super();
}
public JSimpleToggleButton(Icon icon) {
super(icon);
}
public JSimpleToggleButton(Icon icon, boolean selected) {
super(icon, selected);
}
public JSimpleToggleButton(String text) {
super(text);
}
public JSimpleToggleButton(String text, boolean selected) {
super(text, selected);
}
public JSimpleToggleButton(Action a) {
super(a);
}
public JSimpleToggleButton(String text, Icon icon) {
super(text, icon);
}
public JSimpleToggleButton(String text, Icon icon, boolean selected) {
super(text, icon, selected);
}
/**
* Setup the button so that it toggles the border on mose over.
*
*/
private void initialize() {
setBorderPainted(false);
setFocusPainted(true);
setContentAreaFilled(false);
addMouseListener(new MouseAdapter() {
public void mouseEntered(MouseEvent e) {
super.mouseEntered(e);
setBorderPainted(isEnabled());
setContentAreaFilled(isEnabled());
}
public void mouseExited(MouseEvent e) {
super.mouseExited(e);
setBorderPainted(false);
setContentAreaFilled(false);
}
});
addFocusListener(new FocusAdapter() {
public void focusGained(FocusEvent e) {
super.focusGained(e);
setBorderPainted(true && isEnabled());
setContentAreaFilled(isEnabled());
}
public void focusLost(FocusEvent e) {
super.focusLost(e);
setBorderPainted(false);
setContentAreaFilled(false);
}
});
}
}
| 24.365385 | 74 | 0.592739 |
17bf4dda8a1acd0e5b20eadc22e1d733995c15cd
| 2,810 |
package com.example.suche.travelify.Model;
import android.util.Log;
/**
* Created by Shashwat Uttam on 4/4/2017.
*/
public class BasicLocation {
private String mtitle;
private String mdescription;
private String maddress;
private double mrating;
private String mplaceid;
private String mphone;
private String mschedule;
private String mprice;
private String mimageRef ;
private int mimageWidth;
private int mimageHeight;
public BasicLocation(String title , String description , String address, double rating, String placeid,
String phone, String schedule, String price, String imageref, int imageWidth, int imageHeight)
{
mtitle = title;
mdescription = description;
maddress = address;
mphone = phone;
mschedule = schedule;
mprice = price;
mrating = rating;
mplaceid = placeid;
mimageRef = imageref;
mimageWidth = imageWidth;
mimageHeight = imageHeight;
}
public String getTitle() {
return mtitle;
}
public String getDescription() {
return mdescription;
}
public String getAddress() {
return maddress;
}
public String getPhone() {
return mphone;
}
public String getSchedule() {
return mschedule;
}
public String getPrice() {
return mprice;
}
public double getRating(){
return mrating;
}
public String getPlaceid(){
return mplaceid;
}
public String getImageRef(){ return mimageRef; }
public int getImageWidth(){ return mimageWidth; }
public int getImageHeight(){ return mimageHeight; }
public boolean hasPrice(){
return getPrice() != null;
}
public boolean hasPhone(){
return getPhone() != null;
}
public boolean hasAddress(){
return getAddress() != null;
}
public boolean hasSchedule(){
return getSchedule() != null;
}
public boolean hasRating(){
return getRating() != -1;
}
public boolean hasPlaceid(){
return getPlaceid() != null;
}
public boolean hasImageRef(){
return getImageRef() != null;
}
public boolean hasImageWidth(){
return getImageWidth() != -1;
}
public boolean hasImageHeight(){
return getImageHeight() != -1;
}
@Override
public String toString() {
return getTitle() + "\n" + getDescription() + "\n" + getAddress() + "\n" + getPhone() + "\n"
+ getPrice() + "\n" + getSchedule() + "\n" + getRating() + "\n" + getPlaceid() + "\n"
+ getImageRef()+ "\n" + getImageWidth() + "\n" + getImageHeight();
}
}
| 24.434783 | 119 | 0.579359 |
e9d74608ecfa86a25fbd452cff665bf0c4f5741d
| 950 |
package com.keqi.c1;
import java.nio.ByteBuffer;
public class TestByteBufferRead {
/*
针对于这个缓存了网络数据的数组,有很多操作方法,需要好好熟悉下
*/
public static void main(String[] args) {
ByteBuffer buffer = ByteBuffer.allocate(10);
buffer.put(new byte[]{'a','b','c','d'});
buffer.flip();
// 从头开始读
byte[] a = new byte[4];
buffer.get(a);
System.out.println(new String(a));
// 从头读取(重置 position 为 0 )
buffer.rewind();
byte[] b = new byte[4];
buffer.get(b);
System.out.println(new String(b));
// mark & reset
// mark 做一个标记,记录 position 位置,reset 是将 position 重置到 mark 的位置
buffer.rewind();
byte b1 = buffer.get();
buffer.mark();
System.out.println(buffer.position());
byte b2 = buffer.get();
System.out.println(String.valueOf(b1) + " " + String.valueOf(b2));
buffer.reset();
System.out.println(buffer.position());
byte b3 = buffer.get();
System.out.println(String.valueOf(b2) + " " + String.valueOf(b3));
}
}
| 17.592593 | 68 | 0.641053 |
660fa8aeda308c819e6b03b42b4bb7177559f4e1
| 3,229 |
package com.hlytec.cloud.biz.knowledge.controller;
import java.util.List;
import com.hlytec.cloud.biz.knowledge.model.vo.QueryKnowledgeVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hlytec.cloud.biz.knowledge.model.entity.KnowledgeRepository;
import com.hlytec.cloud.biz.knowledge.service.KnowledgeService;
import com.hlytec.cloud.common.controller.BaseController;
import com.hlytec.cloud.common.entity.CommonParamVo;
import com.hlytec.cloud.common.result.CommonResult;
import com.hlytec.cloud.common.result.PageResult;
/**
* @description: KnowledgeController
* @author: JackChen
* @date: 2021/5/26 14:00
*/
@RestController
@RequestMapping("/net/knowledge")
public class KnowledgeController extends BaseController {
@Autowired
private KnowledgeService knowledgeService;
@GetMapping("/{id}")
public CommonResult<Object> findDetails(@PathVariable("id") String id){
KnowledgeRepository knowledgeRepository = knowledgeService.get(id);
return success(knowledgeRepository);
}
@GetMapping("/findAll")
public PageResult<KnowledgeRepository> findDocumentList(Page page){
Page<KnowledgeRepository> knowledgePage = new Page<>(page.getCurrent(),page.getSize(),page.getTotal());
PageResult<KnowledgeRepository> knowledgePageResult = knowledgeService.findPage(knowledgePage,null);
return knowledgePageResult;
}
@PostMapping("/page")
public CommonResult<Object> findPage(@RequestBody QueryKnowledgeVo queryKnowledgeVo){
PageResult<KnowledgeRepository> pageResult = knowledgeService.findKnowledgePage(queryKnowledgeVo);
return success(pageResult);
}
@PostMapping("/find/{keywords}")
public CommonResult<Object> findDocumentByKeywords(@PathVariable("keywords") String keywords){
List<KnowledgeRepository> knowledgeList = knowledgeService.findDocumentByKeywords(keywords);
return success(knowledgeList);
}
@PutMapping("/modify")
public CommonResult<Object> modifyDocument(@RequestBody @Validated KnowledgeRepository knowledgeRepository){
knowledgeService.updateById(knowledgeRepository);
return success();
}
@PutMapping("/updateCount")
public CommonResult<Object> updateCount(@RequestBody QueryKnowledgeVo queryKnowledgeVo){
knowledgeService.updateReviewCount(queryKnowledgeVo);
return success();
}
@PostMapping("/add")
public CommonResult<Object> addDocument(@RequestBody @Validated KnowledgeRepository knowledgeRepository){
knowledgeService.save(knowledgeRepository);
return success();
}
@DeleteMapping("/delete/{id}")
public CommonResult<Object> deleteDocument(@PathVariable("id") String id){
knowledgeService.delete(id);
return success();
}
@DeleteMapping("/delete")
public CommonResult<Object> deleteDocuments(@RequestBody CommonParamVo deleteKnowledgeVo){
knowledgeService.deleteKnowledge(deleteKnowledgeVo);
return success("delete success");
}
}
| 37.988235 | 112 | 0.756271 |
46bffb776c7ff1ad85bbeb0be3f05327cc36a377
| 4,818 |
package org.joget.cardano.lib;
import org.joget.cardano.service.PluginUtil;
import org.joget.cardano.service.BackendUtil;
import com.bloxbean.cardano.client.backend.api.AddressService;
import com.bloxbean.cardano.client.backend.api.BackendService;
import com.bloxbean.cardano.client.backend.model.AddressContent;
import com.bloxbean.cardano.client.common.ADAConversionUtil;
import com.bloxbean.cardano.client.api.model.Result;
import java.math.BigInteger;
import org.joget.apps.app.service.AppUtil;
import org.joget.apps.form.model.Element;
import org.joget.apps.form.model.FormBinder;
import org.joget.apps.form.model.FormData;
import org.joget.apps.form.model.FormLoadBinder;
import org.joget.apps.form.model.FormLoadElementBinder;
import org.joget.apps.form.model.FormRow;
import org.joget.apps.form.model.FormRowSet;
import org.joget.commons.util.LogUtil;
import org.joget.workflow.util.WorkflowUtil;
import static com.bloxbean.cardano.client.common.CardanoConstants.LOVELACE;
public class CardanoAccountLoadBinder extends FormBinder implements FormLoadBinder, FormLoadElementBinder {
BackendService backendService;
AddressService addressService;
protected void initBackend() {
backendService = BackendUtil.getBackendService(getProperties());
addressService = backendService.getAddressService();
}
@Override
public String getName() {
return "Cardano Account Load Binder";
}
@Override
public String getVersion() {
return PluginUtil.getProjectVersion(this.getClass());
}
@Override
public String getDescription() {
return "Load account data from the Cardano blockchain into a form.";
}
@Override
public FormRowSet load(Element element, String primaryKey, FormData formData) {
try {
final String accountAddress = WorkflowUtil.processVariable(getPropertyString("accountAddress"), "", null);
//Prevent error thrown from empty value and invalid hash variable
if (accountAddress.isEmpty() || accountAddress.startsWith("#")) {
return null;
}
initBackend();
//Get account data from blockchain
final Result<AddressContent> addressInfoResult = addressService.getAddressInfo(accountAddress);
if (!addressInfoResult.isSuccessful()) {
LogUtil.warn(getClass().getName(), "Unable to retrieve address info. Response returned --> " + addressInfoResult.getResponse());
return null;
}
final AddressContent addressInfo = addressInfoResult.getValue();
//Get form fields from plugin properties
String balanceField = getPropertyString("balanceField");
String accountType = getPropertyString("accountType");
FormRow row = new FormRow();
row = addRow(row, balanceField, getAdaBalance(addressInfo));
// Dandelion missing this info fyi
row = addRow(row, accountType, getAccountType(addressInfo));
FormRowSet rows = new FormRowSet();
rows.add(row);
return rows;
} catch (Exception ex) {
LogUtil.error(getClass().getName(), ex, "Error executing plugin...");
return null;
}
}
private String getAdaBalance(AddressContent addressInfo) {
if (addressInfo.getAmount().isEmpty()) {
return "No balance found";
}
return String.valueOf(
ADAConversionUtil.lovelaceToAda(
new BigInteger(
addressInfo.getAmount().stream().filter(
accountBalance -> accountBalance.getUnit().equals(LOVELACE)
).findFirst().get().getQuantity()
)
)
);
}
private String getAccountType(AddressContent addressInfo) {
return (addressInfo.getType() != null) ? addressInfo.getType().name() : "";
}
private FormRow addRow(FormRow row, String field, String value) {
if (row != null && !field.isEmpty()) {
row.put(field, value);
}
return row;
}
@Override
public String getLabel() {
return getName();
}
@Override
public String getClassName() {
return getClass().getName();
}
@Override
public String getPropertyOptions() {
String backendConfigs = PluginUtil.readGenericBackendConfigs(getClass().getName());
return AppUtil.readPluginResource(getClass().getName(), "/properties/CardanoAccountLoadBinder.json", new String[]{backendConfigs}, true, PluginUtil.MESSAGE_PATH);
}
}
| 36.5 | 170 | 0.644043 |
241db6df7bba4344bf9000b87b5baddd917b432c
| 965 |
package com.azhuoinfo.cqurity.view.scrollview;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.Transformation;
public class BackAnimimation extends Animation {
int targetHeight;
int originalHeight;
int extraHeight;
View view;
boolean down;
protected BackAnimimation(View view, int targetHeight, boolean down) {
this.view = view;
this.targetHeight = targetHeight;
this.down = down;
originalHeight = view.getHeight();
extraHeight = this.targetHeight - originalHeight;
}
@Override
protected void applyTransformation(float interpolatedTime, Transformation t) {
int newHeight;
newHeight = (int) (targetHeight - extraHeight * (1 - interpolatedTime));
view.getLayoutParams().height = newHeight;
view.requestLayout();
}
@Override
public void initialize(int width, int height, int parentWidth,
int parentHeight) {
super.initialize(width, height, parentWidth, parentHeight);
}
}
| 23.536585 | 79 | 0.761658 |
bac5926e17da46c3cebd519e299e1560193d2d5e
| 2,786 |
/*
* Copyright 2000-2010 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.idea.maven.model;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Properties;
public class MavenModelBase implements Serializable {
private Properties myProperties;
private List<MavenPlugin> myPlugins = Collections.emptyList();
private List<MavenArtifact> myExtensions = Collections.emptyList();
private List<MavenArtifact> myDependencies = Collections.emptyList();
private List<MavenArtifactNode> myDependencyTree = Collections.emptyList();
private List<MavenRemoteRepository> myRemoteRepositories = Collections.emptyList();
private List<String> myModules;
public Properties getProperties() {
if (myProperties == null) myProperties = new Properties();
return myProperties;
}
public void setProperties(Properties properties) {
myProperties = properties;
}
public List<MavenPlugin> getPlugins() {
return myPlugins;
}
public void setPlugins(List<MavenPlugin> plugins) {
myPlugins = new ArrayList<MavenPlugin>(plugins);
}
public List<MavenArtifact> getExtensions() {
return myExtensions;
}
public void setExtensions(List<MavenArtifact> extensions) {
myExtensions = new ArrayList<MavenArtifact>(extensions);
}
public List<MavenArtifact> getDependencies() {
return myDependencies;
}
public void setDependencies(List<MavenArtifact> dependencies) {
myDependencies = new ArrayList<MavenArtifact>(dependencies);
}
public List<MavenArtifactNode> getDependencyTree() {
return myDependencyTree;
}
public void setDependencyTree(List<MavenArtifactNode> dependencyTree) {
myDependencyTree = new ArrayList<MavenArtifactNode>(dependencyTree);
}
public List<MavenRemoteRepository> getRemoteRepositories() {
return myRemoteRepositories;
}
public void setRemoteRepositories(List<MavenRemoteRepository> remoteRepositories) {
myRemoteRepositories = new ArrayList<MavenRemoteRepository>(remoteRepositories);
}
public List<String> getModules() {
return myModules;
}
public void setModules(List<String> modules) {
myModules = new ArrayList<String>(modules);
}
}
| 30.615385 | 85 | 0.758435 |
caf1fdb62b3040ed847e00e5c1121bdea26474a7
| 263 |
package compile.parse;
/**
* Used to distinguish between instances of {@link compile.term.ApplyTerm}
* expressing function invocation, collection indexing, and
* structure addressing.
*/
public enum ApplyFlavor
{
FuncApp,
CollIndex,
StructAddr
}
| 18.785714 | 74 | 0.73384 |
8df95411a5a71d2952a66b7a0cd544dc309061e3
| 4,356 |
/*
* Copyright 2012-2018 ISP RAS (http://www.ispras.ru)
*
* 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 ru.ispras.microtesk.mmu.model.sim;
import ru.ispras.fortress.data.types.bitvector.BitVector;
import ru.ispras.fortress.util.InvariantChecks;
import ru.ispras.fortress.util.Pair;
import java.util.ArrayList;
import java.util.List;
/**
* This class implements a cache set, which is a fully associative buffer consisting of cache lines.
*
* @param <D> the data type.
* @param <A> the address type.
*
* @author <a href="mailto:andrewt@ispras.ru">Andrei Tatarnikov</a>
*/
public class Set<D extends Data, A extends Address> implements Buffer<D, A> {
/** The array of cache lines. */
private final List<Buffer<D, A>> lines = new ArrayList<>();
/** The data replacement policy. */
private final Policy policy;
/**
* Constructs a cache set of the given associativity.
*
* @param associativity the number of lines in the set.
* @param policyId the identifier of the data replacement policy.
* @param matcher the data-address matcher.
*/
public Set(
final int associativity,
final PolicyId policyId,
final Matcher<D, A> matcher) {
InvariantChecks.checkGreaterThanZero(associativity);
InvariantChecks.checkNotNull(policyId);
InvariantChecks.checkNotNull(matcher);
// Fill the set with the default (invalid) lines.
for (int i = 0; i < associativity; i++) {
final Buffer<D, A> line = newLine(matcher);
lines.add(line);
}
this.policy = policyId.newPolicy(associativity);
}
protected Buffer<D, A> newLine(final Matcher<D, A> matcher) {
return new Line<D, A>(matcher);
}
@Override
public final boolean isHit(final A address) {
return getLine(address) != null;
}
@Override
public final D getData(final A address) {
final Buffer<D, A> line = getLine(address);
return line != null ? line.getData(address) : null;
}
@Override
public final D setData(final A address, final D data) {
Buffer<D, A> line = getLine(address);
// If there is a miss, choose a victim.
if (line == null) {
if (null != policy) {
line = lines.get(policy.chooseVictim());
} else {
InvariantChecks.checkTrue(1 == lines.size());
line = lines.get(0);
}
}
return line.setData(address, data);
}
@Override
public Pair<BitVector, BitVector> seeData(final BitVector index, final BitVector way) {
final Buffer<D, A> line = lines.get(way.intValue());
return line != null ? line.seeData(index, way) : null;
}
/**
* Returns the line associated with the given address.
*
* @param address the data address.
* @return the line associated with the given address if it exists; {@code null} otherwise.
*/
private Buffer<D, A> getLine(final A address) {
int index = -1;
for (int i = 0; i < lines.size(); i++) {
final Buffer<D, A> line = lines.get(i);
if (line.isHit(address)) {
if (index != -1) {
throw new IllegalStateException(
String.format("Multiple hits in a cache set. Address=%s:0x%s, Lines=%s",
address.getClass().getSimpleName(),
address.getValue().toHexString(),
lines.toString()
));
}
index = i;
}
}
if (index != -1 && policy != null) {
policy.accessLine(index);
}
return index == -1 ? null : lines.get(index);
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder("Set [");
for (int index = 0; index < lines.size(); index++) {
if (0 != index) {
sb.append(", ");
}
final Buffer<D, A> line = lines.get(index);
sb.append(String.format("%d: %s", index, line));
}
sb.append(']');
return sb.toString();
}
}
| 28.847682 | 100 | 0.639578 |
d151d2bdcd06e6ea9e44dcf65e4a596c6b5058a8
| 1,212 |
package com.hackpro.authserver.domain;
import java.util.List;
import java.util.Set;
import org.springframework.data.cassandra.core.mapping.Column;
import org.springframework.data.cassandra.core.mapping.PrimaryKey;
import org.springframework.data.cassandra.core.mapping.Table;
import lombok.Data;
/**
*
* @author vengatesanns(HackPro)
*
*/
@Data
@Table("client")
public class Client {
@PrimaryKey("client_id")
private String clientId;
@Column("client_secret")
private String clientSecret;
@Column("client_name")
private String clientName;
@Column("scope")
private Set<String> scope;
@Column("resource_ids")
private Set<String> resourceIds;
@Column("authorized_grant_types")
private Set<String> authorizedGrantTypes;
@Column("registered_redirect_uris")
private Set<String> registeredRedirectUris;
@Column("authorities")
private List<String> authorities;
@Column("accesstoken_validity_seconds")
private Integer accessTokenValiditySeconds;
@Column("refreshtoken_validity_seconds")
private Integer refreshTokenValiditySeconds;
@Column("additional_information")
private String additionalInformation;
@Column("auto_approve_scopes")
private Set<String> autoApproveScopes;
}
| 20.896552 | 66 | 0.787129 |
bc0bbfdf61fbc4186e58464be5b352b6f1ad2960
| 1,308 |
package org.obolibrary.robot.exceptions;
/** Template row cannot be parsed. */
public class RowParseException extends Exception {
private static final long serialVersionUID = -646778731149993824L;
public int rowNum = -1;
public int colNum = -1;
public String ruleID;
public String ruleName;
public String cellValue;
/**
* Throw new RowParseException with message.
*
* @param s message
*/
public RowParseException(String s) {
super(s);
}
/**
* Throw new RowParseException with message amd cause.
*
* @param s message
* @param e cause
*/
public RowParseException(String s, Exception e) {
super(s, e);
}
/**
* Throw a new RowParseException with message and location.
*
* @param s message
* @param rowNum row number
* @param colNum column number
* @param cellValue value of cell with exception
*/
public RowParseException(String s, int rowNum, int colNum, String cellValue) {
super(s);
this.rowNum = rowNum;
this.colNum = colNum;
this.cellValue = cellValue;
try {
this.ruleName = s.substring(s.indexOf("#") + 1, s.indexOf("ERROR") + 5).trim().toLowerCase();
} catch (Exception e) {
this.ruleName = "";
}
this.ruleID = "ROBOT-template:" + this.ruleName.replace(" ", "-");
}
}
| 23.781818 | 99 | 0.649083 |
d363ab55bb3197549386c42f137b1ed2254c8035
| 1,707 |
package pattern.creational.singleton.a;
/**
* 单件模式:巧克力工厂
*
* @author leishiguang
* date 2018/8/9 20:37
* @version v1.0
*/
class ChocolateBoiler {
private boolean empty;
private boolean boiled;
private volatile static ChocolateBoiler uniqueInstance;
private ChocolateBoiler() {
empty = true;
boiled = false;
}
/**
* 实例化单例ChocolateBoiler
*/
static ChocolateBoiler getInstance() {
if (uniqueInstance == null) {
// 防止多线程操作时,生成不同的 object
synchronized (ChocolateBoiler.class) {
if (uniqueInstance == null) {
try { // for debugger: 测试线程安全,如果不加同步,则会生成不同的实例...
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
uniqueInstance = new ChocolateBoiler();
}
}
}
return uniqueInstance;
}
void fill() {
if (isEmpty()) {
//在锅炉内填满巧克力和牛奶的混合物
empty = false;
boiled = false;
System.out.println("ChocolateBoiler is Filled...");
}
}
void drain() {
if (!isEmpty() && isBoiled()) {
// 排出煮沸的巧克力和牛奶
empty = true;
System.out.println("ChocolateBoiler is Drained...");
}
}
void boil() {
if (!isEmpty() && !isBoiled()) {
// 将炉内物煮沸
boiled = true;
System.out.println("ChocolateBoiler is Boiled...");
}
}
private boolean isEmpty() {
return empty;
}
private boolean isBoiled() {
return boiled;
}
}
| 23.383562 | 69 | 0.495606 |
1392189d2120a1064f2340ab9908c3fe05cfc6dc
| 522 |
import com.strategyobject.substrateclient.rpc.annotation.RpcEncoder;
import com.strategyobject.substrateclient.rpc.annotation.Scale;
@RpcEncoder
public class RpcEncodableWithoutGetter<T> {
public int a;
@Scale
public int b;
public T c;
public int getB() {
return b;
}
public T getC() {
return c;
}
public void setA(int a) {
this.a = a;
}
public void setB(int b) {
this.b = b;
}
public void setC(T c) {
this.c = c;
}
}
| 15.818182 | 68 | 0.584291 |
6ef3d95fb5a5331fd53360c06b670f7fb6980a6c
| 4,050 |
package com.pg85.otg.forge.gui.dimensions;
import java.util.ArrayList;
import com.pg85.otg.OTG;
import com.pg85.otg.forge.ForgeEngine;
import com.pg85.otg.forge.ForgeWorld;
import com.pg85.otg.forge.gui.IGuiListEntry;
import com.pg85.otg.forge.gui.dimensions.OTGGuiDimensionSettingsList;
import com.pg85.otg.forge.pregenerator.Pregenerator;
import com.pg85.otg.forge.world.ForgeWorldSession;
import net.minecraft.client.Minecraft;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
@SideOnly(Side.CLIENT)
public class PregeneratorSettingsEntry implements IGuiListEntry
{
private final OTGGuiDimensionSettingsList otgGuiDimensionSettingsList;
private final OTGGuiDimensionSettingsList parent;
private Pregenerator pregenerator = null;
PregeneratorSettingsEntry(OTGGuiDimensionSettingsList otgGuiDimensionSettingsList, OTGGuiDimensionSettingsList parent)
{
this.otgGuiDimensionSettingsList = otgGuiDimensionSettingsList;
this.parent = parent;
}
public void drawEntry(int slotIndex, int x, int y, int listWidth, int slotHeight, int mouseX, int mouseY, boolean isSelected, float partialTicks)
{
if(this.pregenerator == null)
{
ForgeWorld forgeWorld = (ForgeWorld)((ForgeEngine)OTG.getEngine()).getWorld(this.parent.controlsScreen.selectedDimensionIndex == 0 ? "overworld" : this.parent.controlsScreen.selectedDimension.PresetName);
if(forgeWorld == null)
{
forgeWorld = (ForgeWorld)((ForgeEngine)OTG.getEngine()).getUnloadedWorld(this.parent.controlsScreen.selectedDimension.PresetName);
}
pregenerator = ((ForgeWorldSession)forgeWorld.getWorldSession()).getPregenerator();
}
ArrayList<String> lines = new ArrayList<String>();
lines.add("");
lines.add("Pre-generating " + (pregenerator.progressScreenWorldSizeInBlocks > 0 ? pregenerator.progressScreenWorldSizeInBlocks + "x" + pregenerator.progressScreenWorldSizeInBlocks + " blocks" : ""));
lines.add("Progress: " + pregenerator.preGeneratorProgress + "%");
lines.add("Chunks: " + pregenerator.preGeneratorProgressStatus);
lines.add("Elapsed: " + pregenerator.progressScreenElapsedTime);
lines.add("Estimated: " + pregenerator.progressScreenEstimatedTime);
if(Minecraft.getMinecraft().isSingleplayer())
{
long i = Runtime.getRuntime().maxMemory();
long j = Runtime.getRuntime().totalMemory();
long k = Runtime.getRuntime().freeMemory();
long l = j - k;
lines.add("Memory: " + Long.valueOf(bytesToMb(l)) + "/" + Long.valueOf(bytesToMb(i)) + " MB");
} else {
lines.add("Memory: " + pregenerator.progressScreenServerUsedMbs + "/" + pregenerator.progressScreenServerTotalMbs + " MB");
}
int linespacing = 11;
for(int a = 0; a < lines.size(); a++)
{
this.otgGuiDimensionSettingsList.mc.fontRenderer.drawString(
lines.get(a),
x + 6,
y + slotHeight - this.otgGuiDimensionSettingsList.mc.fontRenderer.FONT_HEIGHT - 5 + (a * linespacing),
16777215
);
}
}
private long bytesToMb(long bytes)
{
return bytes / 1024L / 1024L;
}
public void keyTyped(char typedChar, int keyCode)
{
}
/**
* Called when the mouse is clicked within this entry. Returning true means that something within this entry was
* clicked and the list should not be dragged.
*/
public boolean mousePressed(int slotIndex, int mouseX, int mouseY, int mouseEvent, int relativeX, int relativeY)
{
return false;
}
/**
* Fired when the mouse button is released. Arguments: index, x, y, mouseEvent, relativeX, relativeY
*/
public void mouseReleased(int slotIndex, int x, int y, int mouseEvent, int relativeX, int relativeY)
{
}
public void updatePosition(int slotIndex, int x, int y, float partialTicks)
{
}
@Override
public String getLabelText() {
return null;
}
@Override
public String getDisplayText() {
return null;
}
}
| 35.840708 | 207 | 0.709877 |
5f8704165cdf5f63b1c52ff71868dd92ba873f3a
| 688 |
package com.bgmagar.mapper;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.springframework.jdbc.core.RowMapper;
import com.bgmagar.domain.Product;
public class ProductMapper implements RowMapper<Product> {
@Override
public Product mapRow(ResultSet rs, int rowNum) throws SQLException {
Product product = new Product();
product.setId(rs.getInt("ID"));
product.setName(rs.getString("NAME"));
product.setRate(rs.getInt("RATE"));
product.setQuantity(rs.getInt("QUANTITY"));
product.setCompany(rs.getString("COMPANY"));
product.setDescription(rs.getString("DESCRIPTION"));
product.setUpdateDate(rs.getDate("UPDATE_DATE"));
return product;
}
}
| 24.571429 | 70 | 0.757267 |
1183bc79f6ffb4aa42f47c9676a8f944e3cea766
| 3,006 |
package uk.gov.ea.wastecarrier.services;
import com.opencsv.CSVReader;
import uk.gov.ea.wastecarrier.services.core.Entity;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.logging.Logger;
public class EntityCsvReader {
private static Logger log = Logger.getLogger(EntityCsvReader.class.getName());
public List<Entity> read(String path) {
List<Entity> entities = new ArrayList<>();
CSVReader reader = null;
String[] nextLine;
try {
reader = new CSVReader(new FileReader(path));
while ((nextLine = reader.readNext()) != null) {
if (skipLine(nextLine)) continue;
entities.add(createEntity(nextLine));
}
} catch(FileNotFoundException e) {
log.severe(String.format("EntityCsvReader - File %s not found: %s", path, e.getMessage()));
} catch(IOException e) {
log.severe("EntityCsvReader - Error reading file: " + e.getMessage());
} finally {
try {
if (reader != null) reader.close();
} catch(IOException e) {
log.severe("EntityCsvReader - Error closing reader: " + e.getMessage());
}
}
return entities;
}
private Boolean skipLine(String[] nextLine) {
String firstValue = nextLine[0] == null ? "" : nextLine[0].trim();
String secondValue = nextLine[1] == null ? "" : nextLine[1].trim();
// Basically we have the header row. The problem is the header row is
// not always the first row!
if (firstValue.equalsIgnoreCase("offender") && secondValue.equalsIgnoreCase("birth date")) return true;
// Only required field is the first field. If its empty ignore the line
if (firstValue == null || firstValue.isEmpty()) return true;
return false;
}
private Entity createEntity(String[] newLine) {
Entity doc = new Entity();
doc.name = newLine[0].trim();
doc.dateOfBirth = parseDate(newLine[1].trim());
doc.companyNumber = newLine[2].trim();
doc.systemFlag = newLine[3].trim();
doc.incidentNumber = newLine[4].trim();
return doc;
}
private Date parseDate(String dob)
{
if (dob == null || dob.trim().isEmpty()) return null;
SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
try {
return formatter.parse(dob);
}
catch (ParseException e) {
// Have a second attempt using a different pattern
try {
formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
return formatter.parse(dob);
} catch (ParseException e1) {
return null;
}
}
}
}
| 31.978723 | 111 | 0.598802 |
508c0de2b3b7e5d6aa5f5348c091f4bb63696427
| 757 |
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*/
package com.microsoft.azure.toolkit.intellij.common;
import com.microsoft.azure.toolkit.lib.common.form.AzureFormInput;
import com.microsoft.azure.toolkit.lib.common.form.AzureValidationInfo;
import javax.swing.*;
public interface AzureFormInputComponent<T> extends AzureFormInput<T> {
default JComponent getInputComponent() {
return (JComponent) this;
}
default void setValidationInfo(AzureValidationInfo info) {
this.set("validationInfo", info);
}
default AzureValidationInfo getValidationInfo() {
return this.get("validationInfo");
}
}
| 29.115385 | 95 | 0.745046 |
6f18e2078679416c031a4cc5433b4b29617c74ef
| 1,956 |
/**
*
* Copyright 2017 Florian Erhard
*
* 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 gedi.oml.remote.Pipeline;
import gedi.core.data.mapper.DisablingGenomicRegionDataMapper;
import gedi.core.data.mapper.GenomicRegionDataMapping;
import gedi.core.reference.ReferenceSequence;
import gedi.core.region.GenomicRegion;
import gedi.core.region.ImmutableReferenceGenomicRegion;
import gedi.gui.genovis.pixelMapping.PixelLocationMapping;
import io.netty.channel.ChannelHandlerContext;
@GenomicRegionDataMapping(fromType=Object.class,toType=Void.class)
public class Sender implements DisablingGenomicRegionDataMapper<Object,Void> {
private String id;
private ChannelHandlerContext ctx;
private boolean disabled = false;
public void setChannelHandlerContext(ChannelHandlerContext ctx) {
this.ctx = ctx;
}
public String getInput() {
return id;
}
public void setInput(String id) {
this.id = id;
}
@Override
public Void map(ReferenceSequence reference, GenomicRegion region,
PixelLocationMapping pixelMapping, Object data) {
ctx.writeAndFlush(new RemotePipelineData(id, new ImmutableReferenceGenomicRegion(reference, region,data)));
return null;
}
public void setDisabled(boolean disabled) {
this.disabled = disabled;
}
@Override
public boolean isDisabled(ReferenceSequence reference, GenomicRegion region, PixelLocationMapping pixelMapping) {
return disabled;
}
}
| 29.636364 | 114 | 0.771472 |
e0243a757ca52cc199e7d04cb9f7f789775e860f
| 715 |
package org.practice.app.operation.raw;
public class SingleUndefinedOperation implements UndefinedOperation{
private final char VALUE;
public SingleUndefinedOperation(char value) {
VALUE = value;
}
@Override
public char getValue() {
return VALUE;
}
@Override
public boolean equals(Object o) {
if (o == this) {
return true;
}
if (!(o instanceof SingleUndefinedOperation)) {
return false;
}
SingleUndefinedOperation other = (SingleUndefinedOperation) o;
return VALUE == other.getValue();
}
@Override
public String toString() {
return Character.toString(VALUE);
}
}
| 20.428571 | 70 | 0.60979 |
6120de2ca47a3a2b888f517388b379c6d3d7128f
| 7,904 |
package com.funnyboyroks.three.LinkedList;
import java.util.*;
import java.util.stream.Collectors;
/**
* A full implementation of the {@link java.util.Queue} interface
* @param <T> The type of data for the class to store.
*/
public class Queue<T> implements java.util.Queue<T> {
public static void main(String[] args) {
Queue<String> testQ = new Queue<>("a");
System.out.println(testQ.toString2()); // a
testQ.enqueue("b");
System.out.println(testQ.toString2()); // a | b
System.out.println(testQ.dequeue()); // a
System.out.println(testQ.toString2()); // b
System.out.println(testQ.isEmpty()); // false
testQ.enqueue("c");
testQ.enqueue("d");
testQ.enqueue("e");
System.out.println(testQ.toString2()); // b | c | d | e
testQ.sendToBack();
System.out.println(testQ.toString2()); // c | d | e | b
System.out.println(testQ.size()); // 4
}
protected Node<T> head = null;
protected Node<T> tail = null;
protected int size = 0;
protected int capacity = -1;
public Queue(int capacity) {
this.capacity = capacity;
}
public Queue(Collection<T> items) {
this.addAll(items);
}
public Queue(T... items) { // Close enough to the required `Queue(T item)` -- Works with that
Collections.addAll(this, items); // Can be done with a for loop, if wanted
}
/**
* Set the maximum capacity of the Queue
*
* @param capacity The new capacity
* @return If the current size is greater than the new capacity
*/
public boolean setCapacity(int capacity) {
this.capacity = capacity;
return this.size > this.capacity;
}
@Override
public int size() {
return this.size;
}
@Override
public boolean isEmpty() {
return this.size == 0 || this.head == null || this.tail == null;
}
@Override
public boolean contains(Object o) {
for (T t : this) { // I made an iterator, might as well use it :P
if (t.equals(o)) return true;
}
return false;
}
@Override
public Iterator<T> iterator() {
return new QueueIterator<>(this);
}
@Override
public Object[] toArray() {
Object[] arr = new Object[this.size];
for (int i = 0; i < this.size(); i++) {
arr[i] = this.get(i);
}
return arr;
}
@Override
public <T1> T1[] toArray(T1[] t1s) {
T1[] arr = Arrays.copyOf(t1s, this.size);
for (int i = 0; i < this.size(); i++) {
arr[i] = (T1) this.get(i);
}
return arr;
}
protected T get(int index) {
return this.getNode(index).getValue();
}
@Override
public boolean add(T item) {
if (this.capacity == size++ && this.capacity > -1) {
throw new IllegalStateException("Queue capacity is full.");
}
if (this.head == null) {
this.head = this.tail = new Node<>(item);
return true;
}
// TODO: "simplify" this
Node<T> n = new Node<>(item);
((this.tail = (n.head = this.tail).tail = n).tail = this.head).head = n;
return true;
}
@Override
public boolean remove(Object o) {
for (int i = 0; i < this.size(); i++) {
Node<T> n = this.getNode(i);
if (n.getValue().equals(o)) {
Node<T> prev = this.getNode(i - 1);
Node<T> next = this.getNode(i + 1);
(prev.tail = next).head = prev; // prev.tail = next and next.head = prev
if (n == this.head) {
this.remove();
}
return true;
}
}
return false;
}
@Override
public boolean containsAll(Collection<?> collection) {
return collection.stream().map(this::contains).reduce(true, Boolean::logicalAnd);
}
@Override
public boolean addAll(Collection<? extends T> collection) {
collection.forEach(this::add);
return true;
}
@Override
public boolean removeAll(Collection<?> collection) {
Queue<T> original = this.copy();
this.clear();
for (T t : original) {
if (!collection.contains(t)) {
this.add(t);
}
}
return original.size() != this.size();
}
@Override
public boolean retainAll(Collection<?> collection) {
Queue<T> original = this.copy();
this.clear();
for (T t : original) {
if (collection.contains(t)) {
this.add(t);
}
}
return original.size() != this.size();
}
@Override
public void clear() {
this.head = this.tail = null;
}
@Override
public boolean offer(T t) {
return this.add(t);
}
/**
* Remove the first item from the Queue
*
* @return The value removed
*/
@Override
public T remove() {
if (this.size <= 0) throw new IndexOutOfBoundsException();
T o = this.head.getValue();
if (this.size == 1) {
this.size = 0;
this.head = this.tail = null;
return o;
}
--this.size;
(this.tail.tail = this.head = this.head.tail).head = this.tail;
return o;
}
@Override
public T poll() {
return this.remove();
}
@Override
public T element() {
return this.peek();
}
@Override
public T peek() {
return this.tail == null ? null : this.tail.getValue();
}
protected Node<T> getNode(int index) {
Node<T> node = this.head;
while (index > 0) {
node = node.tail;
--index;
}
return node;
}
@Override
public String toString() {
// Streams FTW
return "[" + this.stream().map(T::toString).collect(Collectors.joining(", ")) + "]";
}
public Queue<T> copy() {
Queue<T> q = new Queue<>();
Node<T> node = this.head;
int i = 0;
while (node != null && i < size) { // Can't use iterable, since used in QueueIterator
q.add(node.getValue());
node = node.tail;
++i;
}
return q;
}
/**
* Methods specifically for assignment -- mostly just an alias for another method
*/
public boolean enqueue(T item) {
return this.offer(item);
}
public T dequeue() {
return this.poll();
}
/**
* Rotate the items in the queue by one
*
* @return if there were enough items to rotate
*/
public boolean sendToBack() {
if (this.isEmpty() || this.size == 1) return false;
this.tail = this.head;
this.head = this.head.tail;
return true;
}
public String toString2() {
return this.stream().map(T::toString).collect(Collectors.joining(" | "));
}
private static class Node<T> { // TODO: Convert to record (If I feel like it :P)
private final T value;
private Node<T> head;
private Node<T> tail;
public Node(T value) {
this.value = value;
this.head = null;
this.tail = null;
}
public T getValue() {
return value;
}
}
private record QueueIterator<T>(Queue<T> data) implements Iterator<T> {
private QueueIterator(Queue<T> data) {
this.data = data.copy(); // Clone it
}
@Override
public boolean hasNext() {
return !data.isEmpty();
}
@Override
public T next() {
if (!hasNext()) {
throw new RuntimeException("No next value");
}
return data.poll();
}
}
}
| 25.830065 | 97 | 0.518598 |
6955dff2f9d632d36e52ed39330c4ccc4d545082
| 1,160 |
// A binary chop (sometimes called the more prosaic binary search) finds the position of value in a
// sorted array of values. It achieves some efficiency by halving the number of items under consideration
// each time it probes the values: in the first pass it determines whether the required value is in the top
// or the bottom half of the list of values. In the second pass in considers only this half, again
// dividing it in to two. It stops when it finds the value it is looking for, or when it runs out of
// array to search. Binary searches are a favorite of CS lecturers.
//
// This Kata is straightforward. Implement a binary search routine (using the specification below) in the
// language and technique of your choice. Tomorrow, implement it again, using a totally different technique.
// Do the same the next day, until you have five totally unique implementations of a
// binary iterativeChop. (For example, one solution might be the traditional iterative approach, one might be
// recursive, one might use a functional style passing array slices around, and so on).
public class Main {
public static void main(String[] args) {
}
}
| 55.238095 | 109 | 0.764655 |
d21b8b6bd9327a8c167ca56b9ddf3639d1464f23
| 9,941 |
package dev.clojurephant.plugin.common.internal;
import static us.bpsm.edn.Keyword.newKeyword;
import java.io.File;
import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;
import dev.clojurephant.plugin.clojure.tasks.ClojureCompileOptions;
import dev.clojurephant.plugin.clojurescript.ClojureScriptBuild;
import dev.clojurephant.plugin.clojurescript.tasks.ClojureScriptCompileOptions;
import dev.clojurephant.plugin.clojurescript.tasks.FigwheelOptions;
import dev.clojurephant.plugin.clojurescript.tasks.ForeignLib;
import dev.clojurephant.plugin.clojurescript.tasks.Module;
import org.gradle.api.NamedDomainObjectCollection;
import org.gradle.api.file.Directory;
import org.gradle.api.file.FileCollection;
import org.gradle.api.provider.Provider;
import us.bpsm.edn.Keyword;
import us.bpsm.edn.Symbol;
import us.bpsm.edn.parser.Parseable;
import us.bpsm.edn.parser.Parser;
import us.bpsm.edn.parser.Parsers;
import us.bpsm.edn.printer.Printer;
import us.bpsm.edn.printer.Printers;
import us.bpsm.edn.protocols.Protocol;
public class Edn {
private static final Printer.Fn<Enum<?>> ENUM_PRINTER = (self, printer) -> printer.printValue(newKeyword(self.name()));
private static final Printer.Fn<File> FILE_PRINTER = (self, printer) -> printer.printValue(self.getAbsolutePath());
private static final Printer.Fn<FileCollection> FILE_COLLECTION_PRINTER = (self, printer) -> {
if (self.isEmpty()) {
printer.printValue(null);
} else {
printer.printValue(self.getFiles().stream().collect(Collectors.toList()));
}
};
private static final Printer.Fn<NamedDomainObjectCollection<?>> NAMED_DOMAIN_PRINTER = (self, printer) -> {
printer.printValue(self.isEmpty() ? null : self.getAsMap());
};
private static final Printer.Fn<Provider<?>> PROVIDER_PRINTER = (self, printer) -> printer.printValue(self.getOrNull());
private static final Printer.Fn<ClojureCompileOptions> CLOJURE_COMPILE_OPTIONS_PRINTER = (self, printer) -> {
Map<Object, Object> root = new LinkedHashMap<>();
root.put(newKeyword("disable-locals-clearing"), self.isDisableLocalsClearing());
root.put(newKeyword("direct-linking"), self.isDirectLinking());
root.put(newKeyword("elide-metadata"), self.getElideMeta().stream().map(Keyword::newKeyword).collect(Collectors.toList()));
printer.printValue(root);
};
private static final Printer.Fn<ClojureScriptBuild> CLOJURESCRIPT_BUILD_PRINTER = (self, printer) -> {
Map<Object, Object> root = new LinkedHashMap<>();
root.put(newKeyword("output-dir"), self.getOutputDir().map(Directory::getAsFile).getOrNull());
root.put(newKeyword("compiler"), self.getCompiler());
root.put(newKeyword("figwheel"), self.getFigwheel());
printer.printValue(root);
};
private static final Printer.Fn<FigwheelOptions> FIGWHEEL_OPTIONS_PRINTER = (self, printer) -> {
Map<Object, Object> root = new LinkedHashMap<>();
root.put(newKeyword("watch-dirs"), self.getWatchDirs());
root.put(newKeyword("css-dirs"), self.getCssDirs());
root.put(newKeyword("ring-handler"), Edn.toSymbol(self.getRingHandler()));
root.put(newKeyword("ring-server-options"), keywordize(self.getRingServerOptions()));
root.put(newKeyword("rebel-readline"), self.getRebelReadline());
root.put(newKeyword("pprint-config"), self.getPprintConfig());
root.put(newKeyword("open-file-command"), self.getOpenFileCommand());
root.put(newKeyword("figwheel-core"), self.getFigwheelCore());
root.put(newKeyword("hot-reload-cljs"), self.getHotReloadCljs());
root.put(newKeyword("connect-url"), self.getConnectUrl());
root.put(newKeyword("open-url"), self.getOpenUrl());
root.put(newKeyword("reload-clj-files"), self.getReloadCljFiles());
root.put(newKeyword("log-file"), self.getLogFile().getOrNull());
root.put(newKeyword("log-level"), Edn.toKeyword(self.getLogLevel()));
root.put(newKeyword("client-log-level"), Edn.toKeyword(self.getClientLogLevel()));
root.put(newKeyword("log-syntax-error-style"), Edn.toKeyword(self.getLogSyntaxErrorStyle()));
root.put(newKeyword("load-warninged-code"), self.getLoadWarningedCode());
root.put(newKeyword("ansi-color-output"), self.getAnsiColorOutput());
root.put(newKeyword("validate-config"), self.getValidateConfig());
root.put(newKeyword("target-dir"), self.getTargetDir().map(Directory::getAsFile).getOrNull());
root.put(newKeyword("launch-node"), self.getLaunchNode());
root.put(newKeyword("inspect-node"), self.getInspectNode());
root.put(newKeyword("node-command"), self.getNodeCommand());
root.put(newKeyword("cljs-devtools"), self.getCljsDevtools());
Edn.removeEmptyAndNulls(root);
printer.printValue(root);
};
private static final Printer.Fn<ClojureScriptCompileOptions> CLOJURESCRIPT_COMPILE_OPTIONS_PRINTER = (self, printer) -> {
Map<Object, Object> map = new LinkedHashMap<>();
map.put(newKeyword("output-to"), self.getOutputTo().getAsFile().getOrNull());
map.put(newKeyword("output-dir"), self.getOutputDir().getAsFile().getOrNull());
map.put(newKeyword("optimizations"), self.getOptimizations());
map.put(newKeyword("main"), self.getMain());
map.put(newKeyword("asset-path"), self.getAssetPath());
map.put(newKeyword("source-map"), self.getSourceMap());
map.put(newKeyword("verbose"), self.getVerbose());
map.put(newKeyword("pretty-print"), self.getPrettyPrint());
map.put(newKeyword("target"), self.getTarget());
map.put(newKeyword("foreign-libs"), self.getForeignLibs());
map.put(newKeyword("externs"), self.getExterns());
map.put(newKeyword("modules"), parseModules(self.getModules()));
map.put(newKeyword("preloads"), parsePreloads(self.getPreloads()));
map.put(newKeyword("npm-deps"), self.getNpmDeps());
map.put(newKeyword("install-deps"), self.getInstallDeps());
map.put(newKeyword("checked-arrays"), self.getCheckedArrays());
map.put(newKeyword("devcards"), self.getDevcards());
Edn.removeEmptyAndNulls(map);
printer.printValue(map);
};
private static Map<Keyword, Module> parseModules(Map<String, Module> modules) {
return modules.entrySet().stream()
.collect(Collectors.toMap(
e -> newKeyword(e.getKey()),
Map.Entry::getValue));
}
private static List<Symbol> parsePreloads(Collection<String> preloads) {
if (preloads == null) {
return null;
}
return preloads.stream()
.map(Symbol::newSymbol)
.collect(Collectors.toList());
}
private static final Printer.Fn<ForeignLib> FOREIGN_LIB_PRINTER = (self, printer) -> {
Map<Object, Object> map = new LinkedHashMap<>();
map.put(newKeyword("file"), self.getFile());
map.put(newKeyword("file-min"), self.getFileMin());
map.put(newKeyword("provides"), self.getProvides());
map.put(newKeyword("requires"), self.getRequires());
map.put(newKeyword("module-type"), self.getModuleType());
map.put(newKeyword("preprocess"), parsePreprocess(self.getPreprocess()));
map.put(newKeyword("global-exports"), parseGlobalExports(self.getGlobalExports()));
Edn.removeEmptyAndNulls(map);
printer.printValue(map);
};
private static Object parsePreprocess(String value) {
if (value == null) {
return null;
}
Parseable parseable = Parsers.newParseable(value);
Parser parser = Parsers.newParser(Parsers.defaultConfiguration());
return parser.nextValue(parseable);
}
private static Map<Symbol, Symbol> parseGlobalExports(Map<String, String> globalExports) {
return globalExports.entrySet().stream()
.collect(Collectors.toMap(
e -> Symbol.newSymbol(e.getKey()),
e -> Symbol.newSymbol(e.getValue())));
}
private static final Printer.Fn<Module> MODULE_PRINTER = (module, printer) -> {
Map<Object, Object> map = new LinkedHashMap<>();
map.put(newKeyword("output-to"), module.getOutputTo().getAsFile().getOrNull());
map.put(newKeyword("entries"), module.getEntries());
map.put(newKeyword("dependsOn"), module.getDependsOn());
Edn.removeEmptyAndNulls(map);
printer.printValue(map);
};
private static final Protocol<Printer.Fn<?>> PROTOCOL = Printers.prettyProtocolBuilder()
// Core Printers
.put(Enum.class, ENUM_PRINTER)
.put(File.class, FILE_PRINTER)
.put(FileCollection.class, FILE_COLLECTION_PRINTER)
.put(NamedDomainObjectCollection.class, NAMED_DOMAIN_PRINTER)
.put(Provider.class, PROVIDER_PRINTER)
// Clojure
.put(ClojureCompileOptions.class, CLOJURE_COMPILE_OPTIONS_PRINTER)
// ClojureScript
.put(ClojureScriptBuild.class, CLOJURESCRIPT_BUILD_PRINTER)
.put(FigwheelOptions.class, FIGWHEEL_OPTIONS_PRINTER)
.put(ClojureScriptCompileOptions.class, CLOJURESCRIPT_COMPILE_OPTIONS_PRINTER)
.put(ForeignLib.class, FOREIGN_LIB_PRINTER)
.put(Module.class, MODULE_PRINTER)
.build();
public static String print(Object value) {
return Printers.printString(PROTOCOL, value);
}
private static Symbol toSymbol(String name) {
return Optional.ofNullable(name)
.map(Symbol::newSymbol)
.orElse(null);
}
private static Keyword toKeyword(String name) {
return Optional.ofNullable(name)
.map(Keyword::newKeyword)
.orElse(null);
}
public static <V> Map<Keyword, V> keywordize(Map<String, V> map) {
return map.entrySet().stream()
.collect(Collectors.toMap(e -> newKeyword(e.getKey()), e -> e.getValue()));
}
private static <K, V> void removeEmptyAndNulls(Map<K, V> map) {
map.values().removeIf(Objects::isNull);
map.values().removeIf(obj -> (obj instanceof Collection) && ((Collection<?>) obj).isEmpty());
map.values().removeIf(obj -> (obj instanceof Map) && ((Map<?, ?>) obj).isEmpty());
}
}
| 44.182222 | 127 | 0.714013 |
9c24318ea2eb3c4148c9b1f0a3b510d3a8524cc7
| 192 |
package com.windf.study.gof.factory.factorymethod;
public class ProductBFactory implements Factory {
@Override
public Product createProduct() {
return new ProductB();
}
}
| 21.333333 | 50 | 0.713542 |
d02c3b93ac1b5944912799f8c735e5221433aced
| 3,702 |
package org.codepath.instagram;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.parse.GetCallback;
import com.parse.ParseException;
import org.codepath.instagram.Model.Post;
import java.util.ArrayList;
import java.util.List;
public class DetailFragment extends Fragment {
public ImageView ivProfileImage;
public ImageView image;
public TextView userName;
public TextView timeStamp;
public TextView description;
public ImageView commentIcon;
public ImageView likeIcon;
public TextView commentCount;
public RecyclerView rvComments;
public commentAdapter commentAdapter;
public List<Object> comments;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_detail, container, false);
}
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
ivProfileImage = (ImageView) view.findViewById(R.id.ivProfileImage);
image= (ImageView)view.findViewById(R.id.postImage);
userName= (TextView)view.findViewById(R.id.tvUserName);
description= (TextView)view.findViewById(R.id.tvdescript);
commentIcon = (ImageView) view.findViewById(R.id.ivComment);
likeIcon = (ImageView) view.findViewById(R.id.ivLikes);
timeStamp = (TextView) view.findViewById(R.id.tvTimeStamp);
rvComments= (RecyclerView)view.findViewById(R.id.rvComments);
commentCount= view.findViewById(R.id.detailCommentCount);
comments= new ArrayList<>();
commentAdapter= new commentAdapter(comments);
//RecyclerView setup (layout manager, use adapter)
rvComments.setLayoutManager(new LinearLayoutManager(getContext()));
rvComments.setAdapter(commentAdapter);
Bundle args= getArguments();
String id= args.getString("Post");
//query parse for post
Post.Query postQuery= new Post.Query().withUser();
postQuery.getQuery(Post.class).getInBackground(id, new GetCallback<Post>() {
@Override
public void done(Post object, ParseException e) {
try {
userName.setText(object.getUser().fetchIfNeeded().getUsername());
description.setText(object.getDescription());
timeStamp.setText(object.getRelativeTimeAgo());
GlideApp.with(getContext()).load(object.getImage().getUrl())
.into(image);
if (object.getUser().fetchIfNeeded().getParseFile("Profile")!=null){
GlideApp.with(getContext()).load(object.getUser().fetchIfNeeded().getParseFile("Profile").getUrl()).circleCrop()
.into(ivProfileImage);}
comments.clear();
comments.addAll(object.getList("Comment"));
commentCount.setText(""+comments.size());
commentAdapter.notifyDataSetChanged();
} catch (ParseException e1) {
e1.printStackTrace();
}
}
});
}
}
| 36.653465 | 136 | 0.661534 |
305091fa9b4ea441bab40ceae8aec944bb71bcb9
| 8,950 |
/*
* Copyright (c) 2018, 2020, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* The Universal Permissive License (UPL), Version 1.0
*
* Subject to the condition set forth below, permission is hereby granted to any
* person obtaining a copy of this software, associated documentation and/or
* data (collectively the "Software"), free of charge and under any and all
* copyright rights in the Software, and any and all patent rights owned or
* freely licensable by each licensor hereunder covering either (i) the
* unmodified Software as contributed to or provided by such licensor, or (ii)
* the Larger Works (as defined below), to deal in both
*
* (a) the Software, and
*
* (b) any piece of software and/or hardware listed in the lrgrwrks.txt file if
* one is included with the Software each a "Larger Work" to which the Software
* is contributed by such licensors),
*
* without restriction, including without limitation the rights to copy, create
* derivative works of, display, perform, and distribute the Software and make,
* use, sell, offer for sale, import, export, have made, and have sold the
* Software and the Larger Work(s), and to sublicense the foregoing rights on
* either these or other terms.
*
* This license is subject to the following condition:
*
* The above copyright notice and either this complete permission notice or at a
* minimum a reference to the UPL must be included in all copies or substantial
* portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.oracle.truffle.js.runtime.builtins;
import com.oracle.truffle.api.CompilerDirectives;
import com.oracle.truffle.api.CompilerDirectives.CompilationFinal;
import com.oracle.truffle.api.object.DynamicObject;
import com.oracle.truffle.api.object.DynamicObjectLibrary;
import com.oracle.truffle.api.object.Shape;
import com.oracle.truffle.js.runtime.JSContext;
import com.oracle.truffle.js.runtime.JSRealm;
import com.oracle.truffle.js.runtime.array.ArrayAllocationSite;
import com.oracle.truffle.js.runtime.array.ScriptArray;
import com.oracle.truffle.js.runtime.objects.JSObject;
import com.oracle.truffle.js.runtime.objects.JSObjectUtil;
import com.oracle.truffle.js.runtime.util.CompilableBiFunction;
public abstract class JSArrayFactory {
protected final JSContext context;
@CompilationFinal private DynamicObjectLibrary setProto;
static JSArrayFactory create(JSContext context, Shape shape, PrototypeSupplier prototypeSupplier) {
return new JSArrayFactory.WithShape(context, shape, prototypeSupplier);
}
static JSArrayFactory forArray(JSObjectFactory.IntrinsicBuilder builder) {
return new JSArrayFactory.Intrinsic(builder.getContext(), JSArray.INSTANCE::makeInitialShape, builder.nextIndex());
}
static JSArrayFactory forArgumentsObject(JSObjectFactory.IntrinsicBuilder builder, boolean mapped) {
return new JSArrayFactory.ArgumentsObject(builder.getContext(), builder.nextIndex(), mapped);
}
protected JSArrayFactory(JSContext context) {
this.context = context;
}
public final DynamicObject createWithRealm(JSRealm realm,
ScriptArray arrayType, Object array, ArrayAllocationSite site, long length, int usedLength, int indexOffset, int arrayOffset, int holeCount) {
return createWithPrototype(realm, getPrototype(realm), arrayType, array, site, length, usedLength, indexOffset, arrayOffset, holeCount);
}
public final DynamicObject createWithPrototype(JSRealm realm, DynamicObject prototype,
ScriptArray arrayType, Object array, ArrayAllocationSite site, long length, int usedLength, int indexOffset, int arrayOffset, int holeCount) {
assert prototype != null;
Shape shape = getShape(realm, prototype);
if (isInObjectProto()) {
DynamicObject obj = newInstance(shape, arrayType, array, site, length, usedLength, indexOffset, arrayOffset, holeCount);
setPrototype(obj, prototype);
return obj;
}
assert JSObjectFactory.verifyPrototype(shape, prototype);
return newInstance(shape, arrayType, array, site, length, usedLength, indexOffset, arrayOffset, holeCount);
}
protected DynamicObject newInstance(Shape shape, ScriptArray arrayType, Object array, ArrayAllocationSite site, long length, int usedLength, int indexOffset, int arrayOffset, int holeCount) {
return JSArrayObject.create(shape, arrayType, array, site, length, usedLength, indexOffset, arrayOffset, holeCount);
}
protected abstract DynamicObject getPrototype(JSRealm realm);
protected abstract Shape getShape(JSRealm realm, DynamicObject prototype);
protected final void setPrototype(DynamicObject obj, DynamicObject prototype) {
if (setProto == null) {
CompilerDirectives.transferToInterpreterAndInvalidate();
setProto = context.adoptNode(JSObjectUtil.createCached(JSObject.HIDDEN_PROTO, obj));
}
setProto.put(obj, JSObject.HIDDEN_PROTO, prototype);
}
protected final boolean isInObjectProto() {
return context.isMultiContext();
}
private static final class WithShape extends JSArrayFactory {
private final Shape shape;
private final PrototypeSupplier prototypeSupplier;
protected WithShape(JSContext context, Shape shape, PrototypeSupplier prototypeSupplier) {
super(context);
this.shape = shape;
this.prototypeSupplier = prototypeSupplier;
}
@Override
protected DynamicObject getPrototype(JSRealm realm) {
return prototypeSupplier.getIntrinsicDefaultProto(realm);
}
@Override
protected Shape getShape(JSRealm realm, DynamicObject prototype) {
return shape;
}
}
private static class Intrinsic extends JSArrayFactory {
private final int slot;
private final CompilableBiFunction<JSContext, DynamicObject, Shape> shapeSupplier;
@CompilationFinal private Shape shape;
protected Intrinsic(JSContext context, CompilableBiFunction<JSContext, DynamicObject, Shape> shapeSupplier, int slot) {
super(context);
this.shapeSupplier = shapeSupplier;
this.slot = slot;
}
@Override
protected final Shape getShape(JSRealm realm, DynamicObject prototype) {
if (context.isMultiContext()) {
if (shape == null) {
CompilerDirectives.transferToInterpreterAndInvalidate();
shape = shapeSupplier.apply(context, null);
assert isInObjectProto() == JSObjectFactory.hasInObjectProto(shape);
}
return shape;
} else {
Shape realmShape = realm.getObjectFactories().shapes[slot];
if (realmShape == null) {
CompilerDirectives.transferToInterpreterAndInvalidate();
Shape newShape = shapeSupplier.apply(context, prototype);
realmShape = realm.getObjectFactories().shapes[slot] = newShape;
assert isInObjectProto() == JSObjectFactory.hasInObjectProto(realmShape);
}
return realmShape;
}
}
@Override
protected DynamicObject getPrototype(JSRealm realm) {
return realm.getArrayPrototype();
}
}
private static final class ArgumentsObject extends Intrinsic {
private final boolean mapped;
protected ArgumentsObject(JSContext context, int slot, boolean mapped) {
super(context, JSObjectFactory.defaultShapeSupplier(JSArgumentsArray.INSTANCE), slot);
this.mapped = mapped;
}
@Override
protected DynamicObject getPrototype(JSRealm realm) {
return realm.getObjectPrototype();
}
@Override
protected DynamicObject newInstance(Shape shape, ScriptArray arrayType, Object array, ArrayAllocationSite site, long length, int usedLength, int indexOffset, int arrayOffset, int holeCount) {
Object[] elements = (Object[]) array;
if (mapped) {
return JSArgumentsArray.createMapped(shape, elements);
} else {
return JSArgumentsArray.createUnmapped(shape, elements);
}
}
}
}
| 45.431472 | 199 | 0.704246 |
c90b313e4b8f00ae14505db19eedd75a4b3f6522
| 2,563 |
/*
* Copyright 2020, Verizon Media.
* Licensed under the terms of the Apache 2.0 license.
* Please see LICENSE file in the project root for terms.
*/
package com.yahoo.oak;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Fork;
import org.openjdk.jmh.annotations.Measurement;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Param;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.annotations.Threads;
import org.openjdk.jmh.annotations.Warmup;
import org.openjdk.jmh.infra.Blackhole;
import org.openjdk.jmh.runner.Runner;
import org.openjdk.jmh.runner.RunnerException;
import org.openjdk.jmh.runner.options.Options;
import org.openjdk.jmh.runner.options.OptionsBuilder;
import java.nio.ByteBuffer;
import java.util.concurrent.TimeUnit;
public class ByteBufferBenchmark {
@State(Scope.Benchmark)
public static class BenchmarkState {
@Param({"ONHEAP", "OFFHEAP"})
String heap;
ByteBuffer byteBuffer;
final int bytes = 1024 * 1024 * 1024;
@Setup()
public void setup() {
if (heap.equals("ONHEAP")) {
byteBuffer = ByteBuffer.allocate(bytes);
} else {
byteBuffer = ByteBuffer.allocateDirect(bytes);
}
}
}
@Warmup(iterations = 1)
@Measurement(iterations = 10)
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.MILLISECONDS)
@Fork(value = 1)
@Threads(1)
@Benchmark
public void put(Blackhole blackhole, BenchmarkState state) {
for (int i = 0; i < state.bytes; ++i) {
state.byteBuffer.put(i, (byte) i);
}
}
@Warmup(iterations = 1)
@Measurement(iterations = 10)
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.MILLISECONDS)
@Fork(value = 1)
@Threads(1)
@Benchmark
public void get(Blackhole blackhole, BenchmarkState state) {
for (int i = 0; i < state.bytes; ++i) {
blackhole.consume(state.byteBuffer.get(i));
}
}
public static void main(String[] args) throws RunnerException {
Options opt = new OptionsBuilder()
.include(ByteBufferBenchmark.class.getSimpleName())
.forks(1)
.threads(1)
.build();
new Runner(opt).run();
}
}
| 28.164835 | 67 | 0.663285 |
24bc681b26bb5b1d6d5f858e8e3a11093f041ee6
| 1,429 |
package com.sap.olingo.jpa.processor.core.testmodel;
import javax.persistence.Column;
import javax.persistence.Embeddable;
@Embeddable
public class InstanceRestrictionKey {
@Column(name = "\"UserName\"", length = 60)
private String username;
@Column(name = "\"SequenceNumber\"")
private Integer sequenceNumber;
public InstanceRestrictionKey() {
// Needed
}
public InstanceRestrictionKey(String username, Integer sequenceNumber) {
super();
this.username = username;
this.sequenceNumber = sequenceNumber;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((sequenceNumber == null) ? 0 : sequenceNumber.hashCode());
result = prime * result + ((username == null) ? 0 : username.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null) return false;
if (getClass() != obj.getClass()) return false;
InstanceRestrictionKey other = (InstanceRestrictionKey) obj;
if (sequenceNumber == null) {
if (other.sequenceNumber != null) return false;
} else if (!sequenceNumber.equals(other.sequenceNumber)) return false;
if (username == null) {
if (other.username != null) return false;
} else if (!username.equals(other.username)) return false;
return true;
}
}
| 29.163265 | 90 | 0.654304 |
add14dab95f4db4820caf8c03dcd633d03b72e72
| 640 |
package com.ncme.springboot.mapper;
import org.apache.ibatis.annotations.Param;
import com.ncme.springboot.model.PeixunOrg;
public interface PeixunOrgMapper {
int deleteByPrimaryKey(Integer id);
int insert(PeixunOrg record);
int insertSelective(PeixunOrg record);
PeixunOrg selectByPrimaryKey(Integer id);
int updateByPrimaryKeySelective(PeixunOrg record);
int updateByPrimaryKey(PeixunOrg record);
/**
* @author 王印涛
* 2018年1月11日 下午6:30:16
* @Description: 根据项目ID获取项目所属机构
* @param cvSetId
* @return PeixunOrg
*/
PeixunOrg getOrg(@Param("cvSetId")Integer cvSetId);
}
| 22.068966 | 55 | 0.714063 |
1bb572339fc75f44f14fec6b83dfef4c79c8ae6c
| 7,464 |
/*
* Copyright 2021 Couchbase, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.couchbase.client.java.manager.analytics.link;
import com.couchbase.client.core.deps.com.fasterxml.jackson.annotation.JsonAlias;
import com.couchbase.client.core.deps.com.fasterxml.jackson.annotation.JsonProperty;
import com.couchbase.client.core.deps.com.fasterxml.jackson.annotation.JsonValue;
import static com.couchbase.client.core.deps.com.fasterxml.jackson.annotation.JsonProperty.Access.READ_ONLY;
import static java.util.Objects.requireNonNull;
/**
* An analytics link to a remote couchbase cluster.
*/
@SuppressWarnings("unused")
public class CouchbaseRemoteAnalyticsLink extends AnalyticsLink {
@JsonProperty
@JsonAlias("activeHostname")
private String hostname;
@JsonProperty
private EncryptionLevel encryption;
@JsonProperty
private String username;
@JsonProperty(access = READ_ONLY)
private String password;
@JsonProperty
private String certificate;
@JsonProperty
private String clientCertificate;
@JsonProperty(access = READ_ONLY)
private String clientKey;
/**
* Creates a new Analytics Link to a remote Couchbase cluster.
* <p>
* As an alternative to this constructor, {@link AnalyticsLink#couchbaseRemote(String, String)} can be used as well.
* <p>
* Please note that additional parameters are required and must be set on {@link CouchbaseRemoteAnalyticsLink} in order
* for the link to work properly.
*/
public CouchbaseRemoteAnalyticsLink(final String name, final String dataverse) {
super(name, dataverse);
}
// For Jackson
private CouchbaseRemoteAnalyticsLink() {
super("", "");
}
@Override
public AnalyticsLinkType type() {
return AnalyticsLinkType.COUCHBASE_REMOTE;
}
/**
* Returns the hostname of the remote cluster.
*
* @return the hostname of the remote cluster.
*/
public String hostname() {
return hostname;
}
/**
* Sets the hostname of the remote cluster (required).
*
* @param hostname the hostname of the remote cluster.
* @return this {@link CouchbaseRemoteAnalyticsLink} for chaining purposes.
*/
public CouchbaseRemoteAnalyticsLink hostname(final String hostname) {
this.hostname = hostname;
return this;
}
/**
* Returns the encryption level for the link to the remote cluster.
*
* @return the encryption level for the link to the remote cluster.
*/
public EncryptionLevel encryption() {
return encryption;
}
/**
* Sets the encryption level for the link to the remote cluster (required).
*
* @param encryption the encryption level for the link to the remote cluster.
* @return this {@link CouchbaseRemoteAnalyticsLink} for chaining purposes.
*/
public CouchbaseRemoteAnalyticsLink encryption(final EncryptionLevel encryption) {
this.encryption = encryption;
return this;
}
/**
* Returns the username when connecting to the remote cluster.
*
* @return the username when connecting to the remote cluster.
*/
public String username() {
return username;
}
/**
* Sets the username when connecting to the remote cluster (required).
*
* @param username the username when connecting to the remote cluster.
* @return this {@link CouchbaseRemoteAnalyticsLink} for chaining purposes.
*/
public CouchbaseRemoteAnalyticsLink username(final String username) {
this.username = username;
return this;
}
/**
* Sets the password when connecting to the remote cluster.
*
* @return the password when connecting to the remote cluster.
*/
public String password() {
return password;
}
/**
* Sets the password when connecting to the remote cluster (required).
*
* @param password the password when connecting to the remote cluster.
* @return this {@link CouchbaseRemoteAnalyticsLink} for chaining purposes.
*/
public CouchbaseRemoteAnalyticsLink password(final String password) {
this.password = password;
return this;
}
/**
* Returns the certificate when encryption is used.
*
* @return the certificate when encryption is used.
*/
public String certificate() {
return certificate;
}
/**
* Sets the certificate when encryption is used.
*
* @param certificate the certificate when encryption is used.
* @return this {@link CouchbaseRemoteAnalyticsLink} for chaining purposes.
*/
public CouchbaseRemoteAnalyticsLink certificate(final String certificate) {
this.certificate = certificate;
return this;
}
/**
* Returns the client certificate when encryption is used.
*
* @return the client certificate when encryption is used.
*/
public String clientCertificate() {
return clientCertificate;
}
/**
* Sets the client certificate when encryption is used.
*
* @param clientCertificate the client certificate when encryption is used.
* @return this {@link CouchbaseRemoteAnalyticsLink} for chaining purposes.
*/
public CouchbaseRemoteAnalyticsLink clientCertificate(final String clientCertificate) {
this.clientCertificate = clientCertificate;
return this;
}
/**
* Returns the client key.
*
* @return the client key.
*/
public String clientKey() {
return clientKey;
}
/**
* Sets the client key.
*
* @param clientKey the client key.
* @return this {@link CouchbaseRemoteAnalyticsLink} for chaining purposes.
*/
public CouchbaseRemoteAnalyticsLink clientKey(final String clientKey) {
this.clientKey = clientKey;
return this;
}
@Override
public String toString() {
return "CouchbaseRemoteAnalyticsLink{" +
"encryption=" + encryption +
", hostname='" + hostname + '\'' +
", username='" + username + '\'' +
", hasPassword=" + (password != null) +
", certificate='" + certificate + '\'' +
", clientCertificate='" + clientCertificate + '\'' +
", hasClientKey=" + (clientKey != null) +
'}';
}
/**
* Security options for remote Couchbase links.
*/
public enum EncryptionLevel {
/**
* Connect to the remote Couchbase cluster using an unsecured channel.
* Send the password in plaintext.
*/
NONE("none"),
/**
* Connect to the remote Couchbase cluster using an unsecured channel.
* Send the password securely using SASL.
*/
HALF("half"),
/**
* Connect to the remote Couchbase cluster using a channel secured by TLS.
* If a password is used, it is sent over the secure channel.
* <p>
* Requires specifying the certificate to trust.
*
* @see CouchbaseRemoteAnalyticsLink#certificate(String)
*/
FULL("full"),
;
private final String wireName;
EncryptionLevel(String wireName) {
this.wireName = requireNonNull(wireName);
}
@JsonValue
public String wireName() {
return wireName;
}
}
}
| 27.850746 | 121 | 0.696008 |
5c8a95e56e98ed919ce104adcf6d8f848795b159
| 2,249 |
package org.gislers.chinook.persistence.dao.impl;
import org.gislers.chinook.entities.CustomerEntity;
import org.gislers.chinook.entities.EmployeeEntity;
import org.gislers.chinook.entities.InvoiceEntity;
import org.gislers.chinook.persistence.dao.CustomerDao;
import org.gislers.chinook.persistence.dao.EmployeeDao;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.List;
import static org.junit.Assert.*;
/**
* Created by: jgisle
* Created date: 9/11/15
*/
public class CustomerDaoImplTest extends BaseDaoImplTest {
@Autowired
private CustomerDao dao;
@Autowired
private EmployeeDao employeeDao;
@Test
public void testFindOne() throws Exception {
CustomerEntity entity = dao.findOne(1);
assertNotNull(entity);
assertEquals(1, entity.getCustomerId());
EmployeeEntity supportRep = entity.getSupportRep();
assertEquals(3, supportRep.getEmployeeId());
List<InvoiceEntity> invoiceEntities = entity.getInvoiceEntities();
assertNotNull( invoiceEntities );
assertEquals( 7, invoiceEntities.size() );
}
@Test
public void testFindAll() throws Exception {
List<CustomerEntity> customerEntities = dao.findAll();
assertFalse( customerEntities.isEmpty() );
assertEquals(59, customerEntities.size());
}
@Test
public void testUpdate() throws Exception {
CustomerEntity entity = dao.findOne(1);
assertNotNull(entity);
assertEquals( "Gonçalves", entity.getLastName() );
entity.setLastName( "Jones" );
dao.update(entity);
entity = dao.findOne(1);
assertNotNull(entity);
assertEquals("Jones", entity.getLastName());
}
@Test
public void testDelete() throws Exception {
CustomerEntity entity = dao.findOne(1);
assertNotNull(entity);
dao.delete(entity);
entity = dao.findOne(1);
assertNull(entity);
}
@Test
public void testDeleteById() throws Exception {
CustomerEntity entity = dao.findOne(1);
assertNotNull(entity);
dao.deleteById(1);
entity = dao.findOne(1);
assertNull(entity);
}
}
| 27.096386 | 74 | 0.675856 |
ac30f44e47baf6f05818c042f077f9c90339712f
| 6,456 |
package com.joymain.jecs.fi.model;
// Generated 2010-1-14 14:33:37 by Hibernate Tools 3.1.0.beta4
import java.math.BigDecimal;
import com.joymain.jecs.pm.model.JpmProductSaleNew;
/**
* @struts.form include-all="true" extends="BaseForm"
* @hibernate.class
* table="JFI_SUN_MEMBER_ORDER_LIST"
*
*/
public class JfiSunMemberOrderList extends com.joymain.jecs.model.BaseObject implements java.io.Serializable {
// Fields
private Long molId;
private JfiSunMemberOrder jfiSunMemberOrder;
private JpmProductSaleNew jpmProductSaleNew;
private BigDecimal price;
private BigDecimal pv;
private int qty;
private BigDecimal weight;
private BigDecimal volume;
// Constructors
/** default constructor */
public JfiSunMemberOrderList() {
}
/** minimal constructor */
public JfiSunMemberOrderList(long moId, long productId, BigDecimal price, BigDecimal pv, int qty) {
this.price = price;
this.pv = pv;
this.qty = qty;
}
/** full constructor */
public JfiSunMemberOrderList(long moId, long productId, BigDecimal price, BigDecimal pv, int qty, BigDecimal weight, BigDecimal volume) {
this.price = price;
this.pv = pv;
this.qty = qty;
this.weight = weight;
this.volume = volume;
}
// Property accessors
/**
* * @hibernate.id
* generator-class="native"
* type="java.lang.Long"
* column="MOL_ID"
*
*/
public Long getMolId() {
return this.molId;
}
public void setMolId(Long molId) {
this.molId = molId;
}
/**
* * @hibernate.property
* column="PRICE"
* length="18"
* not-null="true"
*
*/
public BigDecimal getPrice() {
return this.price;
}
public void setPrice(BigDecimal price) {
this.price = price;
}
/**
* * @hibernate.property
* column="PV"
* length="18"
* not-null="true"
*
*/
public BigDecimal getPv() {
return this.pv;
}
public void setPv(BigDecimal pv) {
this.pv = pv;
}
/**
* * @hibernate.property
* column="QTY"
* length="5"
* not-null="true"
*
*/
public int getQty() {
return this.qty;
}
public void setQty(int qty) {
this.qty = qty;
}
/**
* * @hibernate.property
* column="WEIGHT"
* length="10"
*
*/
public BigDecimal getWeight() {
return this.weight;
}
public void setWeight(BigDecimal weight) {
this.weight = weight;
}
/**
* * @hibernate.property
* column="VOLUME"
* length="10"
*
*/
public BigDecimal getVolume() {
return this.volume;
}
public void setVolume(BigDecimal volume) {
this.volume = volume;
}
/**
* *
* @hibernate.many-to-one not-null="true"
* @hibernate.column name="MO_ID"
*
*/
public JfiSunMemberOrder getJfiSunMemberOrder() {
return jfiSunMemberOrder;
}
public void setJfiSunMemberOrder(JfiSunMemberOrder jfiSunMemberOrder) {
this.jfiSunMemberOrder = jfiSunMemberOrder;
}
/**
* *
* @hibernate.many-to-one not-null="true"
* @hibernate.column name="PRODUCT_ID"
*
*/
public JpmProductSaleNew getJpmProductSaleNew() {
return jpmProductSaleNew;
}
public void setJpmProductSaleNew(JpmProductSaleNew jpmProductSaleNew) {
this.jpmProductSaleNew = jpmProductSaleNew;
}
/**
* toString
* @return String
*/
public String toString() {
StringBuffer buffer = new StringBuffer();
buffer.append(getClass().getName()).append("@").append(Integer.toHexString(hashCode())).append(" [");
buffer.append("price").append("='").append(getPrice()).append("' ");
buffer.append("pv").append("='").append(getPv()).append("' ");
buffer.append("qty").append("='").append(getQty()).append("' ");
buffer.append("weight").append("='").append(getWeight()).append("' ");
buffer.append("volume").append("='").append(getVolume()).append("' ");
buffer.append("]");
return buffer.toString();
}
public boolean equals(Object other) {
if ( (this == other ) ) return true;
if ( (other == null ) ) return false;
if ( !(other instanceof JfiSunMemberOrderList) ) return false;
JfiSunMemberOrderList castOther = ( JfiSunMemberOrderList ) other;
return ( (this.getMolId()==castOther.getMolId()) || ( this.getMolId()!=null && castOther.getMolId()!=null && this.getMolId().equals(castOther.getMolId()) ) )
&& ( (this.getPrice()==castOther.getPrice()) || ( this.getPrice()!=null && castOther.getPrice()!=null && this.getPrice().equals(castOther.getPrice()) ) )
&& ( (this.getPv()==castOther.getPv()) || ( this.getPv()!=null && castOther.getPv()!=null && this.getPv().equals(castOther.getPv()) ) )
&& (this.getQty()==castOther.getQty())
&& ( (this.getWeight()==castOther.getWeight()) || ( this.getWeight()!=null && castOther.getWeight()!=null && this.getWeight().equals(castOther.getWeight()) ) )
&& ( (this.getVolume()==castOther.getVolume()) || ( this.getVolume()!=null && castOther.getVolume()!=null && this.getVolume().equals(castOther.getVolume()) ) );
}
public int hashCode() {
int result = 17;
result = 37 * result + ( getMolId() == null ? 0 : this.getMolId().hashCode() );
// result = 37 * result + ( this.jpmProductSale == null ? 0 : (int) this.jpmProductSale.getUniNo().hashCode());
result = 37 * result + ( getPrice() == null ? 0 : this.getPrice().hashCode() );
result = 37 * result + ( getPv() == null ? 0 : this.getPv().hashCode() );
result = 37 * result + this.getQty();
result = 37 * result + ( getWeight() == null ? 0 : this.getWeight().hashCode() );
result = 37 * result + ( getVolume() == null ? 0 : this.getVolume().hashCode() );
return result;
}
}
| 28.693333 | 161 | 0.553439 |
4aa8135105cfb2844895525069fc6af474345d59
| 1,174 |
package com.rill.rest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.NameValuePair;
import org.apache.http.client.utils.URLEncodedUtils;
import static com.rill.rest.util.MultiMapUtil.addValueToMap;
/**
* User: rsmith
* Date: 11/8/13 1:28 PM
*/
public class HttpQueryParamParser {
public static Map<String, List<String>> parseParameters(String queryParamStr) {
List<NameValuePair> params = new ArrayList<NameValuePair>();
URLEncodedUtils.parse(params, new Scanner(queryParamStr), "UTF-8");
Map<String, List<String>> paramMap = toMap(params);
return paramMap;
}
private static Map<String, List<String>> toMap(List<NameValuePair> params) {
Map<String, List<String>> paramMap = new HashMap<String, List<String>>();
for (NameValuePair param : params) {
String value = StringUtils.trimToEmpty(param.getValue());
addValueToMap(paramMap, param.getName(), value);
}
return paramMap;
}
}
| 28.634146 | 83 | 0.698467 |
9ab7ba5ffd0579ed4b58d26d05c5fb9f8023b482
| 157 |
public class TokenIsNotNumber extends Exception
{
public TokenIsNotNumber(String str_)
{
super();
str = str_;
}
public String str;
}
| 14.272727 | 47 | 0.649682 |
83c512f6c24f3b493a6d6ad05514d3dcf51b2ee0
| 9,784 |
/* JAT: Java Astrodynamics Toolkit
*
* Copyright (c) 2003 The JAT Project. All rights reserved.
*
* This file is part of JAT. JAT is free software; you can
* redistribute it and/or modify it under the terms of the
* NASA Open Source Agreement, version 1.3 or later.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* NASA Open Source Agreement for more details.
*
* You should have received a copy of the NASA Open Source Agreement
* along with this program; if not, write to the NASA Goddard
* Space Flight Center at opensource@gsfc.nasa.gov.
*
*/
package jat.attitude.util;
import jat.util.FileUtil;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
/**
* <P>
* The JTextFieldPanel provides an efficient way of creating and organizing
* TextField objects. The class extends JPanel and is therefore a JPanel itself.
* And all the components constructed in this class is swing components.
* The main objective of this class is to create input fields with labels
* identifying the fields.
* <P>
* JTextFieldPanel uses BoxLayout to construct a JPanel with 1 row or column of
* JTextField components along with labels.
*
* @author Noriko Takada
* @version Last Modified: 08/12003
*/
public class JTextFieldPanel extends JPanel // This class is the JPanel itself
{
// Instantiate a Font object
Font fancyFont = new Font("Serif", Font.BOLD | Font.ITALIC, 32);
Font titlef = new Font("Dialog", Font.BOLD, 16);
Font boldf = new Font("Dialog", Font.BOLD, 12);
Font italicf = new Font("Dialog", Font.ITALIC, 12);
Font normalf = new Font("Dialog", Font.PLAIN, 12);
// theFrame is used in main() for demonstration purpose
private static JFrame theFrame;
/**
* @param direction (int)1-> X_AXIS, 2-> Y_AXIS
* @param title (String) Title of the panel
* @param labels (String[]) Labels of the corresponding TextFields
* @param fields (JTextField[]) TextFields to be laid out
* @param c (Color) Color of the panel
*/
public JTextFieldPanel(int direction, String title, String labels[],
JTextField fields[], Color c)
{
// Since labels are supposed to be associated with the text fields,
// labels[] and fields[] are assumed to have the same length.
super();
int length = labels.length;
if(direction == 1)
{
setLayout(new BoxLayout(this, BoxLayout.X_AXIS));
int panelRowWidth = length*100 + length * 5 + 5+5;
int panelRowHeight = 30;
Dimension rowSize = new Dimension (panelRowWidth, panelRowHeight);
this.setMaximumSize(rowSize);
this.setPreferredSize(rowSize);
this.setMinimumSize(rowSize);
}
else
{
setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
int panelColumnWidth = 110;
int panelColumnHeight = (length+1)*25 + length * 5 + 5;
Dimension columnSize = new Dimension(panelColumnWidth, panelColumnHeight);
this.setMaximumSize(columnSize);
this.setPreferredSize(columnSize);
this.setMinimumSize(columnSize);
}
this.setBackground(c);
this.setBorder(BorderFactory.createTitledBorder(title));
/* Add JLabel and JTextField component to this JPanel */
for(int i=0;i<length;++i)
{
int fieldWidth = 50;
int fieldHeight = 25;
JPanel unitPanel = new JPanel();
unitPanel.setLayout(new BoxLayout(unitPanel, BoxLayout.X_AXIS));
Dimension unitSize = new Dimension (2*fieldWidth, fieldHeight);
unitPanel.setMaximumSize(unitSize);
unitPanel.setPreferredSize(unitSize);
unitPanel.setMinimumSize(unitSize);
unitPanel.setBackground(c);
if(direction ==1) //X direction
unitPanel.setAlignmentY(CENTER_ALIGNMENT);
else
unitPanel.setAlignmentX(LEFT_ALIGNMENT);
Dimension fieldSize = new Dimension(fieldWidth, fieldHeight);
fields[i].setMaximumSize(fieldSize);
fields[i].setPreferredSize(fieldSize);
fields[i].setMinimumSize(fieldSize);
JLabel label = new JLabel(labels[i], Label.RIGHT);
unitPanel.add(Box.createHorizontalGlue());
unitPanel.add(label );
unitPanel.add(fields[i]);
this.add(Box.createRigidArea(new Dimension(5, 5)));
this.add(unitPanel);
}
this.add(Box.createRigidArea(new Dimension(5,5)));
this.setAlignmentX(LEFT_ALIGNMENT);
}// End of constructor
/*
/**
* Constructor 2
*
* @param direction 1-> X_AXIS
* 2-> Y_AXIS
* @param title Title of the panel
* @param labels[] Labels of the corresponding TextFields
* @param fields[] TextFields to be laid out
* @param c Color of the panel
* @param titleImage Icon image to be added with the title label
*/
/*
public JTextFieldPanel(int direction, String title, String labels[],
JTextField fields[], Color c, ImageIcon titleImage)
{
// Since labels are supposed to be associated with the text fields,
// labels[] and fields[] are assumed to have the same length.
super();
int length = labels.length;
// The target of BoxLayout is 'this' JPanel. /
if(direction == 1)
{
setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
JPanel rowPanel = new JPanel();
rowPanel.setLayout(new BoxLayout(rowPanel, BoxLayout.X_AXIS));
int panelRowWidth = length*150 + length * 5 + 5;
int panelRowHeight = 70;
Dimension rowSize = new Dimension (panelRowWidth, panelRowHeight);
Dimension panelSize = new Dimension (panelRowWidth, panelRowHeight + 50);
rowPanel.setMaximumSize(rowSize);
rowPanel.setPreferredSize(rowSize);
rowPanel.setMinimumSize(rowSize);
rowPanel.setAlignmentX(LEFT_ALIGNMENT);
this.setMaximumSize(panelSize);
this.setPreferredSize(panelSize);
this.setMinimumSize(panelSize);
rowPanel.setBackground(c);
this.setBackground(c);
this.setBorder(BorderFactory.createLineBorder(Color.red));
JLabel titleLabel = new JLabel(title);
// Associate the font with the label
titleLabel.setFont(titlef);
titleLabel.setIcon(titleImage);
// Align the text to the right of the Icon
titleLabel.setHorizontalAlignment(JLabel.RIGHT);
titleLabel.setAlignmentX(LEFT_ALIGNMENT);
this.add(titleLabel);
// Add JLabel and JTextField component to this JPanel
for(int i=0;i<length;++i)
{
JLabel label = new JLabel(labels[i], Label.RIGHT);
rowPanel.add(Box.createHorizontalGlue());
rowPanel.add(label );
rowPanel.add(fields[i]);
}
this.add(rowPanel);
}// End of if
else
{
setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
int panelColumnWidth = 25;
int panelColumnHeight = length*70 + length * 5 + 5;
Dimension columnSize = new Dimension(panelColumnWidth, panelColumnHeight);
this.setMaximumSize(columnSize);
this.setPreferredSize(columnSize);
this.setMinimumSize(columnSize);
this.setBackground(c);
this.setBorder(BorderFactory.createLineBorder(Color.red));
JLabel titleLabel = new JLabel(title);
// Associate the font with the label
titleLabel.setFont(titlef);
titleLabel.setIcon(titleImage);
// Align the text to the right of the Icon
titleLabel.setHorizontalAlignment(JLabel.RIGHT);
add(titleLabel);
// Add JLabel and JTextField component to this JPanel
for(int i=0;i<length;++i)
{
JLabel label = new JLabel(labels[i], Label.RIGHT);
add(Box.createHorizontalGlue());
add(label );
add(fields[i]);
}
}//End of else
}// End of constructor 2
*/
/**
* Demonstrates the use of JTextFieldPanel class
* @param args (String[]) Argument
*/
public static void main(String[] args)
{
/* Create ImageIcon to be used with the JLabel component */
String images_path = FileUtil.getClassFilePath("jat.attitude.thesis", "AttitudeSimulator")+ "images/";
ImageIcon domburi = new ImageIcon(images_path+"Domburi7.gif");
String title = "";
String hobby[] = {"w1", "hobby2","hobby3"};
JTextField hobbyfields[] = new JTextField[3];
hobbyfields[0] = new JTextField(5);
hobbyfields[1] = new JTextField(5);
hobbyfields[2] = new JTextField(5);
JTextFieldPanel theJPanel = new JTextFieldPanel(2,title, hobby, hobbyfields, Color.pink);
theFrame = new JFrame();
theFrame.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.exit(0);}
});
JPanel outerPanel = new JPanel();
outerPanel.setLayout(new BoxLayout(outerPanel, BoxLayout.Y_AXIS));
outerPanel.setSize(750, 550);
outerPanel.add(theJPanel);
//theFrame.getContentPane().setLayout(new BoxLayout(theFrame,BoxLayout.Y_AXIS));
theFrame.getContentPane().add( outerPanel, BorderLayout.CENTER );
theFrame.setTitle("JTextFieldPanel");
Dimension frameSize = theJPanel.getPreferredSize();
//theFrame.setSize((int)frameSize.getWidth(), (int)frameSize.getHeight());
theFrame.setSize(750, 550);
Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
theFrame.setLocation( (d.width - theFrame.getSize().width) / 2,
(d.height - theFrame.getSize().height) / 2);
theFrame.setVisible(true );
}// End of main()
}// End of file
| 34.942857 | 107 | 0.658422 |
ef3ef1331a92ba6ec552cef11f8f32271ed55360
| 3,005 |
package com.tencent.qcloud.cosv4_14313.model;
import android.test.AndroidTestCase;
import org.junit.Test;
/**
* Created by bradyxiao on 2018/1/23.
*/
public class GetObjectMetadataRequestTest extends AndroidTestCase {
@Test
public void setHeaders() throws Exception {
}
@Test
public void setBodys() throws Exception {
}
@Test
public void test() throws Exception {
// QServer qServer = QServer.init(getContext());
// String cosPath = "test.txt";
//
// /** GetObjectMetadataRequest 请求对象 */
// GetObjectMetadataRequest getObjectMetadataRequest = new GetObjectMetadataRequest();
// /** 设置Bucket */
// getObjectMetadataRequest.setBucket(qServer.bucket);
// /** 设置cosPath :远程路径*/
// getObjectMetadataRequest.setCosPath(cosPath);
// /** 设置sign: 签名,此处使用多次签名 */
// getObjectMetadataRequest.setSign(qServer.getSign());
// /** 设置listener: 结果回调 */
// getObjectMetadataRequest.setListener(new ICmdTaskListener() {
// @Override
// public void onSuccess(COSRequest cosRequest, COSResult cosResult) {
// GetObjectMetadataResult getObjectMetadataResult = (GetObjectMetadataResult) cosResult;
// StringBuilder stringBuilder = new StringBuilder();
// stringBuilder.append("查询结果 = ")
// .append(" code = ").append(getObjectMetadataResult.code)
// .append(", msg =").append(getObjectMetadataResult.msg)
// .append(", ctime =").append(getObjectMetadataResult.mtime)
// .append(", mtime =").append( getObjectMetadataResult.ctime).append("\n")
// .append(", filesize =").append(getObjectMetadataResult.filesize)
// .append(", filesize =").append(getObjectMetadataResult.filesize)
// .append(", access_url =").append(getObjectMetadataResult.access_url == null?"null":getObjectMetadataResult.access_url)
// .append(", sha =").append(getObjectMetadataResult.sha == null?"null":getObjectMetadataResult.sha)
// .append(", authority =").append(getObjectMetadataResult.authority == null?"null":getObjectMetadataResult.authority)
// .append(", biz_attr =").append(getObjectMetadataResult.biz_attr == null?"null":getObjectMetadataResult.biz_attr);
// String result = stringBuilder.toString();
// Log.w(QServer.TAG,result);
// }
//
// @Override
// public void onFailed(COSRequest cosRequest, COSResult cosResult) {
// String result = "查询出错: ret =" + cosResult.code + "; msg =" + cosResult.msg
// + "; requestId =" + cosResult.requestId;
// Log.w(QServer.TAG,result);
// }
// });
// /** 发送请求:执行 */
// qServer.cosClient.getObjectMetadata(getObjectMetadataRequest);
}
}
| 46.953125 | 144 | 0.599002 |
a6a6d9a4a5727e9e15114d30db4a7e572d98c6e4
| 302 |
package com.patrick.maaltijdapp.controller.callbacks;
/**
* Created by Patrick on 21/01/2018.
*/
/**
* Occurs after a token has expired or is invalid.
**/
public interface InvalidTokenCallback
{
/**
* Occurs after a token has expired or is invalid.
**/
void onTokenInvalid();
}
| 17.764706 | 54 | 0.668874 |
a436f4c66cd62f2dc1a3bc6b88d2e656e8af87c5
| 485 |
package softuni.artgallery.error;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;
import softuni.artgallery.constants.common.CommonConstants;
@ResponseStatus(code=HttpStatus.CONFLICT,reason = CommonConstants.INVALID_INPUT)
public class UserRegistrationException extends RuntimeException {
public UserRegistrationException() {
}
public UserRegistrationException(String message) {
super(message);
}
}
| 30.3125 | 80 | 0.806186 |
3b9a483d92940220803e709027db79aa6e278dae
| 1,363 |
/*
* $Id$
*
* SARL is an general-purpose agent programming language.
* More details on http://www.sarl.io
*
* Copyright (C) 2014-2021 the original authors 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 io.sarl.tests.api.extensions;
import org.apache.log4j.Level;
import org.junit.jupiter.api.extension.BeforeEachCallback;
import org.junit.jupiter.api.extension.ExtensionContext;
import io.sarl.tests.api.tools.TestUtils;
/** JUnit 5 extension that for reseting the context of a test.
*
* @author $Author: sgalland$
* @version $FullVersion$
* @mavengroupid $GroupId$
* @mavenartifactid $ArtifactId$
* @since 0.11
*/
public class ContextInitExtension implements BeforeEachCallback {
@Override
public void beforeEach(ExtensionContext context) throws Exception {
TestUtils.setGlobalLogLevel(Level.WARN);
}
}
| 30.288889 | 75 | 0.749817 |
6405c5f42bf2f117de46538683508ab0d4cfa046
| 8,359 |
package com.rw.calcx;
import javafx.animation.PauseTransition;
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Insets;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.image.Image;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
import javafx.util.Duration;
public class CalcX extends Application {
static final String ERROR = "Error";
static final char DECIMAL_SEPARATOR = '.';
static final char SUBTRACTION_OPERATOR = '\u2013';
static final char ADDITION_OPERATOR = '+';
static final char MULTIPLICATION_OPERATOR = '*';
static final char DIVISION_OPERATOR = '/';
static final char POWER_OPERATOR = '^';
static final char DEL = '\u232B';
private static final int MARGIN_SPACE = 5;
private static final int SPACING = 5;
private static final int BUTTON_SIZE = 32;
private static final double WIDTH = (long) ((5.0 * (BUTTON_SIZE + SPACING)) + (2.0 * MARGIN_SPACE));
private static final double HEIGHT = (long) ((6.0 * (BUTTON_SIZE + SPACING)) + (MARGIN_SPACE / 2.0));
private ExpressionTextField inputField;
private boolean resultant;
private Button[] buttonNumbers;
private Button buttonDecimalPoint;
private Button buttonAdd, buttonSubtract, buttonMultiply, buttonDivide;
private Button buttonDelete, buttonPower;
private Button buttonRightBracket, buttonLeftBracket;
private Button buttonEqual;
public CalcX() {
}
public static void main(String[] args) {
Application.launch(args);
}
@Override
public void start(Stage primaryStage) throws Exception {
primaryStage.setTitle("Calculator CalcX");
primaryStage.getIcons().add(new Image(CalcX.class.getResourceAsStream("/calcx.png")));
primaryStage.setWidth(WIDTH);
primaryStage.setHeight(HEIGHT);
VBox container = new VBox(SPACING);
container.setPadding(new Insets(MARGIN_SPACE));
initControls();
GridPane buttonsGridPane = new GridPane();
buttonsGridPane.setVgap(SPACING);
buttonsGridPane.setHgap(SPACING);
buttonsGridPane.add(buttonNumbers[7], 0, 0);
buttonsGridPane.add(buttonNumbers[8], 1, 0);
buttonsGridPane.add(buttonNumbers[9], 2, 0);
buttonsGridPane.add(buttonNumbers[4], 0, 1);
buttonsGridPane.add(buttonNumbers[5], 1, 1);
buttonsGridPane.add(buttonNumbers[6], 2, 1);
buttonsGridPane.add(buttonNumbers[1], 0, 2);
buttonsGridPane.add(buttonNumbers[2], 1, 2);
buttonsGridPane.add(buttonNumbers[3], 2, 2);
buttonsGridPane.add(buttonNumbers[0], 1, 3);
buttonsGridPane.add(buttonDecimalPoint, 0, 3);
buttonsGridPane.add(buttonEqual, 2, 3);
buttonsGridPane.add(buttonAdd, 3, 0);
buttonsGridPane.add(buttonSubtract, 3, 1);
buttonsGridPane.add(buttonMultiply, 3, 2);
buttonsGridPane.add(buttonDivide, 3, 3);
buttonsGridPane.add(buttonDelete, 4, 0);
buttonsGridPane.add(buttonPower, 4, 1);
buttonsGridPane.add(buttonRightBracket, 4, 2);
buttonsGridPane.add(buttonLeftBracket, 4, 3);
ButtonActionListener buttonActionListener = new ButtonActionListener();
for (Node node : buttonsGridPane.getChildren()) {
if (node instanceof Button) {
Button button = (Button) node;
setButtonPrefSize(button);
button.setOnAction(buttonActionListener);
}
}
initControlsFunctionality();
container.getChildren().add(inputField);
container.getChildren().add(buttonsGridPane);
Scene primaryScene = new Scene(container);
primaryStage.setScene(primaryScene);
primaryStage.setResizable(false);
primaryStage.show();
}
public ExpressionTextField getInputField() {
return inputField;
}
String evaluate() {
String data;
try {
double result = ExpressionParserEvaluator.evaluate(inputField.getValidExpression());
if ((result % 1) != 0) {
data = String.format("%.4f", result);
for (int i = data.length() - 1; i >= 0; i--) { // trim ending zeros
if (data.charAt(i) == '0') {
data = data.substring(0, i);
} else {
break;
}
}
} else {
data = String.format("%.0f", result);
}
} catch (Exception ex) {
data = ERROR;
}
resultant = true;
return data;
}
void handleEquals() {
inputField.setText(evaluate());
}
void handleBackspace() {
String text = inputField.getText();
if (!text.isEmpty()) {
if (ERROR.equals(text)) {
inputField.setText("");
} else {
text = text.substring(0, text.length() - 1);
inputField.setText(text);
}
}
}
private static void setButtonPrefSize(Button button) {
button.setPrefSize(BUTTON_SIZE, BUTTON_SIZE);
}
private static void addClickAndHoldHandler(Node node, Duration holdTime, EventHandler<MouseEvent> handler) {
MutableWrapper<MouseEvent> eventWrapper = new MutableWrapper<>();
PauseTransition holdTimer = new PauseTransition(holdTime);
holdTimer.setOnFinished(event -> handler.handle(eventWrapper.content));
node.addEventHandler(MouseEvent.MOUSE_PRESSED, event -> {
eventWrapper.content = event;
holdTimer.playFromStart();
});
node.addEventHandler(MouseEvent.MOUSE_RELEASED, event -> holdTimer.stop());
node.addEventHandler(MouseEvent.DRAG_DETECTED, event -> holdTimer.stop());
}
private void initControls() {
inputField = new ExpressionTextField(CalcX.this);
inputField.setPrefHeight(BUTTON_SIZE);
buttonNumbers = new Button[10];
for (int i = 0; i < buttonNumbers.length; i++) {
buttonNumbers[i] = new Button(i + "");
}
buttonAdd = new Button(String.valueOf(ADDITION_OPERATOR));
buttonSubtract = new Button(String.valueOf(SUBTRACTION_OPERATOR));
buttonMultiply = new Button(String.valueOf(MULTIPLICATION_OPERATOR));
buttonDivide = new Button(String.valueOf(DIVISION_OPERATOR));
buttonPower = new Button(String.valueOf(POWER_OPERATOR));
buttonDelete = new Button(String.valueOf(DEL));
buttonDecimalPoint = new Button(String.valueOf(DECIMAL_SEPARATOR));
buttonRightBracket = new Button("(");
buttonLeftBracket = new Button(")");
buttonEqual = new Button("=");
}
private void initControlsFunctionality() {
addClickAndHoldHandler(buttonDelete, Duration.seconds(1), event -> inputField.setText(""));
inputField.addEventHandler(KeyEvent.KEY_TYPED, event -> {
if ("=".equals(event.getCharacter())) {
handleEquals();
event.consume(); // don't type it
}
});
inputField.addEventHandler(KeyEvent.KEY_PRESSED, event -> {
if (KeyCode.BACK_SPACE == event.getCode()) {
handleBackspace();
}
});
}
private static class MutableWrapper<T> {
public T content;
}
private class ButtonActionListener implements EventHandler<ActionEvent> {
@Override
public void handle(ActionEvent event) {
String data = ((Button) event.getSource()).getText();
if (resultant) {
inputField.setText("");
resultant = false;
}
if (DEL == data.charAt(0)) {
handleBackspace();
} else if ("=".equals(data)) {
handleEquals();
} else {
showInput(data.charAt(0));
}
}
private void showInput(char input) {
inputField.appendText(CalcXUtils.getValidInput(input + ""));
}
}
}
| 36.986726 | 112 | 0.620409 |
bcd8fe116094b29c02e27d9cde7e7996ba8c3895
| 224 |
package ijaux.hypergeom;
/*
* This interface defines implementations of distances and metrics
*/
public interface MetricSpace<VectorType> {
double distance(VectorType a, VectorType b);
double norm(VectorType a);
}
| 17.230769 | 66 | 0.758929 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.