text
stringlengths 10
2.72M
|
|---|
class Math_{
private int a,b ;
Math_(int a,int b){
this.a = a ;
this.b = b ;
}
void Print(){
System.out.println("a -> "+a);
System.out.println("b -> "+b);
}
int sum(){
return a+b ;
}
int subtract(){
return a-b ;
}
int multiply(){
return a*b ;
}
int divide(){
return a/b ;
}
int allFor(){
int res = 0;
for (int i = (a<b?a:b)+1 ;i < (a<b?b:a) ;i++ )
res += i ;
return res ;
}
int allWhile(){
int res = 0;
int i = (a<b?a:b) +1 ;
while (i < (a<b?b:a))
res += i++ ;
return res ;
}
int conditionalOperation(){
if (a<b)
return a+b;
else if (a>b && b==0)
return a;
else if (a==b)
return a*b;
else
return a/b;
}
public static void main(String args[]){
Math_ obj = new Math_(4,5);
obj.Print();
System.out.println(obj.divide());
}
}
|
/**
* This is a generated file. DO NOT EDIT ANY CODE HERE, YOUR CHANGES WILL BE LOST.
*/
package br.com.senior.furb.basico;
import br.com.senior.messaging.ErrorPayload;
import br.com.senior.messaging.model.CommandDescription;
import br.com.senior.messaging.model.CommandKind;
import br.com.senior.messaging.model.MessageHandler;
import br.com.senior.furb.basico.ExportGameMapOutput;
/**
* Response method for exportGameMap
*/
@CommandDescription(name="exportGameMapResponse", kind=CommandKind.ResponseCommand, requestPrimitive="exportGameMapResponse")
public interface ExportGameMapResponse extends MessageHandler {
void exportGameMapResponse(ExportGameMapOutput response);
void exportGameMapResponseError(ErrorPayload error);
}
|
package com.c4wrd.loadtester.util;
import java.util.*;
import java.util.function.BiConsumer;
import java.util.function.BinaryOperator;
import java.util.function.Function;
import java.util.function.Supplier;
import java.util.stream.Collector;
/**
* A reservoir sample is an algorithm that takes a list N of n elements
* and selects k random elements from the list into list K, where each element in
* the list N has a 1/n chance of being in K.
* <p>
* This implementation allows the random choosing of elements from an indefinite
* stream of elements, forming an accurate (at the cost of Random not necessarily
* producing random integers).
*
* @param <T>
*/
public class ReservoirCollector<T> implements Collector<T, List<T>, List<T>> {
/**
* The desired number of elements to acquire randomly from the stream
*/
private final int k;
/**
* Random instance used to calculate our seed.
*/
private final Random rand;
/**
* Represents the current index in the stream, used for generating our seed.
*/
private int sIndex;
/**
* Initializes a Reservoir sampler
*
* @param numDesiredItems
*/
public ReservoirCollector(int numDesiredItems) {
this.k = numDesiredItems;
this.rand = new Random();
}
@Override
public Supplier<List<T>> supplier() {
return ArrayList::new;
}
/**
* Accumulates a list of random elements from a stream.
* We first add the first k elements, then proceeding
* we will create a seed based off of a random number
* % read items, which will in the end result in every
* element having a 1/n chance of being selected.
*/
@Override
public BiConsumer<List<T>, T> accumulator() {
return (final List<T> selected, T element) -> {
sIndex++; // increment our sIndex in the stream
if (selected.size() < k) {
// we want to add the first K elements to our array
selected.add(element);
} else {
// note, the sIndex will be off by 1 as
// we are using a zero-sIndex base
int seed = Math.abs(rand.nextInt() % (this.sIndex + 1));
if (seed < k) { // we have an item we can add
selected.set(seed, element);
}
}
};
}
/**
* @return Returns a function to merge two sets of lists
*/
@Override
public BinaryOperator<List<T>> combiner() {
return (left, right) -> {
return left.addAll(right) ? left : left;
};
}
/**
* The resulting stream will be unordered, so let's ensure that Java
* knows this...
*/
@Override
public Set<Characteristics> characteristics() {
return EnumSet.of(Collector.Characteristics.UNORDERED, Collector.Characteristics.IDENTITY_FINISH);
}
/**
* No other operations need to be performed on the stream,
* we can just return the stream.
*/
@Override
public Function<List<T>, List<T>> finisher() {
return (i) -> i;
}
}
|
/**
* <p>Title: </p>
*
* <p>Description: </p>
*
* <p>Copyright: Copyright (c) 2013</p>
*
* <p>Company: </p>
*
* @author billw
* @version 1.0.5
*/
package com.sowrdking.imgpuzzle;
/**
* @author billw
*
*/
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class GridViewFragement extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.gridview_fragement, container, false);
}
}
|
package com.lesports.albatross.utils;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
/**
* 时间工具类
* Created by jiangjianxiong on 16/6/6.
*/
public class DateUtil {
private static final String mDateTimeStringFormat = "yyyy-MM-dd HH:mm:ss";
private static final String mDateStringFormat = "yyyy-MM-dd";
public static final String mTimeStringFormat = "HH:mm:ss";
private static final String mTimeFormat = "HH:mm";
public static Date str2Date(String str) {
return str2Date(str, null);
}
private static Date str2Date(String str, String format) {
if (str == null || str.length() == 0) {
return null;
}
if (format == null || format.length() == 0) {
format = mDateTimeStringFormat;
}
Date date = null;
try {
SimpleDateFormat sdf = new SimpleDateFormat(format);
date = sdf.parse(str);
} catch (Exception e) {
e.printStackTrace();
}
return date;
}
/**
* 获取时间差
*/
public static String getDatePoor(String nowDate) {
String datePoor;
long nd = 1000 * 24 * 60 * 60;
long nh = 1000 * 60 * 60;
long nm = 1000 * 60;
long diff = new Date().getTime() - str2Date(nowDate, mDateTimeStringFormat).getTime();
long day = diff / nd;
long hour = diff % nd / nh;
long min = diff % nd % nh / nm;
if (day > 0) {
datePoor = nowDate.substring(0, nowDate.length() - 3);
} else if (hour > 0) {
datePoor = hour + "小时前";
} else if (min > 0) {
datePoor = min + "分钟前";
} else {
datePoor = "刚刚";
}
return datePoor;
}
/**
* 判断是否过期
*/
public static boolean isExpire(String nowDate) {
long diff = str2Date(nowDate, mDateTimeStringFormat).getTime() - new Date().getTime();
return diff <= 0;
}
//获取当天的时间
public static String getDayByString(String time) {
return new SimpleDateFormat(mDateStringFormat).format(str2Date(time, mDateTimeStringFormat).getTime());
}
//获取改日期的time
public static String getTimeByString(String time) {
return new SimpleDateFormat(mTimeFormat).format(str2Date(time, mDateTimeStringFormat).getTime());
}
//判断是否是今天
public static boolean isToday(String time) {
return isTheDay(str2Date(time, mDateTimeStringFormat), new Date());
}
/**
* 是否是指定日期
*
* @param date
* @param day
* @return
*/
private static boolean isTheDay(final Date date, final Date day) {
return date.getTime() >= dayBegin(day).getTime()
&& date.getTime() <= dayEnd(day).getTime();
}
/**
* 获取指定时间的那天 00:00:00.000 的时间
*
* @param date
* @return
*/
private static Date dayBegin(final Date date) {
Calendar c = Calendar.getInstance();
c.setTime(date);
c.set(Calendar.HOUR_OF_DAY, 0);
c.set(Calendar.MINUTE, 0);
c.set(Calendar.SECOND, 0);
c.set(Calendar.MILLISECOND, 0);
return c.getTime();
}
/**
* 获取指定时间的那天 23:59:59.999 的时间
*
* @param date
* @return
*/
private static Date dayEnd(final Date date) {
Calendar c = Calendar.getInstance();
c.setTime(date);
c.set(Calendar.HOUR_OF_DAY, 23);
c.set(Calendar.MINUTE, 59);
c.set(Calendar.SECOND, 59);
c.set(Calendar.MILLISECOND, 999);
return c.getTime();
}
/**
* 传入date,默认格式为 mDateTimeStringFormat
*
* @param date
* @return
*/
public static String date2Str(Date date) {
if (date == null)
return null;
String dataStr = "";
try {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(mDateTimeStringFormat);
dataStr = simpleDateFormat.format(date);
} catch (Exception e) {
}
return dataStr;
}
public static String date2Str(Date date, String format) {
if (date == null)
return null;
String dataStr = "";
try {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(format);
dataStr = simpleDateFormat.format(date);
} catch (Exception e) {
}
return dataStr;
}
}
|
package msip.go.kr.board.service;
import java.util.List;
import msip.go.kr.board.entity.BoardMaster;
import msip.go.kr.common.entity.Tree;
/**
* 게시판 속성 관련 업무 처리를 위한 Sevice Interface 정의
*
* @author 정승철
* @since 2015.07.10
* @see <pre>
* == 개정이력(Modification Information) ==
*
* 수정일 수정자 수정내용
* ---------------------------------------------------------------------------------
* 2015.07.10 정승철 최초생성
* 2015.07.31 양준호 findAll(boolean isUse) 추가
* </pre>
*/
public interface BoardMasterService {
/**
* 선택된 id에 따라 선택된 게시판 속성 정보를 데이터베이스에서 삭제하도록 요청
* @param CopMaster entity
* @throws Exception
*/
public void remove(BoardMaster entity) throws Exception;
/**
* 새로운 게시판 속성 정보를 입력받아 데이터베이스에 저장하도록 요청
* @param CopMaster entity
* @return Long
* @throws Exception
*/
public void persist(BoardMaster entity) throws Exception;
/**
* 게시판 속성 목록을 데이터베이스에서 읽어와 화면에 출력하도록 요청
* @return List<BoardMaster> 게시판 속성 목록
* @throws Exception
*/
public List<BoardMaster> findAll() throws Exception;
/**
* 사용여부에 따른 게시판 속성 목록을 데이터베이스에서 읽어와 화면에 출력하도록 요청
* @return List<BoardMaster> 게시판 속성 목록
* @throws Exception
*/
public List<BoardMaster> findAll(boolean isuse) throws Exception;
/**
* 수정된 게시판 속성 정보를 데이터베이스에 반영하도록 요청
* @param CopMaster entity
* @throws Exception
*/
public void merge(BoardMaster entity) throws Exception;
/**
* 선택된 id에 따라 데이터베이스에서 게시판 속성 정보를 읽어와 화면에 출력하도록 요청
* @param Long id
* @return BoardMaster entity
* @throws Exception
*/
public BoardMaster findById(Long id) throws Exception;
/**
* 게시판 속성 목록을 Tree 콤포넌트 용으로 조회하도록 요청
* @return List<Tree> 게시판 속성 Tree 목록
* @throws Exception
*/
public List<Tree> treeList() throws Exception;
}
|
package ir.sadeghzadeh.mozhdeh.fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import java.util.HashMap;
import java.util.Map;
import ir.sadeghzadeh.mozhdeh.ApplicationController;
import ir.sadeghzadeh.mozhdeh.Const;
import ir.sadeghzadeh.mozhdeh.R;
import ir.sadeghzadeh.mozhdeh.entity.AuthResponse;
import ir.sadeghzadeh.mozhdeh.utils.Util;
import ir.sadeghzadeh.mozhdeh.volley.GsonRequest;
/**
* Created by reza on 12/10/16.
*/
public class EnterPasswordFragment extends BaseFragment {
public static final String TAG = EnterPasswordFragment.class.getName();
EditText password;
Button next;
@Override
public View onCreateView(LayoutInflater layoutInflater, ViewGroup container, Bundle savedInstanceState) {
setHasOptionsMenu(true);
View view = layoutInflater.inflate(R.layout.enter_password_fragment, container, false);
initPassword(view);
initNext(view);
animate(view.findViewById(R.id.main_layout));
return view;
}
private void initNext(View view) {
next = (Button) view.findViewById(R.id.next);
next.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (password.getText().toString().trim().equals("")) {
password.setError(getString(R.string.invalid_password));
password.requestFocus();
return;
}
Map<String, String> params = new HashMap<>();
params.put(Const.PASSWORD, password.getText().toString());
params.put(Const.USERNAME, Util.fetchFromPreferences(Const.USERNAME));
params.put(Const.FIREBASE_TOKEN, Util.fetchFromPreferences(Const.FIREBASE_TOKEN));
activity.showProgress();
GsonRequest<AuthResponse> request = new GsonRequest<AuthResponse>(Const.AUTH_USER_URL, AuthResponse.class, params, null, new Response.Listener<AuthResponse>() {
@Override
public void onResponse(AuthResponse response) {
if (response.Status == 1) {
Util.saveInPreferences(Const.TOKEN, response.Token);
activity.hideProgress();
NewFragment fragment = new NewFragment();
activity.addFragmentToContainer(fragment, NewFragment.TAG, true);
} else if (response.Status == 0) {
activity.hideProgress();
Toast.makeText(getContext(), getString(R.string.auth_failed), Toast.LENGTH_LONG).show();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
activity.hideProgress();
Toast.makeText(getContext(), getString(R.string.connection_error), Toast.LENGTH_LONG).show();
}
});
ApplicationController.getInstance().addToRequestQueue(request);
}
});
}
private void initPassword(View view) {
password = (EditText) view.findViewById(R.id.password);
}
}
|
package com.esum.framework.security.cms.sign;
import java.io.IOException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.PrivateKey;
import java.security.cert.CertificateEncodingException;
import java.security.cert.CertificateExpiredException;
import java.security.cert.CertificateNotYetValidException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.bouncycastle.cert.jcajce.JcaCertStore;
import org.bouncycastle.cms.CMSException;
import org.bouncycastle.cms.CMSProcessable;
import org.bouncycastle.cms.CMSProcessableByteArray;
import org.bouncycastle.cms.CMSSignedData;
import org.bouncycastle.cms.CMSSignedDataGenerator;
import org.bouncycastle.cms.CMSTypedData;
import org.bouncycastle.cms.SignerInformation;
import org.bouncycastle.cms.SignerInformationStore;
import org.bouncycastle.cms.jcajce.JcaSignerInfoGeneratorBuilder;
import org.bouncycastle.cms.jcajce.JcaSimpleSignerInfoVerifierBuilder;
import org.bouncycastle.operator.ContentSigner;
import org.bouncycastle.operator.OperatorCreationException;
import org.bouncycastle.operator.jcajce.JcaContentSignerBuilder;
import org.bouncycastle.operator.jcajce.JcaDigestCalculatorProviderBuilder;
import org.bouncycastle.util.Store;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.esum.framework.security.cms.CMSConstants;
public class CMSSignerWithBC extends CMSSigner {
private Logger logger = LoggerFactory.getLogger(CMSSignerWithBC.class);
public byte[] sign(byte[] data, X509Certificate cert,
PrivateKey key, String digest) throws NoSuchAlgorithmException, NoSuchProviderException,
CMSException, IOException, CMSSignException {
String signAlgorithm = null;
if (digest.equals(CMSConstants.DIGEST_MD5)) {
signAlgorithm = CMSSignedDataGenerator.DIGEST_MD5;
} else if (digest.equals(CMSConstants.DIGEST_SHA1)) {
signAlgorithm = CMSSignedDataGenerator.DIGEST_SHA1;
} else if (digest.equals(CMSConstants.DIGEST_SHA256)) {
signAlgorithm = CMSSignedDataGenerator.DIGEST_SHA256;
} else if (digest.equals(CMSConstants.DIGEST_SHA512)) {
signAlgorithm = CMSSignedDataGenerator.DIGEST_SHA512;
} else {
throw new CMSSignException("sign()", digest+" not support.");
}
List certList = new ArrayList();
certList.add(cert);
Store certs = null;
try {
certs = new JcaCertStore(certList);
} catch (CertificateEncodingException e) {
logger.error(e.getMessage(), e);
throw new CMSSignException("sign()", e.getMessage());
}
// set up the generator
CMSSignedDataGenerator gen = new CMSSignedDataGenerator();
ContentSigner signer = null;
try {
signer = new JcaContentSignerBuilder(signAlgorithm).setProvider("BC").build(key);
} catch (OperatorCreationException e) {
logger.error(e.getMessage(), e);
throw new CMSSignException("sign()", e.getMessage());
}
try {
gen.addSignerInfoGenerator(new JcaSignerInfoGeneratorBuilder(
new JcaDigestCalculatorProviderBuilder().setProvider("BC").build()).build(
signer, cert));
gen.addCertificates(certs);
} catch (CertificateEncodingException e) {
logger.error(e.getMessage(), e);
throw new CMSSignException("sign()", e.getMessage());
} catch (OperatorCreationException e) {
logger.error(e.getMessage(), e);
throw new CMSSignException("sign()", e.getMessage());
}
// create the signed-data object
CMSTypedData msg = new CMSProcessableByteArray(data);
CMSSignedData signed = gen.generate(msg, false);
return signed.getEncoded();
}
public boolean verify(byte[] orgData, byte[] signedData,
X509Certificate cert) throws CertificateExpiredException, CertificateNotYetValidException,
NoSuchAlgorithmException, NoSuchProviderException, CMSException {
boolean verified = false;
CMSProcessable orgProcessable = new CMSProcessableByteArray(orgData);
CMSSignedData signedProcessable = new CMSSignedData(orgProcessable, signedData);
Store store = signedProcessable.getCertificates();
SignerInformationStore signers = signedProcessable.getSignerInfos();
Iterator iter = signers.getSigners().iterator();
if (iter.hasNext()) {
SignerInformation signer = (SignerInformation)iter.next();
try {
verified = signer.verify(new JcaSimpleSignerInfoVerifierBuilder().setProvider("BC").build(cert));
} catch (OperatorCreationException e) {
logger.error("CMS verify error", e);
}
}
return verified;
}
}
|
package by.orion.onlinertasks.data.datasource.profile.details.local;
import android.support.annotation.NonNull;
import com.pushtorefresh.storio.sqlite.StorIOSQLite;
import javax.inject.Inject;
import by.orion.onlinertasks.data.datasource.profile.details.ProfileDetailsDataSource;
import by.orion.onlinertasks.data.models.common.requests.ProfileDetailsRequestParams;
import by.orion.onlinertasks.data.models.profile.details.Profile;
import io.reactivex.Completable;
import io.reactivex.Single;
public class LocalProfileDetailsDataSource implements ProfileDetailsDataSource {
@NonNull
private final StorIOSQLite storIOSQLite;
@Inject
public LocalProfileDetailsDataSource(@NonNull StorIOSQLite storIOSQLite) {
this.storIOSQLite = storIOSQLite;
}
@Override
public Single<Profile> getValue(@NonNull Integer key) {
throw new UnsupportedOperationException();
}
@Override
public Completable setValue(@NonNull Integer key, @NonNull Profile value) {
throw new UnsupportedOperationException();
}
@Override
public Single<Profile> getProfile(@NonNull ProfileDetailsRequestParams params) {
throw new UnsupportedOperationException();
}
}
|
/*
* Copyright (C) 2019 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License
*/
package com.android.class2greylist;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
/**
* Class which can parse either dex style signatures (e.g. Lfoo/bar/baz$bat;->foo()V) or javadoc
* links to class members (e.g. {@link #toString()} or {@link java.util.List#clear()}).
*/
public class ApiComponents {
private static final String PRIMITIVE_TYPES = "ZBCSIJFD";
private final PackageAndClassName mPackageAndClassName;
// The reference can be just to a class, in which case mMemberName should be empty.
private final String mMemberName;
// If the member being referenced is a field, this will always be empty.
private final String mMethodParameterTypes;
private ApiComponents(PackageAndClassName packageAndClassName, String memberName,
String methodParameterTypes) {
mPackageAndClassName = packageAndClassName;
mMemberName = memberName;
mMethodParameterTypes = methodParameterTypes;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder()
.append(mPackageAndClassName.packageName)
.append(".")
.append(mPackageAndClassName.className);
if (!mMemberName.isEmpty()) {
sb.append("#").append(mMemberName).append("(").append(mMethodParameterTypes).append(
")");
}
return sb.toString();
}
public PackageAndClassName getPackageAndClassName() {
return mPackageAndClassName;
}
public String getMemberName() {
return mMemberName;
}
public String getMethodParameterTypes() {
return mMethodParameterTypes;
}
/**
* Parse a JNI class descriptor. e.g. Lfoo/bar/Baz;
*
* @param sc Cursor over string assumed to contain a JNI class descriptor.
* @return The fully qualified class, in 'dot notation' (e.g. foo.bar.Baz for a class named Baz
* in the foo.bar package). The cursor will be placed after the semicolon.
*/
private static String parseJNIClassDescriptor(StringCursor sc)
throws SignatureSyntaxError, StringCursorOutOfBoundsException {
if (sc.peek() != 'L') {
throw new SignatureSyntaxError(
"Expected JNI class descriptor to start with L, but instead got " + sc.peek(),
sc);
}
// Consume the L.
sc.next();
int semiColonPos = sc.find(';');
if (semiColonPos == -1) {
throw new SignatureSyntaxError("Expected semicolon at the end of JNI class descriptor",
sc);
}
String jniClassDescriptor = sc.next(semiColonPos);
// Consume the semicolon.
sc.next();
return jniClassDescriptor.replace("/", ".");
}
/**
* Parse a primitive JNI type
*
* @param sc Cursor over a string assumed to contain a primitive JNI type.
* @return String containing parsed primitive JNI type.
*/
private static String parseJNIPrimitiveType(StringCursor sc)
throws SignatureSyntaxError, StringCursorOutOfBoundsException {
char c = sc.next();
switch (c) {
case 'Z':
return "boolean";
case 'B':
return "byte";
case 'C':
return "char";
case 'S':
return "short";
case 'I':
return "int";
case 'J':
return "long";
case 'F':
return "float";
case 'D':
return "double";
default:
throw new SignatureSyntaxError(c + " is not a primitive type!", sc);
}
}
/**
* Parse a JNI type; can be either a primitive or object type. Arrays are handled separately.
*
* @param sc Cursor over the string assumed to contain a JNI type.
* @return String containing parsed JNI type.
*/
private static String parseJniTypeWithoutArrayDimensions(StringCursor sc)
throws SignatureSyntaxError, StringCursorOutOfBoundsException {
char c = sc.peek();
if (PRIMITIVE_TYPES.indexOf(c) != -1) {
return parseJNIPrimitiveType(sc);
} else if (c == 'L') {
return parseJNIClassDescriptor(sc);
}
throw new SignatureSyntaxError("Illegal token " + c + " within signature", sc);
}
/**
* Parse a JNI type.
*
* This parameter can be an array, in which case it will be preceded by a number of open square
* brackets (corresponding to its dimensionality)
*
* @param sc Cursor over the string assumed to contain a JNI type.
* @return Same as {@link #parseJniTypeWithoutArrayDimensions}, but also handle arrays.
*/
private static String parseJniType(StringCursor sc)
throws SignatureSyntaxError, StringCursorOutOfBoundsException {
int arrayDimension = 0;
while (sc.peek() == '[') {
++arrayDimension;
sc.next();
}
StringBuilder sb = new StringBuilder();
sb.append(parseJniTypeWithoutArrayDimensions(sc));
for (int i = 0; i < arrayDimension; ++i) {
sb.append("[]");
}
return sb.toString();
}
/**
* Converts the parameters of method from JNI notation to Javadoc link notation. e.g.
* "(IILfoo/bar/Baz;)V" turns into "int, int, foo.bar.Baz". The parentheses and return type are
* discarded.
*
* @param sc Cursor over the string assumed to contain a JNI method parameters.
* @return Comma separated list of parameter types.
*/
private static String convertJNIMethodParametersToJavadoc(StringCursor sc)
throws SignatureSyntaxError, StringCursorOutOfBoundsException {
List<String> methodParameterTypes = new ArrayList<>();
if (sc.next() != '(') {
throw new IllegalArgumentException("Trying to parse method params of an invalid dex " +
"signature: " + sc.getOriginalString());
}
while (sc.peek() != ')') {
methodParameterTypes.add(parseJniType(sc));
}
return String.join(", ", methodParameterTypes);
}
/**
* Generate ApiComponents from a dex signature.
*
* This is used to extract the necessary context for an alternative API to try to infer missing
* information.
*
* @param signature Dex signature.
* @return ApiComponents instance with populated package, class name, and parameter types if
* applicable.
*/
public static ApiComponents fromDexSignature(String signature) throws SignatureSyntaxError {
StringCursor sc = new StringCursor(signature);
try {
String fullyQualifiedClass = parseJNIClassDescriptor(sc);
PackageAndClassName packageAndClassName =
PackageAndClassName.splitClassName(fullyQualifiedClass);
if (!sc.peek(2).equals("->")) {
throw new SignatureSyntaxError("Expected '->'", sc);
}
// Consume "->"
sc.next(2);
String memberName = "";
String methodParameterTypes = "";
int leftParenPos = sc.find('(');
if (leftParenPos != -1) {
memberName = sc.next(leftParenPos);
methodParameterTypes = convertJNIMethodParametersToJavadoc(sc);
} else {
int colonPos = sc.find(':');
if (colonPos == -1) {
throw new IllegalArgumentException("Expected : or -> beyond position "
+ sc.position() + " in " + signature);
} else {
memberName = sc.next(colonPos);
// Consume the ':'.
sc.next();
// Consume the type.
parseJniType(sc);
}
}
return new ApiComponents(packageAndClassName, memberName, methodParameterTypes);
} catch (StringCursorOutOfBoundsException e) {
throw new SignatureSyntaxError(
"Unexpectedly reached end of string while trying to parse signature ", sc);
}
}
/**
* Generate ApiComponents from a link tag.
*
* @param linkTag The contents of a link tag.
* @param contextSignature The signature of the private API that this is an alternative for.
* Used to infer unspecified components.
*/
public static ApiComponents fromLinkTag(String linkTag, String contextSignature)
throws JavadocLinkSyntaxError {
ApiComponents contextAlternative;
try {
contextAlternative = fromDexSignature(contextSignature);
} catch (SignatureSyntaxError e) {
throw new RuntimeException(
"Failed to parse the context signature for public alternative!");
}
StringCursor sc = new StringCursor(linkTag);
try {
String memberName = "";
String methodParameterTypes = "";
int tagPos = sc.find('#');
String fullyQualifiedClassName = sc.next(tagPos);
PackageAndClassName packageAndClassName =
PackageAndClassName.splitClassName(fullyQualifiedClassName);
if (packageAndClassName.packageName.isEmpty()) {
packageAndClassName.packageName = contextAlternative.getPackageAndClassName()
.packageName;
}
if (packageAndClassName.className.isEmpty()) {
packageAndClassName.className = contextAlternative.getPackageAndClassName()
.className;
}
if (tagPos == -1) {
// This suggested alternative is just a class. We can allow that.
return new ApiComponents(packageAndClassName, "", "");
} else {
// Consume the #.
sc.next();
}
int leftParenPos = sc.find('(');
memberName = sc.next(leftParenPos);
if (leftParenPos != -1) {
// Consume the '('.
sc.next();
int rightParenPos = sc.find(')');
if (rightParenPos == -1) {
throw new JavadocLinkSyntaxError(
"Linked method is missing a closing parenthesis", sc);
} else {
methodParameterTypes = sc.next(rightParenPos);
}
}
return new ApiComponents(packageAndClassName, memberName, methodParameterTypes);
} catch (StringCursorOutOfBoundsException e) {
throw new JavadocLinkSyntaxError(
"Unexpectedly reached end of string while trying to parse javadoc link", sc);
}
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof ApiComponents)) {
return false;
}
ApiComponents other = (ApiComponents) obj;
return mPackageAndClassName.equals(other.mPackageAndClassName) && mMemberName.equals(
other.mMemberName) && mMethodParameterTypes.equals(other.mMethodParameterTypes);
}
@Override
public int hashCode() {
return Objects.hash(mPackageAndClassName, mMemberName, mMethodParameterTypes);
}
/**
* Less restrictive comparator to use in case a link tag is missing a method's parameters.
* e.g. foo.bar.Baz#foo will be considered the same as foo.bar.Baz#foo(int, int) and
* foo.bar.Baz#foo(long, long). If the class only has one method with that name, then specifying
* its parameter types is optional within the link tag.
*/
public boolean equalsIgnoringParam(ApiComponents other) {
return mPackageAndClassName.equals(other.mPackageAndClassName) &&
mMemberName.equals(other.mMemberName);
}
}
|
package com.restapi.controller.Exercises;
import com.restapi.model.Emotions;
import com.restapi.model.Response;
import com.restapi.model.User;
import com.restapi.repository.EmotionsRepository;
import com.restapi.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.ArrayList;
import java.util.List;
@RestController
public class EmotionsController {
@Autowired
EmotionsRepository emoRepository;
@Autowired
UserRepository userRepository;
@PostMapping("get_emotions")
public ResponseEntity<Emotions> getEmotions(@RequestParam("username") String username) {
Emotions emo = emoRepository.findByAutor(username);
if (emo == null) {
return new ResponseEntity<Emotions>(HttpStatus.NO_CONTENT);
} else {
return new ResponseEntity<Emotions>(emo, HttpStatus.OK);
}
}
@PostMapping("get_family_emotions")
public ResponseEntity<List<Emotions>> getFamilyEmotions(@RequestParam("username") String username) {
List<Emotions> emoList = new ArrayList<>();
User user = userRepository.findByUsername(username);
if (user == null) {
return new ResponseEntity<List<Emotions>>(HttpStatus.NOT_FOUND);
} else {
if (user.getParentUsernames() == null || user.getParentUsernames().isEmpty()) {
return new ResponseEntity<>(HttpStatus.NO_CONTENT);
} else if (user.getParentUsernames() != null && !user.getParentUsernames().isEmpty()){
for (String usrname : user.getParentUsernames()) {
Emotions emo = emoRepository.findByAutor(usrname);
if (emo != null) {
emoList.add(emo);
}
}
if (emoList == null || emoList.isEmpty()) {
return new ResponseEntity<>(HttpStatus.NO_CONTENT);
} else if (emoList != null && !emoList.isEmpty()) {
return new ResponseEntity<List<Emotions>>(emoList, HttpStatus.OK);
}
}
}
return new ResponseEntity<>(HttpStatus.NO_CONTENT);
}
@PostMapping("save_emotions")
public ResponseEntity<Response> saveEmotions(@RequestParam("username") String username, @RequestParam("emotions") float[] emotions) {
Emotions emo = emoRepository.findByAutor(username);
if (emo == null) {
emoRepository.save(new Emotions(username, emotions));
Response response = new Response("Neuer IST Zustand wurde erzeugt", 201);
return new ResponseEntity<Response>(response, HttpStatus.CREATED);
} else {
emo.setEmotions(emotions);
emoRepository.save(emo);
Response response = new Response("IST Zustand wurde aktualisiert", 200);
return new ResponseEntity<Response>(response, HttpStatus.OK);
}
}
}
|
package peter8icestone.concurrency.chapter4;
public class DaemonThread2 {
public static void main(String[] args) {
Thread t = new Thread(() -> {
Thread innerThread = new Thread(() -> {
try {
while (true) {
System.out.println("do something for health check.");
Thread.sleep(500L);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}, "innerThread");
innerThread.setDaemon(true);
innerThread.start();
try {
Thread.sleep(1_000L);
System.out.println(Thread.currentThread().getName() + " finish done");
} catch (InterruptedException e) {
e.printStackTrace();
}
}, "t");
t.start();
}
}
|
//Figure 2-26 Producer Consumer problem using Semaphores
import Semaphore;
import Item;
import java.util.Vector;
class ProducerConsumer extends Thread {
// Shared by all members in the class
// Number of slots in the buffer
private static final int N = 100;
// Controls access to the critical region
private static Semaphore mutex = new Semaphore(1);
// Counts empty buffer slots
private static Semaphore empty = new Semaphore(N);
// Counts the full buffer slots
private static Semaphore full = new Semaphore(0);
// The shared buffer
private static Vector theData = new Vector();
// Inner classes for the Producer and Consumer
class Producer extends Thread {
public void run() {
while(true) {
Item data = produce_item(); // Generate something to put in
// the buffer
empty.down(); // Decrement empty count
mutex.down(); // Enter critical region
insert_item(data); // Put new item in the buffer
mutex.up(); // Leave critical region
full.up(); // Increment the count of full
// slots
}
}
// Sleep a bit then make an item
private Item produce_item(){
Item data;
try{sleep(1000);}
catch(InterruptedException ex){};
data = new Item(0,itemCount++);
System.out.println("Producer making item " + data);
return data;
}
// Put data at the end of the vector
private void insert_item(Item data){
theData.add(data);
}
// Count of Items created
private int itemCount = 0;
}
public class Consumer extends Thread {
public void run() {
while(true) {
full.down(); // Decrement the full count
mutex.down(); // Enter critical region
Item data = remove_item(); // Take item from the buffer
mutex.up(); // Leave critical region
empty.up(); // Increment count of empty
// slots
consume_item(data); // Do something with the item
}
}
// Print something out and then sleep a bit
private void consume_item(Item data){
System.out.println("Consumer used item " + data);
try{sleep(7000);}
catch(InterruptedException ex){};
}
// Get the first element from the vector
private Item remove_item(){
Item data = (Item) theData.firstElement();
theData.removeElementAt(0);
return data;
}
}
// What the ProducerConsumer Thread does
public void run(){
Producer p;
Consumer c;
// Make and start the producer
p = new Producer();
p.start();
// Make and start the consumer
c = new Consumer();
c.start();
}
// Start the whole thing going
public static void main(String args[]) {
ProducerConsumer pc = new ProducerConsumer();
pc.start();
}
}
|
/*
* Copyright 2002-2023 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.aop.config;
import org.springframework.beans.factory.parsing.ParseState;
import org.springframework.util.StringUtils;
/**
* {@link ParseState} entry representing an aspect.
*
* @author Mark Fisher
* @author Juergen Hoeller
* @since 2.0
*/
public class AspectEntry implements ParseState.Entry {
private final String id;
private final String ref;
/**
* Create a new {@code AspectEntry} instance.
* @param id the id of the aspect element
* @param ref the bean name referenced by this aspect element
*/
public AspectEntry(String id, String ref) {
this.id = id;
this.ref = ref;
}
@Override
public String toString() {
return "Aspect: " + (StringUtils.hasLength(this.id) ? "id='" + this.id + "'"
: "ref='" + this.ref + "'");
}
}
|
package vehicleParts;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.physics.box2d.Body;
import com.badlogic.gdx.physics.box2d.BodyDef;
import com.badlogic.gdx.physics.box2d.Fixture;
import com.badlogic.gdx.physics.box2d.FixtureDef;
import com.badlogic.gdx.physics.box2d.PolygonShape;
import com.badlogic.gdx.physics.box2d.World;
import com.badlogic.gdx.physics.box2d.joints.RevoluteJointDef;
public class BasicCar{
//This class will contain and construct all the requisites of a car, i.e Engine+tires
//TODO add input logging and replaying, probably add a new controller.
//TODO add an engine class maybe so that power comes on and off progressively.
//TODO change the way hitboxes are created for different sized cars
protected float width=2;
protected float length=4.5f;
protected Texture sprite;
//Sprite attached to image
protected Tire[] tires=new Tire[4];
//Array of tires, change this to choose what type of tires you want
protected Vector2[] tirePositions=new Vector2[4];
//Array of tirePositions
protected int maxTurnAngle=40;
//sets maximum lock to lock angle, by defaultits 40;
protected int currentTurn;
protected float driveForce;
protected float maxSpeed;
protected float maxGrip;
public boolean forward;
public boolean backward;
public boolean left;
public boolean right;
protected Body chassis;
RevoluteJointDef[] jointArray=new RevoluteJointDef[4];
//Using this body, things will be attached to it
public BasicCar (World world, Vector2 location){
BodyDef def= new BodyDef();
def.type=BodyDef.BodyType.DynamicBody;
def.position.set(location);
setSize();
PolygonShape shape=new PolygonShape();
shape.setAsBox(width,length);
//probably in future use stored length and width
this.chassis=world.createBody(def);
chassis.setUserData("car");
FixtureDef fixtureDef= new FixtureDef();
fixtureDef.shape=shape;
fixtureDef.density=1f;
Fixture fixture=chassis.createFixture(fixtureDef);
shape.dispose();
//Rectangle for body has now been constructed
setPositions();
fitTires(world);
for (int i=0;i<4;i++){
jointArray[i]=new RevoluteJointDef();
jointArray[i].bodyA=chassis;
jointArray[i].bodyB=tires[i].getTire();
jointArray[i].collideConnected=false;
jointArray[i].enableLimit=true;
if (tires[i].checkSteered()){
jointArray[i].lowerAngle=-maxTurnAngle;
jointArray[i].upperAngle=maxTurnAngle;
}else{
jointArray[i].lowerAngle=0;
jointArray[i].upperAngle=0;
}
//Bottom will be done dependent on state
jointArray[i].localAnchorA.set(tirePositions[i]); //define where onto the chassis it connects
world.createJoint(jointArray[i]);
}
}
public void fitTires(World world){
//OverRide based on drive configuration
for(int i=0;i<2;i++){
tires[i]=new Tire(world, tirePositions[i], true, false, this); //powered but not steered
tires[i].setDriveForce(1000f);
tires[i].setMaxSpeed(40f);
}
for (int i=2;i<4;i++){
tires[i]=new Tire(world, tirePositions[i], false, true, this); //steered but not powered
tires[i].setDriveForce(200f);
tires[i].setMaxSpeed(40f);
}
}
public void setPositions(){
//Override based on new tirePositions
//sets the positions of the tires
//change locations to be relative to the chassis
tirePositions[0]=new Vector2(2f,-3f);// Rear
tirePositions[1]=new Vector2(-2f,-3f);
tirePositions[2]=new Vector2(2f,3f); //Fronts
tirePositions[3]=new Vector2(-2f,3f);
}
public void update(){
for (int i=0;i<4;i++){
tires[i].forward=this.forward;
tires[i].backward=this.backward;
tires[i].update();
}
steer();
}
public void steer(){
float angle=(float) Math.toDegrees(chassis.getAngle());
//Angle in which the chassis is facing
for (int i=0;i<4;i++){
if(tires[i].checkSteered()){
if(left||right){
if (currentTurn<maxTurnAngle){
currentTurn+=5;
//increment by 5 degrees per tick, smooths out steering
}
//maybe have to add a bit of power if speedmatch to get rid of horrendous understeer;
}
if (left){
tires[i].SetAngle(angle+currentTurn);
}else if(right){
tires[i].SetAngle(angle-currentTurn);
}else{
currentTurn=0;
tires[i].SetAngle(angle);
}
}
}
}
public void drift(){
for (int i=0;i<2;i++){
//Slideable backs
tires[i].drifting=true;
}
//TODO takes the two rear tires and lowers max load creating for mean slides;
}
public void unDrift(){
for (int i=0;i<2;i++){
//Slideable backs
tires[i].drifting=false;
}
}
public void SetAngle(float angle){
//sets angle of tire, used for steering
//input is in degrees
this.chassis.setTransform(chassis.getWorldCenter(), (float) Math.toRadians(angle));
}
private Vector2 getDirection(){
Vector2 direction=new Vector2(0,1);
return direction.rotate((float)Math.toDegrees(this.chassis.getAngle()));
}
public Vector2 getForwardVelocity(){
//used here to get forward motion of the car, used in speedometer and tire speed limits
Vector2 forwardDirection=getDirection();
Vector2 linVelocity=chassis.getLinearVelocity();
Vector2 forwardVelocity=forwardDirection.scl(linVelocity.dot(forwardDirection)/forwardDirection.dot(forwardDirection));
return forwardVelocity;
}
public Body getChassis(){
return chassis;
}
public float getWidth(){
return width;
}
public float getLength(){
return length;
}
public Tire returnTire(int i){
if (tires[i]!=null){
return tires[i];
}
return null;
}
public Texture getCarImage(){
return sprite;
}
public void setDriveForce(){
//templates that will be changed to set properties
}
public void setMaxSpeed(){
//templates that will be changed to set properties
}
public void setMaxGrip(){
//override to set the grip of each tire.
}
public void setSize(){
//override to set the dimensions of each car.
}
}
|
package by.htp.student03.main;
import java.util.List;
/*3. Создайте класс с именем Student, содержащий поля: фамилия и инициалы, номер группы, успеваемость (массив из
пяти элементов). Создайте массив из десяти элементов такого типа. Добавьте возможность вывода фамилий и
номеров групп студентов, имеющих оценки, равные только 9 или 10.*/
public class Main {
public static void main(String[] args) {
GroupLogic grLogic = new GroupLogic();
Group group = new Group(10);
group.add(new Student("Verner", "Y.N", 214, new int[] { 8, 6, 7, 3, 9 }));
group.add(new Student("Starostin", "V.G", 214, new int[] { 6, 6, 7, 5, 9 }));
group.add(new Student("Podobed", "O.S", 214, new int[] { 3, 2, 4, 7, 6 }));
group.add(new Student("Varlamov", "M.D", 214, new int[] { 9, 10, 9, 10, 9 }));
group.add(new Student("Aksenov", "D.F", 214, new int[] { 7, 6, 7, 5, 9 }));
group.add(new Student("Panasenko", "N.K", 214, new int[] { 10, 9, 9, 10, 9 }));
group.add(new Student("Korzh", "M.A", 214, new int[] { 6, 6, 7, 6, 8 }));
group.add(new Student("White", "N.H", 214, new int[] { 9, 6, 6, 6, 8 }));
group.add(new Student("Garbuzova", "V.D", 214, new int[] { 2, 2, 9, 9, 9 }));
group.add(new Student("Tereshkova", "V.N", 214, new int[] { 7, 6, 7, 5, 9 }));
List<Student> aLevelStudents;
aLevelStudents = grLogic.takeALevelStudents(group);
printAStudent(aLevelStudents);
}
public static void printAStudent(List<Student> aLevelStudents) {
for (Student st : aLevelStudents) {
System.out.println("_________________");
System.out.println(st.getSurname() + " " + st.getInitials() + " ");
for (int i = 0; i < st.getMarks().length; i++) {
System.out.print(st.getMarks()[i] + " ");
}
System.out.println("");
}
}
}
|
package com.example.apprunner.User.menu2_profile_event.Adapter;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.example.apprunner.R;
import com.example.apprunner.ResultQuery;
import java.util.List;
public class ShowStatUserAdapter extends RecyclerView.Adapter<ShowStatUserAdapter.Holder> {
List<ResultQuery> profile_stat;
Context context;
public ShowStatUserAdapter(Context context,List<ResultQuery> profile_stat) {
this.context = context;
this.profile_stat = profile_stat;
}
@NonNull
@Override
public ShowStatUserAdapter.Holder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.recyclerview_show_stat,parent,false);
return new ShowStatUserAdapter.Holder(view);
}
@Override
public void onBindViewHolder(@NonNull ShowStatUserAdapter.Holder holder, int position) {
final ResultQuery stat = profile_stat.get(position);
holder.kg.setText(stat.getDistance());
holder.cal.setText(stat.getCal());
holder.pace.setText(stat.getPace());
}
@Override
public int getItemCount() {
return profile_stat.size();
}
public class Holder extends RecyclerView.ViewHolder {
TextView kg,cal,pace;
public Holder(@NonNull View itemView) {
super(itemView);
kg = (TextView)itemView.findViewById(R.id.kg);
cal = (TextView)itemView.findViewById(R.id.cal);
pace = (TextView)itemView.findViewById(R.id.pace);
}
}
}
|
package com.occasion.maroc.services.impl;
import java.util.ArrayList;
import java.util.List;
import org.modelmapper.ModelMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.data.web.SpringDataWebProperties.Pageable;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import com.occasion.maroc.entities.UserEntity;
import com.occasion.maroc.repositories.UserRepository;
import com.occasion.maroc.services.UserServices;
import com.occasion.maroc.shared.Utils;
import com.occasion.maroc.shared.dto.ProductDto;
import com.occasion.maroc.shared.dto.UserDto;
@Service
public class UserServiceImpl implements UserServices {
@Autowired
UserRepository userRepository;
@Autowired
Utils utils;
@Autowired
BCryptPasswordEncoder bCryptPasswordEncoder;
@Override
public UserDto createUser(UserDto userDto) {
UserEntity check = userRepository.findByEmail(userDto.getEmail());
if (check != null)
throw new RuntimeException("User Already Existe");
ModelMapper modelMapper = new ModelMapper();
UserEntity userEntity = modelMapper.map(userDto, UserEntity.class);
for (int i = 0; i < userDto.getProducts().size(); i++) {
ProductDto product = userDto.getProducts().get(i);
product.setUser(userDto);
product.setProductId(utils.generateStringId(10));
userDto.getProducts().set(i, product);
}
userEntity.setEncryptedPassword(bCryptPasswordEncoder.encode(userDto.getPassword()));
userEntity.setUserId(utils.generateStringId(10));
UserEntity newUser = userRepository.save(userEntity);
UserDto userCreer = modelMapper.map(newUser, UserDto.class);
return userCreer;
}
@Override
public UserDetails loadUserByUsername(String email) throws UsernameNotFoundException {
UserEntity userEntity = userRepository.findByEmail(email);
if (userEntity == null)
throw new UsernameNotFoundException(email);
return new org.springframework.security.core.userdetails.User(userEntity.getEmail(),
userEntity.getEncryptedPassword(), new ArrayList<>());
}
@Override
public UserDto getUser(String email) {
UserEntity userEntity = userRepository.findByEmail(email);
if (userEntity == null)
throw new UsernameNotFoundException(email);
UserDto userDto = new UserDto();
BeanUtils.copyProperties(userEntity, userDto);
return userDto;
}
@Override
public UserDto getUserByUserId(String id) {
UserEntity userEntity = userRepository.findByUserId(id);
if (userEntity == null) throw new UsernameNotFoundException(id);
UserDto userDto = new UserDto();
BeanUtils.copyProperties(userEntity, userDto);
return userDto;
}
@Override
public UserDto updtateUser(String id, UserDto userDto) {
UserEntity userEntity = userRepository.findByUserId(id);
userEntity.setFirstName(userDto.getFirstName());
userEntity.setLastName(userDto.getLastName());
UserEntity userUpdated = userRepository.save(userEntity);
UserDto user = new UserDto();
BeanUtils.copyProperties(userUpdated, user);
return user;
}
@Override
public void deleteUser(String id) {
UserEntity userEntity = userRepository.findByUserId(id);
userRepository.delete(userEntity);
}
@Override
public List<UserDto> getUsers(int page, int limit) {
List<UserDto> usersDto = new ArrayList<>();
org.springframework.data.domain.Pageable pageblerequest = PageRequest.of(page, limit);
Page<UserEntity> userPage = userRepository.findAll(pageblerequest);
List<UserEntity> users = userPage.getContent();
for (UserEntity userEntity : users) {
UserDto user = new UserDto();
BeanUtils.copyProperties(userEntity, user);
usersDto.add(user);
}
return usersDto;
}
}
|
package com.lenovohit.ssm.payment.manager;
public abstract class PosPayManager implements PayBaseManager{
}
|
package io.ceph.rgw.client.core.bucket;
import io.ceph.rgw.client.model.GetBucketResponse;
import org.junit.Assert;
import org.junit.Test;
import org.junit.experimental.categories.Category;
/**
* @author zhuangshuo
* Created by zhuangshuo on 2020/7/9.
*/
@Category(BucketTests.class)
public class GetBucketTest extends BaseBucketClientTest {
@Test
public void testSync() {
logResponse(bucketClient.prepareGetBucket().withBucketName(bucket).run());
}
@Test
public void testCallback() throws InterruptedException {
Latch latch = newLatch();
bucketClient.prepareGetBucket().withBucketName(bucket).execute(newActionListener(latch));
latch.await();
}
@Test
public void testAsync() {
logResponse(bucketClient.prepareGetBucket().withBucketName(bucket).execute());
}
@Test
public void testNotExists() {
GetBucketResponse response = logResponse(bucketClient.prepareGetBucket().withBucketName("notexists").run());
Assert.assertFalse(response.isExist());
}
}
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package arraylists;
import java.util.ArrayList;
import java.util.Scanner;
/**
*
* @author DylanTadros
*/
public class Arraylists {
public static void display(ArrayList<Integer> n) {
for (int i = 0; i < n.size(); i = i + 1) {
System.out.println(n.get(i));
}
}
public static int find(ArrayList<Integer> n, int v) {
for (int i = 0; i < n.size(); i = i + 1) {
if (n.get(i) == v) {
return 1;
}
}
return -1;
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
Scanner kb = new Scanner(System.in);
System.out.println("enter a command");
String cmd = kb.next();
ArrayList<Integer> numbers = new ArrayList<Integer>();
while (!cmd.equals("q")) {
if (cmd.equals("a")) {
System.out.println("Enter a number");
int value = kb.nextInt();
numbers.add(value);
} else if (cmd.equals("f")) {
System.out.println("Enter a number");
int value = kb.nextInt();
int foundAt = find(numbers, value);
if (foundAt >= 0) {
System.out.println(value + " is fount at postions " + foundAt);
} else {
System.out.println(value + " is not found");
}
} else if (cmd.equals("r")) {
System.out.println("cmd=" + cmd);
} else if (cmd.equals("d")) {
display(numbers);
} else if (cmd.equals("s")) {
System.out.println("cmd=" + cmd);
} else {
System.out.println("cmd is not defined");
}
System.out.println("enter next command");
cmd = kb.next();
}
System.out.println("exit");
System.exit(0);
}
}
|
package by.client.android.railwayapp.ui.page.news;
import java.util.List;
import java.util.concurrent.Callable;
import by.client.android.railwayapp.support.BaseRxObserverListener;
import by.client.android.railwayapp.support.rss.Article;
import by.client.android.railwayapp.ui.mvp.Presenter;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
/**
* Presenter for the news page
*
* @author RPA
*/
public class NewsPresenter extends Presenter implements NewsContract.Presenter {
private final NewsContract.View view;
NewsPresenter(NewsContract.View view) {
this.view = view;
view.setPresenter(this);
super.onViewAttached();
}
@Override
public void load() {
Observable.fromCallable(new NewsLoaderCallable())
.compose(this.<List<Article>>applyBinding())
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new NewsLoaderListener(this));
}
@Override
public void onViewDetached() {
super.onViewDetached();
}
private class NewsLoaderCallable implements Callable<List<Article>> {
@Override
public List<Article> call() {
return new NewsLoader().load();
}
}
private static class NewsLoaderListener extends BaseRxObserverListener<NewsPresenter, List<Article>> {
NewsLoaderListener(NewsPresenter newsPresenter) {
super(newsPresenter);
}
@Override
protected void onStart(NewsPresenter newsPresenter) {
newsPresenter.view.setProgressIndicator(true);
}
@Override
protected void onSuccess(NewsPresenter newsPresenter, List<Article> articles) {
newsPresenter.view.loadNews(articles);
}
@Override
protected void onError(NewsPresenter newsPresenter, Exception exception) {
newsPresenter.view.loadingError(exception);
}
@Override
protected void onFinish(NewsPresenter newsPresenter) {
newsPresenter.view.setProgressIndicator(false);
}
}
}
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package view;
import controller.ControllerTransitions;
import java.util.ArrayList;
import java.util.List;
import javax.swing.DefaultComboBoxModel;
import javax.swing.DefaultListModel;
import javax.swing.JOptionPane;
import models.State;
/**
*
* @author gabriel
*/
public class Home extends javax.swing.JFrame {
private List<State> states;
private List<String> alphabet;
private DefaultListModel<String> listModelState;
private DefaultListModel<String> listModelAlphabet;
private DefaultComboBoxModel<String> cbModelStateInitial;
private DefaultComboBoxModel<String> cbModelAlphabet;
private DefaultComboBoxModel<String> cbModelStateCurrent;
private DefaultComboBoxModel<String> cbModelStateNext;
private ControllerTransitions controllerT;
private DefaultListModel<String> listModelFinalsStates;
/**
* Creates new form Home
*/
public Home() {
states = new ArrayList<>();
alphabet = new ArrayList<>();
listModelAlphabet = new DefaultListModel<>();
listModelState = new DefaultListModel<>();
cbModelStateInitial = new DefaultComboBoxModel<>();
cbModelAlphabet = new DefaultComboBoxModel<>();
cbModelStateCurrent = new DefaultComboBoxModel<>();
cbModelStateNext = new DefaultComboBoxModel<>();
listModelFinalsStates = new DefaultListModel<>();
controllerT = new ControllerTransitions();
initComponents();
jCBStartState3.setModel(cbModelStateInitial);
jListAlphabet3.setModel(listModelAlphabet);
jListState3.setModel(listModelState);
jCBiStateT3.setModel(cbModelStateCurrent);
jCBeStateT3.setModel(cbModelStateNext);
jCBAlphabetT3.setModel(cbModelAlphabet);
jListFinals1.setModel(listModelFinalsStates);
}
private void getStateStart(String s){
for(State state : states){
if(state.getName().equals(s)){
state.setStart(true);
}
}
}
private void transitionState(String pState,String nState, String symbol){
for(State s : states){
if(s.getName().equals(pState)){
for(State s2 : states){
if(s2.getName().equals(nState)){
s.getTransition().put(symbol, s2);
}
}
}
}
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jScrollPane8 = new javax.swing.JScrollPane();
jPanel8 = new javax.swing.JPanel();
jLabel20 = new javax.swing.JLabel();
jTextSymbol3 = new javax.swing.JTextField();
jButton14 = new javax.swing.JButton();
jButton15 = new javax.swing.JButton();
jScrollPane9 = new javax.swing.JScrollPane();
jListAlphabet3 = new javax.swing.JList<>();
jScrollPane10 = new javax.swing.JScrollPane();
jListState3 = new javax.swing.JList<>();
jCBStartState3 = new javax.swing.JComboBox<>();
jLabel21 = new javax.swing.JLabel();
jButton16 = new javax.swing.JButton();
jPanel9 = new javax.swing.JPanel();
jCBiStateT3 = new javax.swing.JComboBox<>();
jCBAlphabetT3 = new javax.swing.JComboBox<>();
jCBeStateT3 = new javax.swing.JComboBox<>();
jLabel22 = new javax.swing.JLabel();
jLabel23 = new javax.swing.JLabel();
jLabel24 = new javax.swing.JLabel();
jLabel25 = new javax.swing.JLabel();
jButton = new javax.swing.JButton();
jPanel10 = new javax.swing.JPanel();
jButton18 = new javax.swing.JButton();
jScrollPane11 = new javax.swing.JScrollPane();
jListFinals1 = new javax.swing.JList<>();
jLabel26 = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jLabel20.setText("Adicione um simbolo no alfabeto");
jButton14.setText("Adicionar");
jButton14.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton14jButton1ActionPerformed(evt);
}
});
jButton15.setText("Adicionar Estado");
jButton15.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton15jButton2ActionPerformed(evt);
}
});
jScrollPane9.setViewportView(jListAlphabet3);
jScrollPane10.setViewportView(jListState3);
jLabel21.setText("Estado Inicial");
jButton16.setText("Finalizar");
jButton16.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton16jButton3ActionPerformed(evt);
}
});
jPanel9.setBackground(new java.awt.Color(0, 153, 153));
jPanel9.setForeground(new java.awt.Color(204, 102, 255));
jLabel22.setText("Estado");
jLabel23.setText("Alfabeto");
jLabel24.setText("Estado");
jLabel25.setText("Transições");
jButton.setText("Adicionar");
jButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButtonjButton4ActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel9Layout = new javax.swing.GroupLayout(jPanel9);
jPanel9.setLayout(jPanel9Layout);
jPanel9Layout.setHorizontalGroup(
jPanel9Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel9Layout.createSequentialGroup()
.addGroup(jPanel9Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel9Layout.createSequentialGroup()
.addGap(29, 29, 29)
.addGroup(jPanel9Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jCBiStateT3, javax.swing.GroupLayout.PREFERRED_SIZE, 128, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel22))
.addGap(18, 18, 18)
.addGroup(jPanel9Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jCBAlphabetT3, javax.swing.GroupLayout.PREFERRED_SIZE, 125, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel23))
.addGap(18, 18, 18)
.addGroup(jPanel9Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel24)
.addComponent(jCBeStateT3, javax.swing.GroupLayout.PREFERRED_SIZE, 125, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGroup(jPanel9Layout.createSequentialGroup()
.addGap(198, 198, 198)
.addComponent(jLabel25)))
.addContainerGap(24, Short.MAX_VALUE))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel9Layout.createSequentialGroup()
.addGap(0, 0, Short.MAX_VALUE)
.addComponent(jButton)
.addGap(184, 184, 184))
);
jPanel9Layout.setVerticalGroup(
jPanel9Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel9Layout.createSequentialGroup()
.addGap(9, 9, 9)
.addComponent(jLabel25)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel9Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel24)
.addComponent(jLabel23)
.addComponent(jLabel22))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel9Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jCBiStateT3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jCBAlphabetT3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jCBeStateT3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(46, 46, 46)
.addComponent(jButton)
.addContainerGap(86, Short.MAX_VALUE))
);
jButton18.setText("Add");
jButton18.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton18ActionPerformed(evt);
}
});
jScrollPane11.setViewportView(jListFinals1);
javax.swing.GroupLayout jPanel10Layout = new javax.swing.GroupLayout(jPanel10);
jPanel10.setLayout(jPanel10Layout);
jPanel10Layout.setHorizontalGroup(
jPanel10Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel10Layout.createSequentialGroup()
.addContainerGap(39, Short.MAX_VALUE)
.addComponent(jScrollPane11, javax.swing.GroupLayout.PREFERRED_SIZE, 167, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jButton18, javax.swing.GroupLayout.PREFERRED_SIZE, 65, javax.swing.GroupLayout.PREFERRED_SIZE))
);
jPanel10Layout.setVerticalGroup(
jPanel10Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel10Layout.createSequentialGroup()
.addGroup(jPanel10Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel10Layout.createSequentialGroup()
.addGap(15, 15, 15)
.addComponent(jScrollPane11, javax.swing.GroupLayout.PREFERRED_SIZE, 171, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel10Layout.createSequentialGroup()
.addGap(73, 73, 73)
.addComponent(jButton18)))
.addContainerGap(33, Short.MAX_VALUE))
);
jLabel26.setText("Adicione os estados finais");
javax.swing.GroupLayout jPanel8Layout = new javax.swing.GroupLayout(jPanel8);
jPanel8.setLayout(jPanel8Layout);
jPanel8Layout.setHorizontalGroup(
jPanel8Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel8Layout.createSequentialGroup()
.addGap(57, 57, 57)
.addGroup(jPanel8Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jScrollPane9)
.addComponent(jLabel20, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jTextSymbol3))
.addGroup(jPanel8Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel8Layout.createSequentialGroup()
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jButton15)
.addGap(60, 60, 60))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel8Layout.createSequentialGroup()
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel8Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(jPanel8Layout.createSequentialGroup()
.addGap(0, 0, Short.MAX_VALUE)
.addComponent(jPanel10, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel8Layout.createSequentialGroup()
.addComponent(jButton14)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jScrollPane10, javax.swing.GroupLayout.PREFERRED_SIZE, 219, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGap(31, 31, 31))))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel8Layout.createSequentialGroup()
.addGroup(jPanel8Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel8Layout.createSequentialGroup()
.addGap(23, 23, 23)
.addComponent(jLabel21, javax.swing.GroupLayout.PREFERRED_SIZE, 121, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel8Layout.createSequentialGroup()
.addGap(15, 15, 15)
.addComponent(jCBStartState3, javax.swing.GroupLayout.PREFERRED_SIZE, 121, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGap(126, 855, Short.MAX_VALUE))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel8Layout.createSequentialGroup()
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(jPanel8Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel8Layout.createSequentialGroup()
.addComponent(jPanel9, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(115, 115, 115)
.addComponent(jButton16)
.addGap(44, 44, 44))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel8Layout.createSequentialGroup()
.addComponent(jLabel26)
.addGap(59, 59, 59))))
);
jPanel8Layout.setVerticalGroup(
jPanel8Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel8Layout.createSequentialGroup()
.addGap(64, 64, 64)
.addGroup(jPanel8Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel20, javax.swing.GroupLayout.PREFERRED_SIZE, 38, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButton15))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel8Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel8Layout.createSequentialGroup()
.addGroup(jPanel8Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jTextSymbol3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButton14))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jScrollPane9, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(133, 133, 133)
.addComponent(jLabel21)
.addGap(18, 18, 18)
.addComponent(jCBStartState3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel8Layout.createSequentialGroup()
.addGroup(jPanel8Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane10, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(jPanel8Layout.createSequentialGroup()
.addGap(262, 262, 262)
.addComponent(jLabel26)))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jPanel10, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel8Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel8Layout.createSequentialGroup()
.addComponent(jButton16)
.addGap(63, 63, 63))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel8Layout.createSequentialGroup()
.addComponent(jPanel9, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(21, 21, 21))))))
);
jScrollPane8.setViewportView(jPanel8);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jScrollPane8)
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jScrollPane8, javax.swing.GroupLayout.DEFAULT_SIZE, 889, Short.MAX_VALUE)
.addContainerGap())
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void jButton14jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton14jButton1ActionPerformed
alphabet.add(jTextSymbol3.getText());
listModelAlphabet.addElement(jTextSymbol3.getText());
cbModelAlphabet.addElement(jTextSymbol3.getText());
}//GEN-LAST:event_jButton14jButton1ActionPerformed
private void jButton15jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton15jButton2ActionPerformed
State state = new State();
states.add(state);
listModelState.addElement(state.getName());
listModelFinalsStates.addElement(state.getName());
cbModelStateInitial.addElement(state.getName());
cbModelStateCurrent.addElement(state.getName());
cbModelStateNext.addElement(state.getName());
}//GEN-LAST:event_jButton15jButton2ActionPerformed
private void jButton16jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton16jButton3ActionPerformed
getStateStart(jCBStartState3.getSelectedItem().toString());
controllerT.setAlphabet(alphabet);
controllerT.setStates(states);
FormSearch form = new FormSearch(controllerT);
this.add(form);
form.setVisible(true);
jScrollPane8.setVisible(false);
}//GEN-LAST:event_jButton16jButton3ActionPerformed
private void jButtonjButton4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonjButton4ActionPerformed
for(State state: states){
if(state.getName().equals(jCBiStateT3.getSelectedItem().toString())){
for(State state2:states){
if(state2.getName().equals(jCBeStateT3.getSelectedItem().toString())){
state.getTransition().put(jCBAlphabetT3.getSelectedItem().toString(), state2);
}
}
}
}
}//GEN-LAST:event_jButtonjButton4ActionPerformed
private void jButton18ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton18ActionPerformed
for(State state : states){
if(state.getName().equals(jListFinals1.getSelectedValue())){
state.setEnd(true);
JOptionPane.showMessageDialog(null, "Estado "+state.getName()+" Adicionado no conjunto de estados finais");
}
}
}//GEN-LAST:event_jButton18ActionPerformed
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(Home.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Home.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Home.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Home.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Home().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton jButton;
private javax.swing.JButton jButton14;
private javax.swing.JButton jButton15;
private javax.swing.JButton jButton16;
private javax.swing.JButton jButton18;
private javax.swing.JComboBox<String> jCBAlphabetT3;
private javax.swing.JComboBox<String> jCBStartState3;
private javax.swing.JComboBox<String> jCBeStateT3;
private javax.swing.JComboBox<String> jCBiStateT3;
private javax.swing.JLabel jLabel20;
private javax.swing.JLabel jLabel21;
private javax.swing.JLabel jLabel22;
private javax.swing.JLabel jLabel23;
private javax.swing.JLabel jLabel24;
private javax.swing.JLabel jLabel25;
private javax.swing.JLabel jLabel26;
private javax.swing.JList<String> jListAlphabet3;
private javax.swing.JList<String> jListFinals1;
private javax.swing.JList<String> jListState3;
private javax.swing.JPanel jPanel10;
private javax.swing.JPanel jPanel8;
private javax.swing.JPanel jPanel9;
private javax.swing.JScrollPane jScrollPane10;
private javax.swing.JScrollPane jScrollPane11;
private javax.swing.JScrollPane jScrollPane8;
private javax.swing.JScrollPane jScrollPane9;
private javax.swing.JTextField jTextSymbol3;
// End of variables declaration//GEN-END:variables
}
|
package fabio.sicredi.evaluation.jms.model;
import fabio.sicredi.evaluation.api.v1.model.PollResultDTO;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.io.Serializable;
import java.util.UUID;
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class PollResultMessage implements Serializable {
static final long serialVersionUID = 6582934048423061777L;
private UUID id;
private PollResultDTO voteResultDTO;
}
|
package utils;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public abstract class DbUtils {
public static ResultSet getFirstRow(ResultSet results) throws SQLException {
results.next();
return results;
}
public static synchronized int getInsertedKey(Statement statement) throws SQLException {
return DbUtils.getFirstRow(statement.getGeneratedKeys()).getInt(1);
}
}
|
package psoft.backend.dao;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import psoft.backend.model.User;
import java.util.List;
@Repository
public interface UserDAO extends JpaRepository<User, String> {
User save(User user);
@Query(value = "Select u from User as u where u.email=:pEmail")
User findByEmail(@Param("pEmail") String email);
List<User> findAll();
@Override
void deleteAll();
}
|
package com.gsccs.sme.plat.svg.service;
import java.util.List;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.gsccs.sme.plat.svg.dao.RegTypeTMapper;
import com.gsccs.sme.plat.svg.model.RegTypeT;
import com.gsccs.sme.plat.svg.model.RegTypeTExample;
/**
* 企业注册类型业务
*
* @author x.d zhang
*
*/
@Service
public class RegtypeServiceImpl implements RegtypeService {
@Autowired
private RegTypeTMapper regTypeTMapper;
/**
* 根据id查询
*/
@Override
public RegTypeT findById(Long id) {
return regTypeTMapper.selectByPrimaryKey(id);
}
@Override
public void insert(RegTypeT chanelT) {
if (null != chanelT) {
regTypeTMapper.insert(chanelT);
}
}
/**
* 修改卖家账号
*/
@Override
public void update(RegTypeT chanelT) {
regTypeTMapper.updateByPrimaryKey(chanelT);
}
@Override
public int count(RegTypeT chanelT) {
RegTypeTExample example = new RegTypeTExample();
RegTypeTExample.Criteria criteria = example.createCriteria();
proSearchParam(chanelT, criteria);
return regTypeTMapper.countByExample(example);
}
@Override
public List<RegTypeT> find(RegTypeT chanelT, String orderstr, int page,
int pagesize) {
RegTypeTExample example = new RegTypeTExample();
RegTypeTExample.Criteria criteria = example.createCriteria();
proSearchParam(chanelT, criteria);
return regTypeTMapper.selectByExample(example);
}
@Override
public List<RegTypeT> find(RegTypeT chanelT) {
RegTypeTExample example = new RegTypeTExample();
RegTypeTExample.Criteria criteria = example.createCriteria();
proSearchParam(chanelT, criteria);
return regTypeTMapper.selectByExample(example);
}
@Override
public void delChannel(Long id) {
regTypeTMapper.deleteByPrimaryKey(id);
}
@Override
public List<RegTypeT> findSubChannel(Long parid) {
if (null != parid) {
RegTypeT chanelT = new RegTypeT();
chanelT.setParid(parid);
RegTypeTExample example = new RegTypeTExample();
RegTypeTExample.Criteria criteria = example.createCriteria();
proSearchParam(chanelT, criteria);
return regTypeTMapper.selectByExample(example);
}
return null;
}
public void proSearchParam(RegTypeT chanelT, RegTypeTExample.Criteria criteria) {
if (null != chanelT) {
if (StringUtils.isNotEmpty(chanelT.getTitle())) {
criteria.andTitleLike("%" + chanelT.getTitle() + "%");
}
if (null != chanelT.getParid()) {
criteria.andParidEqualTo(chanelT.getParid());
}
}
}
@Override
public List<RegTypeT> findByParids(String parids) {
if (null != parids) {
RegTypeT chanelT = new RegTypeT();
RegTypeTExample example = new RegTypeTExample();
RegTypeTExample.Criteria criteria = example.createCriteria();
proSearchParam(chanelT, criteria);
return regTypeTMapper.selectByExample(example);
}
return null;
}
@Override
public JSONArray findChannelTree() {
List<RegTypeT> roots = find(null);
if (null != roots) {
JSONArray rootArray = (JSONArray) JSON.toJSON(roots);
return treeList(rootArray, 0l);
}
return null;
}
public JSONArray treeList(JSONArray nodeList, Long parentId) {
JSONArray nodearray = new JSONArray();
for (Object object : nodeList) {
JSONObject json = (JSONObject) JSON.toJSON(object);
long menuId = json.getLong("id");
long pid = json.getLong("parid");
json.put("text", json.get("title"));
if (parentId == pid) {
JSONArray subitems = treeList(nodeList, menuId);
json.put("children", subitems);
nodearray.add(json);
}
}
return nodearray;
}
}
|
package com.bluespurs.lowpricefinder.searchengine;
import com.bluespurs.lowpricefinder.PriceItem;
public interface SearchEngine {
PriceItem getPriceItem(String name);
}
|
package tbuddy;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFrame;
import javax.swing.table.DefaultTableModel;
import static tbuddy.Mark.markstable;
/**
*
* @author ZAY
*/
public class AddStudent extends javax.swing.JFrame {
int nn=0;
BufferedWriter wr = new BufferedWriter(new FileWriter("names.txt",true));
ArrayList <String> newn = new ArrayList();
public AddStudent() throws IOException {
initComponents();
}
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
snlabel = new javax.swing.JLabel();
jScrollPane2 = new javax.swing.JScrollPane();
namestable = new javax.swing.JTable();
nextbutton = new javax.swing.JButton();
savebutton = new javax.swing.JButton();
SNtext = new javax.swing.JTextField();
snlabel.setText("Student Name");
namestable.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
},
new String [] {
"#", "Name"
}
) {
Class[] types = new Class [] {
java.lang.Integer.class, java.lang.String.class
};
boolean[] canEdit = new boolean [] {
true, false
};
public Class getColumnClass(int columnIndex) {
return types [columnIndex];
}
public boolean isCellEditable(int rowIndex, int columnIndex) {
return canEdit [columnIndex];
}
});
namestable.getTableHeader().setReorderingAllowed(false);
jScrollPane2.setViewportView(namestable);
if (namestable.getColumnModel().getColumnCount() > 0) {
namestable.getColumnModel().getColumn(0).setPreferredWidth(4);
namestable.getColumnModel().getColumn(0).setMaxWidth(5);
}
nextbutton.setText("Next");
nextbutton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
nextbuttonActionPerformed(evt);
}
});
savebutton.setText("Save & Exit");
savebutton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
savebuttonActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap(57, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
.addComponent(nextbutton, javax.swing.GroupLayout.PREFERRED_SIZE, 133, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(savebutton, javax.swing.GroupLayout.PREFERRED_SIZE, 136, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 299, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(72, 72, 72))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addComponent(SNtext, javax.swing.GroupLayout.PREFERRED_SIZE, 148, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(139, 139, 139))))
.addGroup(layout.createSequentialGroup()
.addGap(158, 158, 158)
.addComponent(snlabel)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(93, 93, 93)
.addComponent(snlabel)
.addGap(12, 12, 12)
.addComponent(SNtext, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(nextbutton)
.addComponent(savebutton))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 158, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(60, Short.MAX_VALUE))
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void nextbuttonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_nextbuttonActionPerformed
//add name to file
try {
wr.write(SNtext.getText());
wr.newLine();
} catch (IOException ex) {
Logger.getLogger(AddStudent.class.getName()).log(Level.SEVERE, null, ex);
}
//add name to output graph
nn++;
DefaultTableModel model = (DefaultTableModel)namestable.getModel();
model.addRow(new Object[]{nn, SNtext.getText()});
newn.add(SNtext.getText());
//clear textbox
SNtext.setText("");
SNtext.requestFocusInWindow();
}//GEN-LAST:event_nextbuttonActionPerformed
private void savebuttonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_savebuttonActionPerformed
nn++;
//output to screen names
if(SNtext.getText().length()>0){
newn.add(SNtext.getText());
//input names to file
try {
wr.write(SNtext.getText());
wr.newLine();
} catch (IOException ex) {
Logger.getLogger(AddStudent.class.getName()).log(Level.SEVERE, null, ex);
}
//reset text to file
SNtext.setText("");
}
try {
wr.close();
} catch (IOException ex) {
Logger.getLogger(AddStudent.class.getName()).log(Level.SEVERE, null, ex);
}
Mark.intotable(newn);
if(SNtext.getText().length()>0){
Mark.CalcFinalMark();
}
//exit
this.setVisible(false);
newn.clear();
}//GEN-LAST:event_savebuttonActionPerformed
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(AddStudent.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(AddStudent.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(AddStudent.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(AddStudent.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JTextField SNtext;
private javax.swing.JScrollPane jScrollPane2;
private javax.swing.JTable namestable;
private javax.swing.JButton nextbutton;
public static javax.swing.JButton savebutton;
private javax.swing.JLabel snlabel;
// End of variables declaration//GEN-END:variables
}
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package xml;
/**
*
* @author Paulo Bonifacio
*/
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.XMLReaderFactory;
public class AgentParser {
ArrayList<AgentName> agentname = new ArrayList();
public ArrayList parseAgent(InputStream in) throws IOException{
try {
AgentParserHandler handler = new AgentParserHandler();
XMLReader parser = XMLReaderFactory.createXMLReader();
parser.setContentHandler(handler);
//Create an input source from the XML input stream
InputSource source = new InputSource(in);
//parse the document
parser.parse(source);
//populate the parsed users list in above created empty list; You can return from here also.
agentname = handler.AllData;
} catch (SAXException ex) {
Logger.getLogger(AgentParser.class.getName()).log(Level.SEVERE, null, ex);
}
return agentname;
}
}
|
package com.pepel.games.shuttle.model.shuttles;
import java.io.Serializable;
import java.util.List;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.Transient;
import javax.persistence.UniqueConstraint;
import javax.validation.constraints.NotNull;
import org.hibernate.annotations.Index;
import org.hibernate.validator.constraints.NotBlank;
import org.jboss.solder.core.Veto;
import com.pepel.games.shuttle.model.Player;
import com.pepel.games.shuttle.model.geography.Planet;
@Entity
@Table(name = "shuttles", uniqueConstraints = @UniqueConstraint(columnNames = {
"player_id", "name" }))
@Veto
public class Shuttle implements Serializable {
private static final long serialVersionUID = 7474122973140247977L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
@NotNull
@ManyToOne(fetch = FetchType.EAGER, optional = false)
@JoinColumn(name = "player_id")
@Index(name = "idx_shuttles_player")
private Player player;
@NotBlank
private String name;
@ManyToOne(fetch = FetchType.EAGER, optional = false)
@JoinColumn(name = "departure_planet_id")
private Planet departurePlanet;
@ManyToOne(fetch = FetchType.EAGER, optional = false)
@JoinColumn(name = "destination_planet_id")
private Planet destinationPlanet;
@Column(name = "departure_time")
private long departureTime;
@OneToMany(fetch = FetchType.LAZY, mappedBy = "shuttle")
private List<Container> containers;
public Shuttle() {
}
public Shuttle(Player player, String name) {
this.player = player;
this.name = name;
}
public long getId() {
return id;
}
public Player getPlayer() {
return player;
}
public Planet getDeparturePlanet() {
return departurePlanet;
}
public void setDeparturePlanet(Planet departurePlanet) {
this.departurePlanet = departurePlanet;
}
public Planet getDestinationPlanet() {
return destinationPlanet;
}
public void setDestinationPlanet(Planet destinationPlanet) {
this.destinationPlanet = destinationPlanet;
}
public long getDepartureTime() {
return departureTime;
}
public void setDepartureTime(long departureTime) {
this.departureTime = departureTime;
}
public List<Container> getContainers() {
return containers;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Transient
public double getSpeed() {
return 1;
}
}
|
package com.xianzaishi.wms.tmscore.dao.impl;
import com.xianzaishi.wms.tmscore.dao.itf.IDistributionBoxDao;
import com.xianzaishi.wms.tmscore.vo.DistributionBoxVO;
import com.xianzaishi.wms.common.dao.impl.BaseDaoAdapter;
public class DistributionBoxDaoImpl extends BaseDaoAdapter implements IDistributionBoxDao {
public String getVOClassName() {
return "DistributionBoxDO";
}
}
|
package pt.sinfo.testDrive.domain;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.TreeSet;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.joda.time.DateTime;
import org.joda.time.DateTimeConstants;
import pt.sinfo.testDrive.exception.BookingNotFoundException;
import pt.sinfo.testDrive.exception.TestDriveException;
import pt.sinfo.testDrive.exception.VehicleNotFoundException;
import pt.sinfo.testDrive.exception.VehicleUnavailableException;
public class Root {
private static Root singleton;
private HashMap<String,Dealer> dealers; //DealerId -> Dealer
private HashMap<String,ArrayList<Booking>> bookings; //Exterior hash, hashed by vehicleID,
//interior hash hashed by booking date
private Root() {
this.dealers = new HashMap<String,Dealer>();
this.bookings = new HashMap<String,ArrayList<Booking>>();
}
private boolean verifyString(String s) {
return s == null || s.trim().equals("");
}
public void addNewDealer(Dealer d) {
this.dealers.put(d.getId(), d);
}
public void addNewBooking(Booking b) {
if(this.bookings.containsKey(b.getVehicleId())) {
this.bookings.get(b.getVehicleId()).add(b);
}
else {
ArrayList<Booking> dateBooking = new ArrayList<Booking>();
dateBooking.add(b);
this.bookings.put(b.getVehicleId(), dateBooking);
}
}
public static Root getReference() {
if(singleton == null) {
singleton = new Root();
}
return singleton;
}
public void setDealers(HashMap<String,Dealer> dealers) {
this.dealers = dealers;
}
public void setBookings(HashMap<String,ArrayList<Booking>> bookings) {
this.bookings = bookings;
}
public HashMap<String,ArrayList<Booking>> getBookings(){
return this.bookings;
}
public HashMap<String,Dealer> getDealers(){
return this.dealers;
}
public boolean isAvailable(String vehicleID,DateTime date) {
if(verifyString(vehicleID) || date == null || date.isBeforeNow()) {
throw new TestDriveException();
}
ArrayList<Booking> bookingsForVehicle = bookings.get(vehicleID);
if(bookingsForVehicle==null) {
if(this.vehicleById(vehicleID).equals(new ArrayList<Vehicle>())) {
throw new VehicleNotFoundException();
}else {
bookingsForVehicle = new ArrayList<Booking>();
}
}
Booking booked = null;
for(Booking b : bookingsForVehicle) {
if(b.getPickupDate().equals(date)) {
booked = b;
break;
}
}
if(booked==null||(booked!=null&&booked.getCancelledAt()!=null)) {
return true;
}else {
return false;
}
}
public List<Vehicle> searchVehicle(String model,String fuel,String transmission, String dealerId ){
List<Vehicle> vehicles = new ArrayList<Vehicle>();
for(Dealer dealer : dealers.values()) {
if(!dealer.getId().equals(dealerId) && !dealerId.equals("")) {
continue;
}
List<Vehicle> found = dealer.getVehicles().stream()
.filter( v -> (v.getModel().equals(model)||model.equals(""))
&& (v.getFuel().equals(fuel)||fuel.equals(""))
&& (v.getTransmission().equals(transmission)||transmission.equals(""))).collect(Collectors.toList());
vehicles.addAll(found);
}
return vehicles;
}
public List<Vehicle> vehicleByModel(String model){
if(verifyString(model)) {
throw new TestDriveException();
}
List<Vehicle> vehicles = new ArrayList<Vehicle>();
for(Dealer dealer : dealers.values()) {
List<Vehicle> found = dealer.getVehicles().stream()
.filter( v -> v.getModel().equals(model)).collect(Collectors.toList());
vehicles.addAll(found);
}
return vehicles;
}
public List<Vehicle> vehicleByFuel(String fuel){
if(verifyString(fuel)) {
throw new TestDriveException();
}
List<Vehicle> vehicles = new ArrayList<Vehicle>();
for(Dealer dealer : dealers.values()) {
List<Vehicle> found = dealer.getVehicles().stream()
.filter( v -> v.getFuel().equals(fuel)).collect(Collectors.toList());
vehicles.addAll(found);
}
return vehicles;
}
public List<Vehicle> vehicleByTransmission(String transmission){
if(verifyString(transmission)) {
throw new TestDriveException();
}
List<Vehicle> vehicles = new ArrayList<Vehicle>();
for(Dealer dealer : dealers.values()) {
List<Vehicle> found = dealer.getVehicles().stream()
.filter( v -> v.getTransmission().equals(transmission)).collect(Collectors.toList());
vehicles.addAll(found);
}
return vehicles;
}
public List<Vehicle> vehicleById(String id){
if(verifyString(id)) {
throw new TestDriveException();
}
List<Vehicle> vehicles = new ArrayList<Vehicle>();
for(Dealer dealer : dealers.values()) {
List<Vehicle> found = dealer.getVehicles().stream()
.filter( v -> v.getId().equals(id)).collect(Collectors.toList());
vehicles.addAll(found);
}
return vehicles;
}
public List<Vehicle> vehicleByDealer(String dID){
if(verifyString(dID)) {
throw new TestDriveException();
}
List<Vehicle> vehicles = new ArrayList<Vehicle>();
Dealer dealer = dealers.get(dID);
if(dealer!=null) {
vehicles = dealer.getVehicles();
}
return vehicles;
}
public void bookVehicle(String dealerId,Booking book) {
if(dealerId==null || book == null) {
throw new TestDriveException();
}
if(!isAvailable(book.getVehicleId(), book.getPickupDate())) {
throw new VehicleUnavailableException();
}
Dealer dealer = this.dealers.get(dealerId);
if(dealer==null) {
throw new TestDriveException();
}
Vehicle vehicle = dealer.getVehicles().stream()
.filter(v -> v.getId().equals(book.getVehicleId()))
.findFirst().orElse(null);
if(vehicle==null) {
throw new TestDriveException();
}
if(!vehicle.checkAvailability(book.getPickupDate())) {
throw new VehicleUnavailableException();
}
ArrayList<Booking> currentBookings = this.bookings.get(book.getVehicleId());
if(currentBookings==null) {
currentBookings = new ArrayList<Booking>();
}
currentBookings.add(book);
this.bookings.put(book.getVehicleId(), currentBookings);
}
public void cancelBooking(String bookingId,String cancelReason) {
if(verifyString(bookingId)||verifyString(cancelReason)) {
throw new TestDriveException();
}
Booking bookingToCancel = null;
outerSearch:
for(ArrayList<Booking> booked : this.bookings.values()) {
for(Booking b : booked) {
if(b.getId().equals(bookingId)) {
bookingToCancel = b;
b.cancel(cancelReason);
break outerSearch;
}
}
}
if(bookingToCancel==null) {
throw new BookingNotFoundException();
}
}
public Vehicle findVehicleWithSpecs(Dealer dealer,String model,String fuel,String transmission) {
if(model==null|| transmission==null||fuel==null) {
throw new TestDriveException();
}
return dealer.getVehicles().stream()
.filter(v -> (v.getModel().equals(model)||model.equals(""))
&& (v.getFuel().equals(fuel)||fuel.equals(""))
&& (v.getTransmission().equals(transmission)||transmission.equals("")))
.findFirst().orElse(null);
}
public Dealer closestDealer(String model,String fuel,String transmission,Coordinate position) {
if(position==null) {
throw new TestDriveException();
}
Dealer result = null;
float lat = position.getLatitude();
float longi = position.getLongitude();
double minimalDistance = -1;
for(Dealer dealer : dealers.values()) {
Vehicle vehicle = findVehicleWithSpecs(dealer, model, fuel, transmission);
if(vehicle!=null) {
double distanceToDealer = dealer.getDistance(longi, lat);
if(minimalDistance==-1 || minimalDistance> distanceToDealer) {
minimalDistance = distanceToDealer;
result = dealer;
}
}
}
return result;
}
public TreeSet<Dealer> createDealerTreeSet(Coordinate position) {
return new TreeSet<Dealer>(new Comparator<Dealer>() {
@Override
public int compare(Dealer arg0, Dealer arg1) {
float lat=position.getLatitude();
float longi = position.getLongitude();
double distance0 = arg0.getDistance(longi, lat);
double distance1 = arg1.getDistance(longi, lat);
if (distance0==distance1) {return 0;}
else if(distance0>distance1) {return 1;}
else {return -1;}
}
});
}
public ArrayList<Dealer> dealersWithSpecdVehicles(String model,String fuel,String transmission,Coordinate position) {
TreeSet<Dealer> dealers = createDealerTreeSet(position);
for(Dealer dealer: this.dealers.values()) {
Vehicle vehicle = findVehicleWithSpecs(dealer, model, fuel, transmission);
if (vehicle!=null) {
dealers.add(dealer);
}
}
return new ArrayList<Dealer>(dealers);
}
public ArrayList<Dealer> dealersInPoligon(String model,String fuel,String transmission,Coordinate topRight,Coordinate bottomLeft){
ArrayList<Dealer> result = new ArrayList<Dealer>();
for(Dealer dealer: this.dealers.values()) {
Vehicle vehicle = findVehicleWithSpecs(dealer, model, fuel, transmission);
if (vehicle!=null && dealer.isInPoligon(topRight, bottomLeft) ) {
result.add(dealer);
}
}
return result;
}
}
|
package de.uulm.mmci.scatter;
import java.util.List;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.PorterDuff.Mode;
import android.graphics.PorterDuffXfermode;
import android.graphics.RadialGradient;
import android.graphics.RectF;
public class Scatter implements Drawable {
private float x = 0;
private float y = 0;
private boolean visible = false;
private List<Icon> segs;
private final RectF outerRect = new RectF();
private final RectF innerRect = new RectF();
private final int scatterAngle = 270;
private final int startAngle = 0;
private final int radius = 150;
private final Paint strokePaint, fillPaint;
// Control here if we check for border or not
private final boolean checkBorder = true;
// Variable for how far the non-show bounds are; when 1 then radius of
// scatter.
private final float scaleBorderCheck = 0.66f;
private int selected;
public Scatter() {
strokePaint = new Paint();
strokePaint.setStrokeWidth(2);
strokePaint.setAntiAlias(true);
strokePaint.setColor(Color.BLACK);
strokePaint.setStyle(Paint.Style.STROKE);
fillPaint = new Paint();
fillPaint.setStrokeWidth(2);
fillPaint.setAntiAlias(true);
}
public void show(float x, float y, List<Icon> temp) {
this.x = x;
this.y = y;
this.segs = temp;
selected = -1;
visible = true;
}
public void hide() {
visible = false;
}
public Icon getItemAt(float tx, float ty) {
double polarCoord = Math.atan2(ty - y, tx - x);
double angle = ((Math.toDegrees(polarCoord)) + 225) % 360; // offset to
// startangle
double distFromCenter = Math.sqrt((tx - x) * (tx - x) + (ty - y)
* (ty - y));
// if outside of scatter circle
if (distFromCenter > radius || distFromCenter < radius / 3
|| angle > scatterAngle) {
selected = -1;
return null;
}
// inside of scatter
else {
int segAngle = scatterAngle / segs.size();
selected = (int) (angle / segAngle);
return segs.get(selected);
}
}
/**
* Draw method for Drawable. This method draws the pie menu. The segments
* are drawn with arcs on call of drawpath method of the canvas. Each arc is
* drawn in one RectF. There are two RectF variables one for the outer
* circle and one for the inner circle and each of them got two paint
* objects. The outer one is the stroke and one the fill content. The Path
* object is important because, it ensures, that both drawn arcs are
* automatically connected (look at Path info on Android docs) so that
* segment is build.
*/
@Override
public void doDraw(Canvas canvas) {
if (visible) {
// Logic for bounding collision (border cases)
if (checkBorder) {
int newBounds = (int) (scaleBorderCheck * radius);
if (this.x <= newBounds
|| this.x >= canvas.getWidth() - newBounds
|| this.y <= newBounds
|| this.y >= canvas.getHeight() - newBounds)
return;
}
outerRect.set(x - radius, y - radius, x + radius, y + radius);
innerRect.set(this.x - radius / 3, this.y - radius / 3, this.x
+ radius / 3, this.y + radius / 3);
int segmentAngle = scatterAngle / segs.size();
int segmentOffset = 0;
// draw segments
for (int i = 0; i < segs.size(); i++) {
outerRect.set(x - radius, y - radius, x + radius, y + radius);
fillPaint.setColor(segs.get(i).getColor());
// fillPaint.setAlpha(150);
fillPaint.setStyle(Paint.Style.FILL);
fillPaint.setShader(null);
fillPaint.setXfermode(null);
fillPaint.setDither(true);
if (selected == i) {
outerRect.set(x - radius - 10, y - radius - 10, x + radius
+ 10, y + radius + 10);
int[] col = { segs.get(i).getColor(),
segs.get(i).getColor(), Color.WHITE };
float[] pos = { 0.0f, 0.7f, 1.0f };
RadialGradient gradient = new android.graphics.RadialGradient(
this.x, this.y, 150, col, pos,
android.graphics.Shader.TileMode.CLAMP);
fillPaint.setShader(gradient);
fillPaint
.setXfermode(new PorterDuffXfermode(Mode.SRC_OVER));
fillPaint.setAlpha(255);
}
segmentOffset = i * segmentAngle;
// Rectangles values
Path segmentPath = new Path();
segmentPath.reset();
segmentPath.arcTo(outerRect,
(startAngle - 225) + segmentOffset, segmentAngle);
segmentPath.arcTo(innerRect, (startAngle - 225) + segmentOffset
+ segmentAngle, -segmentAngle);
segmentPath.close();
// Draw path:
canvas.drawPath(segmentPath, fillPaint);
canvas.drawPath(segmentPath, strokePaint);
}
}
}
public boolean isVisible() {
return visible;
}
public Icon getSelected() {
if (selected == -1 || segs == null) // TODO nullpointer without null check???
return null;
return segs.get(selected);
}
}
|
package me.asyc.jchat.network.encryption.impl;
import me.asyc.jchat.network.encryption.CryptoKey;
import javax.crypto.SecretKey;
import java.security.spec.AlgorithmParameterSpec;
/**
* Simple container class for an <b>AES Key</b>.
*/
public final class CryptoKeyAES implements CryptoKey {
private final SecretKey key;
private final AlgorithmParameterSpec algorithmParameterSpec;
public CryptoKeyAES(SecretKey key, AlgorithmParameterSpec algorithmParameterSpec) {
this.key = key;
this.algorithmParameterSpec = algorithmParameterSpec;
}
@Override
public SecretKey getKey() {
return this.key;
}
@Override
public AlgorithmParameterSpec getParameterSpec() {
return this.algorithmParameterSpec;
}
}
|
package com.getomnify.hackernews;
import android.app.Application;
import io.realm.Realm;
/**
* Created by Sharukh Mohammed on 29/05/18 at 12:55.
*/
public class MyApp extends Application {
@Override
public void onCreate() {
super.onCreate();
Realm.init(getApplicationContext());
}
}
|
/*
* Created by SixKeyStudios
* Added in project Technicalities
* File world.objects / TObject
* created on 20.5.2019 , 21:43:20
*/
package technicalities.world.objects;
import SixGen.GameObject.GameObject;
import SixGen.Utils.ID;
import technicalities.ui.tui.TUI;
import technicalities.variables.globals.GlobalVariables;
/**
* TObject
* - class inherited by all independent objects in game
* @author filip
*/
public abstract class TObject extends GameObject implements GlobalVariables{
//objects ui
protected TUI tui;
private int hp = 0;
private int maxHP = 0;
private boolean dead = false;
protected int collisionRadius = 0;
public TObject(float centerX, float centerY, ID id) {
super(centerX, centerY, id);
}
////// METHODS //////
public void collision(TObject o) {
}
public void bigTick() {
}
//// DAMAGE AND DEATH
public void damage(int damage) {
this.hp = hp - damage;
if(hp<0) {
hp = 0;
death();
}
}
protected void death() {
dead = true;
}
////// GETTERS SETTERS //////
public int getHP() {
return hp;
}
protected void setHP(int hp) {
this.hp = hp;
}
protected void setMaxHP(int maxHP) {
this.maxHP = maxHP;
}
public int getMaxHP() {
return maxHP;
}
public TUI getTUI() {
return tui;
}
public int getCollisionRadius() {
return collisionRadius;
}
public boolean isAlive() {
return !dead;
}
public String getTID() {
return null;
}
}
|
package br.com.bd1start.aula2;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.junit.Assert;
import org.junit.Test;
import br.com.db1start.aula2.ExercicioAula11;
public class ExercicioAula11Teste {
// Exercicio 1
@Test
public void deveRetornarListaDeNomes() {
ExercicioAula11 exercicioaula11 = new ExercicioAula11();
List<String> cores = exercicioaula11.cores();
Assert.assertEquals("Preto", cores.get(0));
Assert.assertEquals("Verde", cores.get(1));
}
// Exercicio 2
@Test
public void deveRetornarQuantidadeDeItens() {
ExercicioAula11 aula11 = new ExercicioAula11();
int tamanho = aula11.item(aula11.cores());
Assert.assertEquals(2, tamanho);
}
// Exercicio 3
@Test
public void deveRemoverItem2() {
ExercicioAula11 aula11 = new ExercicioAula11();
List<String> nomes = aula11.addRemoveNomes("Lana", "Ana", "Allana");
Assert.assertEquals("Lana", nomes.get(0));
Assert.assertEquals("Allana", nomes.get(1));
}
// Exercicio 4
@Test
public void deveRetornarListaCoresOrdenada() {
ExercicioAula11 exercicioaula11 = new ExercicioAula11();
List<String> cores = exercicioaula11.coresOrdenadas("Preto", "Verde", "Azul");
Assert.assertEquals("Azul", cores.get(0));
Assert.assertEquals("Preto", cores.get(1));
Assert.assertEquals("Verde", cores.get(2));
}
// Exercicio 5
@Test
public void removerCor() {
ExercicioAula11 exercicioAula11 = new ExercicioAula11();
List<String> cores = exercicioAula11.coresOrdenadas("Preto", "Verde", "Azul");
exercicioAula11.removerCor(cores, "Azul");
Assert.assertEquals("Preto", cores.get(0));
Assert.assertEquals("Verde", cores.get(1));
}
// Exercicio 6
@Test
public void listaInvertida() {
ExercicioAula11 exercicioAula11 = new ExercicioAula11();
List<String> listaLetras = new ArrayList<>();
listaLetras.add("E");
listaLetras.add("B");
listaLetras.add("C");
listaLetras.add("D");
listaLetras.add("A");
exercicioAula11.ordenarDecrescente(listaLetras);
Assert.assertEquals("E", listaLetras.get(0));
Assert.assertEquals("D", listaLetras.get(1));
Assert.assertEquals("C", listaLetras.get(2));
Assert.assertEquals("B", listaLetras.get(3));
Assert.assertEquals("A", listaLetras.get(4));
}
// Exercicio 7
@Test
public void deveRetornarNumerosSeparados() {
ExercicioAula11 ex11 = new ExercicioAula11();
List<Integer> numeros = new ArrayList<>();
for (int i = 0; i < 10; i++) {
numeros.add(i);
}
List<List<Integer>> resultado = new ArrayList<List<Integer>>();
resultado = ex11.retonarListaDeListaParImpar(numeros);
List<Integer> par = resultado.get(0);
List<Integer> impar = resultado.get(1);
List<Integer> listPares = Arrays.asList(0, 2, 4, 6, 8);
List<Integer> listImpares = Arrays.asList(1, 3, 5, 7, 9);
Assert.assertEquals(listPares, par);
Assert.assertEquals(listImpares, impar);
}
// Exercicio 8
@Test
public void listaOrdenada() {
ExercicioAula11 exercicioAula11 = new ExercicioAula11();
List<String> listaNomes = new ArrayList<>();
listaNomes.add("JOSÉ");
listaNomes.add("MARIA");
listaNomes.add("MARCOS");
listaNomes.add("RODOLFO");
listaNomes.add("ROBERVAL");
listaNomes.add("RODOLPHO");
listaNomes.add("VAGNER");
listaNomes.add("JOSÉ");
listaNomes.add("ANA");
listaNomes.add("ANA LAURA");
listaNomes.add("JOSE");
listaNomes.add("WAGNER");
listaNomes.add("JOALDO");
listaNomes.add("CLECIO");
exercicioAula11.listaOrdenada(listaNomes);
Assert.assertEquals("ANA", listaNomes.get(0));
Assert.assertEquals("ANA LAURA", listaNomes.get(1));
Assert.assertEquals("CLECIO", listaNomes.get(2));
Assert.assertEquals("JOALDO", listaNomes.get(3));
Assert.assertEquals("JOSE", listaNomes.get(4));
Assert.assertEquals("JOSÉ", listaNomes.get(5));
Assert.assertEquals("JOSÉ", listaNomes.get(6));
Assert.assertEquals("MARCOS", listaNomes.get(7));
Assert.assertEquals("MARIA", listaNomes.get(8));
Assert.assertEquals("ROBERVAL", listaNomes.get(9));
Assert.assertEquals("RODOLFO", listaNomes.get(10));
Assert.assertEquals("RODOLPHO", listaNomes.get(11));
Assert.assertEquals("VAGNER", listaNomes.get(12));
Assert.assertEquals("WAGNER", listaNomes.get(13));
}
// Exercicio 9
@Test
public void somaValorDaLista() {
ExercicioAula11 exercicioAula11 = new ExercicioAula11();
List<Integer> listaNumero = new ArrayList<>();
listaNumero.add(10);
listaNumero.add(20);
listaNumero.add(30);
int resultado = exercicioAula11.totalDaLista(listaNumero);
Assert.assertEquals(60, resultado);
}
// Exercicio 10
@Test
public void mediaValorDaLista() {
ExercicioAula11 exercicioAula11 = new ExercicioAula11();
List<Double> listaNumero = new ArrayList<>();
listaNumero.add(7.0);
listaNumero.add(5.0);
listaNumero.add(6.0);
double resultado = exercicioAula11.mediaDaLista(listaNumero);
Assert.assertEquals(6, resultado, 0.001);
}
// Exercicio 11
@Test
public void menorValorDaLista() {
ExercicioAula11 exercicioAula11 = new ExercicioAula11();
List<Integer> listaNumero = new ArrayList<>();
listaNumero.add(20);
listaNumero.add(100);
listaNumero.add(10);
int resultado = exercicioAula11.menorValorDaLista(listaNumero);
Assert.assertEquals(10, resultado);
}
// Exercicio 12
@Test
public void maiorValorDaLista() {
ExercicioAula11 exercicioAula11 = new ExercicioAula11();
List<Integer> listaNumero = new ArrayList<>();
listaNumero.add(20);
listaNumero.add(100);
listaNumero.add(1000);
int resultado = exercicioAula11.maiorValorDaLista(listaNumero);
Assert.assertEquals(1000, resultado);
}
// Exercicio 13
@Test
public void retornaApenasPares() {
ExercicioAula11 exercicioAula11 = new ExercicioAula11();
List<Integer> listaNumeros = new ArrayList<>();
listaNumeros.add(1);
listaNumeros.add(2);
listaNumeros.add(3);
listaNumeros.add(4);
listaNumeros.add(5);
listaNumeros.add(6);
exercicioAula11.retornaListaPar(listaNumeros);
Assert.assertEquals(Integer.valueOf(2), listaNumeros.get(0));
Assert.assertEquals(Integer.valueOf(4), listaNumeros.get(1));
Assert.assertEquals(Integer.valueOf(6), listaNumeros.get(2));
}
//Exercicio 14
@Test
public void retornaVogais() {
ExercicioAula11 exercicioAula11 = new ExercicioAula11();
String frase = "Pague o Aluguel";
List<List<Character>> resultado = new ArrayList<List<Character>>();
resultado = exercicioAula11.retornaLetras(frase);
List<Character> listTest = Arrays.asList('a', 'u', 'e', 'o', 'a', 'u', 'u', 'e');
List<Character> listVogais = resultado.get(0);
Assert.assertEquals(listTest, listVogais);
}
}
|
package mb.tianxundai.com.toptoken.secondphase.fgt;
import android.os.Bundle;
import android.support.annotation.Nullable;
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 com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import mb.tianxundai.com.toptoken.R;
import mb.tianxundai.com.toptoken.base.BaseFgt;
import mb.tianxundai.com.toptoken.interfaces.Layout;
import mb.tianxundai.com.toptoken.secondphase.aty.KLainDetailsAty;
import mb.tianxundai.com.toptoken.secondphase.bean.MyMarketBean;
import mb.tianxundai.com.toptoken.uitl.JumpParameter;
/**
* 新行情界面
*/
@Layout(R.layout.fgt_my_market)
public class MyMarketFgt extends BaseFgt {
@BindView(R.id.recycle_market)
RecyclerView recycleMarket;
Unbinder unbinder;
private Unbinder bind;
private MyMarketAdapter adapter;
@Override
public void initViews() {
bind = ButterKnife.bind(this, rootView);
}
@Override
public void initDatas() {
List<MyMarketBean> mList = new ArrayList<>();
for (int i = 0; i < 4; i++) {
MyMarketBean myMarketBean = new MyMarketBean();
if (i == 0) {
myMarketBean.imgs = R.mipmap.bizhong01;
myMarketBean.names = "BTC";
myMarketBean.now_price = "63248";
myMarketBean.low_price = "12300";
myMarketBean.high_price = "645200";
} else if (i == 1) {
myMarketBean.imgs = R.mipmap.bizhong03;
myMarketBean.names = "ETH";
myMarketBean.now_price = "43645";
myMarketBean.low_price = "24656";
myMarketBean.high_price = "856543";
} else if (i == 2) {
myMarketBean.imgs = R.mipmap.bizhong02;
myMarketBean.names = "LTC";
myMarketBean.now_price = "5767";
myMarketBean.low_price = "1223";
myMarketBean.high_price = "7887";
} else if (i == 3) {
myMarketBean.imgs = R.mipmap.bizhong01;
myMarketBean.names = "BTC";
myMarketBean.now_price = "243454";
myMarketBean.low_price = "14345";
myMarketBean.high_price = "977456";
} else if (i == 4) {
myMarketBean.imgs = R.mipmap.bizhong03;
myMarketBean.names = "ETH";
myMarketBean.now_price = "63248";
myMarketBean.low_price = "12300";
myMarketBean.high_price = "645200";
}
mList.add(myMarketBean);
}
// mList.add("BTC");
// mList.add("LTC");
// mList.add("ETH");
//为adapter传入布局和数据
adapter = new MyMarketAdapter(R.layout.item_mumarket_list, mList);
recycleMarket.setLayoutManager(new LinearLayoutManager(me, LinearLayoutManager.VERTICAL, false));
recycleMarket.setAdapter(adapter);
adapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
@Override
public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
jump(KLainDetailsAty.class, new JumpParameter().put("name", mList.get(position))); // K线详情页面
}
});
}
@Override
public void setEvents() {
}
@Override
public void onDestroyView() {
super.onDestroyView();
bind.unbind();
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// TODO: inflate a fragment view
View rootView = super.onCreateView(inflater, container, savedInstanceState);
unbinder = ButterKnife.bind(this, rootView);
return rootView;
}
class MyMarketAdapter extends BaseQuickAdapter<MyMarketBean, BaseViewHolder> {
public MyMarketAdapter(int layoutResId, @Nullable List<MyMarketBean> data) {
super(layoutResId, data);
}
// public MyMarketAdapter(int layoutResId, @Nullable Map<String,String> data) {
// super(layoutResId, data);
// }
@Override
protected void convert(BaseViewHolder helper, MyMarketBean item) {
int layoutPosition = helper.getLayoutPosition();
//控制item整体颜色变换
if (layoutPosition % 2 == 0) {
helper.getView(R.id.my_market_item).setBackgroundResource(R.color.white);
} else {
helper.getView(R.id.my_market_item).setBackgroundResource(R.color.poputextgray5);
}
helper.setImageResource(R.id.iv_type_img,item.imgs);
helper.setText(R.id.tv_names, item.names);
helper.setText(R.id.tv_now_price, item.now_price);
helper.setText(R.id.tv_low_price, item.low_price);
helper.setText(R.id.tv_high_price, item.high_price);
// helper.setBackgroundRes(R.id.tv_now_price, R.color.buttongreen);
helper.setBackgroundRes(R.id.tv_now_price, R.drawable.mymarket_now_price);
}
public void setData(List<MyMarketBean> mdata) {
this.mData = mdata;
}
}
}
|
package zerot.itg;
import org.objectweb.asm.ClassVisitor;
import org.objectweb.asm.Opcodes;
/**
* Created by Zerot on 11/10/2014.
*/
public class Visitor extends ClassVisitor {
private final ClassDataManager classData;
public Visitor(ClassDataManager classData) {
super(Opcodes.ASM5);
this.classData = classData;
}
@Override
public void visit(int version, int access, String name, String signature, String superName, String[] interfaces) {
classData.addClass(name, superName, interfaces);
super.visit(version, access, name, signature, superName, interfaces);
}
}
|
package com.sirma.itt.javacourse.desingpatterns.task4.objectpool;
import java.util.ArrayList;
import java.util.List;
import org.apache.log4j.Logger;
/**
* Pool class that lets us get N user objects.
*
* @param <T>
* The type parameter this class will use.
* @author Simeon Iliev
*/
public class UserPool<T> implements Pool<T> {
private static Logger log = Logger.getLogger(UserPool.class.getName());
private int capacity = 10;
private final T instance;
private final List<T> freeInstances;
private final List<T> usedInstances;
public UserPool(T instance) {
freeInstances = new ArrayList<T>(capacity + 1);
usedInstances = new ArrayList<T>(capacity + 1);
this.instance = instance;
}
public UserPool(int capacity, T instance) {
freeInstances = new ArrayList<T>(capacity + 1);
usedInstances = new ArrayList<T>(capacity + 1);
this.instance = instance;
this.capacity = capacity;
}
@Override
public T acquire() throws NoMoreResourcesException {
if (usedInstances.size() > capacity) {
throw new NoMoreResourcesException("Pool can't return instance");
}
T user;
if (freeInstances.size() != 0) {
user = freeInstances.get(0);
usedInstances.add(user);
freeInstances.remove(0);
} else {
user = initObject();
usedInstances.add(user);
}
return user;
}
@Override
public void release(T object) throws NoMoreResourcesException {
if (freeInstances.size() == capacity) {
throw new NoMoreResourcesException("All instances are free");
}
usedInstances.remove(object);
freeInstances.add(object);
}
@Override
public T initObject() {
@SuppressWarnings("unchecked")
Class<T> object = (Class<T>) instance.getClass();
try {
return object.newInstance();
} catch (InstantiationException | IllegalAccessException e) {
log.error(e.getMessage(), e);
}
return null;
}
}
|
package com.wadi.set;
public interface View {
void refresh();
}
|
package com.myth.springboot.service;
import com.myth.springboot.dao.AdminMapper;
import com.myth.springboot.dao.DeptMapper;
import com.myth.springboot.entity.Class;
import com.myth.springboot.entity.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class DeptService {
@Autowired
DeptMapper mapper;
//部门新增,查询,修改,删除
public int classInsert(Dept dept){
return mapper.deptInsert(dept);
}
public List<Dept> deptSelect(Dept dept){
return mapper.deptSelect(dept);
}
public int deptUpdateById(Dept dept){
return mapper.deptUpdateById(dept);
}
public int deptDeleteById(Dept dept){
return mapper.deptDeleteById(dept);
}
}
|
package com.eegeo.mapapi.picking;
import android.graphics.Point;
import androidx.annotation.NonNull;
import androidx.annotation.UiThread;
import androidx.annotation.WorkerThread;
import com.eegeo.mapapi.INativeMessageRunner;
import com.eegeo.mapapi.IUiMessageRunner;
import com.eegeo.mapapi.geometry.LatLng;
import com.eegeo.mapapi.util.Promise;
/**
* @eegeo.internal
*/
public class PickingApi {
private INativeMessageRunner m_nativeRunner;
private IUiMessageRunner m_uiRunner;
private long m_jniEegeoMapApiPtr;
/**
* @eegeo.internal
*/
public PickingApi(INativeMessageRunner nativeRunner,
IUiMessageRunner uiRunner,
long jniEegeoMapApiPtr) {
this.m_nativeRunner = nativeRunner;
this.m_uiRunner = uiRunner;
this.m_jniEegeoMapApiPtr = jniEegeoMapApiPtr;
}
/**
* @eegeo.internal
*/
@UiThread
public Promise<PickResult> pickFeatureAtScreenPoint(@NonNull final Point point) {
final Promise<PickResult> p = new Promise<>();
m_nativeRunner.runOnNativeThread(new Runnable() {
@Override
public void run() {
final PickResult pickResult = nativePickFeatureAtScreenPoint(m_jniEegeoMapApiPtr, point.x, point.y);
m_uiRunner.runOnUiThread(new Runnable() {
@Override
public void run() {
p.ready(pickResult);
}
});
}
});
return p;
}
/**
* @eegeo.internal
*/
@UiThread
public Promise<PickResult> pickFeatureAtLatLng(@NonNull final LatLng latLng) {
final Promise<PickResult> p = new Promise<>();
m_nativeRunner.runOnNativeThread(new Runnable() {
@Override
public void run() {
final PickResult pickResult = nativePickFeatureAtLatLng(m_jniEegeoMapApiPtr, latLng.latitude, latLng.longitude);
m_uiRunner.runOnUiThread(new Runnable() {
@Override
public void run() {
p.ready(pickResult);
}
});
}
});
return p;
}
@WorkerThread
private native PickResult nativePickFeatureAtScreenPoint(long jniEegeoMapApiPtr, double x, double y);
@WorkerThread
private native PickResult nativePickFeatureAtLatLng(long jniEegeoMapApiPtr, double lat, double lng);
}
|
package com.example.stoom.dao.rowmappers;
import com.example.stoom.entity.Address;
import org.springframework.jdbc.core.RowMapper;
import java.sql.ResultSet;
import java.sql.SQLException;
public final class AddressMapper implements RowMapper {
public Address mapRow(ResultSet rs, int rowNum) throws SQLException {
Address address = new Address();
address.setId(rs.getLong("id"));
address.setStreetName(rs.getString("street_name"));
address.setNumber(rs.getString("address_number"));
address.setComplement(rs.getString("complement"));
address.setNeighbourhood(rs.getString("neighbourhood"));
address.setCity(rs.getString("city"));
address.setState(rs.getString("state"));
address.setCountry(rs.getString("country"));
address.setZipCode(rs.getString("zip_code"));
address.setLatitude(rs.getString("latitude"));
address.setLongitude(rs.getString("longitude"));
return address;
}
}
|
package online.lahloba.www.lahloba.data.model;
import androidx.databinding.BaseObservable;
import androidx.databinding.Bindable;
import android.os.Parcel;
import android.os.Parcelable;
import java.util.Date;
import java.util.HashMap;
import online.lahloba.www.lahloba.BR;
public class OrderItem extends BaseObservable implements Parcelable {
private String id;
private double total;
private AddressItem addressSelected;
private String shippingMethodSelected;
private double hyperlocalCost = 0;
private String pay_method;
private HashMap<String, CartItem> products;
private double orderTotal;
private int orderStatus;
private long orderNumber;
private Date date;
private String marketplaceId;
private String userId;
private String cityId;
private String cityIdStatus;
private String deliveryAllocatedTo;
public OrderItem() {
}
protected OrderItem(Parcel in) {
id = in.readString();
total = in.readDouble();
addressSelected = in.readParcelable(AddressItem.class.getClassLoader());
shippingMethodSelected = in.readString();
hyperlocalCost = in.readDouble();
pay_method = in.readString();
orderTotal = in.readDouble();
products = new HashMap<>();
in.readMap(products, OrderItem.class.getClassLoader());
orderStatus = in.readInt();
orderNumber = in.readLong();
date = (Date) in.readSerializable();
marketplaceId = in.readString();
userId = in.readString();
cityId = in.readString();
cityIdStatus = in.readString();
deliveryAllocatedTo = in.readString();
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(id);
dest.writeDouble(total);
dest.writeParcelable(addressSelected, flags);
dest.writeString(shippingMethodSelected);
dest.writeDouble(hyperlocalCost);
dest.writeString(pay_method);
dest.writeDouble(orderTotal);
dest.writeMap(products);
dest.writeInt(orderStatus);
dest.writeLong(orderNumber);
dest.writeSerializable(date);
dest.writeString(marketplaceId);
dest.writeString(userId);
dest.writeString(cityId);
dest.writeString(cityIdStatus);
dest.writeString(deliveryAllocatedTo);
}
@Override
public int describeContents() {
return 0;
}
public static final Creator<OrderItem> CREATOR = new Creator<OrderItem>() {
@Override
public OrderItem createFromParcel(Parcel in) {
return new OrderItem(in);
}
@Override
public OrderItem[] newArray(int size) {
return new OrderItem[size];
}
};
public String getId() {
return id;
}
public double getTotal() {
return total;
}
public AddressItem getAddressSelected() {
return addressSelected;
}
public String getShippingMethodSelected() {
return shippingMethodSelected;
}
public double getHyperlocalCost() {
return hyperlocalCost;
}
public String getPay_method() {
return pay_method;
}
public HashMap<String, CartItem> getProducts() {
return products;
}
public double getOrderTotal() {
return orderTotal;
}
public int getOrderStatus() {
return orderStatus;
}
@Bindable
public long getOrderNumber() {
return orderNumber;
}
public Date getDate() {
return date;
}
public String getMarketplaceId() {
return marketplaceId;
}
public String getUserId() {
return userId;
}
public void setId(String id) {
this.id = id;
}
public void setTotal(double total) {
this.total = total;
}
public void setAddressSelected(AddressItem addressSelected) {
this.addressSelected = addressSelected;
}
public void setShippingMethodSelected(String shippingMethodSelected) {
this.shippingMethodSelected = shippingMethodSelected;
}
public void setHyperlocalCost(double hyperlocalCost) {
this.hyperlocalCost = hyperlocalCost;
}
public void setPay_method(String pay_method) {
this.pay_method = pay_method;
}
public void setProducts(HashMap<String, CartItem> products) {
this.products = products;
}
public void setOrderTotal(double orderTotal) {
this.orderTotal = orderTotal;
}
public void setOrderStatus(int orderStatus) {
this.orderStatus = orderStatus;
}
public void setOrderNumber(long orderNumber) {
this.orderNumber = orderNumber;
notifyPropertyChanged(BR.orderNumber);
}
public void setDate(Date date) {
this.date = date;
}
public void setMarketplaceId(String marketplaceId) {
this.marketplaceId = marketplaceId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getCityId() {
return cityId;
}
public void setCityId(String cityId) {
this.cityId = cityId;
}
public String getCityIdStatus() {
return cityIdStatus;
}
public void setCityIdStatus(String cityIdStatus) {
this.cityIdStatus = cityIdStatus;
}
public String getDeliveryAllocatedTo() {
return deliveryAllocatedTo;
}
public void setDeliveryAllocatedTo(String deliveryAllocatedTo) {
this.deliveryAllocatedTo = deliveryAllocatedTo;
}
}
|
package com.gxtc.huchuan.adapter;
import android.content.Context;
import com.gxtc.commlibrary.base.AbsBaseAdapter;
import com.gxtc.huchuan.bean.UserRiseDataBean;
import java.util.List;
/**
* Created by Steven on 17/2/23.
*/
public class UserRiseAdapter extends AbsBaseAdapter<UserRiseDataBean> {
public UserRiseAdapter(Context context, List<UserRiseDataBean> datas, int itemLayoutId) {
super(context, datas, itemLayoutId);
}
@Override
public void bindData(AbsBaseAdapter.ViewHolder holder, UserRiseDataBean bean, int position) {
}
}
|
package com.sikeserver.maid.server;
import com.sikeserver.maid.Maid;
import com.sikeserver.maid.task.KeepAliveTask;
import com.sikeserver.maid.util.Logger;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
public class SessionManager {
private static SessionManager instance = new SessionManager();
private static ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor();
private static KeepAliveTask task = new KeepAliveTask();
private boolean isTaskRunning;
private int keepAliveDelay = Integer.parseUnsignedInt(Maid.getConfig().getProperty("Server.KeepAlive", "60000"));
private ScheduledFuture future;
private List<WebSocketListener> sessions = new ArrayList<>();
void add(WebSocketListener socket){
sessions.add(socket);
if (!isTaskRunning) {
future = scheduler.scheduleWithFixedDelay(
task,
keepAliveDelay,
keepAliveDelay,
TimeUnit.MILLISECONDS
);
isTaskRunning = true;
Logger.info("WebSocket task started.");
}
}
void remove(WebSocketListener socket){
sessions.remove(socket);
if (sessions.isEmpty()) {
future.cancel(true);
isTaskRunning = false;
Logger.info("WebSocket task stopped.");
}
}
public void broadcast(String message){
for (WebSocketListener session: sessions) {
session.send(message);
}
}
public static SessionManager getInstance(){
return instance;
}
}
|
package crawlers;
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
import java.util.HashMap;
import java.util.Map;
/**
*
* @author zua
*/
public final class Logos {
private static final Map<String, String> logos = new HashMap<>();
static {
logos.put("global-voices", "https://pbs.twimg.com/profile_images/469223261323018240/OvCrbQzO_400x400.png");
logos.put("abc-news-au", "https://pbs.twimg.com/profile_images/851166911245107200/4xsqBmY5_400x400.jpg");
logos.put("maka-angola", "https://pbs.twimg.com/profile_images/437691631840415744/WAqRENf9_400x400.png");
logos.put("verdade-online", "https://pbs.twimg.com/profile_images/575909011461177344/xnpMR2hO_400x400.jpeg");
logos.put("al-jazeera-english", "https://pbs.twimg.com/profile_images/875638617606987776/YBOKib96_400x400.jpg");
logos.put("ars-technica", "https://pbs.twimg.com/profile_images/2215576731/ars-logo_400x400.png");
logos.put("associated-press", "https://pbs.twimg.com/profile_images/461964160838803457/8z9FImcv_400x400.png");
logos.put("bbc-news", "https://pbs.twimg.com/profile_images/875702138680246273/BfQLzf7G_400x400.jpg");
logos.put("bbc-sport", "https://pbs.twimg.com/profile_images/897379868014411777/xpJaG4a5_400x400.jpg");
logos.put("bloomberg", "https://pbs.twimg.com/profile_images/880845394867097600/qugtOGJn_400x400.jpg");
logos.put("breitbart-news", "https://pbs.twimg.com/profile_images/649329146221297665/5UgMNCwA_400x400.jpg");
logos.put("business-insider", "https://pbs.twimg.com/profile_images/887662979902304257/azSzxYkB_400x400.jpg");
logos.put("business-insider-uk", "https://pbs.twimg.com/profile_images/890152475067650048/6MuA0NTT_400x400.jpg");
logos.put("buzzfeed", "https://pbs.twimg.com/profile_images/796353157576138752/H2xr-NkC_400x400.jpg");
logos.put("cnbc", "https://pbs.twimg.com/profile_images/875399584477962241/CsazvyAF_400x400.jpg");
logos.put("cnn", "https://pbs.twimg.com/profile_images/508960761826131968/LnvhR8ED_400x400.png");
logos.put("daily-mail", "https://pbs.twimg.com/profile_images/930087648202575872/q4pq9RGV_400x400.jpg");
logos.put("der-tagesspiegel", "https://pbs.twimg.com/profile_images/455980930293702658/V0W08c8o_400x400.png");
logos.put("die-zeit", "https://pbs.twimg.com/profile_images/899901264942813184/_n5m0ro7_400x400.jpg");
logos.put("engadget", "https://pbs.twimg.com/profile_images/655059892022022144/Pq3Q_1oU_400x400.png");
logos.put("entertainment-weekly", "https://pbs.twimg.com/profile_images/881539688418471937/lf5NWhm__400x400.jpg");
logos.put("espn", "https://pbs.twimg.com/profile_images/903763131872288768/lR7-Fb1N_400x400.jpg");
logos.put("financial-times", "https://pbs.twimg.com/profile_images/931161479398686721/FI3te2Sw_400x400.jpg");
logos.put("focus", "https://pbs.twimg.com/profile_images/847373919468179456/Zrp-86HU_400x400.jpg");
logos.put("football-italia", "https://pbs.twimg.com/profile_images/2514923001/kvc336eae86bjgy8ys1s_400x400.jpeg");
logos.put("fortune", "https://pbs.twimg.com/profile_images/875382047216467972/3119VjuE_400x400.jpg");
logos.put("four-four-two", "https://pbs.twimg.com/profile_images/981467112391827456/lm1RuRKr_400x400.jpg");
logos.put("google-news", "https://pbs.twimg.com/profile_images/1843856587/news_icon_big_400x400.png");
logos.put("gruenderszene", "https://pbs.twimg.com/profile_images/941240896451997696/x5a6yojl_400x400.jpg");
logos.put("hacker-news", "https://pbs.twimg.com/profile_images/469397708986269696/iUrYEOpJ_400x400.png");
logos.put("handelsblatt", "https://pbs.twimg.com/profile_images/864850500088455169/RhrXxWdw_400x400.jpg");
logos.put("ign", "https://pbs.twimg.com/profile_images/865351828111675393/It7GIxXW_400x400.jpg");
logos.put("independent", "https://pbs.twimg.com/profile_images/583628771972018176/ztJn926g_400x400.png");
logos.put("mashable", "https://pbs.twimg.com/profile_images/941796662770651137/cDtLVz1j_400x400.jpg");
logos.put("metro", "https://pbs.twimg.com/profile_images/884322278699388928/lyQCp-0B_400x400.jpg");
logos.put("mirror", "https://pbs.twimg.com/profile_images/798143742205186048/PpRgSwh0_400x400.jpg");
logos.put("mtv-news", "https://pbs.twimg.com/profile_images/871737880133197824/sGUD5ffo_400x400.jpg");
logos.put("mtv-news-uk", "https://pbs.twimg.com/profile_images/1801520411/MTV_News_Logo_Black_400x400.png");
logos.put("national-geographic", "https://pbs.twimg.com/profile_images/921336759979597825/VTSJ5mRt_400x400.jpg");
logos.put("newsweek", "https://pbs.twimg.com/profile_images/741603495929905152/di0NxkFa_400x400.jpg");
logos.put("new-york-magazine", "https://pbs.twimg.com/profile_images/2939680330/56f025f0104892f84a84c00bdb4ec812_400x400.png");
logos.put("nfl-news", "https://pbs.twimg.com/profile_images/971061480497041416/bib7cPuh_400x400.jpg");
logos.put("polygon", "https://pbs.twimg.com/profile_images/877267279523741696/rzCAYZLP_400x400.jpg");
logos.put("recode", "https://pbs.twimg.com/profile_images/729365899828989952/o0AuZCNW_400x400.jpg");
logos.put("reddit-r-all", "https://pbs.twimg.com/profile_images/868147475852312577/fjCSPU-a_400x400.jpg");
logos.put("reuters", "https://pbs.twimg.com/profile_images/877554927932891136/ZBEs235N_400x400.jpg");
logos.put("spiegel-online", "https://pbs.twimg.com/profile_images/881743612404518912/ALb4Fxzg_400x400.jpg");
logos.put("talksport", "https://pbs.twimg.com/profile_images/875645817381507074/zs6uOcf8_400x400.jpg");
logos.put("techcrunch", "https://pbs.twimg.com/profile_images/969240943671955456/mGuud28F_400x400.jpg");
logos.put("techradar", "https://pbs.twimg.com/profile_images/875421451653873664/P21KAcnr_400x400.jpg");
logos.put("the-economist", "https://pbs.twimg.com/profile_images/879361767914262528/HdRauDM-_400x400.jpg");
logos.put("the-guardian-au", "https://pbs.twimg.com/profile_images/952866338187423744/0hj7a-EH_400x400.jpg");
logos.put("the-guardian-uk", "https://pbs.twimg.com/profile_images/952866338187423744/0hj7a-EH_400x400.jpg");
logos.put("the-hindu", "https://pbs.twimg.com/profile_images/2478394561/nb2te43f8bqf820e1gry_400x400.jpeg");
logos.put("the-huffington-post", "https://pbs.twimg.com/profile_images/184402517/huffpo_400x400.jpg");
logos.put("the-lad-bible", "https://pbs.twimg.com/profile_images/841982132981497856/egozMVKe_400x400.jpg");
logos.put("the-new-york-times", "https://pbs.twimg.com/profile_images/905479981459013637/a6BbKh4k_400x400.jpg");
logos.put("the-next-web", "https://pbs.twimg.com/profile_images/848832036169273344/p5J8QMn7_400x400.jpg");
logos.put("the-sport-bible", "https://pbs.twimg.com/profile_images/2696805135/2140f5c4dc0845d17bc3e55e128a3a77_400x400.jpeg");
logos.put("t3n", "https://pbs.twimg.com/profile_images/964072513679581184/4YV1Q0mR_400x400.jpg");
logos.put("the-times-of-india", "https://pbs.twimg.com/profile_images/651768664056696832/xht4j-S5_400x400.jpg");
logos.put("the-verge", "https://pbs.twimg.com/profile_images/877903823133704194/Mqp1PXU8_400x400.jpg");
logos.put("the-wall-street-journal", "https://pbs.twimg.com/profile_images/971415515754266624/zCX0q9d5_400x400.jpg");
logos.put("the-washington-post", "https://pbs.twimg.com/profile_images/875440182501277696/n-Ic9nBO_400x400.jpg");
logos.put("time", "https://pbs.twimg.com/profile_images/1700796190/Picture_24_400x400.png");
logos.put("wired-de", "https://pbs.twimg.com/profile_images/615598832726970372/jsK-gBSt_400x400.png");
logos.put("wirtschafts-woche", "https://pbs.twimg.com/profile_images/596378323128836096/23C3DVmy_400x400.jpg");
logos.put("jornal-de-angola", "https://pbs.twimg.com/profile_images/894282213495382017/W7pj7SsU_400x400.jpg");
logos.put("bild", "https://pbs.twimg.com/profile_images/916254721274515458/72vChEJI_400x400.jpg");
logos.put("usa-today", "https://pbs.twimg.com/profile_images/924991591642796032/v90LrlR__400x400.jpg");
logos.put("the-telegraph", "https://pbs.twimg.com/profile_images/704632088541134848/ypoRmbv__400x400.jpg");
logos.put("fox-sports", "https://pbs.twimg.com/profile_images/824007776489738241/pFk_8LLO_400x400.jpg");
logos.put("espn-cric-info", "https://pbs.twimg.com/profile_images/888015358958940165/SmaHw6Rj_400x400.jpg");
logos.put("new-scientist", "https://pbs.twimg.com/profile_images/960860144329469953/Tc-GOIGJ_400x400.jpg");
logos.put("the-buggle", "http://thebugle.co.za/images/ui/ban.png");
logos.put("iol-news-za", "https://pbs.twimg.com/profile_images/941569804137385989/m_1r5MV6_400x400.jpg");
logos.put("a-nacao", "http://anacao.cv/wp-content/uploads/2014/10/Logo-A-Na%C3%A7%C3%A3o-300x102.png");
logos.put("tela-non", "https://pbs.twimg.com/profile_images/458228724802928641/ZNA1IeUv_400x400.png");
logos.put("diario-de-noticias-pt", "https://pbs.twimg.com/profile_images/1618752141/dn_avatar_400x400.jpg");
logos.put("angop", "https://pbs.twimg.com/profile_images/2548591418/portal5_400x400.jpg");
logos.put("angonoticias", "https://pbs.twimg.com/profile_images/1553392423/angonoticias_og_400x400.jpg");
logos.put("folha8", "https://pbs.twimg.com/profile_images/465810431387246594/aTgnnt5H_400x400.png");
logos.put("novo-jornal", "https://pbs.twimg.com/profile_images/378800000249630847/8c676e9beb38644915c92e904050145a_400x400.jpeg");
logos.put("correio-angolense", "https://pbs.twimg.com/profile_images/854810761859936257/_FmCY3RJ_400x400.jpg");
logos.put("axios", "https://pbs.twimg.com/profile_images/920371293802733568/ZewRXgpe_400x400.jpg");
logos.put("xinhua-net", "https://pbs.twimg.com/profile_images/417488690714120192/_i50eUX3_400x400.jpeg");
logos.put("ynet", "https://pbs.twimg.com/profile_images/1679844840/logo_400x400.jpg");
logos.put("abc-news", "https://pbs.twimg.com/profile_images/877547979363758080/ny06RNTT_400x400.jpg");
logos.put("aftenposten", "https://pbs.twimg.com/profile_images/529260466657169408/o_fYiMaZ_400x400.jpeg");
logos.put("ansa", "https://pbs.twimg.com/profile_images/563351169460752384/VK18pD2I_400x400.png");
logos.put("argaam", "https://pbs.twimg.com/profile_images/867613052925071360/tpHot1zu_400x400.jpg");
logos.put("ary-news", "https://pbs.twimg.com/profile_images/914757678462881792/5Xng-KWa_400x400.jpg");
logos.put("australian-financial-review", "https://pbs.twimg.com/profile_images/818701236086018050/SlypZOjt_400x400.jpg");
logos.put("blasting-news-br", "https://pbs.twimg.com/profile_images/874179276874166272/055eiNEY_400x400.jpg");
logos.put("bleacher-report", "https://pbs.twimg.com/profile_images/854430488777379840/zFdLhwbT_400x400.jpg");
logos.put("cbc-news", "https://pbs.twimg.com/profile_images/957919598749323264/NuYdCE6a_400x400.jpg");
logos.put("cbs-news", "https://pbs.twimg.com/profile_images/645966750941626368/d0Q4voGK_400x400.jpg");
logos.put("cnn-es", "https://pbs.twimg.com/profile_images/589795319216504832/6a71ZHkx_400x400.jpg");
logos.put("crypto-coins-news", "https://pbs.twimg.com/profile_images/942304759561768960/Gel04P4M_400x400.jpg");
logos.put("el-mundo", "https://pbs.twimg.com/profile_images/959947259780747265/ez18J78k_400x400.jpg");
logos.put("financial-post", "https://pbs.twimg.com/profile_images/877097420882034689/MTfB8m72_400x400.jpg");
logos.put("fox-news", "https://pbs.twimg.com/profile_images/918480715158716419/4X8oCbge_400x400.jpg");
logos.put("globo", "https://pbs.twimg.com/profile_images/936279870488895488/15t1ZHho_400x400.jpg");
logos.put("google-news-ar", "https://pbs.twimg.com/profile_images/993911709357162496/NWRtL2J__400x400.jpg");
logos.put("google-news-au", "https://pbs.twimg.com/profile_images/993911709357162496/NWRtL2J__400x400.jpg");
logos.put("google-news-br", "https://pbs.twimg.com/profile_images/993911709357162496/NWRtL2J__400x400.jpg");
logos.put("google-news-ca", "https://pbs.twimg.com/profile_images/993911709357162496/NWRtL2J__400x400.jpg");
logos.put("google-news-fr", "https://pbs.twimg.com/profile_images/993911709357162496/NWRtL2J__400x400.jpg");
logos.put("google-news-in", "https://pbs.twimg.com/profile_images/993911709357162496/NWRtL2J__400x400.jpg");
logos.put("google-news-is", "https://pbs.twimg.com/profile_images/993911709357162496/NWRtL2J__400x400.jpg");
logos.put("google-news-it", "https://pbs.twimg.com/profile_images/993911709357162496/NWRtL2J__400x400.jpg");
logos.put("google-news-ru", "https://pbs.twimg.com/profile_images/993911709357162496/NWRtL2J__400x400.jpg");
logos.put("google-news-sa", "https://pbs.twimg.com/profile_images/993911709357162496/NWRtL2J__400x400.jpg");
logos.put("google-news-uk", "https://pbs.twimg.com/profile_images/993911709357162496/NWRtL2J__400x400.jpg");
logos.put("il-sole-24-ore", "https://pbs.twimg.com/profile_images/907573891240996864/Dt0vL4al_400x400.jpg");
logos.put("info-money", "https://pbs.twimg.com/profile_images/2626842133/mf2dqgt82kcknejy7scv_400x400.jpeg");
logos.put("infobae", "https://pbs.twimg.com/profile_images/989843885131206657/yvuwyAhg_400x400.jpg");
logos.put("la-gaceta", "https://pbs.twimg.com/profile_images/890208177580593152/SQpRuBm8_400x400.jpg");
logos.put("la-nacion", "https://pbs.twimg.com/profile_images/644564299948625921/ddfxyyqL_400x400.png");
logos.put("la-repubblica", "https://pbs.twimg.com/profile_images/559420141771829248/9sDOqcXf_400x400.png");
logos.put("le-monde", "https://pbs.twimg.com/profile_images/817042499134980096/LTpqSDMM_400x400.jpg");
logos.put("lenta", "https://pbs.twimg.com/profile_images/980506493475844101/-0h-6rWZ_400x400.jpg");
logos.put("lequipe", "https://pbs.twimg.com/profile_images/755312541363036160/fq4d1WN3_400x400.jpg");
logos.put("les-echos", "https://pbs.twimg.com/profile_images/917735975119441920/Otcve69W_400x400.jpg");
logos.put("liberation", "https://pbs.twimg.com/profile_images/854315131395878912/jZceoVi9_400x400.jpg");
logos.put("marca", "https://pbs.twimg.com/profile_images/921140653270208513/3_3K2tJn_400x400.jpg");
logos.put("medical-news-today", "https://pbs.twimg.com/profile_images/846771226483671040/Q352DFzt_400x400.jpg");
logos.put("msnbc", "https://pbs.twimg.com/profile_images/988382060443250689/DijesdNB_400x400.jpg");
logos.put("national-review", "https://pbs.twimg.com/profile_images/471722478822100992/slV_OilN_400x400.jpeg");
logos.put("nbc-news", "https://pbs.twimg.com/profile_images/875411730679173121/l9PSFLJb_400x400.jpg");
logos.put("news-com-au", "https://pbs.twimg.com/profile_images/629244933057032192/zJsuwh_O_400x400.png");
logos.put("news24", "https://pbs.twimg.com/profile_images/875715923793072128/rLqRwylP_400x400.jpg");
logos.put("next-big-future", "https://www.nextbigfuture.com/wp-content/uploads/2017/04/1761eac3b1967fa6e4cafb6af110abcc.png?x71037");
logos.put("nhl-news", "https://pbs.twimg.com/profile_images/136366459/bwpic_400x400.JPG");
logos.put("nrk", "https://pbs.twimg.com/profile_images/687276797776510984/i-qUX8GW_400x400.png");
logos.put("politico", "https://pbs.twimg.com/profile_images/677177503694237697/y6yTzWn6_400x400.png");
logos.put("rbc", "https://pbs.twimg.com/profile_images/1058357925/rbc_400x400.jpg");
logos.put("rt", "https://pbs.twimg.com/profile_images/875388705258831872/H4_uLagc_400x400.jpg");
logos.put("rte", "https://pbs.twimg.com/profile_images/950690125780078592/mjXCvHGQ_400x400.jpg");
logos.put("rtl-nieuws", "https://pbs.twimg.com/profile_images/948470929163800576/8yYXeZbK_400x400.jpg");
logos.put("sabq", "https://pbs.twimg.com/profile_images/548154985884561408/C2ne5SdF_400x400.jpeg");
logos.put("svenska-dagbladet", "https://pbs.twimg.com/profile_images/847728246619725826/jeEROkK-_400x400.jpg");
logos.put("techcrunch-cn", "https://pbs.twimg.com/profile_images/969240943671955456/mGuud28F_400x400.jpg");
logos.put("the-american-conservative", "https://pbs.twimg.com/profile_images/668879829983326208/JXrxthUA_400x400.jpg");
logos.put("the-globe-and-mail", "https://pbs.twimg.com/profile_images/742385672682512384/VfTAuqLg_400x400.jpg");
logos.put("the-hill", "https://pbs.twimg.com/profile_images/907330975587336193/tw7JPE5v_400x400.jpg");
logos.put("the-irish-times", "https://pbs.twimg.com/profile_images/2944517635/5492cf569e6b0b1a9326a7d388009b60_400x400.png");
logos.put("the-washington-times", "https://pbs.twimg.com/profile_images/880048880292941826/99fsdFko_400x400.jpg");
logos.put("vice-news", "https://pbs.twimg.com/profile_images/785208513177985024/Guc3ohmz_400x400.jpg");
logos.put("wired", "https://pbs.twimg.com/profile_images/615598832726970372/jsK-gBSt_400x400.png");
}
public static String getLogo(String sourceId) {
if (sourceId == null) {
return null;
}
if (sourceId.startsWith("global-voices")) {
return logos.get("global-voices");
}
return logos.get(sourceId);
}
public static Map<String, String> getLogos() {
return logos;
}
}
|
package pl.weakpoint.library.service;
import java.util.List;
import java.util.Optional;
import pl.weakpoint.library.model.Author;
public interface AuthorService {
List<Author> getAllAuthors();
Optional<Author> getAuthorById(String id);
}
|
public class NarrowPassage2Easy {
private int[] size;
private int maxSizeSum;
public int count(int[] size, int maxSizeSum) {
this.size = size;
this.maxSizeSum = maxSizeSum;
int[] perm = new int[size.length];
boolean[] used = new boolean[size.length];
int result = 0;
for(int i = 0; i < used.length; ++i) {
used[i] = true;
perm[0] = i;
result += count(perm, used, 1);
used[i] = false;
}
return result;
}
private int count(int[] perm, boolean[] used, int index) {
if(index == size.length) {
for(int i = 0; i < perm.length; ++i) {
for(int j = 0; j < i; ++j) {
if(perm[i] < perm[j] && maxSizeSum < size[perm[i]] + size[perm[j]]) {
return 0;
}
}
for(int j = i + 1; j < size.length; ++j) {
if(perm[j] < perm[i] && maxSizeSum < size[perm[i]] + size[perm[j]]) {
return 0;
}
}
}
return 1;
}
int result = 0;
for(int i = 0; i < used.length; ++i) {
if(!used[i]) {
used[i] = true;
perm[index] = i;
result += count(perm, used, index + 1);
used[i] = false;
}
}
return result;
}
}
|
package formation.formation.service.rest;
import formation.classTmp.ReponseMoyenne;
import formation.domain.Question;
import formation.domain.Reponse;
import formation.formation.service.itf.ReponseItf;
import formation.persistence.question.QuestionDAOItf;
import formation.persistence.reponse.ReponseDAOItf;
import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.net.URI;
import java.util.List;
/**
* Created by victor on 12/12/2015.
*/
@Path("/reponse")
@Produces({MediaType.APPLICATION_JSON})
@Consumes({MediaType.APPLICATION_JSON})
@Stateless
public class ReponseRestService {
@EJB
ReponseItf service;
@EJB
QuestionDAOItf questionDAOItf;
@EJB
ReponseDAOItf reponseDAOItf;
@GET
@Path("/{id}")
public Response get(@PathParam("id")Long id){
Reponse r = service.get(id);
if(r == null){
throw new NotFoundException("Reponse is not found");
}
return Response.ok(r).build();
}
@POST
public Response create(Reponse reponse) throws Exception{
Reponse r = service.create(reponse);
return Response.created(new URI("reponse/"+r.getIdReponse())).build();
}
@GET
@Path("/moyenne/{id}")
public Response getMoyenne(@PathParam("id") @DefaultValue("0")int id){
List<Question> listQ = null;
Question question = null;
if(id == 0) {
listQ = questionDAOItf.findAll();
if(listQ == null || listQ.isEmpty()){
throw new NotFoundException("Question is not found");
}
question = listQ.get(0);
}else{
question = questionDAOItf.find(id);
}
if(question == null ){
throw new NotFoundException("Question is not found");
}
List<Reponse> reponses = reponseDAOItf.findByQuestion(question.getIdQuestion());
//if(reponses == null || reponses.isEmpty()){
// throw new NotFoundException("Reponse is not found");
//}
//System.out.println("taille: "+reponses.size());
ReponseMoyenne rspm = new ReponseMoyenne();
rspm.setLibelleQuestion(question.getLibelle());
for(Reponse resp : reponses){
//System.out.println(resp.getReponse());
if(resp.getReponse().equals("Non")){
rspm.setNbNon(rspm.getNbNon()+1);
}else{
rspm.setNbOui(rspm.getNbOui()+1);
}
}
//return Response.ok(rspm).getHeaders().add("Access-Control-Allow-Origin", "*").build();
return Response
.ok(rspm)
.header("Access-Control-Allow-Origin", "*")
.header("Access-Control-Allow-Headers", "origin, content-type, accept, authorization")
.header("Access-Control-Allow-Credentials", "true")
.header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS, HEAD")
.header("Access-Control-Max-Age", "1209600")
.build();
}
}
|
import gov.nih.mipav.plugins.PlugInGeneric;
import gov.nih.mipav.model.file.*;
import gov.nih.mipav.model.structures.ModelImage;
import gov.nih.mipav.view.*;
import java.io.File;
import java.util.*;
import javax.swing.JFileChooser;
public class PlugInDicom2Conversion implements PlugInGeneric {
public PlugInDicom2Conversion() {}
public void run() {
final ArrayList<Vector<String>> openImagesArrayList = openImage();
if (openImagesArrayList != null) {
for (int i = 0; i < openImagesArrayList.size(); i++) {
final Vector<String> openImageNames = openImagesArrayList.get(i);
// if open failed, then imageNames will be null
if (openImageNames == null) {
return;
}
for (final String imgName : openImageNames) {
final ModelImage img = ViewUserInterface.getReference().getRegisteredImageByName(imgName);
final FileInfoBase[] fInfos = img.getFileInfo();
for (final FileInfoBase fInfo : fInfos) {
if (fInfo instanceof FileInfoDicom) {
((FileInfoDicom) fInfo).containsDICM = true;
}
}
saveImage(img);
}
}
}
}
private ArrayList<Vector<String>> openImage() {
final ViewOpenFileUI openFile = new ViewOpenFileUI(true);
final boolean stackFlag = true;
// set the filter type to the preferences saved filter
int filter = ViewImageFileFilter.TECH;
try {
filter = Integer.parseInt(Preferences.getProperty(Preferences.PREF_FILENAME_FILTER));
} catch (final NumberFormatException nfe) {
// an invalid value was set in preferences -- so fix it!
filter = ViewImageFileFilter.TECH;
Preferences.setProperty(Preferences.PREF_FILENAME_FILTER, Integer.toString(filter));
}
openFile.setFilterType(filter);
return openFile.open(stackFlag);
}
private void saveImage(final ModelImage img) {
final FileWriteOptions options = new FileWriteOptions(true);
int filterType = -1;
String fileName = null;
String extension = null;
String directory = null;
String suffix = null;
int fileType = FileUtility.UNDEFINED;
ViewImageFileFilter vFilter = null;
int i;
// save into its own subdirectory when on SaveAs.
// (preferrably used in multi-file formats., ie DICOM)
options.setSaveInSubdirectory(true);
if (options.isSet()) {
fileName = options.getFileName();
directory = options.getFileDirectory();
} else {
try {
final ViewFileChooserBase fileChooser = new ViewFileChooserBase(true, true);
try {
// try to prefill the "save as" text area
if (img.getFileInfo(0).getFileDirectory() != null) {
fileChooser.getFileChooser().setSelectedFile(
new File(img.getFileInfo(0).getFileDirectory() + img.getImageFileName()));
} else {
fileChooser.getFileChooser().setSelectedFile(new File(img.getImageFileName()));
}
} catch (final Throwable t) {
// if prefill fails, do nothing
}
final JFileChooser chooser = fileChooser.getFileChooser();
// chooser.setName("Save image as");
if (ViewUserInterface.getReference().getDefaultDirectory() != null) {
chooser.setCurrentDirectory(new File(ViewUserInterface.getReference().getDefaultDirectory()));
} else {
chooser.setCurrentDirectory(new File(System.getProperties().getProperty("user.dir")));
}
if (filterType >= 0) {
chooser.addChoosableFileFilter(new ViewImageFileFilter(filterType));
} else {
chooser.addChoosableFileFilter(new ViewImageFileFilter(ViewImageFileFilter.GEN));
chooser.addChoosableFileFilter(new ViewImageFileFilter(ViewImageFileFilter.TECH));
}
final int returnVal = chooser.showSaveDialog(img.getParentFrame());
if (returnVal == JFileChooser.APPROVE_OPTION) {
fileName = chooser.getSelectedFile().getName();
if (filterType >= 0) {
i = fileName.lastIndexOf('.');
if ( (i > 0) && (i < (fileName.length() - 1))) {
extension = fileName.substring(i + 1).toLowerCase();
vFilter = new ViewImageFileFilter(filterType);
if ( !vFilter.accept(extension)) {
MipavUtil.displayError("Extension does not match filter type");
return;
}
} // if ( i > 0 && i < fileName.length() - 1 )
else if (i < 0) {
switch (filterType) {
case ViewImageFileFilter.AVI:
fileName = fileName + ".avi";
break;
case ViewImageFileFilter.VOI:
fileName = fileName + ".voi";
break;
case ViewImageFileFilter.FUNCT:
fileName = fileName + ".fun";
break;
case ViewImageFileFilter.LUT:
fileName = fileName + ".lut";
break;
case ViewImageFileFilter.PLOT:
fileName = fileName + ".plt";
break;
case ViewImageFileFilter.CLASS:
fileName = fileName + ".class";
break;
case ViewImageFileFilter.SCRIPT:
fileName = fileName + ".sct";
break;
case ViewImageFileFilter.SURFACE:
fileName = fileName + ".sur";
break;
case ViewImageFileFilter.FREESURFER:
fileName = fileName + ".asc";
break;
}
} // else if (i < 0)
} // if (filterType >= 0)
directory = String.valueOf(chooser.getCurrentDirectory()) + File.separatorChar;
ViewUserInterface.getReference().setDefaultDirectory(directory);
} else {
return;
}
} catch (final OutOfMemoryError error) {
MipavUtil.displayError("Out of memory: ViewJFrameBase.save");
Preferences.debug("Out of memory: ViewJFrameBase.save\n", Preferences.DEBUG_COMMS);
return;
}
}
/*
* I'm not sure why this wasn't done before.... if we do a save-as we should also update the name of the file
*/
// if (options.isSaveAs()) {
// img.setImageName(fileName.substring(0, fileName.length()-4));
// }
options.setFileName(fileName);
options.setFileDirectory(directory);
if (fileName != null) {
final FileIO fileIO = new FileIO();
fileIO.writeImage(img, options);
}
// set the new fileName and directory in the fileInfo for the img -- so that it's
// updated correctly in memory as well -- don't move this before the saveAllOnSave loop --
// that needs to look at the former settings!
final FileInfoBase[] fileInfo = img.getFileInfo();
if (suffix == null) {
suffix = FileUtility.getExtension(fileName);
if (suffix.equals("")) {
fileName = options.getFileName();
suffix = FileUtility.getExtension(fileName);
}
boolean zerofunused[] = new boolean[1];
fileType = FileUtility.getFileType(fileName, directory, false, false, zerofunused);
}
// now, get rid of any numbers at the end of the name (these
// are part of the dicom file name, but we only want the 'base'
// part of the name
String baseName = new String(fileName);
if (fileType == FileUtility.DICOM) {
final int index = fileName.lastIndexOf(".");
if (index > 0) {
baseName = fileName.substring(0, index);
}
int newIndex = baseName.length();
for (i = baseName.length() - 1; i >= 0; i--) {
final char myChar = baseName.charAt(i);
if (Character.isDigit(myChar)) {
newIndex = i;
} else {
break;
} // as soon as something is NOT a digit, leave loop
}
if (newIndex > 0) {
baseName = baseName.substring(0, newIndex);
}
fileName = new String(baseName + ".dcm");
if ( !directory.endsWith(baseName)) {
directory = new String(directory + baseName + File.separator);
}
}
for (i = 0; i < fileInfo.length; i++) {
fileInfo[i].setFileDirectory(directory);
if (fileType == FileUtility.DICOM) {
fileInfo[i].setFileName(baseName + (i + 1) + ".dcm");
} else {
fileInfo[i].setFileName(fileName);
}
fileInfo[i].setFileSuffix(suffix);
// fileInfo[i].setFileFormat (fileType);
}
}
}
|
/*
* (C) Copyright 2006-2012 Nuxeo SA (http://nuxeo.com/) and others.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Lesser General Public License
* (LGPL) version 2.1 which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/lgpl-2.1.html
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* Contributors:
* Thomas Roger <troger@nuxeo.com>
*/
package org.nuxeo.training.operations;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.nuxeo.ecm.automation.AutomationService;
import org.nuxeo.ecm.automation.OperationChain;
import org.nuxeo.ecm.automation.OperationContext;
import org.nuxeo.ecm.core.api.ClientException;
import org.nuxeo.ecm.core.api.CoreSession;
import org.nuxeo.ecm.core.api.DocumentModel;
import org.nuxeo.ecm.core.test.CoreFeature;
import org.nuxeo.runtime.test.runner.Deploy;
import org.nuxeo.runtime.test.runner.Features;
import org.nuxeo.runtime.test.runner.FeaturesRunner;
import org.nuxeo.runtime.test.runner.LocalDeploy;
import com.google.inject.Inject;
/**
* @author <a href="mailto:troger@nuxeo.com">Thomas Roger</a>
* @since 5.6
*/
@RunWith(FeaturesRunner.class)
@Features(CoreFeature.class)
@Deploy({ "org.nuxeo.ecm.automation.core", "org.nuxeo.ecm.automation.features",
"studio.extensions.ataillefer-SANDBOX", "nuxeo-dev-training" })
@LocalDeploy("nuxeo-dev-training:test-valid-lifecyclestates-contrib.xml")
public class TestOperations {
@Inject
protected CoreSession session;
@Inject
protected AutomationService automationService;
protected DocumentModel archiveFolder;
protected DocumentModel contrat1;
protected DocumentModel contrat2;
@Before
public void initTest() throws ClientException {
archiveFolder = session.createDocument(session.createDocumentModel("/",
"archives", "Folder"));
contrat1 = session.createDocument(session.createDocumentModel("/",
"contrat1", "Contrat"));
contrat2 = session.createDocument(session.createDocumentModel("/",
"contrat2", "Contrat"));
}
@Test
public void testOperation() throws Exception {
contrat2.followTransition("toActif");
contrat2.followTransition("toClosed");
session.save();
OperationContext ctx = new OperationContext(session);
assertNotNull(ctx);
OperationChain chain = new OperationChain("testArchiveContracts");
ctx.setInput(contrat1);
String archiveFolderPath = archiveFolder.getPathAsString();
chain.add(TrainingLifecycleOperation.ID).set("archivePath",
archiveFolderPath);
DocumentModel result = (DocumentModel) automationService.run(ctx, chain);
assertNotNull(result);
assertEquals("/archives/contrat1", result.getPathAsString());
ctx.setInput(contrat2);
chain.add(TrainingLifecycleOperation.ID).set("archivePath",
archiveFolderPath);
result = (DocumentModel) automationService.run(ctx, chain);
assertNotNull(result);
assertEquals("/contrat2", result.getPathAsString());
}
}
|
package GCC;
public class Match
{
public Player player1;
public Player player2;
private String lastMove = "null";
private int counter = 0;
private int[][] matrix = new int[8][8];
public Match(Player p1, Player p2)
{
this.player1 = p1;
this.player2 = p2;
player1.notifyMatch(this);
player2.notifyMatch(this);
}
public boolean checkWinner(Player p, int x, int y)
{
//VERTICALE
int tmp = 0;
for (int i = 0; i < 4; i++)
{
if (x+i > 7)
break;
if (matrix[x][y] != matrix[x+i][y])
break;
tmp++;
}
for (int i = 1; i < 4; i++)
{
if (x-i < 0)
break;
if (matrix[x][y] != matrix[x-i][y])
break;
tmp++;
}
if (tmp >= 4)
return true;
//ORIZZONTALE
tmp = 0;
for (int i = 0; i < 4; i++)
{
if (y+i > 7)
break;
if (matrix[x][y] != matrix[x][y+i])
break;
tmp++;
}
for (int i = 1; i < 4; i++)
{
if (y-i < 0)
break;
if (matrix[x][y] != matrix[x][y-i])
break;
tmp++;
}
if (tmp >= 4)
return true;
//OBLIQUA 1
tmp = 0;
for (int i = 0; i < 4; i++)
{
if (y+i > 7 || x+i > 7)
break;
if (matrix[x][y] != matrix[x+i][y+i])
break;
tmp++;
}
for (int i = 1; i < 4; i++)
{
if (y-i < 0 || x-i < 0)
break;
if (matrix[x][y] != matrix[x-i][y-i])
break;
tmp++;
}
if (tmp >= 4)
return true;
//OBLIQUA 1
tmp = 0;
for (int i = 0; i < 4; i++)
{
if (y+i > 7 || x-i < 0)
break;
if (matrix[x][y] != matrix[x-i][y+i])
break;
tmp++;
}
for (int i = 1; i < 4; i++)
{
if (y-i < 0 || x+i > 7)
break;
if (matrix[x][y] != matrix[x+i][y-i])
break;
tmp++;
}
if (tmp >= 4)
{
return true;
}
return false;
}
public void markTable(int x, int y, Player player)
{
matrix[x][y] = (player==player1)?1:2;
getOpponent(player).getWriter().println(getOpponent(player).gcp.messageComposer(GCP.Codes.move, x+GCP.DELIMITER+y));
if (checkWinner(player, x, y))
{
player1.getWriter().println(player1.gcp.messageComposer(GCP.Codes.match_over, player.getUsername()));
player2.getWriter().println(player2.gcp.messageComposer(GCP.Codes.match_over, player.getUsername()));
Main.appendDebugText(player.getUsername() + " won!");
player1.setMatch(null);
}
}
public Player getOpponent(Player p)
{
return (p==player1)?player2:player1;
}
}
|
/*
* Copyright 2002-2023 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.jca.endpoint;
import javax.transaction.xa.XAResource;
import jakarta.resource.ResourceException;
import jakarta.resource.spi.UnavailableException;
import jakarta.resource.spi.endpoint.MessageEndpoint;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.springframework.aop.framework.ProxyFactory;
import org.springframework.aop.support.DelegatingIntroductionInterceptor;
import org.springframework.lang.Nullable;
import org.springframework.util.Assert;
import org.springframework.util.ReflectionUtils;
/**
* Generic implementation of the JCA 1.7
* {@link jakarta.resource.spi.endpoint.MessageEndpointFactory} interface,
* providing transaction management capabilities for any kind of message
* listener object (e.g. {@link jakarta.jms.MessageListener} objects or
* {@link jakarta.resource.cci.MessageListener} objects).
*
* <p>Uses AOP proxies for concrete endpoint instances, simply wrapping
* the specified message listener object and exposing all of its implemented
* interfaces on the endpoint instance.
*
* <p>Typically used with Spring's {@link GenericMessageEndpointManager},
* but not tied to it. As a consequence, this endpoint factory could
* also be used with programmatic endpoint management on a native
* {@link jakarta.resource.spi.ResourceAdapter} instance.
*
* @author Juergen Hoeller
* @since 2.5
* @see #setMessageListener
* @see #setTransactionManager
* @see GenericMessageEndpointManager
*/
public class GenericMessageEndpointFactory extends AbstractMessageEndpointFactory {
@Nullable
private Object messageListener;
/**
* Specify the message listener object that the endpoint should expose
* (e.g. a {@link jakarta.jms.MessageListener} objects or
* {@link jakarta.resource.cci.MessageListener} implementation).
*/
public void setMessageListener(Object messageListener) {
this.messageListener = messageListener;
}
/**
* Return the message listener object for this endpoint.
* @since 5.0
*/
protected Object getMessageListener() {
Assert.state(this.messageListener != null, "No message listener set");
return this.messageListener;
}
/**
* Wrap each concrete endpoint instance with an AOP proxy,
* exposing the message listener's interfaces as well as the
* endpoint SPI through an AOP introduction.
*/
@Override
public MessageEndpoint createEndpoint(XAResource xaResource) throws UnavailableException {
GenericMessageEndpoint endpoint = (GenericMessageEndpoint) super.createEndpoint(xaResource);
Object target = getMessageListener();
ProxyFactory proxyFactory = new ProxyFactory(target);
DelegatingIntroductionInterceptor introduction = new DelegatingIntroductionInterceptor(endpoint);
introduction.suppressInterface(MethodInterceptor.class);
proxyFactory.addAdvice(introduction);
return (MessageEndpoint) proxyFactory.getProxy(target.getClass().getClassLoader());
}
/**
* Creates a concrete generic message endpoint, internal to this factory.
*/
@Override
protected AbstractMessageEndpoint createEndpointInternal() throws UnavailableException {
return new GenericMessageEndpoint();
}
/**
* Private inner class that implements the concrete generic message endpoint,
* as an AOP Alliance MethodInterceptor that will be invoked by a proxy.
*/
private class GenericMessageEndpoint extends AbstractMessageEndpoint implements MethodInterceptor {
@Override
@Nullable
public Object invoke(MethodInvocation methodInvocation) throws Throwable {
Throwable endpointEx = null;
boolean applyDeliveryCalls = !hasBeforeDeliveryBeenCalled();
if (applyDeliveryCalls) {
try {
beforeDelivery(null);
}
catch (ResourceException ex) {
throw adaptExceptionIfNecessary(methodInvocation, ex);
}
}
try {
return methodInvocation.proceed();
}
catch (Throwable ex) {
endpointEx = ex;
onEndpointException(ex);
throw ex;
}
finally {
if (applyDeliveryCalls) {
try {
afterDelivery();
}
catch (ResourceException ex) {
if (endpointEx == null) {
throw adaptExceptionIfNecessary(methodInvocation, ex);
}
}
}
}
}
private Exception adaptExceptionIfNecessary(MethodInvocation methodInvocation, ResourceException ex) {
if (ReflectionUtils.declaresException(methodInvocation.getMethod(), ex.getClass())) {
return ex;
}
else {
return new InternalResourceException(ex);
}
}
@Override
protected ClassLoader getEndpointClassLoader() {
return getMessageListener().getClass().getClassLoader();
}
}
/**
* Internal exception thrown when a ResourceException has been encountered
* during the endpoint invocation.
* <p>Will only be used if the ResourceAdapter does not invoke the
* endpoint's {@code beforeDelivery} and {@code afterDelivery}
* directly, leaving it up to the concrete endpoint to apply those -
* and to handle any ResourceExceptions thrown from them.
*/
@SuppressWarnings("serial")
public static class InternalResourceException extends RuntimeException {
public InternalResourceException(ResourceException cause) {
super(cause);
}
}
}
|
package modelo;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import javax.swing.JOptionPane;
import Controlador.ConexionBD;
public class tableUsuarioDAO {
ConexionBD con = new ConexionBD();
Connection cnn = con.conexionbd();
PreparedStatement ps;
ResultSet rs;
tableUsuarioDto dat = null;
// INSERTAR
public boolean insertarUsuario(tableUsuarioDto Us) {
int r;
boolean dat = false;
try {
ps = cnn.prepareStatement("INSERT INTO usuario values(?,?,?,?,?)");
ps.setLong(1, Us.getCedula_usuario());
ps.setString(2, Us.getNombre_usuario());
ps.setString(3, Us.getEmail_usuario());
ps.setString(4, Us.getUsuario());
ps.setString(5, Us.getPassword());
r = ps.executeUpdate();
if (r > 0) {
dat = true;
}
} catch (SQLException e) {
e.printStackTrace();
}
return dat;
}
// CONSULTAR
public tableUsuarioDto consultar(tableUsuarioDto User) {
JOptionPane.showMessageDialog(null, User.getCedula_usuario());
ResultSet rs;
tableUsuarioDto dat = null;
try {
ps = cnn.prepareStatement("SELECT * FROM usuario WHERE cedula_usuario=?");
ps.setLong(1, User.getCedula_usuario());
rs = ps.executeQuery();
if (rs.next()) {
dat = new tableUsuarioDto(rs.getLong(1), rs.getString(2), rs.getString(3), rs.getString(4),
rs.getString(5));
}
} catch (SQLException e) {
e.printStackTrace();
}
return dat;
}
//ACTUALIZAR
public int actualizar(tableUsuarioDto usuarios) {
int x = 0;
try {
ps = cnn.prepareStatement(
"UPDATE usuario SET nombre_usuario=?, email_usuario=?, usuario=?, password=? WHERE cedula_usuario=?");
ps.setString(1, usuarios.getNombre_usuario());
ps.setString(2, usuarios.getEmail_usuario());
ps.setString(3, usuarios.getUsuario());
ps.setString(4, usuarios.getPassword());
ps.setLong(5, usuarios.getCedula_usuario());
x = ps.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
return x;
}
//ELIMINAR
public int eliminar(tableUsuarioDto usuarios) {
int x = 0;
try {
ps = cnn.prepareStatement("DELETE FROM usuario WHERE cedula_usuario=?");
ps.setLong(1, usuarios.getCedula_usuario());
x = ps.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
return x;
}
//Consulta "masiva"
public ArrayList<tableUsuarioDto> consultaMasiva(){
ArrayList<tableUsuarioDto>consultaUsuarios=new ArrayList<tableUsuarioDto>();
try {
ps=cnn.prepareStatement("SELECT * FROM usuarios");
rs=ps.executeQuery();
while(rs.next()) {
dat=new tableUsuarioDto(rs.getLong(1), rs.getString(2), rs.getString(3), rs.getString(4), rs.getString(5));
consultaUsuarios.add(dat);
}
} catch (SQLException e) {
// TODO: handle exception
e.printStackTrace();
}
return consultaUsuarios;
}
}
|
package message;
import com.google.gson.internal.StringMap;
import java.lang.reflect.Field;
import java.util.Iterator;
import java.util.Map;
public class ChatContent {
private String account;
public String getAccount() {
return account;
}
public void setAccount(String account) {
this.account = account;
}
public ChatContent(String account, String message) {
this.account = account;
this.message = message;
}
private String message;
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public ChatContent(String message) {
this.message = message;
}
public String toString()
{return message;}
}
|
/**
* ThinkJava C9E1
* @author Victor Lourng
* @version 2016
*/
// import com.google.guava;
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
// # Execise 1 (see getType method below)
// 1. I created a getType method to determine the type of the result.
getType("hello world" + '!'); // concat String
getType("hello world" + 2); // concat String
getType("hello world" + 2.96); // concat String
getType("hello world" + 'a'); // concat String
getType("hello world" + 0202 + "hi"); // concat String
getType("hello world" + 2 + 6 + 8.01 + "hello" + 5); // concat String
getType("hello world" + (2 + 6) + 8.01 + "hello" + 5); // concat and add String
getType(1 + 1.0); // add double
// 2.
// | | boolean | char | int | double | String |
// |---------|---------------|---------------|---------------|---------------|---------------|
// | boolean | illegal | illegal | illegal | illegal | concat String |
// | char | illegal | add int | add int | add double | concat String |
// | int | illegal | add int | add int | add double | concat String |
// | double | illegal | add double | add double | add double | concat String |
// | String | concat String | concat String | concat String | concat String | concat String |
// getType(true + true);
// getType(true + 'c');
// getType(true + 1);
// getType(true + 3.5);
getType(true + "hello");
// getType('c' + true);
getType('c' + 'c');
getType('c' + 1);
getType('c' + 3.5);
getType('c' + "hello");
// getType(1 + true);
getType(1 + 'c');
getType(1 + 1);
getType(1 + 3.5);
getType(1 + "hello");
// getType(3.5 + true);
getType(3.5 + 'c');
getType(3.5 + 1);
getType(3.5 + 3.5);
getType(3.5 + "hello");
getType("hello" + true);
getType("hello" + 'c');
getType("hello" + 1);
getType("hello" + 3.5);
getType("hello" + "hello");
// 3. As a programmer, all of these make sense to me.
//
// The choice to not make booleans addable (except for strings) seems pretty unavoidable.
// I also felt like the choice to allow any type of data to be added to (and converted
// into) Strings seems intentional, to make programming much easier because there are
// any common use cases for this.
//
// What may be confusing for beginners is how understanding char works - it
// stores an ASCII integer value that corresponds to a specific character. Therefore
// that is why it can be added into ints or doubles. It can also be said that the way
// data is stored char is stored is to prevent redundancy with String.
// 4. x++ is valid because you are incrementing the ascii integer value stored inside the char.
// When you add and int to a char, however, the result is an int and by default it cannot be
// stored back into a char.
char x = 'x';
x++;
getType(x); // returns y as a char
x = x+1; // error: incompatible types: possible lossy conversion from int to char
getType(x);
int y = x+1;
getType(y); // 'y' char -> ascii int value is 121 -> + 1 int = 122 int
// 5. It casts entire object into a string and concatnates an empty string
// in front of it, exhibiting the expected behavior to table above.
// | | empty String |
// |---------|---------------|
// | boolean | concat String |
// | char | concat String |
// | int | concat String |
// | double | concat String |
// | String | concat String |
getType("" + true);
getType("" + 'c');
getType("" + 1);
getType("" + 3.5);
getType("" + "hello");
// 6.
// Across: original data type; Down: type of value assigned
// | | boolean | char | int | double | string |
// |---------|---------|------|-----|--------|--------|
// | boolean | yes | no | no | no | no |
// | char | no | yes | yes | no | no |
// | int | no | yes | yes | no | no |
// | double | no | yes | yes | yes | no |
// | String | no | no | no | no | yes |
boolean a1 = true;
boolean a2 = 'c';
boolean a3 = 1;
boolean a4 = 3.5;
boolean a5 = "hello";
char b1 = true;
char b2 = 'c';
char b3 = 1;
char b4 = 3.5;
char b5 = "hello";
int c1 = true;
int c2 = 'c';
int c3 = 1;
int c4 = 3.5;
int c5 = "hello";
double d1 = true;
double d2 = 'c';
double d3 = 1;
double d4 = 3.5;
double d5 = "hello";
String e1 = true;
String e2 = 'c';
String e3 = 1;
String e4 = 3.5;
String e5 = "hello";
// # I also did execise 6 as a quick challenge (see doubloon method below)
System.out.println("abba: "+doubloon("abba"));
System.out.println("coco: "+doubloon("coco"));
System.out.println("isis: "+doubloon("isis"));
System.out.println("mama: "+doubloon("mama"));
System.out.println("murmur: "+doubloon("murmur"));
System.out.println("apple: "+doubloon("apple"));
System.out.println("Wawa: "+doubloon("Wawa"));
System.out.println("temple: "+doubloon("temple"));
}
public static void getType(Object x) {
System.out.println(x);
System.out.println(x.getClass().getName());
}
public static void getType(int line, Object x) {
System.out.println("[Line " + line + "]: " + x);
System.out.println(x.getClass().getName());
}
public static boolean doubloon(String word) {
word = word.toLowercase();
System.out.println(word);
int occurances = 0;
for (int i = 0; i < word.length(); i++) {
occurances = 0;
for (int j = 0; j < word.length(); j++) {
if (word.charAt(j) == word.charAt(i)) {
occurances++;
// System.out.println(word.charAt(j) + " occurance " + occurances);
}
}
if (occurances != 2) {
return false;
}
}
return true;
}
}
|
package f.star.iota.milk.ui.zu80.www;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.ViewGroup;
import f.star.iota.milk.R;
import f.star.iota.milk.base.BaseAdapter;
public class ZUAdapter extends BaseAdapter<ZUViewHolder, ZUBean> {
@Override
public ZUViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
return new ZUViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.item_pure_image, parent, false));
}
@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
((ZUViewHolder) holder).bindView(mBeans);
}
}
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package jacktheripper;
import java.io.File;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.SimpleObjectProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
/**
*
* @author Paul
*/
public class SavingScheme {
private final StringProperty custom1 = new SimpleStringProperty("customee1");
private final ObjectProperty<File> directory = new SimpleObjectProperty<>();
public ObjectProperty FileProperty() {
return directory;
}
public String getCustom1() {
return custom1.get();
}
public void setCustom1(String value) {
custom1.set(value);
}
public StringProperty custom1Property() {
return custom1;
}
private final StringProperty custom2 = new SimpleStringProperty();
public String getCustom2() {
return custom2.get();
}
public void setCustom2(String value) {
custom2.set(value);
}
public StringProperty custom2Property() {
return custom2;
}
private final StringProperty dateTime = new SimpleStringProperty("dateTime");
public String getDateTime() {
return dateTime.get();
}
public void setDateTime(String value) {
dateTime.set(value);
}
public StringProperty dateTimeProperty() {
return dateTime;
}
}
|
package org.maple.jdk8.stream;
import java.util.IntSummaryStatistics;
import java.util.stream.Stream;
/**
* @Author Mapleins
* @Date 2019-04-07 0:34
* @Description
*/
public class Test9 {
public static void main(String[] args) {
// 找出流中大于2的元素,然后将每个元素乘以2,然后忽略掉流中的前两个元素,然后再获取流中的两个元素,最后求出流中元素的总和
Stream<Integer> stream = Stream.iterate(1, x -> x + 2).limit(6);
// 我的写法
// stream.filter(x -> x > 2).map(x -> x * 2).skip(2).limit(2).reduce((x, y) -> x + y).ifPresent(System.out::println);
// 使用 mapToInt 可以避免 Function<T,R> 中将数字自动装箱成 Integer类型,避免了性能的损耗
// int sum = stream.filter(x -> x > 2).mapToInt(x -> x * 2).skip(2).limit(2).sum();
// System.out.println(sum);
// stream.filter(x -> x > 2).mapToInt(x -> x * 2).skip(2).limit(0).min().ifPresent(System.out::println);
// stream.filter(x -> x > 2).mapToInt(x -> x * 2).skip(2).limit(2).max().ifPresent(System.out::println);
// System.out.println(max);
/**
* sum() 如果没有存在的返回 0
* min() max() 如果没有 则返回 empty Optional
*/
IntSummaryStatistics intSummaryStatistics = stream.filter(x -> x > 2).mapToInt(x -> x * 2).skip(2).limit(2).summaryStatistics();
if(intSummaryStatistics.getCount()>0){
System.out.println(intSummaryStatistics.getMax());
System.out.println(intSummaryStatistics.getMin());
System.out.println(intSummaryStatistics.getAverage());
System.out.println(intSummaryStatistics.getSum());
}
}
}
|
package Object.Enum;
/**
* La classe IdoneitaEnum implementa l'enumerazione idoneita di un cibo
*/
public enum IdoneitaEnum {
tutti,
pranzo_cena,
colazione_spuntino,
pranzo,
cena,
colazione,
spuntino
}
|
package com.mglowinski.restaurants.rest;
import com.mglowinski.restaurants.model.dto.PromotionCreateDto;
import com.mglowinski.restaurants.model.dto.PromotionDto;
import com.mglowinski.restaurants.service.promotion.PromotionService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/restaurants/{restaurantId}/promotions")
@RequiredArgsConstructor(onConstructor_ = @Autowired)
public class PromotionRestEndpoint {
private final PromotionService promotionService;
@PostMapping
public ResponseEntity<PromotionDto> createPromotion(@PathVariable Integer restaurantId, @RequestBody PromotionCreateDto promotionCreateDto) {
return ResponseEntity.status(HttpStatus.CREATED).body(promotionService.createPromotion(restaurantId, promotionCreateDto));
}
@GetMapping
public ResponseEntity<List<PromotionDto>> getPromotions(@PathVariable Integer restaurantId) {
return ResponseEntity.status(HttpStatus.OK).body(promotionService.getPromotions(restaurantId));
}
@PutMapping("/{promotionId}/notify")
public ResponseEntity<Void> notifyClients(@PathVariable Integer restaurantId, @PathVariable Integer promotionId) {
promotionService.notifyClients(restaurantId, promotionId);
return ResponseEntity.noContent().build();
}
}
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package josteo.model.paziente;
import josteo.infrastructure.DomainBase.*;
import josteo.model.tipoAnamnesi.TipoAnamnesi;
/**
*
* @author cristiano
*/
public class AnamnesiRemota extends EntityBase {
private Note _note;
private TipoAnamnesi _tipo;
public Note get_Note(){ return this._note;}
public void set_Note(Note val){
if(val!=null && !val.equals(this._note)){
this._note=val;
this.set_IsChanged(true);
}
}
public TipoAnamnesi get_Tipo(){ return this._tipo;}
public void set_Tipo(TipoAnamnesi val){
if(val!=null && !val.equals(this._tipo)){
this._tipo=val;
this.set_IsChanged(true);
}
}
public AnamnesiRemota(){
this(0);
}
public AnamnesiRemota(int key){
this(key, null, null);
}
public AnamnesiRemota(int key, Note note, TipoAnamnesi tipo){
super(key);
this._note = note;
this._tipo = tipo;
}
@Override
protected BrokenRuleMessages GetBrokenRuleMessages(){
return new ValutazioneRuleMessages();
}
@Override
protected void Validate(){
if(this._note==null){
this.get_BrokenRules().add(new BrokenRule("Note","cannot be null"));
}
if(this._note!=null && this._note.get_Descrizione().length()==0){
this.get_BrokenRules().add(new BrokenRule("Descrizione","cannot be empty"));
}
if(this._note!=null && this._note.get_Data() == null){
this.get_BrokenRules().add(new BrokenRule("Data","cannot be null"));
}
if(this._tipo==null){
this.get_BrokenRules().add(new BrokenRule("TipoAnmesi","is mandatory"));
}
if(this._tipo!=null && this._tipo.get_Key()==null){
this.get_BrokenRules().add(new BrokenRule("TipoAnmesi.Key","cannot be null"));
}
}
}
|
package ex0506;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
public class SDAO {
//데이터접속
public Connection con() throws Exception{
String driver = "oracle.jdbc.driver.OracleDriver";
String url = "jdbc:oracle:thin:@localhost:1521:xe";
String user = "haksa";
String password = "pass";
Class.forName(driver);
Connection con=DriverManager.getConnection(url, user, password);
return con;
}
//학생목록출력하기
public ArrayList<SVO> list() throws Exception{
ArrayList<SVO> list=new ArrayList<SVO>();
String sql="select * from stupro";
PreparedStatement ps= con().prepareStatement(sql);
ResultSet rs=ps.executeQuery();
while(rs.next()) {
SVO vo=new SVO();
vo.setScode(rs.getString("scode"));
vo.setSname(rs.getString("sname"));
vo.setDept(rs.getString("dept"));
list.add(vo);
System.out.println(vo.toString());
}
return list;
}
//특정학생이 신청한 강좌목록
public ArrayList<CVO> elist(String scode) throws Exception{
ArrayList<CVO> list=new ArrayList<CVO>();
String sql="select * from couenr where scode=?";
PreparedStatement ps= con().prepareStatement(sql);
ps.setString(1, scode);
ResultSet rs=ps.executeQuery();
while(rs.next()) {
CVO vo=new CVO();
vo.setLcode(rs.getString("lcode"));
vo.setLname(rs.getString("lname"));
vo.setCnt(rs.getInt("grade"));
list.add(vo);
System.out.println(vo.toString());
}
return list;
}
//특정학생의 평균 출력하기
public CVO avg(String scode) throws Exception{
CVO vo=new CVO();
String sql="select scode, avg(grade) avg, count(lcode) cnt from couenr where scode=? group by scode";
PreparedStatement ps=con().prepareStatement(sql);
ps.setString(1, scode);
ResultSet rs=ps.executeQuery();
if(rs.next()) {
vo.setAvg(rs.getDouble("avg"));
vo.setCnt(rs.getInt("cnt"));
}
return vo;
}
}
|
package rafaxplayer.cheftools.recipes;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Parcelable;
import android.support.annotation.NonNull;
import android.support.v7.widget.GridLayoutManager;
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.squareup.picasso.Picasso;
import java.util.ArrayList;
import java.util.List;
import rafaxplayer.cheftools.Globalclasses.BaseActivity;
import rafaxplayer.cheftools.Globalclasses.models.ImageGalleryModel;
import rafaxplayer.cheftools.R;
import rafaxplayer.cheftools.database.SqliteWrapper;
public class GalleryRecipesActivity extends BaseActivity {
private RecyclerView mRecyclerView;
private SqliteWrapper sql;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mRecyclerView = findViewById(R.id.imageList);
mRecyclerView.setLayoutManager(new GridLayoutManager(this, 3));
mRecyclerView.setHasFixedSize(true);
sql = new SqliteWrapper(this);
sql.open();
}
@Override
protected int getLayoutResourceId() {
return R.layout.activity_gallery_recipes;
}
@Override
protected String getCustomTitle() {
return getString(R.string.gallery_recipes);
}
@Override
public void onResume() {
super.onResume();
List<ImageGalleryModel> lst = sql.getImages();
mRecyclerView.setAdapter(new GalleryAdapter(this, lst));
}
public class GalleryAdapter extends RecyclerView.Adapter<GalleryAdapter.ViewHolder> {
final List<ImageGalleryModel> listImages;
final Context context;
GalleryAdapter(Context con, List<ImageGalleryModel> list) {
this.listImages = list;
this.context = con;
}
@Override
public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
Picasso.get().load(listImages.get(position).ImagePath)
.resizeDimen(R.dimen.dimen_gallery_thumbnail_min, R.dimen.dimen_gallery_thumbnail_min)
.centerCrop()
.placeholder(R.drawable.placeholder_recetas)
.into(holder.img);
holder.txtTitle.setText(listImages.get(position).Title);
}
@Override
public int getItemCount() {
return listImages.size();
}
@NonNull
@Override
public GalleryAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent,
int viewType) {
// Create a new view by inflating the row item xml.
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.image_gallery_recipes, parent, false);
// Set the view to the ViewHolder
return new ViewHolder(v);
}
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
final ImageView img;
final TextView txtTitle;
ViewHolder(View v) {
super(v);
img = v.findViewById(R.id.imageGallery);
txtTitle = v.findViewById(R.id.textImageGallery);
v.setOnClickListener(this);
}
@Override
public void onClick(View v) {
Intent intent = new Intent(context, GalleryDetalle_Activity.class);
intent.putParcelableArrayListExtra("data", (ArrayList<? extends Parcelable>) listImages);
intent.putExtra("pos", ViewHolder.this.getAdapterPosition());
startActivity(intent);
}
}
}
}
|
package com.proyecto.patas.services;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.proyecto.patas.model.Adopter;
import com.proyecto.patas.model.PetAnimal;
import com.proyecto.patas.model.PetShelter;
import com.proyecto.patas.repositories.PetAnimalRepository;
@Service
public class PetAnimalService {
@Autowired
PetAnimalRepository repository;
public PetAnimal insert(PetAnimal p) {
return repository.save(p);
}
public void delete(long id) {
repository.deleteById(id);
}
public void delete(PetAnimal p) {
if (!p.getImage().isEmpty())
//storageService.delete(p.getImagen());
repository.delete(p);
}
public PetAnimal edit(PetAnimal p) {
return repository.save(p);
}
public PetAnimal findById(long id) {
return repository.findById(id).orElse(null);
}
public List<PetAnimal> findAll() {
return repository.findAll();
}
public List<PetAnimal> PetAnimalsFromAdopter(Adopter a) {
return repository.findByAdopter(a);
}
public List<PetAnimal> PetAnimalsFromShelter(PetShelter s) {
return repository.findByPetShelter(s);
}
public List<PetAnimal> PetAnimalsWithoutAdopter() {
return repository.findByAdopterIsNull();
}
public List<PetAnimal> manyFromId(List<Long> ids) {
return repository.findAllById(ids);
}
}
|
package com.lotus.controller;
import java.util.LinkedList;
import java.util.concurrent.ConcurrentHashMap;
import com.lotus.model.TweetDetails;
import com.lotus.util.Pair;
public interface Controller {
/*first is user and second will be tweets list*/
public static ConcurrentHashMap<String, ConcurrentHashMap<String, Integer>> userToHashtagsMap =
new ConcurrentHashMap<String, ConcurrentHashMap<String, Integer>>();
public static ConcurrentHashMap<String, Integer> hashtagCountMap = new ConcurrentHashMap<String, Integer>();
public static LinkedList<Pair<String,Integer>> top100hashtags =
new LinkedList<Pair<String,Integer>>();
public static ConcurrentHashMap<String, Integer> locationTweetCountMap = new ConcurrentHashMap<String, Integer>();
public static ConcurrentHashMap<String, LinkedList<TweetDetails>> userToTweet =
new ConcurrentHashMap<String, LinkedList<TweetDetails>>();
public static LinkedList<Pair<String,Integer>> milestoneUser = new LinkedList<Pair<String,Integer>>();
public void parseTweet(TweetDetails tweet);
}
|
package com.junyoung.searchwheretogoapi.service.auth;
import com.junyoung.searchwheretogoapi.model.data.User;
import java.util.Optional;
public interface JwtService {
String toToken(User user);
Optional<String> getUserIdFromToken(String token);
}
|
package Parte01;
public class P1PG46 {
public static void main(String[] args) {
double d = 5.22; // Cotação do dólar
double q1=10; // Qtde de moedas de 1 dolar
double q2=30; // Qtde de moedas de 50 cents de dolar
double q3=10; // Qtde de moedas de 25 cents de dolar
double q4=10; // Qtde de moedas de 10 cents de dolar
double q5=2; // Qtde de moedas de 5 cents de dolar
double q6=10; // Qtde de moedas de 1 cents de dolar
double r =(q1+0.5*q2+0.25*q3+0.1*q4+0.05*q5+0.01*q6)*d;
System.out.println("O total das moedas deu R$: "+r+" reais");
}
}
|
package com.hrms.hrms.entities.concretes;
import java.time.LocalDate;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
import com.hrms.hrms.entities.abstracts.User;
import lombok.Data;
import lombok.EqualsAndHashCode;
@Data
@Entity
@EqualsAndHashCode(callSuper=false)
@Table(name = " job_seekers")
public class JobSeeker extends User {
@Column(name = " first_name")
private String firstName;
@Column(name = " last_name")
private String lastName;
@Column(name = " identity_number")
private String identityNumber;
@Column(name = " birth_date")
private LocalDate birthDate;
}
|
package Patterns.aStrategy.Buildings;
import Patterns.aStrategy.Wiapons.Behavior;
import Patterns.aStrategy.Wiapons.Behaviors;
import Patterns.aStrategy.Wiapons.Bow;
import Patterns.aStrategy.Wiapons.Sword;
import java.util.Random;
/**
* Created by Zigner on 11/1/2015.
*/
public class Armory {
Behavior behavior;
int weaponVariations = Behaviors.values().length;
int choise = new Random().nextInt(weaponVariations-0)+1;
public Armory() {
switch (choise){
case 1: behavior = new Sword();
break;
case 2: behavior = new Bow();
break;
default: behavior = null;
}
}
public Behavior getBehavior() {
return behavior;
}
}
|
package com.zs.ui.device.iviews;
import android.support.v4.widget.SwipeRefreshLayout;
import com.zs.common.AppBaseActivity;
/**
* author: admin
* date: 2018/05/07
* version: 0
* mail: secret
* desc: IDeviceListView
*/
public interface IDeviceListView {
AppBaseActivity getContext();
SwipeRefreshLayout getRefView();
}
|
package com.example.contentproviderdemo;
import android.app.Application;
import android.util.Log;
/**
* Author wangyu1
* Data 2018/12/27
* Description
**/
public class MyApplication extends Application {
private static MyApplication mInstance = null;
@Override
public void onCreate() {
super.onCreate();
mInstance = this;
}
public static MyApplication getInstance() {
return mInstance;
}
}
|
/*
* @(#) SvcInfoDAO.java
* Copyright (c) 2007 eSumTech Co., Ltd. All Rights Reserved.
*/
package com.esum.wp.ims.svcinfo.dao.impl;
import java.util.List;
import com.esum.appframework.dao.impl.SqlMapDAO;
import com.esum.appframework.exception.ApplicationException;
import com.esum.wp.ims.svcinfo.dao.ISvcInfoDAO;
/**
*
* @author heowon@esumtech.com
* @version $Revision: 1.1 $ $Date: 2008/07/31 02:00:18 $
*/
public class SvcInfoDAO extends SqlMapDAO implements ISvcInfoDAO {
/**
* Default constructor. Can be used in place of getInstance()
*/
public SvcInfoDAO () {}
public String loginID = "";
public String ssoLoginID = "";
public String updatePasswordID = "";
public String updateLangtypeID = "";
public String selectPageListID = "";
public String svcInfoDetailID = "";
public String getSelectPageListID() {
return selectPageListID;
}
public void setSelectPageListID(String selectPageListID) {
this.selectPageListID = selectPageListID;
}
public List selectPageList(Object object) throws ApplicationException {
try {
return getSqlMapClientTemplate().queryForList(selectPageListID, object);
} catch (Exception e) {
throw new ApplicationException(e);
}
}
public List svcInfoDetail(Object object) throws ApplicationException {
try {
return getSqlMapClientTemplate().queryForList(svcInfoDetailID, object);
} catch (Exception e) {
throw new ApplicationException(e);
}
}
public List login(Object object) throws ApplicationException {
try {
return getSqlMapClientTemplate().queryForList(loginID, object);
} catch (Exception e) {
throw new ApplicationException(e);
}
}
public List ssoLogin(Object object) throws ApplicationException {
try {
return getSqlMapClientTemplate().queryForList(ssoLoginID, object);
} catch (Exception e) {
throw new ApplicationException(e);
}
}
public int updatePassword(Object object) throws ApplicationException {
try {
return getSqlMapClientTemplate().update(updatePasswordID, object);
} catch (Exception e) {
throw new ApplicationException(e);
}
}
public int updateLangtype(Object object) throws ApplicationException {
try {
return getSqlMapClientTemplate().update(updateLangtypeID, object);
} catch (Exception e) {
throw new ApplicationException(e);
}
}
public String getLoginID() {
return loginID;
}
public void setLoginID(String loginID) {
this.loginID = loginID;
}
public String getUpdatePasswordID() {
return updatePasswordID;
}
public void setUpdatePasswordID(String updatePasswordID) {
this.updatePasswordID = updatePasswordID;
}
public String getUpdateLangtypeID() {
return updateLangtypeID;
}
public void setUpdateLangtypeID(String updateLangtypeID) {
this.updateLangtypeID = updateLangtypeID;
}
public String getSvcInfoDetailID() {
return svcInfoDetailID;
}
public void setSvcInfoDetailID(String svcInfoDetailID) {
this.svcInfoDetailID = svcInfoDetailID;
}
public String getSsoLoginID() {
return ssoLoginID;
}
public void setSsoLoginID(String ssoLoginID) {
this.ssoLoginID = ssoLoginID;
}
}
|
package cn.demo;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
/**
*
* @author wanzhongqiang
* 创建一个类继承HttpServlet类
* 创建一个Servlet类的名称为Test继承HttpServlet类同时覆写doGet方法和doPost方法。
*
*/
public class Test extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
setResponseAccess(response);
// 设置响应内容类型
// 设置响应内容类型
response.setContentType("text/json; charset=utf-8");
PrintWriter out = response.getWriter();
//创建一个json对象,相当于一个容器,当然这个容器还可以套在另外一个容器里面,这个看业务需要
JsonObject jsonContainer =new JsonObject();
//为当前的json对象添加键值对
jsonContainer.addProperty("count", 5);
jsonContainer.addProperty("status", 1);
//构建json数组,数组里面也是json
JsonArray arrayPlayer = new JsonArray();
//构建json数组中的对象
JsonObject player1 = new JsonObject();
player1.addProperty("addr", "湖南省长沙市雨花区中意一路与湘府路交汇处");
player1.addProperty("name", "湖南 长沙市 德思勤四季汇店");
player1.addProperty("tel", "0731-88990501");
JsonObject player2 = new JsonObject();
player2.addProperty("addr", "浙江省杭州市临安区锦北街道农林大路99号");
player2.addProperty("name", "浙江 杭州市 临安宝龙店");
player2.addProperty("tel", "0571-66558052");
JsonObject player3 = new JsonObject();
player3.addProperty("addr", "广东省深圳市光明区松白路与长春路交汇处");
player3.addProperty("name", "广东 深圳市 光明天汇城购物中心店");
player3.addProperty("tel", "0755-22337379");
JsonObject player4 = new JsonObject();
player4.addProperty("addr", "上海市青浦区淀山湖大道899弄B区—B1-A万达茂广场");
player4.addProperty("name", "上海 青浦万达茂店");
player4.addProperty("tel", "021-88220228");
JsonObject player5 = new JsonObject();
player5.addProperty("addr", "广东省广州市增城区新塘镇章陂工业大道万达广场");
player5.addProperty("name", "广东 广州市 新塘万达广场店");
player5.addProperty("tel", "020-88838779");
//将json对象添加到数组中
arrayPlayer.add(player1);
arrayPlayer.add(player2);
arrayPlayer.add(player3);
arrayPlayer.add(player4);
arrayPlayer.add(player5);
//最后将json数组装到jsonContainer中
jsonContainer.add("shops", arrayPlayer);
PrintWriter writer = response.getWriter();
System.out.println(jsonContainer);
out.println(jsonContainer);
}
/**
* @author wanzhongqiang
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
private void setResponseAccess(HttpServletResponse response) {
// 允许该域发起跨域请求
response.setHeader("Access-Control-Allow-Origin", "*");//*允许任何域
// 允许的外域请求方式
response.setHeader("Access-Control-Allow-Methods", "POST, GET");
// 在999999秒内,不需要再发送预检验请求,可以缓存该结果
response.setHeader("Access-Control-Max-Age", "999999");
// 允许跨域请求包含某请求头,x-requested-with请求头为异步请求
response.setHeader("Access-Control-Allow-Headers",
"x-requested-with");
}
}
|
package kr.or.ddit.interview.dao;
import java.util.List;
import java.util.Map;
import kr.or.ddit.vo.CalendarVO;
import kr.or.ddit.vo.JoinVO;
import kr.or.ddit.vo.ProjectVO;
import kr.or.ddit.vo.SuccessBoardCommentVO;
import kr.or.ddit.vo.SuccessBoardVO;
import oracle.net.aso.p;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.ibatis.sqlmap.client.SqlMapClient;
import com.lowagie.text.Paragraph;
import com.sun.swing.internal.plaf.metal.resources.metal;
@Repository
public class InterviewDaoImpl implements IInterviewDao {
@Autowired
private SqlMapClient client;
@Override
public List<Map<String, String>> selectNotConfirmApplyList(
Map<String, String> params) throws Exception {
return client.queryForList("interview.selectNotConfirmApplyList", params);
}
// ********************************************* JSON ********************************************* //
// 신청자 명단
@Override
public List<Map<String, String>> selectConfirmApplyList(Map<String, String> params)
throws Exception {
return client.queryForList("interview.selectConfirmApplyList", params);
}
@Override
public Map<String, String> infographic(Map<String, String> params)
throws Exception {
return (Map<String, String>) client.queryForObject("interview.infographic", params);
}
@Override
public int hireMember(Map<String, String> params) throws Exception {
return client.update("interview.hireMember", params);
}
@Override
public Map<String, String> selectMypageDeveloper(Map<String, String> params)
throws Exception {
return (Map<String, String>) client.queryForObject("interview.selectMypageDeveloper", params);
}
// 면접 캘린더
@Override
public List<CalendarVO> selectInterviewCalendar(
Map<String, String> params) throws Exception {
return client.queryForList("interview.selectInterviewCalendar", params);
}
@Override
public String insertInterviewCalendar(Map<String, String> params)
throws Exception {
return (String) client.insert("interview.insertInterviewCalendar", params);
}
@Override
public Map<String, String> selectMemberInfo(Map<String, String> params)
throws Exception {
return (Map<String, String>) client.queryForObject("interview.selectMemberInfo", params);
}
@Override
public int modifyInterviewCalendar(Map<String, String> params)
throws Exception {
return client.update("interview.modifyInterviewCalendar", params);
}
@Override
public int deleteInterviewCalendar(Map<String, String> params)
throws Exception {
return client.delete("interview.deleteInterviewCalendar", params);
}
@Override
public Map<String, String> selectProjectApply(Map<String, String> params)
throws Exception {
return (Map<String, String>) client.queryForObject("interview.selectProjectApply", params);
}
@Override
public String insertInterview(Map<String, String> params) throws Exception {
return (String) client.insert("interview.insertInterview", params);
}
@Override
public Map<String, String> selectInterview(Map<String, String> params)
throws Exception {
return (Map<String, String>) client.queryForObject("interview.selectInterview", params);
}
@Override
public int updateInterview(Map<String, String> params) throws Exception {
return client.update("interview.updateInterview", params);
}
@Override
public int updateInterviewCalendar(Map<String, String> params)
throws Exception {
return client.update("interview.updateInterviewCalendar", params);
}
@Override
public int insertInterviewee(Map<String, String> params) throws Exception {
int chk = 0;
Object obj = client.insert("interview.insertInterviewee", params);
if (obj == null) {
chk = 1;
}
return chk;
}
@Override
public int deleteProjectApply(Map<String, String> params) throws Exception {
return client.delete("interview.deleteProjectApply", params);
}
@Override
public Map<String, String> selectIntervieweeInfo(Map<String, String> params)
throws Exception {
return (Map<String, String>) client.queryForObject("interview.selectIntervieweeInfo", params);
}
@Override
public int deleteInterviewee(Map<String, String> params) throws Exception {
return client.delete("interview.deleteInterviewee", params);
}
@Override
public int insertProjectApply(Map<String, String> params) throws Exception {
int chk = 0;
Object obj = client.insert("interview.insertProjectApply", params);
if (obj == null) {
chk = 1;
}
return chk;
}
@Override
public int selectSuccessProjectCnt(Map<String, String> params)
throws Exception {
int result = 0;
Object obj = client.queryForObject("interview.selectSuccessProjectCnt", params);
if (obj == null) {
result = 0;
} else {
result = (int) obj;
}
return result;
}
@Override
public int selectInsertPortfolioCnt(Map<String, String> params)
throws Exception {
int result = 0;
Object obj = client.queryForObject("interview.selectInsertPortfolioCnt", params);
if (obj == null) {
result = 0;
} else {
result = (int) obj;
}
return result;
}
@Override
public int selectCareerCnt(Map<String, String> params) throws Exception {
int result = 0;
Object obj = client.queryForObject("interview.selectCareerCnt", params);
if (obj == null) {
result = 0;
} else {
result = (int) obj;
}
return result;
}
@Override
public List<Map<String, String>> selectAttendInterview(
Map<String, String> params) throws Exception {
return client.queryForList("interview.selectAttendInterview", params);
}
@Override
public int endInterviewSchedule(String id) throws Exception {
return client.update("interview.endInterviewSchedule", id);
}
@Override
public Map<String, String> selectCalendarInterview(String id)
throws Exception {
return (Map<String, String>) client.queryForObject("interview.selectCalendarInterview", id);
}
}
|
package com.esum.framework.queue;
import javax.jms.DeliveryMode;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.MessageProducer;
import javax.jms.Queue;
import javax.jms.Session;
import javax.jms.TextMessage;
import junit.framework.TestCase;
import com.esum.framework.FrameworkSystemVariables;
import com.esum.framework.common.util.MessageIDGenerator;
import com.esum.framework.core.component.ComponentConstants;
import com.esum.framework.core.config.Configurator;
import com.esum.framework.core.management.ManagementConstants;
import com.esum.framework.core.management.mbean.queue.QueueControlMBean;
import com.esum.framework.core.queue.QueueHandlerFactory;
import com.esum.framework.core.queue.mq.JmsQueueMessageHandler;
import com.esum.framework.core.queue.mq.MessageCreator;
import com.esum.framework.core.queue.mq.ProducerCallback;
import com.esum.framework.jmx.JmxClientTemplate;
import com.esum.framework.net.queue.HornetQServer;
public class SyncTest extends TestCase {
protected void setUp(){
System.setProperty("xtrus.home", "D:/test/xtrus-4.0.0");
try {
Configurator.init(System.getProperty("xtrus.home")+"/conf/env.properties");
Configurator.init(Configurator.DEFAULT_DB_PROPERTIES_ID,
System.getProperty("xtrus.home")+"/conf/db.properties");
System.setProperty(FrameworkSystemVariables.NODE_ID, Configurator.getInstance().getString("node.id"));
System.setProperty(FrameworkSystemVariables.NODE_TYPE, ComponentConstants.LOCATION_TYPE_MAIN);
System.setProperty(FrameworkSystemVariables.NODE_CODE, Configurator.getInstance().getString("node.code"));
Configurator.init(QueueHandlerFactory.CONFIG_QUEUE_HANDLER_ID, Configurator.getInstance().getString("queue.properties"));
HornetQServer.getInstance().start();
} catch (Exception e) {
fail(e.getMessage());
}
}
protected void tearDown(){
try {
HornetQServer.getInstance().stop();
} catch (Exception e) {
}
}
public void testSync() throws Exception{
JmxClientTemplate jmxClient = JmxClientTemplate.createJmxClient("localhost", 9026);
QueueControlMBean mbean = jmxClient.query(ManagementConstants.OBJECT_NAME_QUEUE_CONTROL, QueueControlMBean.class);
mbean.createQueue("IN_XTR_CHANNEL1", false);
mbean.createQueue("IN_XTR_CHANNEL2", false);
jmxClient.close();
final JmsQueueMessageHandler queueHandler = (JmsQueueMessageHandler)QueueHandlerFactory.getInstance("IN_XTR_CHANNEL1");
queueHandler.setMessageListener(new SyncMessageListener());
for(int i=0;i<1;i++) {
new Thread() {
public void run() {
try {
String correlationId = MessageIDGenerator.generateMessageID();
System.out.println("Sent message. correlation Id : "+correlationId);
Message receivedMessage = queueHandler.sendWait("IN_XTR_CHANNEL2",
new MessageCreator() {
@Override
public Message createMessage(Session session) throws JMSException {
return session.createTextMessage("test message");
}
}, correlationId);
assertNotNull(receivedMessage);
System.out.println("Reply received. ::: "+((TextMessage)receivedMessage).getText());
} catch (Exception e){
e.printStackTrace();
}
}
}.start();
}
Thread.sleep(1000*1000);
queueHandler.close();
}
class SyncMessageListener implements MessageListener {
public void onMessage(Message message) {
JmsQueueMessageHandler replyHandler = null;
try {
TextMessage tMsg = (TextMessage)message;
final String correlationId = tMsg.getJMSCorrelationID();
System.out.println("Received : "+tMsg.getText()+", correlationId : "+correlationId);
Destination replyTo = message.getJMSReplyTo();
message.acknowledge();
if(replyTo==null)
return;
replyHandler = (JmsQueueMessageHandler)QueueHandlerFactory.getInstance(((Queue)replyTo).getQueueName());
replyHandler.send(((Queue)replyTo).getQueueName(), new ProducerCallback() {
@Override
public void execute(Session session, MessageProducer producer) throws JMSException {
TextMessage replyMessage = session.createTextMessage("response message :: "+correlationId);
replyMessage.setJMSCorrelationID(correlationId);
producer.send(replyMessage, DeliveryMode.NON_PERSISTENT, Message.DEFAULT_PRIORITY, Message.DEFAULT_TIME_TO_LIVE);
}
});
System.out.println("REPLY sent.");
} catch (Exception e) {
e.printStackTrace();
} finally {
if(replyHandler!=null)
replyHandler.close();
replyHandler = null;
}
}
}
}
|
package com.base.utils.location;
/**
* 定位接口
*
* @author jianfei.geng
* @since 2016.08.31
*/
public interface LocationApi {
/**
* 初始化定位参数
*/
public void initLocationParam();
/**
* 开始定位
*
* @param locationCallback
*/
public void startLocation(LocationCallback locationCallback);
/**
* 结束定位(建议在生命周期onStop()中调用)
*/
public void stopLocation();
/**
* 定位回调接口
*/
public interface LocationCallback {
public void locationSuccess(PerfectLocation location);
public void locationFailed();
}
public enum LocationMode {
AMAPLOCATION
}
}
|
package com.duanc.web.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import com.duanc.api.web.ShowService;
import com.duanc.model.dto.PhoneDTO;
@Controller
@RequestMapping("/show")
public class ShowController {
@Autowired
private ShowService showService;
@RequestMapping(value = "/getPage")
public String getShowPage(Model model, Integer phoneId){
if(phoneId == null ) {
return "redirect:/index/index";
}
PhoneDTO phoneDTO = showService.getPhoneDTO(phoneId);
model.addAttribute("showPhone", phoneDTO);
return "show";
}
}
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package threadprogramming;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author RolfMoikjær
*/
public class ThreadProgramming {
static BlockingQueue<Integer> s1 = new ArrayBlockingQueue(11);
static BlockingQueue<Long> s2 = new ArrayBlockingQueue(11);
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
Thread1 t1 = new Thread1();
t1.start();
}
public static class Thread1 extends Thread {
// Producer p2 = new Producer();
// Producer p3 = new Producer();
// Producer p4 = new Producer();
Consumer c1 = new Consumer();
public void run() {
try {
s1.put(4);
s1.put(5);
s1.put(8);
s1.put(12);
s1.put(21);
s1.put(22);
s1.put(34);
s1.put(35);
s1.put(36);
s1.put(37);
s1.put(42);
} catch (InterruptedException ex) {
Logger.getLogger(ThreadProgramming.class.getName()).log(Level.SEVERE, null, ex);
}
c1.start();
ExecutorService executor = Executors.newFixedThreadPool(4);
for (int i = 0; i < 4; i++) {
executor.execute(new Producer());
}
executor.shutdown();
while (!executor.isTerminated()) {
}
System.out.println("SLUTT!!");
c1.interrupt();
}
}
public static class Producer extends Thread {
long s1Result;
public void run() {
while (!s1.isEmpty()) {
try {
s1Result = s1.poll();
s2.put(fib(s1Result));
} catch (Exception e) {
}
}
}
}
public static class Consumer extends Thread {
long temp;
long totalRes;
public void run() {
while (true) {
try {
temp = s2.take();
} catch (Exception e) {
break;
}
System.out.println("Consumer s2 input: " + temp);
totalRes += temp;
System.out.println("Total sum: " + totalRes);
}
}
}
public static synchronized long fib(long n) {
if ((n == 0) || (n == 1)) {
return n;
} else {
return fib(n - 1) + fib(n - 2);
}
}
}
|
package com.github.ytjojo.supernestedlayout;
import android.graphics.PointF;
public class PtrIndicator {
public static final float INVALID_MAXOFFSETRATIO = -1;
public static final int POS_START = 0;
protected int mOffsetToRefresh = 0;
private PointF mPtLastMove = new PointF();
private float mOffsetDx;
private float mOffsetDy;
private int mCurrentPos = 0;
private int mLastPos = 0;
private int mStableRefreshOffset;
private int mPressedPos = 0;
private float mRatioOfHeaderHeightToRefresh = 1.2F;
private float mMaxDistanceRatio = 3F;
private boolean mIsUnderTouch = false;
private int mOffsetToKeepHeaderWhileLoading = -1;
private int mRefreshCompleteY = 0;
private int mMaxContentOffsetY;
private long mDelayScrollInitail;
public void setDelayScrollInitail(long delayScrollInitail){
this.mDelayScrollInitail = delayScrollInitail;
}
public long getDelayScrollInitail(){
return mDelayScrollInitail;
}
public PtrIndicator() {
}
public boolean isUnderTouch() {
return this.mIsUnderTouch;
}
public float getMaxDistanceRatio() {
return this.mMaxDistanceRatio;
}
public void setMaxDistanceRatio(float maxDistanceRatio) {
this.mMaxDistanceRatio = maxDistanceRatio;
mMaxContentOffsetY = (int) (mMaxDistanceRatio * mStableRefreshOffset);
}
public void onRelease() {
this.mIsUnderTouch = false;
}
public void onUIRefreshComplete() {
this.mRefreshCompleteY = this.mCurrentPos;
}
public boolean goDownCrossFinishPosition() {
return this.mCurrentPos >= this.mRefreshCompleteY;
}
protected void processOnMove(float currentX, float currentY, float offsetDx, float offsetDy) {
this.setOffset(offsetDx, offsetDy);
}
public void setRatioOfHeaderHeightToRefresh(float ratio) {
this.mRatioOfHeaderHeightToRefresh = ratio;
this.mOffsetToRefresh = (int)((float)this.mStableRefreshOffset * ratio);
}
public float getRatioOfHeaderToHeightToRefresh() {
return this.mRatioOfHeaderHeightToRefresh;
}
public int getOffsetToRefresh() {
return this.mOffsetToRefresh;
}
public void setOffsetToRefresh(int offset) {
this.mRatioOfHeaderHeightToRefresh = (float)this.mStableRefreshOffset * 1.0F / (float)offset;
this.mOffsetToRefresh = offset;
}
public void onPressDown() {
this.mIsUnderTouch = true;
}
public final void onMove(float x, float y) {
float offsetDx = x - this.mPtLastMove.x;
float offsetDy = y - this.mPtLastMove.y;
this.processOnMove(x, y, offsetDx, offsetDy);
this.mPtLastMove.set(x, y);
setCurrentPos((int) y);
}
protected void setOffset(float x, float y) {
this.mOffsetDx = x;
this.mOffsetDy = y;
}
public float getOffsetDx() {
return this.mOffsetDx;
}
public float getOffsetDy() {
return this.mOffsetDy;
}
public int getLastPosY() {
return this.mLastPos;
}
public int getCurrentPosY() {
return this.mCurrentPos;
}
public final void setCurrentPos(int current) {
this.mLastPos = this.mCurrentPos;
this.mCurrentPos = current;
this.onUpdatePos(current, this.mLastPos);
}
protected void onUpdatePos(int current, int last) {
}
public int getStableRefreshOffset() {
return this.mStableRefreshOffset;
}
public void setStableRefreshOffset(int stableOffset) {
this.mStableRefreshOffset = stableOffset;
this.updateValue();
}
protected void updateValue() {
this.mOffsetToRefresh = (int)(this.mRatioOfHeaderHeightToRefresh * (float)this.mStableRefreshOffset);
if(mMaxDistanceRatio !=INVALID_MAXOFFSETRATIO){
this.mMaxContentOffsetY = (int) (mMaxDistanceRatio * mStableRefreshOffset);
}
}
public int getMaxContentOffsetY(){
return mMaxContentOffsetY;
}
public void setMaxContentOffsetY(int maxOffsetY){
if(maxOffsetY>0){
mMaxDistanceRatio = INVALID_MAXOFFSETRATIO;
mMaxContentOffsetY = maxOffsetY;
}
}
public void convertFrom(PtrIndicator ptrSlider) {
this.mCurrentPos = ptrSlider.mCurrentPos;
this.mLastPos = ptrSlider.mLastPos;
this.mStableRefreshOffset = ptrSlider.mStableRefreshOffset;
}
public boolean hasLeftStartPosition() {
return this.mCurrentPos > 0;
}
public boolean hasJustLeftStartPosition() {
return this.mLastPos == 0 && this.hasLeftStartPosition();
}
public boolean hasJustBackToStartPosition() {
return this.mLastPos != 0 && this.isInStartPosition();
}
public boolean isOverOffsetToRefresh() {
return this.mCurrentPos >= this.getOffsetToRefresh();
}
public boolean hasMovedAfterPressedDown() {
return this.mCurrentPos != this.mPressedPos;
}
public boolean isInStartPosition() {
return this.mCurrentPos == 0;
}
public boolean crossRefreshLineFromTopToBottom() {
return this.mLastPos < this.getOffsetToRefresh() && this.mCurrentPos >= this.getOffsetToRefresh();
}
public boolean hasJustReachedHeaderHeightFromTopToBottom() {
return this.mLastPos < this.mStableRefreshOffset && this.mCurrentPos >= this.mStableRefreshOffset;
}
public boolean isOverOffsetToKeepHeaderWhileLoading() {
return this.mCurrentPos > this.getOffsetToKeepHeaderWhileLoading();
}
public void setOffsetToKeepHeaderWhileLoading(int offset) {
this.mOffsetToKeepHeaderWhileLoading = offset;
}
public int getOffsetToKeepHeaderWhileLoading() {
return this.mOffsetToKeepHeaderWhileLoading >= 0?this.mOffsetToKeepHeaderWhileLoading:this.mStableRefreshOffset;
}
public boolean isAlreadyHere(int to) {
return this.mCurrentPos == to;
}
public float getLastPercent() {
float oldPercent = this.mStableRefreshOffset == 0?0.0F:(float)this.mLastPos * 1.0F / (float)this.mStableRefreshOffset;
return oldPercent;
}
public float getCurrentPercent() {
float currentPercent = this.mStableRefreshOffset == 0?0.0F:(float)this.mCurrentPos * 1.0F / (float)this.mStableRefreshOffset;
return currentPercent;
}
public boolean willOverTop(int to) {
return to < 0;
}
}
|
package com.creche.crecheapi.request;
import com.creche.crecheapi.entity.Telefone;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.List;
import java.util.stream.Collectors;
@Builder
@Data
@NoArgsConstructor
@AllArgsConstructor
public class TelefoneRequest {
private String numero;
private String tipo;
public static List<Telefone> convert(List<TelefoneRequest> telefoneRequest) {
return telefoneRequest.stream().map(Telefone::new).collect(Collectors.toList());
}
}
|
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JLabel;
import javax.swing.SwingConstants;
public class MyFrame extends JFrame {
private JPanel contentPane;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
MyFrame frame = new MyFrame();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public MyFrame() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JLabel text = new JLabel("Nada");
text.setHorizontalAlignment(SwingConstants.CENTER);
text.setBounds(134, 33, 179, 14);
contentPane.add(text);
JButton btnClicMe = new JButton("Click me");
btnClicMe.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
text.setText("Tu m'as cliqué");
}
});
btnClicMe.setBounds(154, 100, 89, 23);
contentPane.add(btnClicMe);
}
}
|
package com;
public class Split {
public static void main(String[] args) {
String strDev = "Samsung#Nokia#Mi";
char[] strarr = strDev.toCharArray();
String str;
int size = strDev.length();
System.out.println("Size of String is " + size);
}
}
|
package scraper.ui.utils;
import common.elements.UiElementsFactory;
import common.elements.interfaces.ITextBox;
import common.environment.TestEnvironment;
import org.openqa.selenium.support.PageFactory;
import scraper.ui.pagefactory.LoginPageUIElements;
public class LoginUI {
private static final LoginUI ourInstance = new LoginUI();
public static LoginUI getInstance() {
return ourInstance;
}
private LoginUI() {
}
private LoginPageUIElements getPage() {
return PageFactory.initElements(TestEnvironment.getDriver(), LoginPageUIElements.class);
}
public void loginAsAdmin() throws Exception {
this.login("admin", "12345");
}
public void login(String userName, String password) throws Exception {
ITextBox userNameField = UiElementsFactory.getTextBox(getPage().getUserName());
userNameField.assertDisplayed().setText(userName);
ITextBox pwdField = UiElementsFactory.getTextBox(getPage().getPassword());
pwdField.assertDisplayed().setText(password);
UiElementsFactory.getButton(getPage().getLoginButton()).assertDisplayed().click();
}
}
|
package wannaapp.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.logging.log4j2.Log4J2LoggingSystem;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import wannaapp.model.User;
import wannaapp.service.UserService;
@Controller
public class AppController {
@Autowired
private UserService service;
@RequestMapping("/")
public String viewHomePage(Model model) {
List<User> users=service.listAll();
model.addAttribute("listUsers", users);
model.addAttribute("test", "test");
System.out.println("passed");
return "index";
}
@RequestMapping("/new")
public String addUserPage(Model model) {
User user=new User();
model.addAttribute("user",user);
return "new_user";
}
@RequestMapping(value = "/save",method = RequestMethod.POST)
public String saveUser(@ModelAttribute("user") User user) {
service.save(user);
return "redirect:/";
}
@RequestMapping(value = "/edit/{id}")
public ModelAndView editUser(@PathVariable(name="id") int id) {
ModelAndView mav=new ModelAndView("edit_user");
User user=service.get(id);
mav.addObject("user",user);
return mav;
}
@RequestMapping("/delete/{id}")
public String deleteUser( int id) {
service.delete(id);
return "redirect:/";
}
}
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package Controller;
import Model.MediaLog;
import Model.Medium;
import Model.User;
import java.util.Date;
import junit.framework.TestCase;
/**
*
* @author Anthony
*/
public class MediaLog_controllerTest extends TestCase {
public MediaLog_controllerTest(String testName) {
super(testName);
}
@Override
protected void setUp() throws Exception {
super.setUp();
}
@Override
protected void tearDown() throws Exception {
super.tearDown();
}
/**
* Test of addLog method, of class MediaLog_controller.
*/
public void testAddLog() {
MediaLog medialog = new MediaLog();
System.out.println("addLog");
User user = null;
Medium medium = null;
String item = "";
Double rating = null;
Double timeSpent = null;
Date dateFinished = null;
MediaLog_controller instance = new MediaLog_controller();
Boolean expResult = null;
Boolean result = instance.addLog(user, medium, item, rating, timeSpent, dateFinished);
assertEquals(expResult, result);
// TODO review the generated test code and remove the default call to fail.
fail("The test case is a prototype.");
}
/**
* Test of listLog method, of class MediaLog_controller.
*/
public void testListLog() {
System.out.println("listLog");
MediaLog_controller instance = new MediaLog_controller();
instance.listLog();
// TODO review the generated test code and remove the default call to fail.
fail("The test case is a prototype.");
}
/**
* Test of updateLog method, of class MediaLog_controller.
*/
public void testUpdateLog() {
System.out.println("updateLog");
int logId = 0;
User user = null;
Medium medium = null;
String item = "";
Double rating = null;
Double timeSpent = null;
Date dateFinished = null;
MediaLog_controller instance = new MediaLog_controller();
Boolean expResult = null;
Boolean result = instance.updateLog(logId, user, medium, item, rating, timeSpent, dateFinished);
assertEquals(expResult, result);
// TODO review the generated test code and remove the default call to fail.
fail("The test case is a prototype.");
}
/**
* Test of deleteLog method, of class MediaLog_controller.
*/
public void testDeleteLog() {
System.out.println("deleteLog");
Integer logId = null;
MediaLog_controller instance = new MediaLog_controller();
Boolean expResult = null;
Boolean result = instance.deleteLog(logId);
assertEquals(expResult, result);
// TODO review the generated test code and remove the default call to fail.
fail("The test case is a prototype.");
}
}
|
package com.cedo.cat2auth.dao;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.cedo.cat2auth.model.RoleMenu;
import org.apache.ibatis.annotations.Mapper;
/**
* 角色-菜单
*
* @author chendong
* @email sunlightcs@gmail.com
* @date 2019-03-02 20:45:19
*/
@Mapper
public interface RoleMenuMapper extends BaseMapper<RoleMenu> {
}
|
package com.renuka.controllers;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/api/greeting")
public class Greeting {
@GetMapping("/open/{name}")
public String greet(@PathVariable("name") String name) {
return "Hello " + name;
}
@GetMapping("/protected/{name}")
public String greetProtected(@PathVariable("name") String name) {
return "Hello " + name + ", we have a secret for you. That is 4445-998 රේණුක!";
}
@PreAuthorize("hasRole('ROLE_ADMIN')")
@GetMapping("/admin/{name}")
public String greetAdmin(@PathVariable("name") String name) {
return "Hello " + name + ", FROM ADMIN";
}
}
|
/*
* Copyright 2002-2023 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.web.servlet.function.support;
import java.util.List;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.core.Ordered;
import org.springframework.core.log.LogFormatUtils;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.lang.Nullable;
import org.springframework.util.Assert;
import org.springframework.web.context.request.async.AsyncWebRequest;
import org.springframework.web.context.request.async.WebAsyncManager;
import org.springframework.web.context.request.async.WebAsyncUtils;
import org.springframework.web.servlet.HandlerAdapter;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.function.HandlerFunction;
import org.springframework.web.servlet.function.RouterFunctions;
import org.springframework.web.servlet.function.ServerRequest;
import org.springframework.web.servlet.function.ServerResponse;
/**
* {@code HandlerAdapter} implementation that supports {@link HandlerFunction}s.
*
* @author Arjen Poutsma
* @since 5.2
*/
public class HandlerFunctionAdapter implements HandlerAdapter, Ordered {
private static final Log logger = LogFactory.getLog(HandlerFunctionAdapter.class);
private int order = Ordered.LOWEST_PRECEDENCE;
@Nullable
private Long asyncRequestTimeout;
/**
* Specify the order value for this HandlerAdapter bean.
* <p>The default value is {@code Ordered.LOWEST_PRECEDENCE}, meaning non-ordered.
* @see org.springframework.core.Ordered#getOrder()
*/
public void setOrder(int order) {
this.order = order;
}
@Override
public int getOrder() {
return this.order;
}
/**
* Specify the amount of time, in milliseconds, before concurrent handling
* should time out. In Servlet 3, the timeout begins after the main request
* processing thread has exited and ends when the request is dispatched again
* for further processing of the concurrently produced result.
* <p>If this value is not set, the default timeout of the underlying
* implementation is used.
* <p>A value of 0 or less indicates that the asynchronous operation will never
* time out.
* @param timeout the timeout value in milliseconds
*/
public void setAsyncRequestTimeout(long timeout) {
this.asyncRequestTimeout = timeout;
}
@Override
public boolean supports(Object handler) {
return handler instanceof HandlerFunction;
}
@Nullable
@Override
public ModelAndView handle(HttpServletRequest servletRequest,
HttpServletResponse servletResponse,
Object handler) throws Exception {
WebAsyncManager asyncManager = getWebAsyncManager(servletRequest, servletResponse);
ServerRequest serverRequest = getServerRequest(servletRequest);
ServerResponse serverResponse;
if (asyncManager.hasConcurrentResult()) {
serverResponse = handleAsync(asyncManager);
}
else {
HandlerFunction<?> handlerFunction = (HandlerFunction<?>) handler;
serverResponse = handlerFunction.handle(serverRequest);
}
if (serverResponse != null) {
return serverResponse.writeTo(servletRequest, servletResponse, new ServerRequestContext(serverRequest));
}
else {
return null;
}
}
private WebAsyncManager getWebAsyncManager(HttpServletRequest servletRequest, HttpServletResponse servletResponse) {
AsyncWebRequest asyncWebRequest = WebAsyncUtils.createAsyncWebRequest(servletRequest, servletResponse);
asyncWebRequest.setTimeout(this.asyncRequestTimeout);
WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(servletRequest);
asyncManager.setAsyncWebRequest(asyncWebRequest);
return asyncManager;
}
private ServerRequest getServerRequest(HttpServletRequest servletRequest) {
ServerRequest serverRequest =
(ServerRequest) servletRequest.getAttribute(RouterFunctions.REQUEST_ATTRIBUTE);
Assert.state(serverRequest != null, () -> "Required attribute '" +
RouterFunctions.REQUEST_ATTRIBUTE + "' is missing");
return serverRequest;
}
@Nullable
private ServerResponse handleAsync(WebAsyncManager asyncManager) throws Exception {
Object result = asyncManager.getConcurrentResult();
asyncManager.clearConcurrentResult();
LogFormatUtils.traceDebug(logger, traceOn -> {
String formatted = LogFormatUtils.formatValue(result, !traceOn);
return "Resume with async result [" + formatted + "]";
});
if (result instanceof ServerResponse response) {
return response;
}
else if (result instanceof Exception exception) {
throw exception;
}
else if (result instanceof Throwable throwable) {
throw new ServletException("Async processing failed", throwable);
}
else if (result == null) {
return null;
}
else {
throw new IllegalArgumentException("Unknown result from WebAsyncManager: [" + result + "]");
}
}
@Override
@SuppressWarnings("deprecation")
public long getLastModified(HttpServletRequest request, Object handler) {
return -1L;
}
private static class ServerRequestContext implements ServerResponse.Context {
private final ServerRequest serverRequest;
public ServerRequestContext(ServerRequest serverRequest) {
this.serverRequest = serverRequest;
}
@Override
public List<HttpMessageConverter<?>> messageConverters() {
return this.serverRequest.messageConverters();
}
}
}
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package Cliente;
import Modelo.Alumno;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
/**
*
* @author alexeik
*/
public class AlumnoRequest implements Runnable{
GUILogin parent;
GUIAlumno alu;
private Alumno alumno;
private int id;
private String contrasenia;
private int operation;
private char request;
private final String IP_ADDRESS = "127.0.0.1";
private final int PORT = 8200;
AlumnoRequest(GUILogin aThis, Alumno alumno, char c) {
this.alumno=alumno;
this.request=c;
this.parent=aThis;
}
AlumnoRequest(GUIAlumno aThis, Alumno alumno, char c) {
this.alumno=alumno;
this.request=c;
this.alu=aThis;
}
public Alumno sendAutentificar(){
Alumno a = new Alumno();
boolean exitoso = false;
try {
Socket socket = new Socket(IP_ADDRESS, PORT);
ObjectOutputStream peticion = new ObjectOutputStream(socket.getOutputStream());
ObjectInputStream respuesta = new ObjectInputStream(socket.getInputStream());
//SE MANDA CADENA DE LA TABLA ESPECÍFICA
peticion.writeObject("alumno");
peticion.writeObject("autentificar");//Se manda operacion
peticion.writeObject(this.alumno);//Se manda objeto
a = (Alumno) respuesta.readObject();
exitoso = (boolean) respuesta.readObject();
if (exitoso) {
JOptionPane.showMessageDialog(null, "Alumno Encontrado", "Exito", JOptionPane.INFORMATION_MESSAGE);
synchronized (this.parent) {
this.parent.cerrar(alumno);
}
} else {
JOptionPane.showMessageDialog(null, "Se produjo un error", "Error", JOptionPane.INFORMATION_MESSAGE);
}
peticion.close();
respuesta.close();
socket.close();
System.out.println("Conexion cerrada 2");
} catch (IOException ex) {
Logger.getLogger(AlumnoRequest.class.getName()).log(Level.SEVERE, null, ex);
} catch (ClassNotFoundException ex) {
Logger.getLogger(AlumnoRequest.class.getName()).log(Level.SEVERE, null, ex);
}
return a;
}
@Override
public void run() {
if (this.request == 'u') {
//sendUpdate();
} else if (this.request == 'd') {
//sendDelete();
} else if (this.request == 'b') {
//sendBuscar();
} else if (this.request == 'l') {
//sendListar();
} else if (this.request == 'c'){
sendAutentificar();
}
}
}
|
package com.citibank.newcpb.vo;
import java.util.ArrayList;
import java.util.Date;
import org.apache.commons.lang.StringUtils;
import com.citibank.newcpb.enums.TableTypeEnum;
import com.citibank.newcpb.enun.CustomerTypeEnum;
import com.citibank.newcpb.util.FormatUtils;
public class RegisterDataCustomerVO {
//ID DO REGISTRO
private String cpfCnpj; // Numero do CPF ou CNPJ
private String numberGFCID; // Numero do GFCID - origem AMC
// Informações Cliente (PF e PJ)
private String customerTypeDesc; // Tipo de cliente F (fisica) / J (juridica)
private String customerType; // Tipo de cliente F (fisica) / J (juridica)
private String name; // Nome completo - origem AMC
private String numberEM; // Numero do EM gerado no Onnesource
private String nameBanker;
// Informações Cliente PF
private String customerStatus; // status do cliente A (Ativo) / E (Encerrado)
private String customerTitulo; // titulo do cliente ....
private String birthDate; // Data de Nascimento
private String gender; // Sexo do cliente F/ M
private String filiation1; // Filiacao do cliente
private String filiation2; // Filiacao do cliente
private String civilState; // Codigo do estado civil (TPL_PRVT_DMN_CIVIL_STAT)
private Integer numberDependents; // Numero de dependentes
private String spouseName; // Nome do Conjuge
private String countryBirth; // Pais de nascimento (TPL_PRVT_DMN_CTRY ) (PF) e Codigo do pais de constituicao da empresa (TPL_PRVT_DMN_CTRY ) (PJ)
private String placeOfBirth; // Cidade de nascimento
private String ufPlaceOfBirth; // Estado de nascimento (TPL_PRVT_DMN_UF)
private String identityDocument; // Documento de identidade
private String emitType; // Sequencial do tipo de orgao emissor (tabela TPL_PRVT_DMN_EMIT_TYPE)
private String emitDocumentUF; // Estado do documento de identidade (TPL_PRVT_DMN_UF)
private String emitDocumentDate; // Data de emissao do documento de identidade
private String occupation; // Profissao
private String occupationNature; // Codigo da natureza da ocupacao (TPL_PRVT_DMN_OCCUP_NATR)
private String declaredIncome; // Valor da renda declarada
private String declaredHeritage; // Valor do patrimonio delcarado
private Boolean isEmployee; // Indicador de funcionario. S (funcionario) / N (nao funcionario)
private Boolean isDeceased; // Indicador de cliente falecido. S/N
private String SOEIDBankerNumber; // SOEID do Officer
private String SOEIDBankerName;
private Boolean haveGreenCard; // Indicador se o cliente e portador de green card ou ssn. S (green card) / N (social security nbr)
private String socialSecurityNumber; // Numero do Green Card ou SSN
private Boolean exemptIR; // Indica se cliente ou empresa tem isencao de imposto de renda. S (isento) / N (nao isento)
// Informações Cliente PJ
private String activityMain; // Codigo da atividade principal da empresa (TPL_PRVT_DMN_CNAE)
private String constType; // Codigo do tipo de empresa (TPL_PRVT_DMN_CO_TYPE)
private String naicNumber; // Codigo NAIC (North American Industry Classification. TPL_PRVT_DMN_NAIC) - Origem AMC
private String sicNumber; // Codigo SIC (Standard Industrial Classification. TPL_PRVT_DMN_SIC ) - Origem AMC
private String foundationDate; // Data de fundacao da empresa
private String countryConstitution; // Pais de Constituiçao
private String averageMonthBilling; // Valor do faturamento mensal
private String admName; // Nome do administrador da empresa
private String admCpf; // CPF do administrador da empresa
private Boolean hasFlexAccount; // Indicador de conta no Flex DDA. S / N
// Classificação Citi
// private String numberER;
// private String customerRoleRelationship;
public ErEmVO er_em;
private Boolean isSensitive; // Indicador de cliente sensível. S/N
private String typeClass; // Tipo de figura publica S (senior public fig) / P (Prominent publc fig)
private Boolean derogatoryInformation; //Indicador de cliente derrogatorio. S/N
private Date lastAuthDate; // Data e hora da última autorizacao
private String lastAuthUser; // Usuario que realizou a ultima autorizacao
private Date lastUpdDate; // Data e hora da última atualização
private String lastUpdUser; // Usuario que realizou a ultima atualizacao
private String recStatCode; // Status do Registro
// Endereço
private AddressVO residentialAddress;
private AddressVO businessAddress;
private AddressVO otherAddress;
private AddressVO headOfficeAddress;
//FATCA / CRS
private Boolean isFatca; // Indicador de Fatca S/N
private Boolean isCrs; // Indicador de CRS S/N
private String formType; // Tipo de formulario (w8) / 9 (w9)
private String signatureDateFatca;
private String signatureDateCrs;
private Boolean custFatcaPjInUs;
private Boolean custFatcaPjOutUs;
private Boolean custFatcaPjOwnrUs;
private Boolean custCrsPjAddrOutUs;
private Boolean custCrsPjEnfLiab;
private Boolean custCrsPjInvstOut;
private String custCreateDate;
private String custCreateUser;
private Boolean isAnnualReview;
private Date lastAnnualReviewDate;
private String custCreateDateAndUser;
private String lastAuthDateFormatedDDMMYYYYAndUser;
// Indicador do tipo de w8. 1 (codigo da atividade) / 2 (participacao acionaria)
// Data e hora de criação do cliente na PCL
// Usuario que autorizou a criação do cliente
// Data da última revisão cadastral
// Telefones
private ArrayList<TelephoneVO> telephoneList;
// Emails
private ArrayList<MailVO> mailList;
// Cidadanias
private ArrayList<CustomerCountryVO> citizenshipList;
// Residencias Fiscal
private ArrayList<CustomerCountryVO> fiscalResidenceList;
private TableTypeEnum tableOrigin;
public Date getLastAuthDate() {
return lastAuthDate;
}
public String getLastAuthDateFormatedDDMMYYYY() {
if(lastAuthDate!=null){
return FormatUtils.dateToString(lastAuthDate, FormatUtils.C_FORMAT_DATE_DD_MM_YYYY);
}else{
return "";
}
}
public void setLastAuthDate(Date lastAuthDate) {
this.lastAuthDate = lastAuthDate;
}
public String getLastAuthUser() {
return lastAuthUser;
}
public void setLastAuthUser(String lastAuthUser) {
this.lastAuthUser = lastAuthUser;
}
public Date getLastUpdDate() {
return lastUpdDate;
}
public void setLastUpdDate(Date lastUpdDate) {
this.lastUpdDate = lastUpdDate;
}
public String getLastUpdDateFormatedSafe() {
if(lastUpdDate!=null){
return FormatUtils.dateToString(lastUpdDate, FormatUtils.C_FORMAT_DATE_DD_MM_YYYY_HHMMSS);
}else{
return "";
}
}
public String getLastUpdDateFormatedDDMMYYYY() {
if(lastUpdDate!=null){
return FormatUtils.dateToString(lastUpdDate, FormatUtils.C_FORMAT_DATE_DD_MM_YYYY);
}else{
return "";
}
}
public String getLastUpdUser() {
return lastUpdUser;
}
public void setLastUpdUser(String lastUpdUser) {
this.lastUpdUser = lastUpdUser;
}
public String getLastUpdUserSafe() {
if(lastUpdUser!=null){
return lastUpdUser;
}else{
return "";
}
}
public String getCustomerType() {
return customerType;
}
public void setCustomerType(String customerType) {
this.customerType = customerType;
}
public String getCpfCnpj() {
return cpfCnpj;
}
public void setCpfCnpj(String cpfCnpj) {
this.cpfCnpj = cpfCnpj;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getNumberEM() {
return numberEM;
}
public void setNumberEM(String numberEM) {
this.numberEM = numberEM;
}
public String getNumberGFCID() {
return numberGFCID;
}
public void setNumberGFCID(String numberGFCID) {
this.numberGFCID = numberGFCID;
}
public String getNameBanker() {
return nameBanker;
}
public void setNameBanker(String nameBanker) {
this.nameBanker = nameBanker;
}
public String getCustomerStatus() {
return customerStatus;
}
public void setCustomerStatus(String customerStatus) {
this.customerStatus = customerStatus;
}
public String getCustomerTitulo() {
return customerTitulo;
}
public void setCustomerTitulo(String customerTitulo) {
this.customerTitulo = customerTitulo;
}
public String getBirthDate() {
return birthDate;
}
public void setBirthDate(String birthDate) {
this.birthDate = birthDate;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getCivilState() {
return civilState;
}
public void setCivilState(String civilState) {
this.civilState = civilState;
}
public Integer getNumberDependents() {
return numberDependents;
}
public void setNumberDependents(Integer numberDependents) {
this.numberDependents = numberDependents;
}
public String getSpouseName() {
return spouseName;
}
public void setSpouseName(String spouseName) {
this.spouseName = spouseName;
}
public String getCountryBirth() {
return countryBirth;
}
public void setCountryBirth(String countryBirth) {
this.countryBirth = countryBirth;
}
public String getPlaceOfBirth() {
return placeOfBirth;
}
public void setPlaceOfBirth(String placeOfBirth) {
this.placeOfBirth = placeOfBirth;
}
public String getUfPlaceOfBirth() {
return ufPlaceOfBirth;
}
public void setUfPlaceOfBirth(String ufPlaceOfBirth) {
this.ufPlaceOfBirth = ufPlaceOfBirth;
}
public String getIdentityDocument() {
return identityDocument;
}
public void setIdentityDocument(String identityDocument) {
this.identityDocument = identityDocument;
}
public String getEmitType() {
return emitType;
}
public void setEmitType(String emitType) {
this.emitType = emitType;
}
public String getEmitDocumentUF() {
return emitDocumentUF;
}
public void setEmitDocumentUF(String emitDocumentUF) {
this.emitDocumentUF = emitDocumentUF;
}
public String getEmitDocumentDate() {
return emitDocumentDate;
}
public void setEmitDocumentDate(String emitDocumentDate) {
this.emitDocumentDate = emitDocumentDate;
}
public String getOccupation() {
return occupation;
}
public void setOccupation(String occupation) {
this.occupation = occupation;
}
public String getOccupationNature() {
return occupationNature;
}
public void setOccupationNature(String occupationNature) {
this.occupationNature = occupationNature;
}
public String getDeclaredIncome() {
return declaredIncome;
}
public void setDeclaredIncome(String declaredIncome) {
this.declaredIncome = declaredIncome;
}
public String getDeclaredHeritage() {
return declaredHeritage;
}
public void setDeclaredHeritage(String declaredHeritage) {
this.declaredHeritage = declaredHeritage;
}
public Boolean getIsEmployee() {
return isEmployee;
}
public void setIsEmployee(Boolean isEmployee) {
this.isEmployee = isEmployee;
}
public Boolean getIsDeceased() {
return isDeceased;
}
public void setIsDeceased(Boolean isDeceased) {
this.isDeceased = isDeceased;
}
public String getSOEIDBankerNumber() {
return SOEIDBankerNumber;
}
public void setSOEIDBankerNumber(String sOEIDBankerNumber) {
SOEIDBankerNumber = sOEIDBankerNumber;
}
public String getSOEIDBankerName() {
return SOEIDBankerName;
}
public void setSOEIDBankerName(String sOEIDBankerName) {
SOEIDBankerName = sOEIDBankerName;
}
public Boolean getHaveGreenCard() {
return haveGreenCard;
}
public void setHaveGreenCard(Boolean haveGreenCard) {
this.haveGreenCard = haveGreenCard;
}
public String getSocialSecurityNumber() {
return socialSecurityNumber;
}
public void setSocialSecurityNumber(String socialSecurityNumber) {
this.socialSecurityNumber = socialSecurityNumber;
}
public Boolean getExemptIR() {
return exemptIR;
}
public void setExemptIR(Boolean exemptIR) {
this.exemptIR = exemptIR;
}
public String getActivityMain() {
return activityMain;
}
public void setActivityMain(String activityMain) {
this.activityMain = activityMain;
}
public String getConstType() {
return constType;
}
public void setConstType(String constType) {
this.constType = constType;
}
public String getNaicNumber() {
return naicNumber;
}
public void setNaicNumber(String naicNumber) {
this.naicNumber = naicNumber;
}
public String getSicNumber() {
return sicNumber;
}
public void setSicNumber(String sicNumber) {
this.sicNumber = sicNumber;
}
public String getFoundationDate() {
return foundationDate;
}
public void setFoundationDate(String foundationDate) {
this.foundationDate = foundationDate;
}
public String getAverageMonthBilling() {
return averageMonthBilling;
}
public void setAverageMonthBilling(String averageMonthBilling) {
this.averageMonthBilling = averageMonthBilling;
}
public String getAdmName() {
return admName;
}
public void setAdmName(String admName) {
this.admName = admName;
}
public String getAdmCpf() {
return admCpf;
}
public void setAdmCpf(String admCpf) {
this.admCpf = admCpf;
}
public Boolean getHasFlexAccount() {
return hasFlexAccount;
}
public void setHasFlexAccount(Boolean hasFlexAccount) {
this.hasFlexAccount = hasFlexAccount;
}
public Boolean getIsSensitive() {
return isSensitive;
}
public void setIsSensitive(Boolean isSensitive) {
this.isSensitive = isSensitive;
}
public String getTypeClass() {
return typeClass;
}
public void setTypeClass(String typeClass) {
this.typeClass = typeClass;
}
public Boolean getDerogatoryInformation() {
return derogatoryInformation;
}
public void setDerogatoryInformation(Boolean derogatoryInformation) {
this.derogatoryInformation = derogatoryInformation;
}
public AddressVO getResidentialAddress() {
if(residentialAddress ==null){
residentialAddress = new AddressVO();
}
return residentialAddress;
}
public void setResidentialAddress(AddressVO residentialAddress) {
this.residentialAddress = residentialAddress;
}
public AddressVO getBusinessAddress() {
if(businessAddress ==null){
businessAddress = new AddressVO();
}
return businessAddress;
}
public void setBusinessAddress(AddressVO businessAddress) {
this.businessAddress = businessAddress;
}
public AddressVO getOtherAddress() {
if(otherAddress ==null){
otherAddress = new AddressVO();
}
return otherAddress;
}
public void setOtherAddress(AddressVO otherAddress) {
this.otherAddress = otherAddress;
}
public AddressVO getHeadOfficeAddress() {
if(headOfficeAddress ==null){
headOfficeAddress = new AddressVO();
}
return headOfficeAddress;
}
public void setHeadOfficeAddress(AddressVO headOfficeAddress) {
this.headOfficeAddress = headOfficeAddress;
}
public ArrayList<TelephoneVO> getTelephoneList() {
return telephoneList;
}
public void setTelephoneList(ArrayList<TelephoneVO> telephoneList) {
this.telephoneList = telephoneList;
}
public ArrayList<MailVO> getMailList() {
return mailList;
}
public void setMailList(ArrayList<MailVO> mailList) {
this.mailList = mailList;
}
public ArrayList<CustomerCountryVO> getCitizenshipList() {
return citizenshipList;
}
public void setCitizenshipList(ArrayList<CustomerCountryVO> citizenshipList) {
this.citizenshipList = citizenshipList;
}
public TableTypeEnum getTableOrigin() {
return tableOrigin;
}
public void setTableOrigin(TableTypeEnum tableOrigin) {
this.tableOrigin = tableOrigin;
}
public ArrayList<CustomerCountryVO> getFiscalResidenceList() {
return fiscalResidenceList;
}
public void setFiscalResidenceList(ArrayList<CustomerCountryVO> fiscalResidenceList) {
this.fiscalResidenceList = fiscalResidenceList;
}
public Boolean getIsFatca() {
return isFatca;
}
public void setIsFatca(Boolean isFatca) {
this.isFatca = isFatca;
}
public Boolean getIsCrs() {
return isCrs;
}
public void setIsCrs(Boolean isCrs) {
this.isCrs = isCrs;
}
public String getFormType() {
return formType;
}
public void setFormType(String formType) {
this.formType = formType;
}
public String getRecStatCode() {
return recStatCode;
}
public void setRecStatCode(String recStatCode) {
this.recStatCode = recStatCode;
}
public String getRecStatCodeText() {
if(recStatCode!=null){
if(recStatCode.equals("A")){
return "Alteração";
}else if(recStatCode.equals("U")){
return "Inclusão";
}else if(recStatCode.equals("I")){
return "Exclusão";
}else{
return "";
}
}else{
return "";
}
}
public String getCustomerTypeDesc() {
if(!StringUtils.isBlank(customerType)){
if(CustomerTypeEnum.fromValue(customerType)!=null){
customerTypeDesc = CustomerTypeEnum.fromValue(customerType).getDesc();
}
}
return customerTypeDesc;
}
public void setCustomerTypeDesc(String customerTypeDesc) {
this.customerTypeDesc = customerTypeDesc;
}
public String getCustCreateDate() {
return custCreateDate;
}
public void setCustCreateDate(String custCreateDate) {
this.custCreateDate = custCreateDate;
}
public String getCustCreateUser() {
return custCreateUser;
}
public void setCustCreateUser(String custCreateUser) {
this.custCreateUser = custCreateUser;
}
public String getCountryConstitution() {
return countryConstitution;
}
public void setCountryConstitution(String countryConstitution) {
this.countryConstitution = countryConstitution;
}
public Boolean getIsAnnualReview() {
return isAnnualReview;
}
public void setIsAnnualReview(Boolean isAnnualReview) {
this.isAnnualReview = isAnnualReview;
}
public ErEmVO getEr_em() {
if(er_em ==null){
er_em = new ErEmVO();
}
return er_em;
}
public void setEr_em(ErEmVO er_em) {
this.er_em = er_em;
}
public Date getLastAnnualReviewDate() {
return lastAnnualReviewDate;
}
public void setLastAnnualReviewDate(Date lastAnnualReviewDate) {
this.lastAnnualReviewDate = lastAnnualReviewDate;
}
public String getLastAnnualReviewDateFormatedDDMMYYYY() {
if(lastAnnualReviewDate!=null){
return FormatUtils.dateToString(lastAnnualReviewDate, FormatUtils.C_FORMAT_DATE_DD_MM_YYYY);
}else{
return "";
}
}
public String getCustCreateDateAndUser() {
if(!StringUtils.isBlank(getCustCreateDate()) || !StringUtils.isBlank(getCustCreateUser())){
return getCustCreateDate() + " - " +getCustCreateUser();
}else{
return "";
}
}
public void setCustCreateDateAndUser(String custCreateDateAndUser) {
this.custCreateDateAndUser = custCreateDateAndUser;
}
public String getLastAuthDateFormatedDDMMYYYYAndUser() {
if(!StringUtils.isBlank(getLastAuthDateFormatedDDMMYYYY()) || !StringUtils.isBlank(getLastAuthUser()) || !StringUtils.isBlank(getLastUpdUserSafe())){
return getLastAuthDateFormatedDDMMYYYY() + " - " + getLastUpdUserSafe() + " - " + getLastAuthUser();
}else{
return "";
}
}
public void setLastAuthDateFormatedDDMMYYYYAndUser(
String lastAuthDateFormatedDDMMYYYYAndUser) {
this.lastAuthDateFormatedDDMMYYYYAndUser = lastAuthDateFormatedDDMMYYYYAndUser;
}
public String getFiliation1() {
return filiation1;
}
public void setFiliation1(String filiation1) {
this.filiation1 = filiation1;
}
public String getFiliation2() {
return filiation2;
}
public void setFiliation2(String filiation2) {
this.filiation2 = filiation2;
}
public String getSignatureDateFatca() {
return signatureDateFatca;
}
public void setSignatureDateFatca(String signatureDateFatca) {
this.signatureDateFatca = signatureDateFatca;
}
public String getSignatureDateCrs() {
return signatureDateCrs;
}
public void setSignatureDateCrs(String signatureDateCrs) {
this.signatureDateCrs = signatureDateCrs;
}
public Boolean getCustFatcaPjInUs() {
return custFatcaPjInUs;
}
public void setCustFatcaPjInUs(Boolean custFatcaPjInUs) {
this.custFatcaPjInUs = custFatcaPjInUs;
}
public Boolean getCustFatcaPjOutUs() {
return custFatcaPjOutUs;
}
public void setCustFatcaPjOutUs(Boolean custFatcaPjOutUs) {
this.custFatcaPjOutUs = custFatcaPjOutUs;
}
public Boolean getCustFatcaPjOwnrUs() {
return custFatcaPjOwnrUs;
}
public void setCustFatcaPjOwnrUs(Boolean custFatcaPjOwnrUs) {
this.custFatcaPjOwnrUs = custFatcaPjOwnrUs;
}
public Boolean getCustCrsPjAddrOutUs() {
return custCrsPjAddrOutUs;
}
public void setCustCrsPjAddrOutUs(Boolean custCrsPjAddrOutUs) {
this.custCrsPjAddrOutUs = custCrsPjAddrOutUs;
}
public Boolean getCustCrsPjEnfLiab() {
return custCrsPjEnfLiab;
}
public void setCustCrsPjEnfLiab(Boolean custCrsPjEnfLiab) {
this.custCrsPjEnfLiab = custCrsPjEnfLiab;
}
public Boolean getCustCrsPjInvstOut() {
return custCrsPjInvstOut;
}
public void setCustCrsPjInvstOut(Boolean custCrsPjInvstOut) {
this.custCrsPjInvstOut = custCrsPjInvstOut;
}
public ArrayList<String> equals(RegisterDataCustomerVO other) {
ArrayList<String> idDiffList = new ArrayList<String>();
if (other != null){
if (this.cpfCnpj != null && other.cpfCnpj != null) {
if (!this.cpfCnpj.equals(other.cpfCnpj)) {
idDiffList.add("cpfCnpj");
}
} else if ((this.cpfCnpj == null && other.cpfCnpj != null) || (other.cpfCnpj == null && this.cpfCnpj != null)) {
idDiffList.add("cpfCnpj");
}
if (this.numberGFCID != null && other.numberGFCID != null) {
if (!this.numberGFCID.equals(other.numberGFCID)) {
idDiffList.add("numberGFCID");
}
} else if ((this.numberGFCID == null && other.numberGFCID != null) || (other.numberGFCID == null && this.numberGFCID != null)) {
idDiffList.add("numberGFCID");
}
if (this.customerType != null && other.customerType != null) {
if (!this.customerType.equals(other.customerType)) {
idDiffList.add("customerType");
}
} else if ((this.customerType == null && other.customerType != null) || (other.customerType == null && this.customerType != null)) {
idDiffList.add("customerType");
}
if (this.name != null && other.name != null) {
if (!this.name.equals(other.name)) {
idDiffList.add("name");
}
} else if ((this.name == null && other.name != null) || (other.name == null && this.name != null)) {
idDiffList.add("name");
}
if (this.numberEM != null && other.numberEM != null) {
if (!this.numberEM.equals(other.numberEM)) {
idDiffList.add("numberEM");
}
} else if ((this.numberEM == null && other.numberEM != null) || (other.numberEM == null && this.numberEM != null)) {
idDiffList.add("numberEM");
}
if (this.nameBanker != null && other.nameBanker != null) {
if (!this.nameBanker.equals(other.nameBanker)) {
idDiffList.add("nameBanker");
}
} else if ((this.nameBanker == null && other.nameBanker != null) || (other.nameBanker == null && this.nameBanker != null)) {
idDiffList.add("nameBanker");
}
if (this.customerStatus != null && other.customerStatus != null) {
if (!this.customerStatus.equals(other.customerStatus)) {
idDiffList.add("customerStatus");
}
} else if ((this.customerStatus == null && other.customerStatus != null) || (other.customerStatus == null && this.customerStatus != null)) {
idDiffList.add("customerStatus");
}
if (this.birthDate != null && other.birthDate != null) {
if (!this.birthDate.equals(other.birthDate)) {
idDiffList.add("birthDate");
}
} else if ((this.birthDate == null && other.birthDate != null) || (other.birthDate == null && this.birthDate != null)) {
idDiffList.add("birthDate");
}
if (this.gender != null && other.gender != null) {
if (!this.gender.equals(other.gender)) {
idDiffList.add("gender");
}
} else if ((this.gender == null && other.gender != null) || (other.gender == null && this.gender != null)) {
idDiffList.add("gender");
}
if (this.filiation1 != null && other.filiation1 != null) {
if (!this.filiation1.equals(other.filiation1)) {
idDiffList.add("filiation1");
}
} else if ((this.filiation1 == null && other.filiation1 != null) || (other.filiation1 == null && this.filiation1 != null)) {
idDiffList.add("filiation1");
}
if (this.filiation2 != null && other.filiation2 != null) {
if (!this.filiation2.equals(other.filiation2)) {
idDiffList.add("filiation2");
}
} else if ((this.filiation2 == null && other.filiation2 != null) || (other.filiation2 == null && this.filiation2 != null)) {
idDiffList.add("filiation2");
}
if (this.civilState != null && other.civilState != null) {
if (!this.civilState.equals(other.civilState)) {
idDiffList.add("civilState");
}
} else if ((this.civilState == null && other.civilState != null) || (other.civilState == null && this.civilState != null)) {
idDiffList.add("civilState");
}
if (this.numberDependents != null && other.numberDependents != null) {
if (!this.numberDependents.equals(other.numberDependents)) {
idDiffList.add("numberDependents");
}
} else if ((this.numberDependents == null && other.numberDependents != null) || (other.numberDependents == null && this.numberDependents != null)) {
idDiffList.add("numberDependents");
}
if (this.spouseName != null && other.spouseName != null) {
if (!this.spouseName.equals(other.spouseName)) {
idDiffList.add("spouseName");
}
} else if ((this.spouseName == null && other.spouseName != null) || (other.spouseName == null && this.spouseName != null)) {
idDiffList.add("spouseName");
}
if (this.countryBirth != null && other.countryBirth != null) {
if (!this.countryBirth.equals(other.countryBirth)) {
idDiffList.add("countryBirth");
}
} else if ((this.countryBirth == null && other.countryBirth != null) || (other.countryBirth == null && this.countryBirth != null)) {
idDiffList.add("countryBirth");
}
if (this.placeOfBirth != null && other.placeOfBirth != null) {
if (!this.placeOfBirth.equals(other.placeOfBirth)) {
idDiffList.add("");
}
} else if ((this.placeOfBirth == null && other.placeOfBirth != null) || (other.placeOfBirth == null && this.placeOfBirth != null)) {
idDiffList.add("placeOfBirth");
}
if (this.ufPlaceOfBirth != null && other.ufPlaceOfBirth != null) {
if (!this.ufPlaceOfBirth.equals(other.ufPlaceOfBirth)) {
idDiffList.add("ufPlaceOfBirth");
}
} else if ((this.ufPlaceOfBirth == null && other.ufPlaceOfBirth != null) || (other.ufPlaceOfBirth == null && this.ufPlaceOfBirth != null)) {
idDiffList.add("ufPlaceOfBirth");
}
if (this.identityDocument != null && other.identityDocument != null) {
if (!this.identityDocument.equals(other.identityDocument)) {
idDiffList.add("identityDocument");
}
} else if ((this.identityDocument == null && other.identityDocument != null) || (other.identityDocument == null && this.identityDocument != null)) {
idDiffList.add("identityDocument");
}
if (this.emitType != null && other.emitType != null) {
if (!this.emitType.equals(other.emitType)) {
idDiffList.add("emitType");
}
} else if ((this.emitType == null && other.emitType != null) || (other.emitType == null && this.emitType != null)) {
idDiffList.add("emitType");
}
if (this.emitDocumentUF != null && other.emitDocumentUF != null) {
if (!this.emitDocumentUF.equals(other.emitDocumentUF)) {
idDiffList.add("emitDocumentUF");
}
} else if ((this.emitDocumentUF == null && other.emitDocumentUF != null) || (other.emitDocumentUF == null && this.emitDocumentUF != null)) {
idDiffList.add("emitDocumentUF");
}
if (this.emitDocumentDate != null && other.emitDocumentDate != null) {
if (!this.emitDocumentDate.equals(other.emitDocumentDate)) {
idDiffList.add("emitDocumentDate");
}
} else if ((this.emitDocumentDate == null && other.emitDocumentDate != null) || (other.emitDocumentDate == null && this.emitDocumentDate != null)) {
idDiffList.add("emitDocumentDate");
}
if (this.occupation != null && other.occupation != null) {
if (!this.occupation.equals(other.occupation)) {
idDiffList.add("occupation");
}
} else if ((this.occupation == null && other.occupation != null) || (other.occupation == null && this.occupation != null)) {
idDiffList.add("occupation");
}
if (this.occupationNature != null && other.occupationNature != null) {
if (!this.occupationNature.equals(other.occupationNature)) {
idDiffList.add("occupationNature");
}
} else if ((this.occupationNature == null && other.occupationNature != null) || (other.occupationNature == null && this.occupationNature != null)) {
idDiffList.add("occupationNature");
}
if (this.declaredIncome != null && other.declaredIncome != null) {
if (!this.declaredIncome.equals(other.declaredIncome)) {
idDiffList.add("declaredIncome");
}
} else if ((this.declaredIncome == null && other.declaredIncome != null) || (other.declaredIncome == null && this.declaredIncome != null)) {
idDiffList.add("declaredIncome");
}
if (this.declaredHeritage != null && other.declaredHeritage != null) {
if (!this.declaredHeritage.equals(other.declaredHeritage)) {
idDiffList.add("declaredHeritage");
}
} else if ((this.declaredHeritage == null && other.declaredHeritage != null) || (other.declaredHeritage == null && this.declaredHeritage != null)) {
idDiffList.add("declaredHeritage");
}
if (this.isEmployee != null && other.isEmployee != null) {
if (!this.isEmployee.equals(other.isEmployee)) {
idDiffList.add("employeeDiv");
}
} else if ((this.isEmployee == null && other.isEmployee != null) || (other.isEmployee == null && this.isEmployee != null)) {
idDiffList.add("employeeDiv");
}
if (this.isDeceased != null && other.isDeceased != null) {
if (!this.isDeceased.equals(other.isDeceased)) {
idDiffList.add("deceasedDiv");
}
} else if ((this.isDeceased == null && other.isDeceased != null) || (other.isDeceased == null && this.isDeceased != null)) {
idDiffList.add("deceasedDiv");
}
if (this.SOEIDBankerNumber != null && other.SOEIDBankerNumber != null) {
if (!this.SOEIDBankerNumber.equals(other.SOEIDBankerNumber)) {
idDiffList.add("SOEIDBankerNumber");
}
} else if ((this.SOEIDBankerNumber == null && other.SOEIDBankerNumber != null) || (other.SOEIDBankerNumber == null && this.SOEIDBankerNumber != null)) {
idDiffList.add("SOEIDBankerNumber");
}
if (this.SOEIDBankerName != null && other.SOEIDBankerName != null) {
if (!this.SOEIDBankerName.equals(other.SOEIDBankerName)) {
idDiffList.add("SOEIDBankerName");
}
} else if ((this.SOEIDBankerName == null && other.SOEIDBankerName != null) || (other.SOEIDBankerName == null && this.SOEIDBankerName != null)) {
idDiffList.add("SOEIDBankerName");
}
if (this.haveGreenCard != null && other.haveGreenCard != null) {
if (!this.haveGreenCard.equals(other.haveGreenCard)) {
idDiffList.add("haveGreenCardDiv");
}
} else if ((this.haveGreenCard == null && other.haveGreenCard != null) || (other.haveGreenCard == null && this.haveGreenCard != null)) {
idDiffList.add("haveGreenCardDiv");
}
if (this.socialSecurityNumber != null && other.socialSecurityNumber != null) {
if (!this.socialSecurityNumber.equals(other.socialSecurityNumber)) {
idDiffList.add("socialSecurityNumber");
}
} else if ((this.socialSecurityNumber == null && other.socialSecurityNumber != null) || (other.socialSecurityNumber == null && this.socialSecurityNumber != null)) {
idDiffList.add("socialSecurityNumber");
}
if (this.exemptIR != null && other.exemptIR != null) {
if (!this.exemptIR.equals(other.exemptIR)) {
idDiffList.add("exemptIRDiv");
}
} else if ((this.exemptIR == null && other.exemptIR != null) || (other.exemptIR == null && this.exemptIR != null)) {
idDiffList.add("exemptIRDiv");
}
if (this.activityMain != null && other.activityMain != null) {
if (!this.activityMain.equals(other.activityMain)) {
idDiffList.add("activityMain");
}
} else if ((this.activityMain == null && other.activityMain != null) || (other.activityMain == null && this.activityMain != null)) {
idDiffList.add("activityMain");
}
if (this.constType != null && other.constType != null) {
if (!this.constType.equals(other.constType)) {
idDiffList.add("constType");
}
} else if ((this.constType == null && other.constType != null) || (other.constType == null && this.constType != null)) {
idDiffList.add("constType");
}
if (this.naicNumber != null && other.naicNumber != null) {
if (!this.naicNumber.equals(other.naicNumber)) {
idDiffList.add("naicNumber");
}
} else if ((this.naicNumber == null && other.naicNumber != null) || (other.naicNumber == null && this.naicNumber != null)) {
idDiffList.add("naicNumber");
}
if (this.sicNumber != null && other.sicNumber != null) {
if (!this.sicNumber.equals(other.sicNumber)) {
idDiffList.add("sicNumber");
}
} else if ((this.sicNumber == null && other.sicNumber != null) || (other.sicNumber == null && this.sicNumber != null)) {
idDiffList.add("sicNumber");
}
if (this.foundationDate != null && other.foundationDate != null) {
if (!this.foundationDate.equals(other.foundationDate)) {
idDiffList.add("foundationDate");
}
} else if ((this.foundationDate == null && other.foundationDate != null) || (other.foundationDate == null && this.foundationDate != null)) {
idDiffList.add("foundationDate");
}
if (this.averageMonthBilling != null && other.averageMonthBilling != null) {
if (!this.averageMonthBilling.equals(other.averageMonthBilling)) {
idDiffList.add("averageMonthBilling");
}
} else if ((this.averageMonthBilling == null && other.averageMonthBilling != null) || (other.averageMonthBilling == null && this.averageMonthBilling != null)) {
idDiffList.add("averageMonthBilling");
}
if (this.admName != null && other.admName != null) {
if (!this.admName.equals(other.admName)) {
idDiffList.add("admName");
}
} else if ((this.admName == null && other.admName != null) || (other.admName == null && this.admName != null)) {
idDiffList.add("admName");
}
if (this.admCpf != null && other.admCpf != null) {
if (!this.admCpf.equals(other.admCpf)) {
idDiffList.add("admCpf");
}
} else if ((this.admCpf == null && other.admCpf != null) || (other.admCpf == null && this.admCpf != null)) {
idDiffList.add("admCpf");
}
if (this.hasFlexAccount != null && other.hasFlexAccount != null) {
if (!this.hasFlexAccount.equals(other.hasFlexAccount)) {
idDiffList.add("hasFlexAccountDiv");
}
} else if ((this.hasFlexAccount == null && other.hasFlexAccount != null) || (other.hasFlexAccount == null && this.hasFlexAccount != null)) {
idDiffList.add("hasFlexAccountDiv");
}
if (this.isSensitive != null && other.isSensitive != null) {
if (!this.isSensitive.equals(other.isSensitive)) {
idDiffList.add("sensitiveDiv");
}
} else if ((this.isSensitive == null && other.isSensitive != null) || (other.isSensitive == null && this.isSensitive != null)) {
idDiffList.add("sensitiveDiv");
}
if (this.typeClass != null && other.typeClass != null) {
if (!this.typeClass.equals(other.typeClass)) {
idDiffList.add("typeClassDiv");
}
} else if ((this.typeClass == null && other.typeClass != null) || (other.typeClass == null && this.typeClass != null)) {
idDiffList.add("typeClassDiv");
}
if (this.derogatoryInformation != null && other.derogatoryInformation != null) {
if (!this.derogatoryInformation.equals(other.derogatoryInformation)) {
idDiffList.add("derogatoryInformationDiv");
}
} else if ((this.derogatoryInformation == null && other.derogatoryInformation != null) || (other.derogatoryInformation == null && this.derogatoryInformation != null)) {
idDiffList.add("derogatoryInformationDiv");
}
if (this.isFatca != null && other.isFatca != null) {
if (!this.isFatca.equals(other.isFatca)) {
idDiffList.add("isFatcaTr");
}
} else if ((this.isFatca == null && other.isFatca != null) || (other.isFatca == null && this.isFatca != null)) {
idDiffList.add("isFatcaTr");
}
if (this.isCrs != null && other.isCrs != null) {
if (!this.isCrs.equals(other.isCrs)) {
idDiffList.add("isCrsTr");
}
} else if ((this.isCrs == null && other.isCrs != null) || (other.isCrs == null && this.isCrs != null)) {
idDiffList.add("isCrsTr");
}
if (this.formType != null && other.formType != null) {
if (!this.formType.equals(other.formType)) {
idDiffList.add("formTypeDiv");
}
} else if ((this.formType == null && other.formType != null) || (other.formType == null && this.formType != null)) {
idDiffList.add("formTypeDiv");
}
if (this.signatureDateFatca != null && other.signatureDateFatca != null) {
if (!this.signatureDateFatca.equals(other.signatureDateFatca)) {
idDiffList.add("signatureDateFatca");
}
} else if ((this.signatureDateFatca == null && other.signatureDateFatca != null) || (other.signatureDateFatca == null && this.signatureDateFatca != null)) {
idDiffList.add("signatureDateFatca");
}
if (this.signatureDateCrs != null && other.signatureDateCrs != null) {
if (!this.signatureDateCrs.equals(other.signatureDateCrs)) {
idDiffList.add("signatureDateCrs");
}
} else if ((this.signatureDateCrs == null && other.signatureDateCrs != null) || (other.signatureDateCrs == null && this.signatureDateCrs != null)) {
idDiffList.add("signatureDateCrs");
}
String residentialAddressType ="residentialAddress." ;
String businessAddressType ="businessAddress." ;
String otherAddressType = "otherAddress.";
String headOfficeAddressType = "headOfficeAddress." ;
if (this.residentialAddress != null && other.residentialAddress != null) {
idDiffList.addAll(this.residentialAddress.equals(other.residentialAddress, residentialAddressType));
} else if ((this.residentialAddress == null && other.residentialAddress != null) || (other.residentialAddress == null && this.residentialAddress != null)) {
idDiffList.add(residentialAddressType+"street");
idDiffList.add(residentialAddressType+"neighborhood");
idDiffList.add(residentialAddressType+"city");
idDiffList.add(residentialAddressType+"uf");
idDiffList.add(residentialAddressType+"zipCode");
idDiffList.add(residentialAddressType+"isCorrespondenceDiv");
}
if (this.businessAddress != null && other.businessAddress != null) {
idDiffList.addAll(this.businessAddress.equals(other.businessAddress,businessAddressType));
} else if ((this.businessAddress == null && other.businessAddress != null) || (other.businessAddress == null && this.businessAddress != null)) {
idDiffList.add(businessAddressType+"street");
idDiffList.add(businessAddressType+"neighborhood");
idDiffList.add(businessAddressType+"city");
idDiffList.add(businessAddressType+"uf");
idDiffList.add(businessAddressType+"zipCode");
idDiffList.add(businessAddressType+"isCorrespondenceDiv");
}
if (this.otherAddress != null && other.otherAddress != null) {
idDiffList.addAll(this.otherAddress.equals(other.otherAddress, otherAddressType));
} else if ((this.otherAddress == null && other.otherAddress != null) || (other.otherAddress == null && this.otherAddress != null)) {
idDiffList.add(otherAddressType+"street");
idDiffList.add(otherAddressType+"neighborhood");
idDiffList.add(otherAddressType+"city");
idDiffList.add(otherAddressType+"uf");
idDiffList.add(otherAddressType+"zipCode");
idDiffList.add(otherAddressType+"isCorrespondenceDiv");
}
if (this.headOfficeAddress != null && other.headOfficeAddress != null) {
idDiffList.addAll(this.headOfficeAddress.equals(other.headOfficeAddress, headOfficeAddressType));
} else if ((this.headOfficeAddress == null && other.headOfficeAddress != null) || (other.headOfficeAddress == null && this.headOfficeAddress != null)) {
idDiffList.add(headOfficeAddressType+"street");
idDiffList.add(headOfficeAddressType+"neighborhood");
idDiffList.add(headOfficeAddressType+"city");
idDiffList.add(headOfficeAddressType+"uf");
idDiffList.add(headOfficeAddressType+"zipCode");
idDiffList.add(headOfficeAddressType+"isCorrespondenceDiv");
}
if (this.telephoneList != null && other.telephoneList != null) {
ArrayList<TelephoneVO> largerList = new ArrayList<TelephoneVO>();
ArrayList<TelephoneVO> smallerList = new ArrayList<TelephoneVO>();
if(this.telephoneList.size() > other.telephoneList.size()){
smallerList = other.telephoneList;
largerList = this.telephoneList;
}else{
smallerList = this.telephoneList;
largerList = other.telephoneList;
}
for (TelephoneVO item : largerList) {
boolean isNew = true;
for (TelephoneVO itemOther : smallerList) {
if(item.getPosition()!=null && itemOther.getPosition()!=null && item.getPosition().equals(itemOther.getPosition())){
idDiffList.addAll(item.equals(itemOther));
isNew = false;
}
}
if(isNew){
idDiffList.add("telephoneList["+item.getPositionIndex()+"].ddd");
idDiffList.add("telephoneList["+item.getPositionIndex()+"].number");
}
}
}else if(this.telephoneList == null && other.telephoneList != null){
for (TelephoneVO item : other.telephoneList) {
if(item.getPosition()!=null){
idDiffList.add("telephoneList["+item.getPositionIndex()+"].ddd");
idDiffList.add("telephoneList["+item.getPositionIndex()+"].number");
}
}
}else if(other.telephoneList == null && this.telephoneList != null){
for (TelephoneVO item : this.telephoneList) {
if(item.getPosition()!=null){
idDiffList.add("telephoneList["+item.getPositionIndex()+"].ddd");
idDiffList.add("telephoneList["+item.getPositionIndex()+"].number");
}
}
}
if (this.mailList != null && other.mailList != null) {
ArrayList<MailVO> largerList = new ArrayList<MailVO>();
ArrayList<MailVO> smallerList = new ArrayList<MailVO>();
if(this.mailList.size() > other.mailList.size()){
smallerList = other.mailList;
largerList = this.mailList;
}else{
smallerList = this.mailList;
largerList = other.mailList;
}
for (MailVO item : largerList) {
boolean isNew = true;
for (MailVO itemOther : smallerList) {
if(item.getPosition()!=null && itemOther.getPosition()!=null && item.getPosition().equals(itemOther.getPosition())){
idDiffList.addAll(item.equals(itemOther));
isNew = false;
}
}
if(isNew){
idDiffList.add("mailList["+item.getPositionIndex()+"].mail");
}
}
}else if(this.mailList == null && other.mailList != null){
for (MailVO item : other.mailList) {
if(item.getPosition()!=null){
idDiffList.add("mailList["+item.getPositionIndex()+"].mail");
}
}
}else if(other.mailList == null && this.mailList != null){
for (MailVO item : this.mailList) {
if(item.getPosition()!=null){
idDiffList.add("mailList["+item.getPositionIndex()+"].mail");
}
}
}
if (this.citizenshipList != null && other.citizenshipList != null) {
ArrayList<CustomerCountryVO> largerList = new ArrayList<CustomerCountryVO>();
ArrayList<CustomerCountryVO> smallerList = new ArrayList<CustomerCountryVO>();
if(this.citizenshipList.size() > other.citizenshipList.size()){
smallerList = other.citizenshipList;
largerList = this.citizenshipList;
}else{
smallerList = this.citizenshipList;
largerList = other.citizenshipList;
}
for (CustomerCountryVO item : largerList) {
boolean isNew = true;
for (CustomerCountryVO itemOther : smallerList) {
if(item.getPosition()!=null && itemOther.getPosition()!=null && item.getPosition().equals(itemOther.getPosition())){
idDiffList.addAll(item.equals(itemOther));
isNew = false;
}
}
if(isNew){
idDiffList.add("citizenshipList["+item.getPositionIndex()+"].country");
}
}
}else if(this.citizenshipList == null && other.citizenshipList != null){
for (CustomerCountryVO item : other.citizenshipList) {
if(item.getPosition()!=null){
idDiffList.add("citizenshipList["+item.getPositionIndex()+"].country");
}
}
}else if(other.citizenshipList == null && this.citizenshipList != null){
for (CustomerCountryVO item : this.citizenshipList) {
if(item.getPosition()!=null){
idDiffList.add("citizenshipList["+item.getPositionIndex()+"].country");
}
}
}
if (this.fiscalResidenceList != null && other.fiscalResidenceList != null) {
ArrayList<CustomerCountryVO> largerList = new ArrayList<CustomerCountryVO>();
ArrayList<CustomerCountryVO> smallerList = new ArrayList<CustomerCountryVO>();
if(this.fiscalResidenceList.size() > other.fiscalResidenceList.size()){
smallerList = other.fiscalResidenceList;
largerList = this.fiscalResidenceList;
}else{
smallerList = this.fiscalResidenceList;
largerList = other.fiscalResidenceList;
}
for (CustomerCountryVO item : largerList) {
boolean isNew = true;
for (CustomerCountryVO itemOther : smallerList) {
if(item.getPosition()!=null && itemOther.getPosition()!=null && item.getPosition().equals(itemOther.getPosition())){
idDiffList.addAll(item.equals(itemOther));
isNew = false;
}
}
if(isNew){
idDiffList.add("fiscalResidenceList["+item.getPositionIndex()+"].country");
}
}
}else if(this.fiscalResidenceList == null && other.fiscalResidenceList != null){
for (CustomerCountryVO item : other.fiscalResidenceList) {
if(item.getPosition()!=null){
idDiffList.add("fiscalResidenceList["+item.getPositionIndex()+"].country");
}
}
}else if(other.fiscalResidenceList == null && this.fiscalResidenceList != null){
for (CustomerCountryVO item : this.fiscalResidenceList) {
if(item.getPosition()!=null){
idDiffList.add("fiscalResidenceList["+item.getPositionIndex()+"].country");
}
}
}
if (this.er_em != null && other.er_em != null) {
idDiffList.addAll(this.er_em.equals(other.er_em));
} else if ((this.er_em == null && other.er_em != null) || (other.er_em == null && this.er_em != null)) {
idDiffList.add("er_em");
}
}else{
idDiffList.add("cpfCnpj");
idDiffList.add("numberGFCID");
idDiffList.add("customerType");
idDiffList.add("name");
idDiffList.add("numberEM");
idDiffList.add("nameBanker");
idDiffList.add("customerStatus");
idDiffList.add("birthDate");
idDiffList.add("gender");
idDiffList.add("filiation1");
idDiffList.add("filiation2");
idDiffList.add("civilState");
idDiffList.add("numberDependents");
idDiffList.add("spouseName");
idDiffList.add("countryBirth");
idDiffList.add("");
idDiffList.add("ufPlaceOfBirth");
idDiffList.add("identityDocument");
idDiffList.add("emitType");
idDiffList.add("emitDocumentUF");
idDiffList.add("emitDocumentDate");
idDiffList.add("occupation");
idDiffList.add("occupationNature");
idDiffList.add("declaredIncome");
idDiffList.add("declaredHeritage");
idDiffList.add("employeeDiv");
idDiffList.add("deceasedDiv");
idDiffList.add("SOEIDBankerNumber");
idDiffList.add("SOEIDBankerName");
idDiffList.add("haveGreenCardDiv");
idDiffList.add("socialSecurityNumber");
idDiffList.add("exemptIRDiv");
idDiffList.add("activityMain");
idDiffList.add("constType");
idDiffList.add("naicNumber");
idDiffList.add("sicNumber");
idDiffList.add("foundationDate");
idDiffList.add("averageMonthBilling");
idDiffList.add("admName");
idDiffList.add("admCpf");
idDiffList.add("hasFlexAccountDiv");
idDiffList.add("sensitiveDiv");
idDiffList.add("typeClassDiv");
idDiffList.add("derogatoryInformationDiv");
idDiffList.add("isFatcaTr");
idDiffList.add("isCrsTr");
idDiffList.add("formTypeDiv");
idDiffList.add("signatureDateCrs");
idDiffList.add("signatureDateFatca");
idDiffList.addAll(this.residentialAddress.equals(null, "residentialAddress."));
idDiffList.addAll(this.businessAddress.equals(null,"businessAddress."));
idDiffList.addAll(this.otherAddress.equals(null, "otherAddress."));
idDiffList.addAll(this.headOfficeAddress.equals(null, "headOfficeAddress."));
if (this.telephoneList!=null) {
for (TelephoneVO item : this.telephoneList) {
idDiffList.add("telephoneList["+item.getPosition()+"].ddd");
idDiffList.add("telephoneList["+item.getPosition()+"].number");
}
}
if (this.mailList!=null) {
for (MailVO item : this.mailList) {
idDiffList.add("mailList["+item.getPosition()+"].mail");
}
}
if (this.citizenshipList!=null) {
for (CustomerCountryVO item : this.citizenshipList) {
idDiffList.add("citizenshipList["+item.getPosition()+"].country");
}
}
if (this.fiscalResidenceList!=null) {
for (CustomerCountryVO item : this.fiscalResidenceList) {
idDiffList.add("fiscalResidenceList["+item.getPosition()+"].country");
}
}
idDiffList.add("er_em");
}
if (this.custFatcaPjInUs != null && other.custFatcaPjInUs != null) {
if (!this.custFatcaPjInUs.equals(other.custFatcaPjInUs)) {
idDiffList.add("custFatcaPjInUsDiv");
}
} else if ((this.custFatcaPjInUs == null && other.custFatcaPjInUs != null) || (other.custFatcaPjInUs == null && this.custFatcaPjInUs != null)) {
idDiffList.add("custFatcaPjInUsDiv");
}
if (this.custFatcaPjOutUs != null && other.custFatcaPjOutUs != null) {
if (!this.custFatcaPjOutUs.equals(other.custFatcaPjOutUs)) {
idDiffList.add("custFatcaPjOutUsDiv");
}
} else if ((this.custFatcaPjOutUs == null && other.custFatcaPjOutUs != null) || (other.custFatcaPjOutUs == null && this.custFatcaPjOutUs != null)) {
idDiffList.add("custFatcaPjOutUsDiv");
}
if (this.custFatcaPjOwnrUs != null && other.custFatcaPjOwnrUs != null) {
if (!this.custFatcaPjOwnrUs.equals(other.custFatcaPjOwnrUs)) {
idDiffList.add("custFatcaPjOwnrUsDiv");
}
} else if ((this.custFatcaPjOwnrUs == null && other.custFatcaPjOwnrUs != null) || (other.custFatcaPjOwnrUs == null && this.custFatcaPjOwnrUs != null)) {
idDiffList.add("custFatcaPjOwnrUsDiv");
}
if (this.custCrsPjAddrOutUs != null && other.custCrsPjAddrOutUs != null) {
if (!this.custCrsPjAddrOutUs.equals(other.custCrsPjAddrOutUs)) {
idDiffList.add("custCrsPjAddrOutUsDiv");
}
} else if ((this.custCrsPjAddrOutUs == null && other.custCrsPjAddrOutUs != null) || (other.custCrsPjAddrOutUs == null && this.custCrsPjAddrOutUs != null)) {
idDiffList.add("custCrsPjAddrOutUsDiv");
}
if (this.custCrsPjEnfLiab != null && other.custCrsPjEnfLiab != null) {
if (!this.custCrsPjEnfLiab.equals(other.custCrsPjEnfLiab)) {
idDiffList.add("custCrsPjEnfLiabDiv");
}
} else if ((this.custCrsPjEnfLiab == null && other.custCrsPjEnfLiab != null) || (other.custCrsPjEnfLiab == null && this.custCrsPjEnfLiab != null)) {
idDiffList.add("custCrsPjEnfLiabDiv");
}
if (this.custCrsPjInvstOut != null && other.custCrsPjInvstOut != null) {
if (!this.custCrsPjInvstOut.equals(other.custCrsPjInvstOut)) {
idDiffList.add("custCrsPjInvstOutDiv");
}
} else if ((this.custCrsPjInvstOut == null && other.custCrsPjInvstOut != null) || (other.custCrsPjInvstOut == null && this.custCrsPjInvstOut != null)) {
idDiffList.add("custCrsPjInvstOutDiv");
}
return idDiffList;
}
}
|
package com.in28mins.jdbctojpademo.jpa;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.TypedQuery;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import com.in28mins.jdbctojpademo.model.Course;
import com.in28mins.jdbctojpademo.model.Review;
@Repository
@Transactional
public class CourseRepository implements BeanPostProcessor {
Logger logger = LoggerFactory.getLogger(CourseRepository.class);
@Autowired
EntityManager en;
public List<Course> findAll() {
TypedQuery<Course> courseQuery = en.createNamedQuery("find_all_courses",Course.class);
return courseQuery.getResultList();
}
public Course findById(Long id) {
return en.find(Course.class, id);
}
public void deleteById(Long id) {
Course c = en.find(Course.class, id);
en.remove(c);
}
public Course save(Course c) {
if(c.getId() == null) {
en.persist(c);
}else {
en.merge(c);
}
return c;
}
public void playWithEntityManager() {
Course c = new Course("webservices beginner");
Course c1 = new Course("Angular beginner");
//persist will only update the respective object with entity manager and wont run query
en.persist(c);
en.persist(c1);
//Flush will run query and save to database
en.flush();
//If we exits out of method,due to @Transactional,query will run to
//update the below name
c.setName("webservices expert");
//run select query and update the c object present in entity manager,
//above setname wont get executed after method exit out of method
en.refresh(c);
//Entity manager wont keep track of the c object as it is detached
//changes happed in c object wont get saved in db.
en.detach(c);
}
public void saveReviewsForCourse(Long courseId, List<Review> reviews) {
//Get Course
Course course = en.find(Course.class, courseId );
//get Reviews
logger.info("Reviews =>{}",course.getReviews());
for(Review review : reviews) {
course.addReview(review);
review.setCourse(course);
en.persist(review);
}
}
}
|
package com.esum.comp.dbc.task;
import java.io.File;
import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import org.apache.commons.lang.StringUtils;
import com.esum.comp.dbc.DbcCode;
import com.esum.comp.dbc.DbcConfig;
import com.esum.comp.dbc.DbcException;
import com.esum.framework.common.sql.SQLUtil;
import com.esum.framework.common.util.SysUtil;
import com.esum.framework.core.config.Configurator;
import com.esum.framework.jdbc.JdbcException;
import com.esum.framework.jdbc.MapRowMapper;
import com.esum.framework.jdbc.RecordMap;
import com.esum.framework.jdbc.SqlParameterValues;
import com.esum.framework.jdbc.SqlTemplate;
import com.esum.framework.jdbc.datasource.DataSourceManager;
import com.esum.framework.jdbc.datasource.JdbcDataSource;
import com.esum.framework.utils.Assert;
/**
* DataSource를 사용할 수 있는 TaskHandler를 구현한다.
* DataSource는 ${xtrus.home}/conf/db/connections/이 정의되어 있어야 한다.
* initTask()시에 DataSource에 대해 초기화를 수행한다. Source/Target으로 구분되며, Target은 ','로 나뉘어 여러개로 정의될 수 있다.
*/
public abstract class DataSourceTaskHandler extends AbstractTaskHandler {
private SqlTemplate sourceSqlTemplate = null;
protected JdbcDataSource triggerDs;
protected JdbcDataSource sourceDs;
protected void initTriggerDataSource() throws DbcException {
}
public void initTask(String traceId) throws DbcException {
Assert.notNull(infoRecord, "'infoRecord' attribute must not be null.");
this.traceId = traceId;
initTriggerDataSource();
if(StringUtils.isNotEmpty(infoRecord.getSourceJdbcName())) {
this.sourceDs = initDataSource(infoRecord.getSourceJdbcName());
}
List<String> jdbcConfigs = infoRecord.getTargetJdbcNames();
if(jdbcConfigs!=null && jdbcConfigs.size()>0) {
for(String targetConfig : jdbcConfigs){
initDataSource(targetConfig);
}
}
logger.debug(traceId+"TaskHandler initialized.");
}
/**
* Trigger에 대한 DataSource를 리턴한다. Trigger에 대한 DataSource가 없는 경우 null을 리턴한다.
*/
public JdbcDataSource getTriggerJdbc() {
return triggerDs;
}
/**
* Source에 대한 DataSource를 리턴한다. DBC_INFO에 소스설정파일에 대한 DataSource이다.
*/
protected JdbcDataSource getSourceJdbc() {
return this.sourceDs;
}
/**
* Source DataSource로 부터 Connection객체를 가져온다.
*/
protected Connection getSourceConnection(boolean autoCommit) throws SQLException {
Connection connection = this.sourceDs.getConnection();
connection.setAutoCommit(autoCommit);
return connection;
}
protected JdbcDataSource initDataSource(String jdbcProperties) throws DbcException {
try {
Configurator.init(jdbcProperties,
SysUtil.replacePropertyToValue(DbcConfig.CONNECTION_PATH + File.separator + jdbcProperties));
} catch (IOException e) {
throw new DbcException(DbcCode.ERROR_CREATE_JDBC_DATA_SOURCE,
"initDataSource()", "'"+jdbcProperties+"' db properties not found.");
}
JdbcDataSource jds = null;
try {
if(logger.isDebugEnabled())
logger.debug(traceId+"Initializing JDBC. config : "+jdbcProperties);
jds = DataSourceManager.getInstance().createDataSourceById(jdbcProperties);
if(logger.isDebugEnabled())
logger.debug(traceId+"JDBC initialized. config : "+jdbcProperties);
} catch (JdbcException e) {
throw new DbcException(DbcCode.ERROR_CREATE_JDBC_DATA_SOURCE,
"initDataSource()", "'"+jdbcProperties+"' db properties. Jdbc DataSource initializing failed.", e);
}
return jds;
}
/**
* Target DB에 대한 Connection을 생성하여 리턴한다.
*/
protected Connection getTargetConnection(String targetDataSourceName) throws SQLException {
Assert.notNull(targetDataSourceName, "'targetDataSourceName' properties must not be null.");
JdbcDataSource ds = DataSourceManager.getInstance().get(targetDataSourceName);
if(ds==null)
throw new SQLException("'"+targetDataSourceName+"' is not initialzed. check a datasource name is valid.");
SqlTemplate sqlTemplate = new SqlTemplate();
sqlTemplate.setDataSource(ds.getDataSource());
return sqlTemplate.getDataSource().getConnection();
}
/**
* Trigger DB Connection에 대한 SqlTemplate를 생성하여 리턴한다.
* Trigger DataSource가 null인 경우 null을 리턴한다.
*/
protected SqlTemplate getTriggerSqlTemplate() {
if(triggerDs==null)
return null;
SqlTemplate template = new SqlTemplate();
template.setDataSource(triggerDs.getDataSource());
return template;
}
/**
* Source DB Connection에 대한 SqlTemplate를 생성하여 리턴한다.
*/
protected SqlTemplate getSourceSqlTemplate() {
if(this.sourceSqlTemplate!=null)
return this.sourceSqlTemplate;
sourceSqlTemplate = new SqlTemplate();
sourceSqlTemplate.setDataSource(sourceDs.getDataSource());
return sourceSqlTemplate;
}
/**
* Target DB에 대한 SqlTemplate를 생성하여 리턴한다.
*/
protected SqlTemplate getTargetSqlTemplate(String properties) {
Assert.notNull(properties, "properties must not be null.");
JdbcDataSource ds = DataSourceManager.getInstance().get(properties);
SqlTemplate sqlTemplate = new SqlTemplate();
sqlTemplate.setDataSource(ds.getDataSource());
return sqlTemplate;
}
/**
* Source DB Properties로부터 Record정보를 select하여 리턴한다.
*/
protected RecordMap select(Connection connection,
String query, SqlParameterValues params) throws SQLException {
return new SqlTemplate().selectOne(connection, query.toString(), params);
}
/**
* Source DB Properties로부터 Record정보를 select하여 리턴한다.
*/
protected List<RecordMap> selectList(Connection connection,
String query, SqlParameterValues params) throws SQLException {
return new SqlTemplate().selectList(connection, query.toString(), params, new MapRowMapper());
}
/**
* 특정 connection을 가지고 입력된 query를 통해 update를 수행한다.
*
* @return update를 한 결과를 리턴한다.
*/
protected int update(Connection connection,
String query, SqlParameterValues params, boolean commit) throws SQLException {
int result = new SqlTemplate().update(connection, query, params);
if(commit)
connection.commit();
return result;
}
/**
* 배치 업데이트를 수행한다. 입력된 connection을 통해 특정 query에 대한 paramList정보를 가지고 배치를 수행한다.
* 수행한 결과를 리턴한다.
*/
protected int batchUpdate(Connection connection,
String query, List<SqlParameterValues> paramList, boolean commit) throws SQLException {
if(paramList==null || paramList.size()==0)
return 0;
int[] result = new SqlTemplate().batchUpdate(connection, query, paramList);
if(commit)
connection.commit();
return result.length;
}
protected void closeConnection(Connection conn) {
SQLUtil.closeQuietly(conn);
}
protected void commit(Connection connection) {
try {
if(connection!=null && connection.isClosed()==false)
connection.commit();
} catch (SQLException e) {
}
}
protected void rollback(Connection connection) {
try {
if(connection!=null && connection.isClosed()==false)
connection.rollback();
} catch (SQLException e) {
}
}
protected void closeResultSet(ResultSet rs) {
try {
if(rs!=null)
rs.close();
} catch (SQLException e) {
}
rs = null;
}
}
|
package com.thoughtworks.shoppingweb.web;
import com.thoughtworks.shoppingweb.domain.Address;
import com.thoughtworks.shoppingweb.domain.ShopCart;
import com.thoughtworks.shoppingweb.service.AddressService;
import com.thoughtworks.shoppingweb.service.ShopCartService;
import com.thoughtworks.shoppingweb.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Controller
public class ShopCartController {
@Autowired
ShopCartService shopCartService;
@Autowired
UserService userService;
@Autowired
AddressService addressService;
@RequestMapping(value = "/productCart", method = RequestMethod.POST)
public ResponseEntity productCart(@RequestBody ShopCart shopCart) {
return new ResponseEntity(shopCartService.insertToCart(shopCart), HttpStatus.OK);
}
@RequestMapping(value = "/shopCartShow", method = RequestMethod.POST)
public ResponseEntity shopCartShow(@RequestBody String userName) {
Map result = new HashMap();
List<ShopCart> cartProduct = shopCartService.cartProduct(userName);
List<ShopCart> allCartProduct = shopCartService.allCartProduct(userName);
result.put("cartProduct",cartProduct);
result.put("allCartProduct",allCartProduct);
result.put("searchUser",userService.searchUser(userName));
return new ResponseEntity(result, HttpStatus.OK);
}
@RequestMapping(value = "/goToMyShopCart", method = RequestMethod.GET)
public String goToMyShopCart(@RequestParam(value="userName",
defaultValue = "", required = false) String userName, Model model) {
model.addAttribute("allCartProduct",shopCartService.allCartProduct(userName));
List<Address> getAllAddresses=addressService.getaddresses(userName);
model.addAttribute("allAddresses",getAllAddresses);
return "shopcartdetail";
}
}
|
package com.lifeplan.lifeplanapplication;
public class LifePlanGraph2IncomListItem {
/**
* フィールド
*/
long id;
private String mKoumoku = null;
private Float mWariai = null;
private Integer mSougaku = null;
/**
* コンストラクタ
*/
public LifePlanGraph2IncomListItem() {
}
/**
* プロパティ
*/
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public void setKoumoku(String koumoku) {
mKoumoku = koumoku;
}
public String getKoumoku() {
return mKoumoku;
}
public void setWariai(Float wariai) {
mWariai = wariai;
}
public Float getWariai() {
return mWariai;
}
public void setSougaku(Integer sougaku) {
mSougaku = sougaku;
}
public Integer getSougaku() {
return mSougaku;
}
}
|
package com.icss.bean;
import java.awt.Menu;
public class MenuBean {
private int num;
private int sort_id;
private String name;
private String code;
private String unit;
private double unit_price;
private String state;
public MenuBean(){ };
public int getNum() {
return num;
}
public void setNum(int num) {
this.num = num;
}
public int getSort_id() {
return sort_id;
}
public void setSort_id(int sort_id) {
this.sort_id = sort_id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getUnit() {
return unit;
}
public void setUnit(String unit) {
this.unit = unit;
}
public double getUnit_price() {
return unit_price;
}
public void setUnit_price(double unit_price) {
this.unit_price = unit_price;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
}
|
package com.rednovo.ace.data.events;
/**
* 封号
*/
public class SealNumberEvent extends BaseEvent {
public String content;
public SealNumberEvent(int eventId, String content) {
super(eventId);
this.content = content;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.