hexsha stringlengths 40 40 | size int64 3 1.05M | ext stringclasses 1 value | lang stringclasses 1 value | max_stars_repo_path stringlengths 5 1.02k | max_stars_repo_name stringlengths 4 126 | max_stars_repo_head_hexsha stringlengths 40 78 | max_stars_repo_licenses list | max_stars_count float64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 5 1.02k | max_issues_repo_name stringlengths 4 114 | max_issues_repo_head_hexsha stringlengths 40 78 | max_issues_repo_licenses list | max_issues_count float64 1 92.2k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 5 1.02k | max_forks_repo_name stringlengths 4 136 | max_forks_repo_head_hexsha stringlengths 40 78 | max_forks_repo_licenses list | max_forks_count float64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | avg_line_length float64 2.55 99.9 | max_line_length int64 3 1k | alphanum_fraction float64 0.25 1 | index int64 0 1M | content stringlengths 3 1.05M |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
3e12ce04ee12de90db7c92c5efeb66ba06891a3c | 1,630 | java | Java | AnotherScroll/app/src/main/java/com/test/anotherscroll/GridElement.java | Agies/HorizontalSelector | 1b95cd8f8636e26d072485076c9a2083db8bf4d5 | [
"MIT"
] | null | null | null | AnotherScroll/app/src/main/java/com/test/anotherscroll/GridElement.java | Agies/HorizontalSelector | 1b95cd8f8636e26d072485076c9a2083db8bf4d5 | [
"MIT"
] | null | null | null | AnotherScroll/app/src/main/java/com/test/anotherscroll/GridElement.java | Agies/HorizontalSelector | 1b95cd8f8636e26d072485076c9a2083db8bf4d5 | [
"MIT"
] | null | null | null | 27.166667 | 75 | 0.727607 | 7,934 | package com.test.anotherscroll;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Point;
import android.graphics.drawable.Drawable;
import android.nfc.Tag;
import android.text.TextPaint;
import android.util.AttributeSet;
import android.util.Log;
import android.view.Display;
import android.view.View;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.HorizontalScrollView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import java.util.Random;
class Randomizer {
public static Random instance = new Random();
}
/**
* TODO: document your custom view class.
*/
public class GridElement extends ScrollView {
public static final String TAG = "GridElement";
public TextView card;
public int id;
public TextView body;
public float progress;
public GridElement(Context context) {
super(context);
init();
}
public GridElement(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public GridElement(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init();
}
private void init() {
inflate(getContext(), R.layout.scroll_grid_element, this);
//this.setBackgroundColor(Randomizer.instance.nextInt());
card = (TextView) findViewById(R.id.scroll_card);
body = (TextView) findViewById(R.id.scroll_body);
}
} |
3e12ce6db478fd46e57672f4e9c526788d96c720 | 739 | java | Java | flyway-core/src/main/java/com/googlecode/flyway/core/util/logging/package-info.java | kamilszymanski/flyway | 8345b0e61b6eba512130f8a635187501578a04ff | [
"Apache-2.0"
] | 1 | 2019-07-20T19:09:42.000Z | 2019-07-20T19:09:42.000Z | flyway-core/src/main/java/com/googlecode/flyway/core/util/logging/package-info.java | kamilszymanski/flyway | 8345b0e61b6eba512130f8a635187501578a04ff | [
"Apache-2.0"
] | null | null | null | flyway-core/src/main/java/com/googlecode/flyway/core/util/logging/package-info.java | kamilszymanski/flyway | 8345b0e61b6eba512130f8a635187501578a04ff | [
"Apache-2.0"
] | null | null | null | 38.894737 | 75 | 0.73613 | 7,935 | /**
* Copyright (C) 2010-2013 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Private API. No compatibility guarantees provided.
*/
package com.googlecode.flyway.core.util.logging; |
3e12cf025a7a5e17c23a47709db6b67e585542a4 | 2,549 | java | Java | app/src/main/java/com/handsomexi/homework/adapter/TagAdapter.java | CatDogS/HomeWork | 827410518a9b971107fdbe1bc26a61260492924d | [
"Apache-2.0"
] | 1 | 2020-12-30T02:52:40.000Z | 2020-12-30T02:52:40.000Z | app/src/main/java/com/handsomexi/homework/adapter/TagAdapter.java | CatDogS/HomeWork | 827410518a9b971107fdbe1bc26a61260492924d | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/handsomexi/homework/adapter/TagAdapter.java | CatDogS/HomeWork | 827410518a9b971107fdbe1bc26a61260492924d | [
"Apache-2.0"
] | null | null | null | 29.988235 | 105 | 0.675167 | 7,936 | package com.handsomexi.homework.adapter;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.util.SparseBooleanArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.handsomexi.homework.R;
import java.util.ArrayList;
import java.util.List;
public class TagAdapter extends RecyclerView.Adapter<TagAdapter.ViewHolder> {
private List<String> tagList1=new ArrayList<>();
private List<String> tagList;
private SparseBooleanArray stateCheckedMap = new SparseBooleanArray();
private Context context;
public TagAdapter(Context context, List<String> tagList) {
tagList1.clear();
tagList1.addAll(tagList);
this.tagList = tagList1;
this.context=context;
stateCheckedMap.clear();
for(int i=0;i<tagList1.size();i++)
stateCheckedMap.put(i,false);
}
public interface Textviewclick{
void textviewclick(int i);
}
private Textviewclick mTextviewclick;
public void setTextviewclick(Textviewclick mTextviewclick){
this.mTextviewclick=mTextviewclick;
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.layout_tag, parent, false);
ViewHolder vh = new ViewHolder(view);
return vh;
}
@Override
public void onBindViewHolder(final ViewHolder holder, final int position) {
holder.mTextView.setText(tagList.get(position));
holder.itemView.setTag(tagList.get(position));
holder.mTextView.setOnClickListener(v -> {
for(int i = 0; i <tagList.size();i++){
stateCheckedMap.put(i,false);
}
stateCheckedMap.put(position,true);
TagAdapter.this.notifyDataSetChanged();
mTextviewclick.textviewclick(position);
});
if(stateCheckedMap.valueAt(position)){
holder.mTextView.setBackgroundResource(R.drawable.tag_checked_bg);
}else{
holder.mTextView.setBackgroundResource(R.drawable.tag_normal_bg);
}
}
@Override
public int getItemCount() {
return tagList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
public TextView mTextView;
public ViewHolder(View view) {
super(view);
mTextView = view.findViewById(R.id.tag_tv);
}
}
}
|
3e12cf1791fbd1430ee10d4a0e021a3cbec299bf | 10,831 | java | Java | src/main/java/org/eclipse/jgit/transport/TransportAmazonLambdaS3.java | santiagopampillo/sima-github-bucket | 7026fc6863ae5cf06bec1166f820fe5b17309efa | [
"0BSD"
] | 56 | 2017-02-05T09:31:02.000Z | 2020-07-31T12:55:56.000Z | src/main/java/org/eclipse/jgit/transport/TransportAmazonLambdaS3.java | santiagopampillo/sima-github-bucket | 7026fc6863ae5cf06bec1166f820fe5b17309efa | [
"0BSD"
] | 2 | 2018-03-14T17:45:47.000Z | 2018-04-12T02:24:20.000Z | src/main/java/org/eclipse/jgit/transport/TransportAmazonLambdaS3.java | santiagopampillo/sima-github-bucket | 7026fc6863ae5cf06bec1166f820fe5b17309efa | [
"0BSD"
] | 12 | 2017-05-01T18:00:57.000Z | 2020-04-06T18:39:59.000Z | 36.594595 | 129 | 0.585395 | 7,937 | package org.eclipse.jgit.transport;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.model.*;
import com.amazonaws.util.Md5Utils;
import org.apache.tika.config.TikaConfig;
import org.apache.tika.detect.Detector;
import org.apache.tika.io.FilenameUtils;
import org.apache.tika.io.TikaInputStream;
import org.apache.tika.metadata.Metadata;
import org.eclipse.jgit.errors.NotSupportedException;
import org.eclipse.jgit.errors.TransportException;
import org.eclipse.jgit.internal.JGitText;
import org.eclipse.jgit.lib.*;
import org.eclipse.jgit.lib.Ref.Storage;
import java.io.*;
import java.text.MessageFormat;
import java.util.*;
import static org.eclipse.jgit.transport.TransportAmazonS3.S3_SCHEME;
/**
* A jgit transport intended to be used with AWS Lambda.
*
* @author Matthias Berla (kenaa@example.com)
* @version $Revision$ $Date$
*/
public class TransportAmazonLambdaS3 extends Transport implements WalkTransport {
private static final Detector TIKA_DETECTOR = TikaConfig.getDefaultConfig().getDetector();
private final AmazonS3 s3;
private final String bucket;
private final String keyPrefix;
private TransportAmazonLambdaS3(Repository local, URIish uri, AmazonS3 client) {
super(local, uri);
bucket = uri.getHost();
String p = uri.getPath();
if (p.startsWith("/")) {
p = p.substring(1);
}
if (p.endsWith("/")) {
p = p.substring(0, p.length() - 1);
}
this.keyPrefix = p;
this.s3 = client;
}
public FetchConnection openFetch() throws TransportException {
final DatabaseS3 c = new DatabaseS3(bucket, keyPrefix + "/objects");
final WalkFetchConnection r = new WalkFetchConnection(this, c);
r.available(c.readAdvertisedRefs());
return r;
}
public PushConnection openPush() throws TransportException {
final DatabaseS3 c = new DatabaseS3(bucket, keyPrefix + "/objects");
final WalkPushConnection r = new WalkPushConnection(this, c);
r.available(c.readAdvertisedRefs());
return r;
}
@Override
public void close() {
// No explicit connections are maintained.
}
public static final class TransportProtocolS3 extends TransportProtocol {
private final AmazonS3 client;
public TransportProtocolS3(AmazonS3 client) {
this.client = client;
}
public String getName() {
return "Amazon S3 from Lambda";
}
public Set<String> getSchemes() {
return Collections.singleton(S3_SCHEME);
}
public Set<URIishField> getRequiredFields() {
return Collections.unmodifiableSet(EnumSet.of(URIishField.HOST, URIishField.PATH));
}
public Transport open(URIish uri, Repository local, String remoteName) throws NotSupportedException {
return new TransportAmazonLambdaS3(local, uri, client);
}
}
@SuppressWarnings("Duplicates")
class DatabaseS3 extends WalkRemoteObjectDatabase {
private final String bucketName;
private final String objectsKey;
DatabaseS3(final String b, final String o) {
bucketName = b;
objectsKey = o;
}
private String resolveKey(String subpath) {
if (subpath.endsWith("/")) //$NON-NLS-1$
subpath = subpath.substring(0, subpath.length() - 1);
String k = objectsKey;
while (subpath.startsWith(ROOT_DIR)) {
k = k.substring(0, k.lastIndexOf('/'));
subpath = subpath.substring(3);
}
return k + "/" + subpath; //$NON-NLS-1$
}
@Override
URIish getURI() {
URIish u = new URIish();
u = u.setScheme(S3_SCHEME);
u = u.setHost(bucketName);
u = u.setPath("/" + objectsKey); //$NON-NLS-1$
return u;
}
@Override
Collection<WalkRemoteObjectDatabase> getAlternates() throws IOException {
try {
return readAlternates(INFO_ALTERNATES);
}
catch (FileNotFoundException err) {
// Fall through.
}
return null;
}
@Override
WalkRemoteObjectDatabase openAlternate(final String location) throws IOException {
return new DatabaseS3(bucketName, resolveKey(location));
}
@Override
Collection<String> getPackNames() throws IOException {
final HashSet<String> have = new HashSet<>();
String prefix = resolveKey("pack");
List<S3ObjectSummary> pack = getS3ObjectSummaries(prefix);
for (S3ObjectSummary s3ObjectSummary : pack) {
have.add(s3ObjectSummary.getKey().substring(prefix.length() + 1));
}
final Collection<String> packs = new ArrayList<>();
for (final String n : have) {
if (!n.startsWith("pack-") || !n.endsWith(".pack")) //$NON-NLS-1$ //$NON-NLS-2$
continue;
final String in = n.substring(0, n.length() - 5) + ".idx"; //$NON-NLS-1$
if (have.contains(in))
packs.add(n);
}
return packs;
}
private List<S3ObjectSummary> getS3ObjectSummaries(String prefix) {
// S3 limits the size of the response to 1000 entries. Batch the requests.
ObjectListing listing = s3.listObjects(bucket, prefix);
List<S3ObjectSummary> summaries = listing.getObjectSummaries();
while (listing.isTruncated()) {
listing = s3.listNextBatchOfObjects(listing);
summaries.addAll(listing.getObjectSummaries());
}
return summaries;
}
@Override
FileStream open(final String path) throws IOException {
String resolveKey = resolveKey(path);
if (!s3.doesObjectExist(bucketName, resolveKey)) {
// Throwing a FileNotFoundException is the
// default behaviour of other walking services
throw new FileNotFoundException(resolveKey);
}
S3Object c = s3.getObject(bucket, resolveKey);
S3ObjectInputStream raw = c.getObjectContent();
long len = c.getObjectMetadata().getContentLength();
return new FileStream(raw, len);
}
@Override
void deleteFile(final String path) throws IOException {
s3.deleteObject(bucket, resolveKey(path));
}
@Override
OutputStream writeFile(final String path, final ProgressMonitor monitor, final String monitorTask) throws IOException {
// TODO find a way to stream content to S3. Maybe direct HTTP-API call?
return new ByteArrayOutputStream() {
@Override
public void close() throws IOException {
writeFile(path, toByteArray());
}
};
}
@Override
void writeFile(final String path, final byte[] data) throws IOException {
ObjectMetadata bucketMetadata = new ObjectMetadata();
bucketMetadata.setContentMD5(Md5Utils.md5AsBase64(data));
bucketMetadata.setContentLength(data.length);
// Give Tika a few hints for the content detection
Metadata tikaMetadata = new Metadata();
tikaMetadata.set(Metadata.RESOURCE_NAME_KEY, FilenameUtils.getName(FilenameUtils.normalize(path)));
// Fire!
try (InputStream bis = TikaInputStream.get(data, tikaMetadata)) {
bucketMetadata.setContentType(TIKA_DETECTOR.detect(bis, tikaMetadata).toString());
s3.putObject(bucket, resolveKey(path), bis, bucketMetadata);
}
}
Map<String, Ref> readAdvertisedRefs() throws TransportException {
final TreeMap<String, Ref> avail = new TreeMap<>();
readPackedRefs(avail);
readLooseRefs(avail);
readRef(avail, Constants.HEAD);
return avail;
}
private void readLooseRefs(final TreeMap<String, Ref> avail) throws TransportException {
try {
// S3 limits the size of the response to 1000 entries. Batch the requests.
String prefix = resolveKey(ROOT_DIR + "refs");
List<S3ObjectSummary> refs = getS3ObjectSummaries(prefix);
for (final S3ObjectSummary ref : refs) {
readRef(avail, "refs/" + ref.getKey().substring(prefix.length() + 1));
}
}
catch (IOException e) {
throw new TransportException(getURI(), JGitText.get().cannotListRefs, e);
}
}
private Ref readRef(final TreeMap<String, Ref> avail, final String rn) throws TransportException {
final String s;
String ref = ROOT_DIR + rn;
try {
try (BufferedReader br = openReader(ref)) {
s = br.readLine();
}
}
catch (FileNotFoundException noRef) {
return null;
}
catch (IOException err) {
throw new TransportException(getURI(), MessageFormat.format(JGitText.get().transportExceptionReadRef, ref), err);
}
if (s == null)
throw new TransportException(getURI(), MessageFormat.format(JGitText.get().transportExceptionEmptyRef, rn));
if (s.startsWith("ref: ")) { //$NON-NLS-1$
final String target = s.substring("ref: ".length()); //$NON-NLS-1$
Ref r = avail.get(target);
if (r == null)
r = readRef(avail, target);
if (r == null)
r = new ObjectIdRef.Unpeeled(Storage.NEW, target, null);
r = new SymbolicRef(rn, r);
avail.put(r.getName(), r);
return r;
}
if (ObjectId.isId(s)) {
final Ref r = new ObjectIdRef.Unpeeled(loose(avail.get(rn)), rn, ObjectId.fromString(s));
avail.put(r.getName(), r);
return r;
}
throw new TransportException(getURI(), MessageFormat.format(JGitText.get().transportExceptionBadRef, rn, s));
}
private Storage loose(final Ref r) {
if (r != null && r.getStorage() == Storage.PACKED)
return Storage.LOOSE_PACKED;
return Storage.LOOSE;
}
@Override
void close() {
// We do not maintain persistent connections.
}
}
}
|
3e12d00408289d170c204b0f8ff89284f842c6cb | 383 | java | Java | gulimall-product/src/main/java/qiu/kai/xin/gulimall/product/dao/AttrGroupDao.java | MissQiukaixin/gulimall | df16b8cc94f65cbcdb9bbe59d76c55ce0d180850 | [
"Apache-2.0"
] | null | null | null | gulimall-product/src/main/java/qiu/kai/xin/gulimall/product/dao/AttrGroupDao.java | MissQiukaixin/gulimall | df16b8cc94f65cbcdb9bbe59d76c55ce0d180850 | [
"Apache-2.0"
] | null | null | null | gulimall-product/src/main/java/qiu/kai/xin/gulimall/product/dao/AttrGroupDao.java | MissQiukaixin/gulimall | df16b8cc94f65cbcdb9bbe59d76c55ce0d180850 | [
"Apache-2.0"
] | null | null | null | 21.222222 | 67 | 0.764398 | 7,938 | package qiu.kai.xin.gulimall.product.dao;
import qiu.kai.xin.gulimall.product.entity.AttrGroupEntity;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper;
/**
* 属性分组
*
* @author qiukaixin
* @email anpch@example.com
* @date 2021-09-15 20:10:32
*/
@Mapper
public interface AttrGroupDao extends BaseMapper<AttrGroupEntity> {
}
|
3e12d14de8f3fcdd341428ee881ff2c905ef34b1 | 1,585 | java | Java | src/com/nevergetme/codeText/huawei/huawei02/Main.java | hTangle/AlgorithmPractice | 64ce6de1041c855719d9ba153f57245ef726e35b | [
"Apache-2.0"
] | null | null | null | src/com/nevergetme/codeText/huawei/huawei02/Main.java | hTangle/AlgorithmPractice | 64ce6de1041c855719d9ba153f57245ef726e35b | [
"Apache-2.0"
] | null | null | null | src/com/nevergetme/codeText/huawei/huawei02/Main.java | hTangle/AlgorithmPractice | 64ce6de1041c855719d9ba153f57245ef726e35b | [
"Apache-2.0"
] | null | null | null | 32.346939 | 100 | 0.533123 | 7,939 | package com.nevergetme.codeText.huawei.huawei02;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int[] x=new int[5];
int[] y=new int[5];
for(int i=0;i<5;i++){
x[i]=in.nextInt();
y[i]=in.nextInt();
}
System.out.println(new Main().getMinDistance(x,y));
}
public int getMinDistance(int[] x,int[] y){
boolean[] isVisited=new boolean[5];
for(int i=0;i<x.length;i++){
isVisited[i]=true;
getMinDistance(x,y,i,isVisited,getDistance(0,0,x[i],y[i]));
isVisited[i]=false;
}
return (int)minDistance;
}
public double getDistance(int x1,int y1,int x2,int y2){
return Math.sqrt((x1-x2)*(x1-x2)+(y1-y2)*(y1-y2));
}
public double minDistance=Double.MAX_VALUE;
public void getMinDistance(int[] x,int[] y,int before,boolean[] isVisited,double distance){
boolean isAllVisited=true;
for(int i=0;i<5;i++){
if(!isVisited[i]){
isAllVisited=false;
break;
}
}
if(isAllVisited){
minDistance=Math.min(minDistance,distance+getDistance(0,0,x[before],y[before]));
return;
}
for(int i=0;i<5;i++){
if(!isVisited[i]){
isVisited[i]=true;
getMinDistance(x,y,i,isVisited,getDistance(x[before],y[before],x[i],y[i])+distance);
isVisited[i]=false;
}
}
}
} |
3e12d16575ca8f3ed1a0e8a0efea7db4aacca108 | 308 | java | Java | smp-leave/src/main/java/top/itning/smp/smpleave/security/LoginUser.java | itning/smp-server | 515da18d462ab5d403cdd547126af2d6eb819091 | [
"Apache-2.0"
] | 24 | 2020-05-20T14:17:46.000Z | 2022-03-16T12:59:02.000Z | smp-leave/src/main/java/top/itning/smp/smpleave/security/LoginUser.java | itning/smp-server | 515da18d462ab5d403cdd547126af2d6eb819091 | [
"Apache-2.0"
] | null | null | null | smp-leave/src/main/java/top/itning/smp/smpleave/security/LoginUser.java | itning/smp-server | 515da18d462ab5d403cdd547126af2d6eb819091 | [
"Apache-2.0"
] | 9 | 2020-08-11T03:03:12.000Z | 2022-03-16T12:59:00.000Z | 17.111111 | 48 | 0.727273 | 7,940 | package top.itning.smp.smpleave.security;
import lombok.Data;
import java.io.Serializable;
/**
* @author itning
*/
@Data
public class LoginUser implements Serializable {
private String name;
private String username;
private String roleId;
private String email;
private String tel;
}
|
3e12d17820494a5c3cf179512342269cc77714d6 | 1,004 | java | Java | src/main/java/io/github/zomky/FileSystemNodeStorage.java | pmackowski/rsocket-playground | aef307a15e06fd6c0453abc056040306693a4e08 | [
"Apache-2.0"
] | 2 | 2019-09-30T13:37:57.000Z | 2019-10-24T11:12:13.000Z | src/main/java/io/github/zomky/FileSystemNodeStorage.java | pmackowski/rsocket-playground | aef307a15e06fd6c0453abc056040306693a4e08 | [
"Apache-2.0"
] | 9 | 2019-08-26T08:18:54.000Z | 2019-09-09T09:18:16.000Z | src/main/java/io/github/zomky/FileSystemNodeStorage.java | pmackowski/rsocket-raft | aef307a15e06fd6c0453abc056040306693a4e08 | [
"Apache-2.0"
] | 1 | 2021-11-09T10:38:52.000Z | 2021-11-09T10:38:52.000Z | 31.375 | 123 | 0.739044 | 7,941 | package io.github.zomky;
import io.github.zomky.storage.FileSystemRaftStorage;
import io.github.zomky.storage.RaftStorage;
import io.github.zomky.storage.RaftStorageConfiguration;
import java.nio.file.Path;
import java.nio.file.Paths;
public class FileSystemNodeStorage implements NodeStorage {
private static final String DEFAULT_DIRECTORY = System.getProperty("rsocket.raft.dir", System.getProperty("user.dir"));
private Path directory;
public FileSystemNodeStorage(Path directory) {
this.directory = directory;
}
public FileSystemNodeStorage(String directory) {
this.directory = Paths.get(directory);
}
@Override
public RaftStorage openRaftStorage(String groupName) {
RaftStorageConfiguration storageConfiguration = RaftStorageConfiguration.builder()
.directory(Paths.get(directory.toAbsolutePath().toString(), groupName))
.build();
return new FileSystemRaftStorage(storageConfiguration);
}
}
|
3e12d26499f81c6d981128db771d33c3a53ecfe8 | 3,719 | java | Java | compss/runtime/adaptors/engine/src/main/java/es/bsc/compss/types/data/location/BindingObjectLocation.java | eflows4hpc/compss | c497f6d34722103c6c8f83ebc314b495573ce054 | [
"Apache-2.0"
] | 31 | 2018-03-06T09:30:03.000Z | 2022-03-23T09:51:05.000Z | compss/runtime/adaptors/engine/src/main/java/es/bsc/compss/types/data/location/BindingObjectLocation.java | eflows4hpc/compss | c497f6d34722103c6c8f83ebc314b495573ce054 | [
"Apache-2.0"
] | 3 | 2020-08-28T17:16:50.000Z | 2021-11-11T21:58:02.000Z | compss/runtime/adaptors/engine/src/main/java/es/bsc/compss/types/data/location/BindingObjectLocation.java | eflows4hpc/compss | c497f6d34722103c6c8f83ebc314b495573ce054 | [
"Apache-2.0"
] | 15 | 2018-06-07T10:03:27.000Z | 2022-02-23T14:59:42.000Z | 26.375887 | 114 | 0.628664 | 7,942 | /*
* Copyright 2002-2021 Barcelona Supercomputing Center (www.bsc.es)
*
* 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 es.bsc.compss.types.data.location;
import es.bsc.compss.types.BindingObject;
import es.bsc.compss.types.resources.Resource;
import es.bsc.compss.types.uri.MultiURI;
import java.util.LinkedList;
import java.util.List;
public class BindingObjectLocation extends DataLocation {
private String id;
private BindingObject bindingObject;
private MultiURI uri;
/**
* Binding location constructor.
*
* @param host Resource
* @param bo BindingObject reference
*/
public BindingObjectLocation(Resource host, BindingObject bo) {
super();
this.id = bo.getId();
this.uri = new MultiURI(ProtocolType.BINDING_URI, host, id + "#" + bo.getType() + "#" + bo.getElements());
this.bindingObject = bo;
}
@Override
public LocationType getType() {
return LocationType.BINDING;
}
@Override
public ProtocolType getProtocol() {
return ProtocolType.BINDING_URI;
}
public String getId() {
return this.id;
}
public BindingObject getBindingObject() {
return this.bindingObject;
}
@Override
public List<MultiURI> getURIs() {
List<MultiURI> list = new LinkedList<>();
list.add(this.uri);
return list;
}
@Override
public List<Resource> getHosts() {
List<Resource> list = new LinkedList<>();
list.add(this.uri.getHost());
return list;
}
@Override
public MultiURI getURIInHost(Resource targetHost) {
if (this.uri.getHost().equals(targetHost)) {
return this.uri;
} else {
return null;
}
}
@Override
public boolean isTarget(DataLocation target) {
if (target.getType() != LocationType.BINDING) {
return false;
}
return this.id.equals(((BindingObjectLocation) target).id);
}
@Override
public String getSharedDisk() {
return null;
}
@Override
public String getPath() {
return this.uri.getPath();
}
@Override
public String getLocationKey() {
return this.uri.getPath() + ":" + this.uri.getHost().getName();
}
@Override
public int compareTo(DataLocation o) {
if (o == null) {
throw new NullPointerException();
}
if (o.getClass() != BindingObjectLocation.class) {
return (this.getClass().getName()).compareTo(BindingObjectLocation.class.toString());
} else {
return this.uri.compareTo(((BindingObjectLocation) o).uri);
}
}
@Override
public String toString() {
return this.uri.toString();
}
@Override
public void modifyPath(String path) {
this.id = path;
this.bindingObject = new BindingObject(path, bindingObject.getType(), bindingObject.getElements());
MultiURI olduri = this.uri;
this.uri = new MultiURI(ProtocolType.BINDING_URI, olduri.getHost(),
id + "#" + bindingObject.getType() + "#" + bindingObject.getElements());
}
}
|
3e12d29db72f51154b6f759e8051240519f4b51e | 9,932 | java | Java | plugins/svn4idea/src/org/jetbrains/idea/svn/annotate/BaseSvnFileAnnotation.java | ekudel/intellij-community | 7b79a61fbb7a949b7a55a2a60bb9ad30e82c4521 | [
"Apache-2.0"
] | 1 | 2018-10-13T19:43:36.000Z | 2018-10-13T19:43:36.000Z | plugins/svn4idea/src/org/jetbrains/idea/svn/annotate/BaseSvnFileAnnotation.java | ekudel/intellij-community | 7b79a61fbb7a949b7a55a2a60bb9ad30e82c4521 | [
"Apache-2.0"
] | null | null | null | plugins/svn4idea/src/org/jetbrains/idea/svn/annotate/BaseSvnFileAnnotation.java | ekudel/intellij-community | 7b79a61fbb7a949b7a55a2a60bb9ad30e82c4521 | [
"Apache-2.0"
] | null | null | null | 31.232704 | 147 | 0.716371 | 7,943 | // Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.idea.svn.annotate;
import com.intellij.openapi.vcs.VcsKey;
import com.intellij.openapi.vcs.annotate.*;
import com.intellij.openapi.vcs.history.VcsFileRevision;
import com.intellij.openapi.vcs.history.VcsRevisionNumber;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.text.DateFormatUtil;
import com.intellij.xml.util.XmlStringUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.idea.svn.SvnBundle;
import org.jetbrains.idea.svn.SvnConfiguration;
import org.jetbrains.idea.svn.SvnRevisionNumber;
import org.jetbrains.idea.svn.SvnVcs;
import org.jetbrains.idea.svn.api.Revision;
import org.jetbrains.idea.svn.checkin.CommitInfo;
import org.jetbrains.idea.svn.history.SvnFileRevision;
import java.util.*;
public abstract class BaseSvnFileAnnotation extends FileAnnotation {
protected final String myContents;
protected final VcsRevisionNumber myBaseRevision;
private final MyPartiallyCreatedInfos myInfos;
protected final SvnVcs myVcs;
private final Map<Long, SvnFileRevision> myRevisionMap = new HashMap<>();
private final LineAnnotationAspect DATE_ASPECT = new SvnAnnotationAspect(LineAnnotationAspect.DATE, true) {
@Override
public String getValue(@NotNull CommitInfo info) {
return DateFormatUtil.formatPrettyDate(info.getDate());
}
};
private final LineAnnotationAspect REVISION_ASPECT = new SvnAnnotationAspect(LineAnnotationAspect.REVISION, false) {
@Override
public String getValue(@NotNull CommitInfo info) {
return String.valueOf(info.getRevision());
}
};
private final LineAnnotationAspect ORIGINAL_REVISION_ASPECT = new SvnAnnotationAspect(SvnBundle.message("annotation.original.revision"), false) {
@Override
public String getValue(int lineNumber) {
final long value = myInfos.originalRevision(lineNumber);
return (value == -1) ? "" : String.valueOf(value);
}
@Override
protected long getRevision(int lineNum) {
return myInfos.originalRevision(lineNum);
}
@Override
public String getTooltipText(int lineNumber) {
// TODO: Check what is the difference in returning "" or null
if (!myInfos.isValid(lineNumber)) return "";
CommitInfo info = myInfos.get(lineNumber);
if (info == null) return null;
SvnFileRevision revision = myRevisionMap.get(info.getRevision());
return revision != null ? XmlStringUtil.escapeString("Revision " + info.getRevision() + ": " + revision.getCommitMessage()) : "";
}
};
private final LineAnnotationAspect AUTHOR_ASPECT = new SvnAnnotationAspect(LineAnnotationAspect.AUTHOR, true) {
@Override
public String getValue(@NotNull CommitInfo info) {
return info.getAuthor();
}
};
private final SvnConfiguration myConfiguration;
private final boolean myShowMergeSources;
// null if full annotation
private SvnRevisionNumber myFirstRevisionNumber;
public void setRevision(final long revision, final SvnFileRevision svnRevision) {
myRevisionMap.put(revision, svnRevision);
}
public SvnFileRevision getRevision(final long revision) {
return myRevisionMap.get(revision);
}
public void setFirstRevision(Revision revision) {
myFirstRevisionNumber = new SvnRevisionNumber(revision);
}
public SvnRevisionNumber getFirstRevisionNumber() {
return myFirstRevisionNumber;
}
public BaseSvnFileAnnotation(@NotNull SvnVcs vcs, final String contents, final VcsRevisionNumber baseRevision) {
super(vcs.getProject());
myVcs = vcs;
myContents = contents;
myBaseRevision = baseRevision;
myConfiguration = vcs.getSvnConfiguration();
myShowMergeSources = myConfiguration.isShowMergeSourcesInAnnotate();
myInfos = new MyPartiallyCreatedInfos();
}
@Override
public LineAnnotationAspect[] getAspects() {
return new LineAnnotationAspect[]{REVISION_ASPECT, DATE_ASPECT, AUTHOR_ASPECT};
}
@Override
public String getToolTip(final int lineNumber) {
final CommitInfo info = myInfos.getOrNull(lineNumber);
if (info == null) return "";
SvnFileRevision revision = myRevisionMap.get(info.getRevision());
if (revision != null) {
String prefix = myInfos.getAnnotationSource(lineNumber).showMerged() ? "Merge source revision" : "Revision";
return prefix + " " + info.getRevision() + ": " + revision.getCommitMessage();
}
return "";
}
@Override
public String getAnnotatedContent() {
return myContents;
}
public void setLineInfo(int lineNumber, @NotNull CommitInfo info, @Nullable CommitInfo mergeInfo) {
myInfos.appendNumberedLineInfo(lineNumber, info, mergeInfo);
}
@Override
@Nullable
public VcsRevisionNumber originalRevision(final int lineNumber) {
SvnFileRevision revision = myInfos.isValid(lineNumber) ? myRevisionMap.get(myInfos.originalRevision(lineNumber)) : null;
return revision != null ? revision.getRevisionNumber() : null;
}
@Override
public VcsRevisionNumber getLineRevisionNumber(final int lineNumber) {
CommitInfo info = myInfos.getOrNull(lineNumber);
return info != null && info.getRevision() >= 0 ? new SvnRevisionNumber(Revision.of(info.getRevision())) : null;
}
@Override
public Date getLineDate(int lineNumber) {
CommitInfo info = myInfos.getOrNull(lineNumber);
return info != null ? info.getDate() : null;
}
@Override
public List<VcsFileRevision> getRevisions() {
final List<VcsFileRevision> result = new ArrayList<>(myRevisionMap.values());
Collections.sort(result, (o1, o2) -> o2.getRevisionNumber().compareTo(o1.getRevisionNumber()));
return result;
}
@Override
@Nullable
public AnnotationSourceSwitcher getAnnotationSourceSwitcher() {
if (! myShowMergeSources) return null;
return new AnnotationSourceSwitcher() {
@Override
@NotNull
public AnnotationSource getAnnotationSource(int lineNumber) {
return myInfos.getAnnotationSource(lineNumber);
}
@Override
public boolean mergeSourceAvailable(int lineNumber) {
return myInfos.mergeSourceAvailable(lineNumber);
}
@Override
@NotNull
public LineAnnotationAspect getRevisionAspect() {
return ORIGINAL_REVISION_ASPECT;
}
@Override
@NotNull
public AnnotationSource getDefaultSource() {
return AnnotationSource.getInstance(myShowMergeSources);
}
@Override
public void switchTo(AnnotationSource source) {
myInfos.setShowMergeSource(source.showMerged());
}
};
}
@Override
public int getLineCount() {
return myInfos.size();
}
@Override
public VcsKey getVcsKey() {
return SvnVcs.getKey();
}
private abstract class SvnAnnotationAspect extends LineAnnotationAspectAdapter {
SvnAnnotationAspect(String id, boolean showByDefault) {
super(id, showByDefault);
}
protected long getRevision(final int lineNum) {
final CommitInfo lineInfo = myInfos.get(lineNum);
return (lineInfo == null) ? -1 : lineInfo.getRevision();
}
@Override
protected void showAffectedPaths(int lineNum) {
if (myInfos.isValid(lineNum)) {
final long revision = getRevision(lineNum);
if (revision >= 0) {
showAllAffectedPaths(new SvnRevisionNumber(Revision.of(revision)));
}
}
}
@Override
public String getValue(int lineNumber) {
CommitInfo info = myInfos.getOrNull(lineNumber);
return info == null ? "" : getValue(info);
}
public String getValue(@NotNull CommitInfo info) {
return "";
}
}
protected abstract void showAllAffectedPaths(SvnRevisionNumber number);
private static class MyPartiallyCreatedInfos {
private boolean myShowMergeSource;
private final Map<Integer, CommitInfo> myMappedLineInfo;
private final Map<Integer, CommitInfo> myMergeSourceInfos;
private int myMaxIdx;
private MyPartiallyCreatedInfos() {
myMergeSourceInfos = ContainerUtil.newHashMap();
myMappedLineInfo = ContainerUtil.newHashMap();
myMaxIdx = 0;
}
void setShowMergeSource(boolean showMergeSource) {
myShowMergeSource = showMergeSource;
}
int size() {
return myMaxIdx + 1;
}
void appendNumberedLineInfo(final int lineNumber, @NotNull CommitInfo info, @Nullable CommitInfo mergeInfo) {
if (myMappedLineInfo.get(lineNumber) != null) return;
myMaxIdx = (myMaxIdx < lineNumber) ? lineNumber : myMaxIdx;
myMappedLineInfo.put(lineNumber, info);
if (mergeInfo != null) {
myMergeSourceInfos.put(lineNumber, mergeInfo);
}
}
CommitInfo get(final int idx) {
if (myShowMergeSource) {
final CommitInfo lineInfo = myMergeSourceInfos.get(idx);
if (lineInfo != null) {
return lineInfo;
}
}
return myMappedLineInfo.get(idx);
}
@Nullable
CommitInfo getOrNull(int lineNumber) {
return isValid(lineNumber) ? get(lineNumber) : null;
}
private boolean isValid(int lineNumber) {
return lineNumber >= 0 && lineNumber < size();
}
AnnotationSource getAnnotationSource(final int line) {
return myShowMergeSource ? AnnotationSource.getInstance(myMergeSourceInfos.containsKey(line)) : AnnotationSource.LOCAL;
}
public long originalRevision(final int line) {
CommitInfo info = line < size() ? myMappedLineInfo.get(line) : null;
return info == null ? -1 : info.getRevision();
}
public boolean mergeSourceAvailable(int lineNumber) {
return myMergeSourceInfos.containsKey(lineNumber);
}
}
@Nullable
@Override
public VcsRevisionNumber getCurrentRevision() {
return myBaseRevision;
}
}
|
3e12d2b73a2ef3effc6640560afdeae364394eaf | 5,569 | java | Java | tests/agent-opentracing/src/test/java/org/hawkular/apm/tests/agent/opentracing/server/http/JavaxServletSyncServerITest.java | pavolloffay/hawkular-btm | bf74839eb4e1b275396643e94b0966dbf475f856 | [
"Apache-2.0"
] | 1 | 2018-05-17T15:27:05.000Z | 2018-05-17T15:27:05.000Z | tests/agent-opentracing/src/test/java/org/hawkular/apm/tests/agent/opentracing/server/http/JavaxServletSyncServerITest.java | pavolloffay/hawkular-btm | bf74839eb4e1b275396643e94b0966dbf475f856 | [
"Apache-2.0"
] | null | null | null | tests/agent-opentracing/src/test/java/org/hawkular/apm/tests/agent/opentracing/server/http/JavaxServletSyncServerITest.java | pavolloffay/hawkular-btm | bf74839eb4e1b275396643e94b0966dbf475f856 | [
"Apache-2.0"
] | null | null | null | 32.758824 | 88 | 0.680194 | 7,944 | /*
* Copyright 2015-2017 Red Hat, Inc. and/or its affiliates
* and other contributors as indicated by the @author tags.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.hawkular.apm.tests.agent.opentracing.server.http;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Collections;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.eclipse.jetty.security.ConstraintMapping;
import org.eclipse.jetty.security.ConstraintSecurityHandler;
import org.eclipse.jetty.security.HashLoginService;
import org.eclipse.jetty.security.LoginService;
import org.eclipse.jetty.security.authentication.BasicAuthenticator;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.util.security.Constraint;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
/**
* @author gbrown
*/
public class JavaxServletSyncServerITest extends JavaxServletTestBase {
private static final String GREETINGS_REQUEST = "Greetings";
private static final String HELLO_URL = "http://localhost:8180/hello";
private static final String QUERY_STRING = "to=me";
private static final String HELLO_URL_WITH_QS = HELLO_URL + "?" + QUERY_STRING;
private static final String HELLO_WORLD_RESPONSE = "<h1>HELLO WORLD</h1>";
private static Server server = null;
@BeforeClass
public static void initClass() throws Exception {
server = new Server(8180);
LoginService loginService = new HashLoginService("MyRealm",
"src/test/resources/realm.properties");
server.addBean(loginService);
ConstraintSecurityHandler security = new ConstraintSecurityHandler();
server.setHandler(security);
Constraint constraint = new Constraint();
constraint.setName("auth");
constraint.setAuthenticate(true);
constraint.setRoles(new String[] { "user", "admin" });
ConstraintMapping mapping = new ConstraintMapping();
mapping.setPathSpec("/*");
mapping.setConstraint(constraint);
security.setConstraintMappings(Collections.singletonList(mapping));
security.setAuthenticator(new BasicAuthenticator());
security.setLoginService(loginService);
ServletContextHandler context = new ServletContextHandler();
context.setContextPath("/");
context.addServlet(EmbeddedServlet.class, "/hello");
security.setHandler(context);
server.start();
}
@AfterClass
public static void closeClass() throws Exception {
server.stop();
}
@Test
public void testGet() throws IOException {
testJettyServlet("GET", HELLO_URL, null, false, true);
}
@Test
public void testGetWithQS() throws IOException {
testJettyServlet("GET", HELLO_URL_WITH_QS, null, false, true);
}
@Test
public void testGetNoResponse() throws IOException {
testJettyServlet("GET", HELLO_URL, null, false, false);
}
@Test
public void testGetWithFault() throws IOException {
testJettyServlet("GET", HELLO_URL, null, true, true);
}
@Test
public void testPut() throws IOException {
testJettyServlet("PUT", HELLO_URL, GREETINGS_REQUEST, false, true);
}
@Test
public void testPutWithFault() throws IOException {
testJettyServlet("PUT", HELLO_URL, GREETINGS_REQUEST, true, true);
}
@Test
public void testPost() throws IOException {
testJettyServlet("POST", HELLO_URL, GREETINGS_REQUEST, false, true);
}
@Test
public void testPostWithFault() throws IOException {
testJettyServlet("POST", HELLO_URL, GREETINGS_REQUEST, true, true);
}
public static class EmbeddedServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
@Override
protected void service(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
InputStream is = request.getInputStream();
byte[] b = new byte[is.available()];
is.read(b);
is.close();
System.out.println("REQUEST(INPUTSTREAM) RECEIVED: " + new String(b));
response.setContentType("text/html; charset=utf-8");
if (request.getHeader("test-fault") != null) {
response.sendError(401, "Unauthorized");
} else {
response.setStatus(HttpServletResponse.SC_OK);
if (request.getHeader("test-no-data") == null) {
OutputStream os = response.getOutputStream();
byte[] resp = HELLO_WORLD_RESPONSE.getBytes();
os.write(resp, 0, resp.length);
os.flush();
os.close();
}
}
}
}
}
|
3e12d3ee40b04599c598ae98b227bb7dad11d8de | 2,317 | java | Java | sem2/homework2/task3/src/test/java/group144/goldov/ConvertMatrixToStringTest.java | ivangoldov/spbuHomework | 0e0b4a5d7a107561e489bf9079c58cd459e134d8 | [
"Apache-2.0"
] | null | null | null | sem2/homework2/task3/src/test/java/group144/goldov/ConvertMatrixToStringTest.java | ivangoldov/spbuHomework | 0e0b4a5d7a107561e489bf9079c58cd459e134d8 | [
"Apache-2.0"
] | 9 | 2019-04-10T12:57:42.000Z | 2019-06-13T14:11:28.000Z | sem2/homework2/task3/src/test/java/group144/goldov/ConvertMatrixToStringTest.java | ivangoldov/spbuHomework | 0e0b4a5d7a107561e489bf9079c58cd459e134d8 | [
"Apache-2.0"
] | null | null | null | 40.649123 | 96 | 0.657315 | 7,945 | package group144.goldov;
import org.junit.jupiter.api.Test;
import java.io.*;
import static org.junit.jupiter.api.Assertions.*;
class ConvertMatrixToStringTest {
@Test
public void convertArrayOfOneElement() throws IOException {
FileSpiralWriter fileWriter = new FileSpiralWriter("test1Actual.txt");
int[][] a = {{1}};
fileWriter.print(a);
BufferedReader readerExpected = new BufferedReader(new FileReader("test1Expected.txt"));
BufferedReader readerActual = new BufferedReader(new FileReader("test1Actual.txt"));
assertEquals(readerExpected.readLine(), readerActual.readLine());
}
@Test
public void convertArrayWithEvenSize() throws IOException {
FileSpiralWriter fileWriter = new FileSpiralWriter("test2Actual.txt");
int[][] a = {{1, 2}, {3, 4}};
fileWriter.print(a);
BufferedReader readerActual = new BufferedReader(new FileReader("test2Actual.txt"));
BufferedReader readerExpected = new BufferedReader(new FileReader("test2Expected.txt"));
assertEquals(readerExpected.readLine(), readerActual.readLine());
}
@Test
public void convertArrayOfNineElements() throws IOException {
FileSpiralWriter fileWriter = new FileSpiralWriter("test3Actual.txt");
int[][] a = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
fileWriter.print(a);
BufferedReader readerActual = new BufferedReader(new FileReader("test3Actual.txt"));
BufferedReader readerExpected = new BufferedReader(new FileReader("test3Expected.txt"));
assertEquals(readerExpected.readLine(), readerActual.readLine());
}
@Test
public void convertArrayOfTwentyFiveElements() throws IOException {
FileSpiralWriter fileWriter = new FileSpiralWriter("test4Actual.txt");
int[][] a = new int[5][5];
int k = 1;
for (int i = 0; i < 5; ++i) {
for (int j = 0; j < 5; ++j) {
a[i][j] = k;
k++;
}
}
fileWriter.print(a);
BufferedReader readerActual = new BufferedReader(new FileReader("test4Actual.txt"));
BufferedReader readerExpected = new BufferedReader(new FileReader("test4Expected.txt"));
assertEquals(readerExpected.readLine(), readerActual.readLine());
}
} |
3e12d426c3ae17076591f25e8cdbc492c1725ce2 | 1,104 | java | Java | demo/src/main/java/com/daimajia/swipedemo/Generator.java | furmmon/list_orange | e932e5ca957d19b2d35de3c9e9b655400c75389c | [
"MIT"
] | null | null | null | demo/src/main/java/com/daimajia/swipedemo/Generator.java | furmmon/list_orange | e932e5ca957d19b2d35de3c9e9b655400c75389c | [
"MIT"
] | null | null | null | demo/src/main/java/com/daimajia/swipedemo/Generator.java | furmmon/list_orange | e932e5ca957d19b2d35de3c9e9b655400c75389c | [
"MIT"
] | null | null | null | 25.674419 | 80 | 0.652174 | 7,946 | package com.daimajia.swipedemo;
import android.content.Context;
import java.util.ArrayList;
/**
* Created by vincenthoulbreque on 09/09/16.
*/
public class Generator {
protected static ArrayList<Contact> contacts = new ArrayList<Contact>();
protected static ArrayList<Contact> contactlist1 = new ArrayList<Contact>();
protected static ArrayList<Contact> contactlist2 = new ArrayList<Contact>();
protected static ArrayList<Contact> contactlist3 = new ArrayList<Contact>();
protected static ArrayList<Contact> contactlist4 = new ArrayList<Contact>();
protected static ArrayList<Contact> contactlist5 = new ArrayList<Contact>();
protected static DBHandler db;
public Generator(Context context){
db = new DBHandler(context);
contacts = db.getAllContacts();
}
public ArrayList<Contact> getList1() {
if (contacts.size() > 10) {
for (int i=0; i<10;i++){
contactlist1.add(contacts.get(i));
}
return contactlist1;
} else {
return contacts;
}
}
}
|
3e12d46b5484def547280648d3114f4f7092d131 | 11,632 | java | Java | practica-4/resources/given/jade/src/jade/src/jade/domain/RequestFIPAServiceBehaviour.java | ulises-jeremias/pdytr | e22628acfc4195a75397f771e6878f68f89b572a | [
"MIT"
] | 2 | 2021-01-12T12:34:59.000Z | 2021-01-12T14:39:43.000Z | Project1/jade/src/jade/domain/RequestFIPAServiceBehaviour.java | TitoGrine/AIAD_Project | 68eeecdd9882b1a59d2bcd57e5918d2b0c8dbcb7 | [
"MIT"
] | null | null | null | Project1/jade/src/jade/domain/RequestFIPAServiceBehaviour.java | TitoGrine/AIAD_Project | 68eeecdd9882b1a59d2bcd57e5918d2b0c8dbcb7 | [
"MIT"
] | 1 | 2021-02-04T11:20:06.000Z | 2021-02-04T11:20:06.000Z | 35.463415 | 158 | 0.711056 | 7,947 | /*****************************************************************
JADE - Java Agent DEvelopment Framework is a framework to develop
multi-agent systems in compliance with the FIPA specifications.
Copyright (C) 2000 CSELT S.p.A.
GNU Lesser General Public License
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation,
version 2.1 of the License.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the
Free Software Foundation, Inc., 59 Temple Place - Suite 330,
Boston, MA 02111-1307, USA.
*****************************************************************/
package jade.domain;
//#MIDP_EXCLUDE_FILE
//#APIDOC_EXCLUDE_FILE
import java.util.Date;
import java.util.Vector;
import jade.util.leap.*;
import jade.core.*;
import jade.lang.acl.ACLMessage;
import jade.lang.acl.MessageTemplate;
import jade.domain.FIPANames;
import jade.domain.FIPAAgentManagement.*;
import jade.content.onto.Ontology;
import jade.content.onto.basic.Action;
import jade.content.onto.basic.Result;
import jade.content.ContentElementList;
import jade.content.ContentElement;
import jade.content.lang.Codec;
import jade.content.lang.sl.SLCodec;
import jade.proto.SimpleAchieveREInitiator;
/**
This class extends the <code>FipaRequestIntiatorBehaviour</code> in order to request an agent, e.g. <em>DF or AMS</em>
to perform a specific action. <br>
This class implements all the abstract method of the super classes, therefore the behaviour can be immediately added to an agent. <br>
In some cases, it might be usefull to extend this class to override
some of its methods and
react to the received messages in an application-specific manner. <br>
The class has two constructor. The first generic constructor can be used for all the action an agent can perform. In the case of a
a search action the default search constraints are used. <br>
The second constructor is specific for a search action and it allows
to specify additional search constraints.
@see jade.domain.DFService
@see jade.domain.AMSService
@author Fabio Bellifemine (CSELT S.p.A.)
@version $Date: 2003-11-24 14:47:00 +0100 (lun, 24 nov 2003) $ $Revision: 4597 $
*/
public class RequestFIPAServiceBehaviour extends SimpleAchieveREInitiator{
/**
Exception class for timeouts. This exception is thrown when trying
to obtain an <code>ACLMessage</code> from an <code>Handle</code>
and no message has been yet received and the timeout limit is not yet
elapsed.
@see jade.core.behaviours.ReceiverBehaviour.Handle#getMessage()
*/
public static class NotYetReady extends Exception {
NotYetReady() {
super("Requested message is not ready yet.");
}
}
/**
@serial
*/
private ACLMessage lastMsg;
/**
@serial
*/
private boolean notYetReady;
/**
@serial
*/
//to set a timeout for the search request: 5 minutes.
private long timeout = 300000;
/**
* Create a behaviour to request an agent to perform a specific action.
* Using this constructor, is possible to pass all information necessary to
* request a search operation.
* @param a The agent this behaviour belongs to, i.e. the agent who is
* interested in the search result.
* @param receiver The agent who will be requested to perform the action.
* @param agentDescription An agent descriptor used according to the action required.
* @param constraints The search contraints for the search action.
@exception FIPAException A suitable exception can be thrown
when
the method locally discovers that the passed parameters are not valid.
* @see jade.domain.FIPAAgentManagement.SearchConstraints
*/
public RequestFIPAServiceBehaviour(Agent a, AID receiver, String actionName, Object agentDescription, SearchConstraints constraints) throws FIPAException {
//super(a, new ACLMessage(ACLMessage.REQUEST), mt);
super(a,new ACLMessage(ACLMessage.REQUEST));
ACLMessage msg = FIPAService.createRequestMessage(a,receiver);
Action act = new Action();
act.setActor(receiver);
if (actionName.equalsIgnoreCase(FIPAManagementVocabulary.REGISTER)) {
Register action = new Register();
action.setDescription(agentDescription);
act.setAction(action);
}
else if (actionName.equalsIgnoreCase(FIPAManagementVocabulary.DEREGISTER)) {
Deregister action = new Deregister();
action.setDescription(agentDescription);
act.setAction(action);
}
else if (actionName.equalsIgnoreCase(FIPAManagementVocabulary.MODIFY)) {
Modify action = new Modify();
action.setDescription(agentDescription);
act.setAction(action);
}
else if (actionName.equalsIgnoreCase(FIPAManagementVocabulary.SEARCH)) {
Search action = new Search();
action.setDescription(agentDescription);
action.setConstraints(constraints);
act.setAction(action);
// set a timeout for the recursive search.
msg.setReplyByDate(new Date(System.currentTimeMillis()+ timeout));
}
else
throw new UnsupportedFunction();
// initialize SL0 Codec and FIPAManagementVocabulary
if (a.getContentManager().lookupOntology(FIPAManagementOntology.NAME) == null)
a.getContentManager().registerOntology(FIPAManagementOntology.getInstance());
if (a.getContentManager().lookupLanguage(FIPANames.ContentLanguage.FIPA_SL0) == null)
a.getContentManager().registerLanguage(new SLCodec(0),FIPANames.ContentLanguage.FIPA_SL0);
// Write the action in the :content slot of the request
try {
a.getContentManager().fillContent(msg, act);
} catch (Exception e) {
e.printStackTrace();
throw new UnrecognisedValue("content");
}
reset(msg);
notYetReady=true;
}
/**
* Create a behaviour to request an agent to perform a specific action.
* The default search constraints are used.
*
* @param a The agent this behaviour belongs to, i.e the agent who is interested in the action.
* @param dfName The DF who will perform the action.
* @param dfAction The action requested to the DF.
* @param dfd An agent descriptor that will be use according to the action required to the DF.
* @see #RequestFIPAServiceBehaviour(Agent a, AID receiver, String actionName, Object agentDescription, SearchConstraints constraints)
*/
public RequestFIPAServiceBehaviour(Agent a, AID receiver, String actionName, Object agentDescription) throws FIPAException
{
this(a,receiver,actionName,agentDescription,new SearchConstraints());
}
/**
Method to handle <code>not-understood</code> replies.
@param reply The actual ACL message received. It is of
<code>not-understood</code> type and matches the conversation
template.
*/
protected void handleNotUnderstood(ACLMessage reply) {
notYetReady=false;
lastMsg=(ACLMessage)reply.clone();
}
/**
Method to handle <code>refuse</code> replies.
@param reply The actual ACL message received. It is of
<code>refuse</code> type and matches the conversation
template.
*/
protected void handleRefuse(ACLMessage reply) {
notYetReady=false;
lastMsg=(ACLMessage)reply.clone();
}
/**
Method to handle <code>agree</code> replies.
@param reply The actual ACL message received. It is of
<code>agree</code> type and matches the conversation
template.
*/
protected void handleAgree(ACLMessage reply) {
}
/**
Method to handle <code>failure</code> replies.
@param reply The actual ACL message received. It is of
<code>failure</code> type and matches the conversation
template.
*/
protected void handleFailure(ACLMessage reply) {
notYetReady=false;
lastMsg=(ACLMessage)reply.clone();
}
/**
Method to handle <code>inform</code> replies.
@param reply The actual ACL message received. It is of
<code>inform</code> type and matches the conversation
template.
*/
protected void handleInform(ACLMessage reply) {
notYetReady=false;
lastMsg=(ACLMessage)reply.clone();
}
/**
Method to handle out of sequence replies.
@param reply The actual ACL message received.
*/
protected void handleOutOfSequence(ACLMessage reply){
notYetReady = false;
lastMsg = (ACLMessage)reply.clone();
}
/**
This method handle is called after receiving all the responses and when the timeout is expired( in this case no reply has been received.
*/
protected void handleAllResponses(Vector reply){
notYetReady = false;
if(reply.size() == 0)
//the timeout has expired: no replies received.
lastMsg = new ACLMessage(ACLMessage.NOT_UNDERSTOOD);
else
lastMsg = (ACLMessage)((ACLMessage)reply.elementAt(0)).clone();
}
// This exception object records last outcome. When it is
// 'null', all went OK.
/**
@serial
*/
private FIPAException outcome = null;
/**
This public method allows to get the INFORM message received in the final
* state of this FIPA-Request protocol.
*@return the ACLMessage received
@exception FIPAException A suitable exception can be thrown
when the protocol was finished with a FAILURE/REFUSE or NOT-UNDERSTOOD
* performative.
* @exception NotYetReady is thrown if the protocol is not yet finished.
**/
public ACLMessage getLastMsg() throws FIPAException,NotYetReady {
if (notYetReady)
throw new NotYetReady();
if (lastMsg.getPerformative() != ACLMessage.INFORM)
throw new FIPAException(lastMsg);
return lastMsg;
}
//#ALL_EXCLUDE_BEGIN
/**
This public method allows to get the results of a search operation.
@return the List of Objects received an a result of the search.
@exception FIPAException A suitable exception can be thrown
when the protocol was finished with a FAILURE/REFUSE or NOT-UNDERSTOOD
performative.
@exception NotYetReady is thrown if the protocol is not yet finished.
@deprecated Use getSearchResults() instead.
*/
public java.util.List getSearchResult() throws FIPAException,NotYetReady {
Object[] r = getSearchResults();
java.util.List l = new java.util.ArrayList();
for (int i = 0; i < r.length; ++i) {
l.add(r[i]);
}
return l;
}
//#ALL_EXCLUDE_END
/**
This public method allows to get the results of a search operation.
*@return An array of Objects containing the items found as
the result of the search.
@exception FIPAException A suitable exception can be thrown
when the protocol was finished with a FAILURE/REFUSE or NOT-UNDERSTOOD
* performative.
* @exception NotYetReady is thrown if the protocol is not yet finished.
**/
public Object[] getSearchResults() throws FIPAException,NotYetReady {
if (notYetReady)
throw new NotYetReady();
if (lastMsg.getPerformative() != ACLMessage.INFORM)
throw new FIPAException(lastMsg);
List l = null;
try {
Result r = (Result)((ContentElement)myAgent.getContentManager().extractContent(lastMsg));
l = r.getItems();
} catch (Exception e) {
e.printStackTrace();
throw new UnrecognisedValue("content");
}
return l.toArray();
}
}
|
3e12d4e8e055b470024d5d4044303695b992a067 | 1,605 | java | Java | engine/src/main/java/org/hibernate/validator/internal/engine/valueextraction/MapPropertyValueExtractor.java | Sanne/hibernate-validator | 2427912f7bf3ec698c9229e9920b50dfa83d21be | [
"Apache-2.0"
] | 2 | 2020-04-16T03:24:39.000Z | 2020-04-16T03:24:40.000Z | engine/src/main/java/org/hibernate/validator/internal/engine/valueextraction/MapPropertyValueExtractor.java | yangchengfu123/hibernate-validator | ea430d86a6b3b637f111948b32049377f7c9427b | [
"Apache-2.0"
] | 2 | 2021-12-18T18:30:36.000Z | 2022-01-04T16:47:20.000Z | engine/src/main/java/org/hibernate/validator/internal/engine/valueextraction/MapPropertyValueExtractor.java | yangchengfu123/hibernate-validator | ea430d86a6b3b637f111948b32049377f7c9427b | [
"Apache-2.0"
] | 1 | 2020-10-14T13:32:47.000Z | 2020-10-14T13:32:47.000Z | 36.477273 | 118 | 0.781931 | 7,948 | /*
* Hibernate Validator, declare and validate application constraints
*
* License: Apache License, Version 2.0
* See the license.txt file in the root directory or <http://www.apache.org/licenses/LICENSE-2.0>.
*/
package org.hibernate.validator.internal.engine.valueextraction;
import java.util.Map;
import jakarta.validation.valueextraction.ExtractedValue;
import jakarta.validation.valueextraction.ValueExtractor;
import org.hibernate.validator.internal.IgnoreForbiddenApisErrors;
import org.hibernate.validator.internal.engine.path.NodeImpl;
import javafx.beans.property.MapProperty;
import javafx.beans.value.ObservableValue;
/**
* A value extractor for the value of JavaFX's {@link MapProperty}.
* <p>
* It is necessary to define one as {@link MapProperty} inherits from both {@link Map} and {@link ObservableValue} and
* it is not possible to determine the corresponding {@link ValueExtractor} without creating a specific one.
*
* @author Guillaume Smet
*/
@SuppressWarnings("restriction")
@IgnoreForbiddenApisErrors(reason = "Usage of JavaFX classes")
class MapPropertyValueExtractor implements ValueExtractor<MapProperty<?, @ExtractedValue ?>> {
static final ValueExtractorDescriptor DESCRIPTOR = new ValueExtractorDescriptor( new MapPropertyValueExtractor() );
private MapPropertyValueExtractor() {
}
@Override
public void extractValues(MapProperty<?, ?> originalValue, ValueExtractor.ValueReceiver receiver) {
for ( Map.Entry<?, ?> entry : originalValue.entrySet() ) {
receiver.keyedValue( NodeImpl.MAP_VALUE_NODE_NAME, entry.getKey(), entry.getValue() );
}
}
}
|
3e12d54e04086f10f0bc13f8c80cbe755d3ecc43 | 3,179 | java | Java | server/src/main/java/org/cloudfoundry/identity/uaa/authentication/LoginServerTokenEndpointFilter.java | CarthageKing/uaa | 78971006ec1bb7a4831d4ec64c8988883903dd95 | [
"Apache-2.0"
] | 5 | 2016-11-01T19:39:38.000Z | 2018-11-20T22:45:34.000Z | server/src/main/java/org/cloudfoundry/identity/uaa/authentication/LoginServerTokenEndpointFilter.java | 3d3n/uaa | 78971006ec1bb7a4831d4ec64c8988883903dd95 | [
"Apache-2.0"
] | null | null | null | server/src/main/java/org/cloudfoundry/identity/uaa/authentication/LoginServerTokenEndpointFilter.java | 3d3n/uaa | 78971006ec1bb7a4831d4ec64c8988883903dd95 | [
"Apache-2.0"
] | 3 | 2017-01-26T00:19:30.000Z | 2020-05-13T14:29:37.000Z | 44.152778 | 166 | 0.70022 | 7,949 | /*
* ******************************************************************************
* Cloud Foundry
* Copyright (c) [2009-2016] Pivotal Software, Inc. All Rights Reserved.
*
* This product is licensed to you under the Apache License, Version 2.0 (the "License").
* You may not use this product except in compliance with the License.
*
* This product includes a number of subcomponents with
* separate copyright notices and license terms. Your use of these
* subcomponents is subject to the terms and conditions of the
* subcomponent's license, as noted in the LICENSE file.
* ******************************************************************************
*/
package org.cloudfoundry.identity.uaa.authentication;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.OAuth2RequestFactory;
import org.springframework.security.oauth2.provider.endpoint.TokenEndpointAuthenticationFilter;
import org.springframework.util.StringUtils;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class LoginServerTokenEndpointFilter extends TokenEndpointAuthenticationFilter {
private List<String> parameterNames = Collections.emptyList();
/**
* @param authenticationManager an AuthenticationManager for the incoming request
*/
public LoginServerTokenEndpointFilter(AuthenticationManager authenticationManager, OAuth2RequestFactory oAuth2RequestFactory, List<String> addNewUserParameters) {
super(authenticationManager, oAuth2RequestFactory);
this.parameterNames = addNewUserParameters;
}
@Override
protected void onSuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response, Authentication authResult) throws IOException {
super.onSuccessfulAuthentication(request, response, authResult);
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
if (auth instanceof OAuth2Authentication) {
((OAuth2Authentication)auth).setAuthenticated(true);
}
}
@Override
protected Authentication extractCredentials(HttpServletRequest request) {
String grantType = request.getParameter("grant_type");
if (grantType != null && grantType.equals("password")) {
Map<String,String> loginInfo = new HashMap<>();
for (String p : parameterNames) {
String value = request.getParameter(p);
if (StringUtils.hasText(value)) {
loginInfo.put(p, value);
}
}
Authentication result = new AuthzAuthenticationRequest(loginInfo,new UaaAuthenticationDetails(request));
return result;
}
return null;
}
}
|
3e12d55470349529a38d2e402ae21bc5fd9c7fbd | 2,248 | java | Java | src/main/java/org/kilocraft/essentials/commands/misc/PingCommand.java | MCrafterzz/KiloEssentials | 6b0d952a06ab17994a0f630d5a0cf96ea58eb635 | [
"MIT"
] | 1 | 2020-03-04T17:13:20.000Z | 2020-03-04T17:13:20.000Z | src/main/java/org/kilocraft/essentials/commands/misc/PingCommand.java | MCrafterzz/KiloEssentials | 6b0d952a06ab17994a0f630d5a0cf96ea58eb635 | [
"MIT"
] | null | null | null | src/main/java/org/kilocraft/essentials/commands/misc/PingCommand.java | MCrafterzz/KiloEssentials | 6b0d952a06ab17994a0f630d5a0cf96ea58eb635 | [
"MIT"
] | null | null | null | 45.877551 | 116 | 0.760231 | 7,950 | package org.kilocraft.essentials.commands.misc;
import com.mojang.brigadier.CommandDispatcher;
import com.mojang.brigadier.builder.RequiredArgumentBuilder;
import net.minecraft.command.EntitySelector;
import net.minecraft.server.command.ServerCommandSource;
import net.minecraft.server.network.ServerPlayerEntity;
import org.kilocraft.essentials.CommandPermission;
import org.kilocraft.essentials.api.ModConstants;
import org.kilocraft.essentials.api.text.TextFormat;
import org.kilocraft.essentials.api.command.EssentialCommand;
import org.kilocraft.essentials.api.command.ArgumentCompletions;
import org.kilocraft.essentials.chat.KiloChat;
import org.kilocraft.essentials.commands.CommandUtils;
import static net.minecraft.command.arguments.EntityArgumentType.getPlayer;
import static net.minecraft.command.arguments.EntityArgumentType.player;
import static org.kilocraft.essentials.KiloCommands.hasPermission;
public class PingCommand extends EssentialCommand {
public PingCommand() {
super("ping", CommandPermission.PING_SELF, new String[]{"latency"});
}
public void register(CommandDispatcher<ServerCommandSource> dispatcher) {
RequiredArgumentBuilder<ServerCommandSource, EntitySelector> selectorArgument = argument("player", player())
.requires(src -> hasPermission(src, CommandPermission.PING_OTHERS))
.suggests(ArgumentCompletions::allPlayers)
.executes(ctx -> execute(ctx.getSource(), getPlayer(ctx, "player")));
argumentBuilder.executes(ctx -> execute(ctx.getSource(), ctx.getSource().getPlayer()));
commandNode.addChild(selectorArgument.build());
}
private static int execute(ServerCommandSource source, ServerPlayerEntity target) {
if (CommandUtils.areTheSame(source, target)) {
KiloChat.sendLangMessageTo(source, "command.ping.self",
TextFormat.getFormattedPing(target.pingMilliseconds), target.pingMilliseconds);
return 1;
}
KiloChat.sendLangMessageTo(source, "command.ping.others", target.getName().asString(),
TextFormat.getFormattedPing(target.pingMilliseconds), target.pingMilliseconds);
return target.pingMilliseconds;
}
}
|
3e12d5a6d181efd766c2d0deb22ea151ab916bb2 | 493 | java | Java | Chapter18/src/main/java/section_06/TestEOF.java | letitgone/thinking_in_java | 3c439d2d75851ab0b6953bfd8b7236e09c4367bb | [
"MIT"
] | 3 | 2019-03-09T01:12:47.000Z | 2019-03-18T11:31:22.000Z | Chapter18/src/main/java/section_06/TestEOF.java | letitgone/thinking-in-java | 3c439d2d75851ab0b6953bfd8b7236e09c4367bb | [
"MIT"
] | null | null | null | Chapter18/src/main/java/section_06/TestEOF.java | letitgone/thinking-in-java | 3c439d2d75851ab0b6953bfd8b7236e09c4367bb | [
"MIT"
] | null | null | null | 29 | 128 | 0.679513 | 7,951 | package section_06;
import java.io.*;
/**
* @Author ZhangGJ
* @Date 2019/10/03
*/
public class TestEOF {
public static void main(String[] args) throws IOException {
DataInputStream in = new DataInputStream(new BufferedInputStream(new FileInputStream(
"/Users/zhanggengjia/Downloads/IntellijProject/thinking-in-java/Chapter18/src/main/java/section_06/TestEOF.java")));
while (in.available() != 0)
System.out.print((char) in.readByte());
}
}
|
3e12d70e4ec700d06a742160c2a9571c03df1fef | 2,100 | java | Java | src/test/java/seedu/address/storage/StorageManagerTest.java | pyokagan/CS2103AUG2016-T11-C4-main | e294eb3d466b06596ab4587320f828883fb79a68 | [
"MIT"
] | 1 | 2016-10-20T02:15:12.000Z | 2016-10-20T02:15:12.000Z | src/test/java/seedu/address/storage/StorageManagerTest.java | pyokagan/CS2103AUG2016-T11-C4-main | e294eb3d466b06596ab4587320f828883fb79a68 | [
"MIT"
] | 169 | 2016-10-05T07:47:34.000Z | 2016-11-07T17:38:34.000Z | src/test/java/seedu/address/storage/StorageManagerTest.java | pyokagan/CS2103AUG2016-T11-C4-main | e294eb3d466b06596ab4587320f828883fb79a68 | [
"MIT"
] | 7 | 2016-10-01T17:25:14.000Z | 2017-08-30T02:49:53.000Z | 30.434783 | 107 | 0.719524 | 7,952 | package seedu.address.storage;
import static junit.framework.TestCase.assertNotNull;
import static org.junit.Assert.assertEquals;
import java.io.IOException;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import seedu.address.model.ReadOnlyTaskBook;
import seedu.address.model.TaskBook;
import seedu.address.model.TaskBookBuilder;
public class StorageManagerTest {
private StorageManager storageManager;
@Rule
public TemporaryFolder testFolder = new TemporaryFolder();
@Before
public void setup() {
storageManager = new StorageManager(getTempFilePath("config"), getTempFilePath("ab"));
}
private String getTempFilePath(String fileName) {
return testFolder.getRoot().getPath() + fileName;
}
/*
* Note: This is an integration test that verifies the StorageManager is properly wired to the
* {@link JsonUserPrefsStorage} class.
* More extensive testing of UserPref saving/reading is done in {@link JsonUserPrefsStorageTest} class.
*/
@Test
public void addressBookReadSave() throws Exception {
final TaskBook original = new TaskBookBuilder().addTypicalTasks().build();
storageManager.saveTaskBook(original);
ReadOnlyTaskBook retrieved = storageManager.readTaskBook().get();
assertEquals(original, new TaskBook(retrieved));
//More extensive testing of TaskBook saving/reading is done in JsonTaskBookStorageTest
}
@Test
public void getAddressBookFilePath() {
assertNotNull(storageManager.getTaskBookFilePath());
}
/**
* A Stub class to throw an exception when the save method is called
*/
class JsonTaskBookStorageExceptionThrowingStub extends JsonTaskBookStorage {
JsonTaskBookStorageExceptionThrowingStub(String filePath) {
super(filePath);
}
@Override
public void saveTaskBook(ReadOnlyTaskBook addressBook, String filePath) throws IOException {
throw new IOException("dummy exception");
}
}
}
|
3e12d7988c6ccf76b4fce453240826ffbed8b23e | 3,711 | java | Java | modules/datamodel/src/main/java/org/shaolin/bmdp/datamodel/pagediagram/PageNodeType.java | akondasif/uimaster | 9c083a1ffeb43c67ce95b163f14ab3d85e240758 | [
"Apache-2.0"
] | null | null | null | modules/datamodel/src/main/java/org/shaolin/bmdp/datamodel/pagediagram/PageNodeType.java | akondasif/uimaster | 9c083a1ffeb43c67ce95b163f14ab3d85e240758 | [
"Apache-2.0"
] | null | null | null | modules/datamodel/src/main/java/org/shaolin/bmdp/datamodel/pagediagram/PageNodeType.java | akondasif/uimaster | 9c083a1ffeb43c67ce95b163f14ab3d85e240758 | [
"Apache-2.0"
] | null | null | null | 26.697842 | 113 | 0.631636 | 7,953 | //
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.6
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2014.09.08 at 02:15:27 PM CST
//
package org.shaolin.bmdp.datamodel.pagediagram;
import java.io.Serializable;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;
import org.shaolin.bmdp.datamodel.common.ExpressionType;
import org.shaolin.bmdp.datamodel.common.TargetEntityType;
/**
* diaply node from UIPage
*
* <p>Java class for PageNodeType complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="PageNodeType">
* <complexContent>
* <extension base="{http://bmdp.shaolin.org/datamodel/PageDiagram}WebNodeType">
* <sequence>
* <element name="sourceEntity" type="{http://bmdp.shaolin.org/datamodel/Common}TargetEntityType"/>
* <element name="operation" type="{http://bmdp.shaolin.org/datamodel/Common}ExpressionType"/>
* </sequence>
* <attribute name="needTransaction" type="{http://www.w3.org/2001/XMLSchema}boolean" default="false" />
* </extension>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "PageNodeType", propOrder = {
"sourceEntity",
"operation"
})
public class PageNodeType
extends WebNodeType
implements Serializable
{
private final static long serialVersionUID = 1L;
@XmlElement(required = true)
protected TargetEntityType sourceEntity;
@XmlElement(required = true)
protected ExpressionType operation;
@XmlAttribute(name = "needTransaction")
protected Boolean needTransaction;
/**
* Gets the value of the sourceEntity property.
*
* @return
* possible object is
* {@link TargetEntityType }
*
*/
public TargetEntityType getSourceEntity() {
return sourceEntity;
}
/**
* Sets the value of the sourceEntity property.
*
* @param value
* allowed object is
* {@link TargetEntityType }
*
*/
public void setSourceEntity(TargetEntityType value) {
this.sourceEntity = value;
}
/**
* Gets the value of the operation property.
*
* @return
* possible object is
* {@link ExpressionType }
*
*/
public ExpressionType getOperation() {
return operation;
}
/**
* Sets the value of the operation property.
*
* @param value
* allowed object is
* {@link ExpressionType }
*
*/
public void setOperation(ExpressionType value) {
this.operation = value;
}
/**
* Gets the value of the needTransaction property.
*
* @return
* possible object is
* {@link Boolean }
*
*/
public boolean isNeedTransaction() {
if (needTransaction == null) {
return false;
} else {
return needTransaction;
}
}
/**
* Sets the value of the needTransaction property.
*
* @param value
* allowed object is
* {@link Boolean }
*
*/
public void setNeedTransaction(Boolean value) {
this.needTransaction = value;
}
}
|
3e12d813a1aae39c8bd16e19ad0af3b726df360f | 2,272 | java | Java | service/src/main/java/uk/gov/hmcts/reform/fpl/model/CloseCase.java | uk-gov-mirror/hmcts.fpl-ccd-configuration | 2c3c155261d12fa05f61a1d706d2afad5c58df09 | [
"MIT"
] | null | null | null | service/src/main/java/uk/gov/hmcts/reform/fpl/model/CloseCase.java | uk-gov-mirror/hmcts.fpl-ccd-configuration | 2c3c155261d12fa05f61a1d706d2afad5c58df09 | [
"MIT"
] | null | null | null | service/src/main/java/uk/gov/hmcts/reform/fpl/model/CloseCase.java | uk-gov-mirror/hmcts.fpl-ccd-configuration | 2c3c155261d12fa05f61a1d706d2afad5c58df09 | [
"MIT"
] | null | null | null | 33.910448 | 115 | 0.738116 | 7,954 | package uk.gov.hmcts.reform.fpl.model;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import uk.gov.hmcts.reform.fpl.enums.YesNo;
import uk.gov.hmcts.reform.fpl.enums.ccd.fixedlists.CloseCaseReason;
import uk.gov.hmcts.reform.fpl.validation.groups.CloseCaseGroup;
import java.time.LocalDate;
import javax.validation.constraints.PastOrPresent;
import static uk.gov.hmcts.reform.fpl.enums.YesNo.NO;
import static uk.gov.hmcts.reform.fpl.enums.YesNo.YES;
import static uk.gov.hmcts.reform.fpl.enums.ccd.fixedlists.CloseCaseReason.DEPRIVATION_OF_LIBERTY;
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
@JsonIgnoreProperties(ignoreUnknown = true)
public class CloseCase {
// This field is hidden so runs into our favourite CCD issue of not persisting, we are ignoring the
// deserialization of the object as we can infer what it is supposed to be from which reason field is populated
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
private YesNo showFullReason;
@PastOrPresent(message = "The close case date must be in the past", groups = CloseCaseGroup.class)
private LocalDate date;
private String details;
@JsonIgnore
private CloseCaseReason reason;
@JsonProperty("fullReason")
public CloseCaseReason getFullReason() {
return showFullReason == YES ? reason : null;
}
@JsonProperty("fullReason")
public void setFullReason(CloseCaseReason fullReason) {
if (fullReason != null) {
this.reason = fullReason;
this.showFullReason = YES;
}
}
@JsonProperty("partialReason")
public CloseCaseReason getPartialReason() {
return showFullReason == NO ? reason : null;
}
@JsonProperty("partialReason")
public void setPartialReason(CloseCaseReason partialReason) {
if (partialReason != null) {
this.reason = partialReason;
this.showFullReason = NO;
}
}
public boolean hasDeprivationOfLiberty() {
return DEPRIVATION_OF_LIBERTY == reason;
}
}
|
3e12d84a3ac05193dcfcf32e513407273480fcb0 | 143 | java | Java | jmock-example/src/main/java/org/jmock/example/qcon/Playlist.java | msm416/virt-jmock | 56c6feab3c088c41e9a54ea29b80b253279fbb76 | [
"BSD-3-Clause"
] | 97 | 2015-01-18T19:56:00.000Z | 2022-02-07T11:53:29.000Z | jmock-example/src/main/java/org/jmock/example/qcon/Playlist.java | msm416/virt-jmock | 56c6feab3c088c41e9a54ea29b80b253279fbb76 | [
"BSD-3-Clause"
] | 131 | 2015-01-29T14:58:44.000Z | 2021-08-02T05:21:44.000Z | jmock-example/src/main/java/org/jmock/example/qcon/Playlist.java | msm416/virt-jmock | 56c6feab3c088c41e9a54ea29b80b253279fbb76 | [
"BSD-3-Clause"
] | 61 | 2015-04-16T23:32:34.000Z | 2022-01-14T15:00:47.000Z | 20.428571 | 41 | 0.762238 | 7,955 | package org.jmock.example.qcon;
public interface Playlist {
boolean hasTrackFor(String location);
String trackFor(String location);
}
|
3e12d8990b27d8474a7f08cf466273702f92200f | 10,314 | java | Java | src/main/java/com/reposify/client/ReposifyClient.java | reposify/reposify-java | ab6248bcf889376c7dbbb6b58954beda9716671c | [
"MIT"
] | null | null | null | src/main/java/com/reposify/client/ReposifyClient.java | reposify/reposify-java | ab6248bcf889376c7dbbb6b58954beda9716671c | [
"MIT"
] | null | null | null | src/main/java/com/reposify/client/ReposifyClient.java | reposify/reposify-java | ab6248bcf889376c7dbbb6b58954beda9716671c | [
"MIT"
] | null | null | null | 42.444444 | 599 | 0.67898 | 7,956 | package com.reposify.client;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.reposify.client.domain.account.AccountStatusResponse;
import com.reposify.client.domain.discovery.DiscoveryHostArgument;
import com.reposify.client.domain.discovery.ScanResponse;
import com.reposify.client.domain.discovery.StatusResponse;
import com.reposify.client.domain.insights.InsightsCountResponse;
import com.reposify.client.domain.insights.InsightsSearchResponse;
import com.reposify.client.exception.CustomResponseErrorHandler;
import org.springframework.http.*;
import org.springframework.util.Assert;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;
import java.net.URI;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class ReposifyClient {
private static final String TOKEN = "token";
private static final String USER_AGENT = "User-Agent";
private static final String JAVA_API_CLIENT = "JAVA-API Client";
private String apiUrl = "https://api.reposify.com";
private String token;
private RestTemplate restTemplate;
public ReposifyClient(String token) {
this.token = token;
this.restTemplate = new RestTemplate();
this.restTemplate.setErrorHandler(new CustomResponseErrorHandler());
}
public ReposifyClient(String apiUrl, String token) {
this.token = token;
this.apiUrl = apiUrl;
this.restTemplate = new RestTemplate();
this.restTemplate.setErrorHandler(new CustomResponseErrorHandler());
}
/**
* This method perform queries on Reposify’s insights. You can query by text on devices
* response’s banner and by filters.
*
* @param banner the banner to be matched
* @param filter the filters to be applied
* @param page the page number
* @return the search response
*/
public InsightsSearchResponse searchInsights(String banner, String filter, Integer page) {
MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
if (banner != null) {
params.add("banner", banner);
}
if (filter != null) {
params.add("filter", filter);
}
if (page != null) {
params.add("page", page.toString());
}
return request("insights", "search", null, params, null, HttpMethod.GET, InsightsSearchResponse.class);
}
/**
* This method return number of devices matched to specified banner and filters.
*
* @param banner the banner to be matched
* @param filter the filters to be applied
* @return the count response
*/
public InsightsCountResponse getInsightsCount(String banner, String filter) {
MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
if (banner != null) {
params.add("banner", banner);
}
if (filter != null) {
params.add("filter", filter);
}
return request("insights", "count", null, params, null, HttpMethod.GET, InsightsCountResponse.class);
}
/**
* This endpoint return account information such as current account’s plan and insights credits balance.
*
* @return the response with the account information
*/
public AccountStatusResponse getAccountStatus() {
return request("account", "status", null, null, null, HttpMethod.GET, AccountStatusResponse.class);
}
/**
* This endpoint allows to query all public devices for the specified port and protocol.
* Only one such request can be active at a time.
*
* @param protocol the protocol to filter
* @param port the port to filter
* @return the response of the scan
*/
public ScanResponse scanInternet(String protocol, Integer port) {
MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
if (protocol != null) {
params.add("protocol", protocol);
}
if (port != null) {
params.add("port", port.toString());
}
return request("scan", "internet", null, null, params, HttpMethod.POST, ScanResponse.class);
}
/**
* This endpoint allows the user to discover devices and protocols on specific IP addresses or CIDR networks.
* You are limited to 65536 unique address per query, and consequentially, CIDR network masks of at least 16 bits in size.
* You are also limited to three active queries at a time. This endpoint accepts two arguments, a list of IP
* addresses and a list of ports, protocols, and transports.
* The list of IP addresses is a comma delimited list of IPv4 addresses and/or CIDR networks in standard CIDR notation.
* As mentioned before the overall number of unique addresses cannot exceed 65536. This argument is mandatory.
* The second argument is a list of tuples of port, protocol and transport combinations, in that order.
* If transport is supplied it must represent a valid transport for the specified protocol (e.g., DNS can work over TCP
* or UDP but HTTP must work over TCP). In contrast, port numbers can be freely supplied and discovery will be attempted on the port-protocol-transport combination even if the port is not a usual one for the given protocol. It is also allowed to supply only port number, only protocol, or only port and protocol in a given tuple. In that case the missing arguments will be automatically inferred. This argument is optional. In case it is not provided, auto-discovery will be preformed on the supplied addresses and the correct port-protocol-transport combination will be inferred where possible.
* The list of tuples should be encoded as a strictly valid JSON. See the HTTP/cURL usage for formatting examples.
* SDK users on the other hand should supply normal dictionary objects since encoding issues are abstracted away for them.
*
* @param ips the list of ips to be searched
* @param arguments the argument list (tuples <port>;<protocol>)
* @return
*/
public ScanResponse scanHost(String ips, List<DiscoveryHostArgument> arguments) {
Assert.notNull(ips, "mandatory argument");
MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
if (ips != null) {
params.add("ips", ips);
}
if (arguments != null) {
try {
params.add("arguments", new ObjectMapper().writeValueAsString(arguments));
} catch (JsonProcessingException e) {
// unable to parse the json arguments
}
}
return request("scan", "host", null, null, params, HttpMethod.POST, ScanResponse.class);
}
/**
* This endpoint is useful for polling the server for the state of your Discovery requests.
* To identify the request you will need to use the job ID that is returned when the request is submitted.
* Once the scan is completed you will receive an email with a detailed report.
*
* @param jobId the job_id to be searched
* @return the status response
*/
public StatusResponse scanStatus(String jobId) {
Assert.notNull(jobId, "job_id must not be null");
MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
if (jobId != null) {
params.add("job_id", jobId);
}
return request("scan", "status", null, params, null, HttpMethod.GET, StatusResponse.class);
}
/**
* Internal method that actually handle the call logic. It delegates the HTTP call to spring rest template.
*
* @param endpoint the name of the endpoint
* @param action the name of the action
* @param version the api version
* @param requestParams the URL request params
* @param formData the form data
* @param method the method to be used
* @param responseType the class of the response type
* @param <T> the generic class of the response to be returned identified by <code>reponseType</code>
* @return
*/
private <T> T request(String endpoint, String action, String version, MultiValueMap<String, String> requestParams, MultiValueMap<String, String> formData, HttpMethod method, Class<T> responseType) {
// if version is not provided we default to the first one
if (version == null) {
version = "1";
}
if (requestParams == null) {
requestParams = new LinkedMultiValueMap<>();
}
String url = getFormattedUrl(endpoint, action, version);
requestParams.add(TOKEN, this.token);
UriComponentsBuilder builder = UriComponentsBuilder.fromUriString(url).queryParams(requestParams);
URI uri = builder.buildAndExpand(requestParams).toUri();
HttpHeaders headers = new HttpHeaders();
headers.add(USER_AGENT, JAVA_API_CLIENT);
ResponseEntity<T> response = null;
if (method == HttpMethod.GET) {
HttpEntity<?> entity = new RequestEntity<Void>(headers, method, uri);
response = restTemplate.exchange(uri, method, entity, responseType);
} else if (method == HttpMethod.POST) {
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<>(formData, headers);
response = restTemplate.exchange(uri, method, requestEntity, responseType);
}
return response.getBody();
}
/**
* Gets the URL formated as follows: <base_url>/<version>/<endpoint>/<action>/
*
* @param endpoint the name of the endpoint
* @param action the name of the action
* @param version the version
* @return returns the fully defined URL string to be used
*/
private String getFormattedUrl(String endpoint, String action, String version) {
return MessageFormat.format("{0}/v{1}/{2}/{3}", apiUrl, version, endpoint, action);
}
}
|
3e12d8bba3f26e3e27fd80903b57a535178cfac1 | 2,218 | java | Java | src/main/java/ch/hslu/sw10/temperatur/Temperatur.java | flawas/OOProgrammierung | 7ad9402d09e9f7a56dff6976e6366a9c2fc0d59a | [
"Apache-2.0"
] | null | null | null | src/main/java/ch/hslu/sw10/temperatur/Temperatur.java | flawas/OOProgrammierung | 7ad9402d09e9f7a56dff6976e6366a9c2fc0d59a | [
"Apache-2.0"
] | null | null | null | src/main/java/ch/hslu/sw10/temperatur/Temperatur.java | flawas/OOProgrammierung | 7ad9402d09e9f7a56dff6976e6366a9c2fc0d59a | [
"Apache-2.0"
] | null | null | null | 26.094118 | 157 | 0.62128 | 7,957 | /*
* Copyright (c) 2022.
* Flavio Waser, flaviowaser.ch
* Version 1.0, 2022.4.13
*/
package ch.hslu.sw10.temperatur;
import java.util.Objects;
public class Temperatur {
private static final float KELVIN_OFFSET = 273.15f;
private float celsius;
private float kelvin;
public Temperatur(float celsius) {
this.celsius = this.celsius;
kelvin = convertCelsiusToKelvin(this.celsius);
}
public Temperatur(final float temperatur, final Unit unit){
switch (unit){
case KELVIN -> this.setKelvin(temperatur);
case CELSIUS -> this.setCelsius(temperatur);
}
}
public float getCelsius() {
return celsius;
}
public float getKelvin() {
return kelvin;
}
public void setCelsius(float celsius) {
this.celsius = celsius;
kelvin = convertCelsiusToKelvin(this.celsius);
}
public void setKelvin(float kelvin) {
this.kelvin = kelvin;
celsius = convertKelvinToCelsius(this.kelvin);
}
public float convertKelvinToCelsius(float kelvin){
return this.kelvin - KELVIN_OFFSET;
}
public float convertCelsiusToKelvin(float celsius){
return this.celsius + KELVIN_OFFSET;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Temperatur that = (Temperatur) o;
return Float.compare(that.KELVIN_OFFSET, KELVIN_OFFSET) == 0 && Float.compare(that.celsius, celsius) == 0 && Float.compare(that.kelvin, kelvin) == 0;
}
@Override
public int hashCode() {
return Objects.hash(KELVIN_OFFSET, celsius, kelvin);
}
@Override
public String toString() {
return "Temperatur{" +
"KELVIN_OFFSET=" + KELVIN_OFFSET +
", celsius=" + celsius +
", kelvin=" + kelvin +
'}';
}
protected static Temperatur createFromCelsius(final float celsius){
return new Temperatur(celsius, Unit.CELSIUS);
}
protected static Temperatur createFromKelvin(final float kelvin){
return new Temperatur(kelvin, Unit.KELVIN);
}
}
|
3e12d9d20ecf7f32c7be1fb443de2b2a260d53a9 | 397 | java | Java | jlox/src/main/java/com/nay/lox/Token.java | montreal91/kind-kestrel | 6f7b86261bcd805b8529059d650f112e107597da | [
"BSD-3-Clause"
] | null | null | null | jlox/src/main/java/com/nay/lox/Token.java | montreal91/kind-kestrel | 6f7b86261bcd805b8529059d650f112e107597da | [
"BSD-3-Clause"
] | null | null | null | jlox/src/main/java/com/nay/lox/Token.java | montreal91/kind-kestrel | 6f7b86261bcd805b8529059d650f112e107597da | [
"BSD-3-Clause"
] | null | null | null | 16.541667 | 66 | 0.639798 | 7,958 | package com.nay.lox;
public class Token {
private final TokenType type;
private final String value;
Token(TokenType type, String value) {
this.type = type;
this.value = value;
}
public TokenType getType() {
return type;
}
String getValue() {
return value;
}
public String toString() {
return String.format("Token %s:[%s]", type.toString(), value);
}
}
|
3e12da6e41754cc130e0aeda2bcb5d855392984c | 6,194 | java | Java | ThirdPartyAdapters/facebook/facebook/src/main/java/com/google/ads/mediation/facebook/FacebookRewardedAd.java | Boxing01/googleads-mobile-android-mediation | d29418b24ebcf19385df74e6c581c8540181185d | [
"Apache-2.0"
] | null | null | null | ThirdPartyAdapters/facebook/facebook/src/main/java/com/google/ads/mediation/facebook/FacebookRewardedAd.java | Boxing01/googleads-mobile-android-mediation | d29418b24ebcf19385df74e6c581c8540181185d | [
"Apache-2.0"
] | 1 | 2019-08-30T10:10:25.000Z | 2019-08-30T10:10:25.000Z | ThirdPartyAdapters/facebook/facebook/src/main/java/com/google/ads/mediation/facebook/FacebookRewardedAd.java | Boxing01/googleads-mobile-android-mediation | d29418b24ebcf19385df74e6c581c8540181185d | [
"Apache-2.0"
] | null | null | null | 34.99435 | 97 | 0.623991 | 7,959 | package com.google.ads.mediation.facebook;
import android.content.Context;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import com.facebook.ads.Ad;
import com.facebook.ads.AdError;
import com.facebook.ads.RewardedVideoAd;
import com.facebook.ads.RewardedVideoAdExtendedListener;
import com.google.android.gms.ads.mediation.MediationAdLoadCallback;
import com.google.android.gms.ads.mediation.MediationRewardedAd;
import com.google.android.gms.ads.mediation.MediationRewardedAdCallback;
import com.google.android.gms.ads.mediation.MediationRewardedAdConfiguration;
import java.util.concurrent.atomic.AtomicBoolean;
import static com.google.ads.mediation.facebook.FacebookMediationAdapter.TAG;
public class FacebookRewardedAd implements MediationRewardedAd, RewardedVideoAdExtendedListener {
private MediationRewardedAdConfiguration adConfiguration;
private MediationAdLoadCallback<MediationRewardedAd, MediationRewardedAdCallback>
mMediationAdLoadCallback;
/**
* Facebook rewarded video ad instance.
*/
private RewardedVideoAd rewardedAd;
/**
* Mediation rewarded video ad listener used to forward rewarded video ad events from
* the Facebook Audience Network SDK to the Google Mobile Ads SDK.
*/
private MediationRewardedAdCallback mRewardedAdCallback;
private boolean isRtbAd = false;
private AtomicBoolean didRewardedAdClose = new AtomicBoolean();
public FacebookRewardedAd(MediationRewardedAdConfiguration adConfiguration,
MediationAdLoadCallback<MediationRewardedAd,
MediationRewardedAdCallback> callback) {
this.adConfiguration = adConfiguration;
this.mMediationAdLoadCallback = callback;
}
public void render() {
final Context context = adConfiguration.getContext();
Bundle serverParameters = adConfiguration.getServerParameters();
if (!FacebookMediationAdapter.isValidRequestParameters(context, serverParameters)) {
mMediationAdLoadCallback.onFailure("Invalid request");
return;
}
String decodedBid = adConfiguration.getBidResponse();
if (!TextUtils.isEmpty(decodedBid)) {
isRtbAd = true;
}
final String placementID = FacebookMediationAdapter.getPlacementID(serverParameters);
if (isRtbAd) {
rewardedAd = new RewardedVideoAd(context, placementID);
rewardedAd.setAdListener(this);
rewardedAd.loadAdFromBid(decodedBid);
} else {
FacebookInitializer.getInstance().initialize(context, placementID,
new FacebookInitializer.Listener() {
@Override
public void onInitializeSuccess() {
createAndLoadRewardedVideo(context, placementID);
}
@Override
public void onInitializeError(String message) {
String logMessage = "Failed to load ad from Facebook: " + message;
Log.w(TAG, logMessage);
if (mMediationAdLoadCallback != null) {
mMediationAdLoadCallback.onFailure(logMessage);
}
}
});
}
}
@Override
public void showAd(Context context) {
if (rewardedAd.isAdLoaded()) {
rewardedAd.show();
if (mRewardedAdCallback != null) {
mRewardedAdCallback.onVideoStart();
mRewardedAdCallback.onAdOpened();
}
} else {
if (mRewardedAdCallback != null) {
mRewardedAdCallback.onAdFailedToShow("No ads to show");
}
}
}
private void createAndLoadRewardedVideo(Context context, String placementID) {
rewardedAd = new RewardedVideoAd(context, placementID);
rewardedAd.setAdListener(this);
rewardedAd.loadAd(true);
}
@Override
public void onRewardedVideoCompleted() {
mRewardedAdCallback.onVideoComplete();
mRewardedAdCallback.onUserEarnedReward(new FacebookReward());
}
@Override
public void onError(Ad ad, AdError adError) {
String errorMessage = adError.getErrorMessage();
if (!TextUtils.isEmpty(errorMessage)) {
Log.w(TAG, "Failed to load ad from Facebook: " + errorMessage);
}
if (mMediationAdLoadCallback != null) {
mMediationAdLoadCallback.onFailure(errorMessage);
}
rewardedAd.destroy();
}
@Override
public void onAdLoaded(Ad ad) {
if (mMediationAdLoadCallback != null) {
mRewardedAdCallback = mMediationAdLoadCallback.onSuccess(this);
}
}
@Override
public void onAdClicked(Ad ad) {
if (mRewardedAdCallback != null) {
if (isRtbAd) {
// TODO: Upon approval, add this callback back in.
// mRewardedAdCallback.reportAdClicked();
} else {
mRewardedAdCallback.reportAdClicked();
}
}
}
@Override
public void onLoggingImpression(Ad ad) {
if (mRewardedAdCallback != null) {
if (isRtbAd) {
// TODO: Upon approval, add this callback back in.
// mRewardedAdCallback.reportAdImpression();
} else {
mRewardedAdCallback.reportAdImpression();
}
}
}
@Override
public void onRewardedVideoClosed() {
if (!didRewardedAdClose.getAndSet(true) && mRewardedAdCallback != null) {
mRewardedAdCallback.onAdClosed();
}
if (rewardedAd != null) {
rewardedAd.destroy();
}
}
@Override
public void onRewardedVideoActivityDestroyed() {
if (!didRewardedAdClose.getAndSet(true) && mRewardedAdCallback != null) {
mRewardedAdCallback.onAdClosed();
}
if (rewardedAd != null) {
rewardedAd.destroy();
}
}
}
|
3e12db25b490130aca98ec0e27b153c660817000 | 1,581 | java | Java | xap-core/xap-datagrid/src/main/java/com/gigaspaces/internal/io/IOArrayException.java | InsightEdge/xap | 25fb3f6de1b25fa2abeefd73ef30fe4eaef07cf6 | [
"Apache-2.0"
] | 90 | 2016-08-09T16:37:44.000Z | 2022-03-30T10:33:17.000Z | xap-core/xap-datagrid/src/main/java/com/gigaspaces/internal/io/IOArrayException.java | InsightEdge/xap | 25fb3f6de1b25fa2abeefd73ef30fe4eaef07cf6 | [
"Apache-2.0"
] | 33 | 2016-10-10T17:29:11.000Z | 2022-03-17T07:27:48.000Z | xap-core/xap-datagrid/src/main/java/com/gigaspaces/internal/io/IOArrayException.java | InsightEdge/xap | 25fb3f6de1b25fa2abeefd73ef30fe4eaef07cf6 | [
"Apache-2.0"
] | 48 | 2016-08-09T15:55:20.000Z | 2022-03-31T12:21:50.000Z | 27.736842 | 99 | 0.698292 | 7,960 | /*
* Copyright (c) 2008-2016, GigaSpaces Technologies, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.gigaspaces.internal.io;
import java.io.IOException;
/**
* This exception is thrown when an array serialization/deserialization fails on an IOException. It
* contains the index of the item which caused the exception in addition to the original cause.
*
* @author Niv Ingberg
* @since 7.1.1
*/
@com.gigaspaces.api.InternalApi
public class IOArrayException extends IOException {
private static final long serialVersionUID = 1L;
private int _index;
public IOArrayException() {
super();
}
public IOArrayException(int index) {
super();
this._index = index;
}
public IOArrayException(int index, String message) {
super(message);
this._index = index;
}
public IOArrayException(int index, String message, IOException cause) {
this(index, message);
initCause(cause);
}
public int getIndex() {
return _index;
}
}
|
3e12dbc78aa51f36ca74530802e7f684cb60590f | 2,719 | java | Java | sdk/greengrass/greengrass-client/src/event-stream-rpc-java/model/software/amazon/awssdk/aws/greengrass/model/UpdateConfigurationRequest.java | FThompsonAWS/aws-iot-device-sdk-java-v2 | b0aa0542869663e5f3c27a519687363358a08cb6 | [
"Apache-2.0"
] | 57 | 2019-11-29T19:28:27.000Z | 2022-03-27T18:49:16.000Z | sdk/greengrass/greengrass-client/src/event-stream-rpc-java/model/software/amazon/awssdk/aws/greengrass/model/UpdateConfigurationRequest.java | QPC-database/aws-iot-device-sdk-java-v2 | c3b4e5ea8c81a3c447e2d1d8016cb5da45e9a022 | [
"Apache-2.0"
] | 95 | 2020-01-22T01:47:05.000Z | 2022-03-31T19:28:24.000Z | sdk/greengrass/greengrass-client/src/event-stream-rpc-java/model/software/amazon/awssdk/aws/greengrass/model/UpdateConfigurationRequest.java | QPC-database/aws-iot-device-sdk-java-v2 | c3b4e5ea8c81a3c447e2d1d8016cb5da45e9a022 | [
"Apache-2.0"
] | 63 | 2019-12-19T19:12:42.000Z | 2022-03-29T07:14:51.000Z | 25.175926 | 98 | 0.704303 | 7,961 | package software.amazon.awssdk.aws.greengrass.model;
import com.google.gson.annotations.Expose;
import java.lang.Object;
import java.lang.Override;
import java.lang.String;
import java.time.Instant;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import software.amazon.awssdk.eventstreamrpc.model.EventStreamJsonMessage;
public class UpdateConfigurationRequest implements EventStreamJsonMessage {
public static final String APPLICATION_MODEL_TYPE = "aws.greengrass#UpdateConfigurationRequest";
public static final UpdateConfigurationRequest VOID;
static {
VOID = new UpdateConfigurationRequest() {
@Override
public boolean isVoid() {
return true;
}
};
}
@Expose(
serialize = true,
deserialize = true
)
private Optional<List<String>> keyPath;
@Expose(
serialize = true,
deserialize = true
)
private Optional<Instant> timestamp;
@Expose(
serialize = true,
deserialize = true
)
private Optional<Map<String, Object>> valueToMerge;
public UpdateConfigurationRequest() {
this.keyPath = Optional.empty();
this.timestamp = Optional.empty();
this.valueToMerge = Optional.empty();
}
public List<String> getKeyPath() {
if (keyPath.isPresent()) {
return keyPath.get();
}
return null;
}
public void setKeyPath(final List<String> keyPath) {
this.keyPath = Optional.ofNullable(keyPath);
}
public Instant getTimestamp() {
if (timestamp.isPresent()) {
return timestamp.get();
}
return null;
}
public void setTimestamp(final Instant timestamp) {
this.timestamp = Optional.ofNullable(timestamp);
}
public Map<String, Object> getValueToMerge() {
if (valueToMerge.isPresent()) {
return valueToMerge.get();
}
return null;
}
public void setValueToMerge(final Map<String, Object> valueToMerge) {
this.valueToMerge = Optional.ofNullable(valueToMerge);
}
@Override
public String getApplicationModelType() {
return APPLICATION_MODEL_TYPE;
}
@Override
public boolean equals(Object rhs) {
if (rhs == null) return false;
if (!(rhs instanceof UpdateConfigurationRequest)) return false;
if (this == rhs) return true;
final UpdateConfigurationRequest other = (UpdateConfigurationRequest)rhs;
boolean isEquals = true;
isEquals = isEquals && this.keyPath.equals(other.keyPath);
isEquals = isEquals && this.timestamp.equals(other.timestamp);
isEquals = isEquals && this.valueToMerge.equals(other.valueToMerge);
return isEquals;
}
@Override
public int hashCode() {
return Objects.hash(keyPath, timestamp, valueToMerge);
}
}
|
3e12dc61c435aebdefbaf369c9e56b07e0a7970c | 2,381 | java | Java | app/src/main/java/edu/hm/cs/fs/app/ui/fs/presence/PresenceFragment.java | Fachschaft07/fs-app | 988b178470c074fc8ef3a8c6f57d65320eb5abd6 | [
"Apache-2.0"
] | 8 | 2015-02-08T12:48:52.000Z | 2015-12-16T17:56:07.000Z | app/src/main/java/edu/hm/cs/fs/app/ui/fs/presence/PresenceFragment.java | Fachschaft07/fs-app | 988b178470c074fc8ef3a8c6f57d65320eb5abd6 | [
"Apache-2.0"
] | 55 | 2015-02-18T14:06:15.000Z | 2016-01-28T10:05:07.000Z | app/src/main/java/edu/hm/cs/fs/app/ui/fs/presence/PresenceFragment.java | Fachschaft07/fs-app | 988b178470c074fc8ef3a8c6f57d65320eb5abd6 | [
"Apache-2.0"
] | 9 | 2015-02-08T12:49:53.000Z | 2015-11-19T20:49:49.000Z | 25.880435 | 96 | 0.696766 | 7,962 | package edu.hm.cs.fs.app.ui.fs.presence;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.View;
import com.fk07.R;
import java.util.List;
import butterknife.Bind;
import butterknife.ButterKnife;
import edu.hm.cs.fs.app.presenter.PresencePresenter;
import edu.hm.cs.fs.app.ui.BaseFragment;
import edu.hm.cs.fs.app.view.IPresenceView;
import edu.hm.cs.fs.common.model.Presence;
/**
* Created by FHellman on 11.08.2015.
*/
public class PresenceFragment extends BaseFragment<PresencePresenter> implements IPresenceView {
@Bind(R.id.toolbar)
Toolbar mToolbar;
@Bind(R.id.swipeContainer)
SwipeRefreshLayout mSwipeRefreshLayout;
@Bind(R.id.listView)
RecyclerView mListView;
private PresenceAdapter mAdapter;
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
ButterKnife.bind(this, view);
mToolbar.setNavigationIcon(getMainActivity().getToolbar().getNavigationIcon());
mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
getMainActivity().openDrawer();
}
});
mAdapter = new PresenceAdapter(getActivity());
mListView.setAdapter(mAdapter);
mListView.setLayoutManager(new LinearLayoutManager(getActivity()));
initSwipeRefreshLayout(mSwipeRefreshLayout);
setPresenter(new PresencePresenter(this));
getPresenter().loadPresence();
}
@Override
protected int getLayout() {
return R.layout.fragment_presence;
}
@Override
public boolean hasCustomToolbar() {
return true;
}
@Override
protected int getTitle() {
return R.string.student_council;
}
@Override
public void showContent(@NonNull List<Presence> content) {
mAdapter.setData(content);
}
@Override
public void onRefresh() {
getPresenter().loadPresence();
}
@Override
public void onDestroyView() {
super.onDestroyView();
ButterKnife.unbind(this);
}
}
|
3e12de6d7e1b6d5a6f69806466f6d1d21b8f6a2f | 2,766 | java | Java | archive-portal/src/main/java/com/ecm/portal/archivegc/workflowEvent/Deploy2RecordStorageListener.java | liaojiyongde/ArchiveGC | 640ff16a3e2328c1c05193cb059e1e21806dba0c | [
"Apache-2.0"
] | null | null | null | archive-portal/src/main/java/com/ecm/portal/archivegc/workflowEvent/Deploy2RecordStorageListener.java | liaojiyongde/ArchiveGC | 640ff16a3e2328c1c05193cb059e1e21806dba0c | [
"Apache-2.0"
] | null | null | null | archive-portal/src/main/java/com/ecm/portal/archivegc/workflowEvent/Deploy2RecordStorageListener.java | liaojiyongde/ArchiveGC | 640ff16a3e2328c1c05193cb059e1e21806dba0c | [
"Apache-2.0"
] | null | null | null | 35.922078 | 108 | 0.782357 | 7,963 | package com.ecm.portal.archivegc.workflowEvent;
import java.util.List;
import java.util.Map;
import org.flowable.engine.delegate.DelegateExecution;
import org.flowable.engine.delegate.JavaDelegate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;
import com.ecm.core.entity.EcmDocument;
import com.ecm.core.entity.EcmFolder;
import com.ecm.core.exception.AccessDeniedException;
import com.ecm.core.exception.EcmException;
import com.ecm.core.exception.NoPermissionException;
import com.ecm.core.service.AuthService;
import com.ecm.core.service.DocumentService;
import com.ecm.core.service.FolderPathService;
import com.ecm.core.service.FolderService;
import com.ecm.icore.service.IEcmSession;
import com.ecm.portal.archivegc.utils.EcmSessionFactory;
@Component(value="deploy2RecordStorage")
public class Deploy2RecordStorageListener implements JavaDelegate {
private Logger log=LoggerFactory.getLogger(this.getClass());
@Autowired
DocumentService documentService;
@Autowired
private Environment env;
@Autowired
private AuthService authService;
@Autowired
private FolderService folderService;
@Autowired
private FolderPathService folderPathService;
@Override
public void execute(DelegateExecution execution) {
// TODO Auto-generated method stub
IEcmSession session=EcmSessionFactory.getWorkflowSession(env, authService);
String token=session.getToken();
String formId= execution.getVariable("formId").toString();
String sql="select child_id as ID from ecm_relation where name='irel_children' and parent_id='"+formId+"'"
+ " union select child_id as ID from ecm_relation where parent_id in(select child_id from ecm_relation"
+ " where parent_id ='"+formId+"')";
try {
List<Map<String,Object>> objList= documentService.getMapList(token, sql);
for (Map<String, Object> map : objList) {
String relevantArchiveId= map.get("ID").toString();
EcmDocument arrchive= documentService.getObjectById(token, relevantArchiveId);
String folderId= folderPathService.getFolderId(token, arrchive.getAttributes(), "2");
EcmFolder folder= folderService.getObjectById(token, folderId);
arrchive.setFolderId(folderId);
arrchive.setAclName(folder.getAclName());
arrchive.setStatus("整编");
documentService.updateObject(token, arrchive, null);
}
} catch (EcmException | NoPermissionException | AccessDeniedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
log.error(e.getMessage());
}finally {
if(session!=null) {
EcmSessionFactory.releaseSession(authService, session);
}
}
}
}
|
3e12df85fd789bc9e5235bcacd3c6a1800d8b905 | 725 | java | Java | src/main/java/com/bergerkiller/bukkit/common/entity/type/CommonMinecartRideable.java | Magnum97/BKCommonLib | c742f3ea90d96f27feac8ff17fee10ce7931b6b6 | [
"MIT"
] | 123 | 2015-03-23T16:10:47.000Z | 2022-03-24T10:24:57.000Z | src/main/java/com/bergerkiller/bukkit/common/entity/type/CommonMinecartRideable.java | Magnum97/BKCommonLib | c742f3ea90d96f27feac8ff17fee10ce7931b6b6 | [
"MIT"
] | 113 | 2015-06-21T07:04:35.000Z | 2022-03-11T18:21:47.000Z | src/main/java/com/bergerkiller/bukkit/common/entity/type/CommonMinecartRideable.java | Magnum97/BKCommonLib | c742f3ea90d96f27feac8ff17fee10ce7931b6b6 | [
"MIT"
] | 86 | 2015-03-09T21:39:50.000Z | 2021-11-07T05:29:16.000Z | 24.166667 | 78 | 0.736552 | 7,964 | package com.bergerkiller.bukkit.common.entity.type;
import org.bukkit.Material;
import org.bukkit.entity.minecart.RideableMinecart;
import org.bukkit.inventory.ItemStack;
import java.util.Arrays;
import java.util.List;
/**
* A Common Entity implementation for Minecarts without a Block that can be
* entered by players
*/
public class CommonMinecartRideable extends CommonMinecart<RideableMinecart> {
public CommonMinecartRideable(RideableMinecart base) {
super(base);
}
@Override
public List<ItemStack> getBrokenDrops() {
return Arrays.asList(new ItemStack(Material.MINECART, 1));
}
@Override
public Material getCombinedItem() {
return Material.MINECART;
}
}
|
3e12e020366611b092041f8151c2a440cd2a1461 | 4,720 | java | Java | spring-boot-mybatis/src/main/java/io/ymq/mybatis/config/druid/AbstractDruidDBConfig.java | yangxiongj/springboot-learning-example | b50ea97e365f990b0470877c41a9f3fc70c309d8 | [
"Apache-2.0"
] | null | null | null | spring-boot-mybatis/src/main/java/io/ymq/mybatis/config/druid/AbstractDruidDBConfig.java | yangxiongj/springboot-learning-example | b50ea97e365f990b0470877c41a9f3fc70c309d8 | [
"Apache-2.0"
] | null | null | null | spring-boot-mybatis/src/main/java/io/ymq/mybatis/config/druid/AbstractDruidDBConfig.java | yangxiongj/springboot-learning-example | b50ea97e365f990b0470877c41a9f3fc70c309d8 | [
"Apache-2.0"
] | null | null | null | 40.689655 | 119 | 0.741525 | 7,965 | package io.ymq.mybatis.config.druid;
import com.alibaba.druid.pool.DruidDataSource;
import com.github.pagehelper.PageHelper;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.ApplicationContextException;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import javax.annotation.Resource;
import javax.sql.DataSource;
import java.sql.SQLException;
import java.util.Properties;
/**
* 描述: 提供基础数据源功能
* author: yanpenglei
* Date: 2017/9/8 19:50
*/
@Configuration
@EnableConfigurationProperties(DruidDbProperties.class)
@Import({DruidMonitConfig.class})
public abstract class AbstractDruidDBConfig {
private Logger logger = LoggerFactory.getLogger(AbstractDruidDBConfig.class);
@Resource
private DruidDbProperties druidDbProperties;
public DruidDataSource createDataSource(String url, String username, String password) {
if (StringUtils.isEmpty(url)) {
System.out.println(
"Your database connection pool configuration is incorrect!" + " Please check your Spring profile");
throw new ApplicationContextException("Database connection pool is not configured correctly");
}
DruidDataSource datasource = new DruidDataSource();
datasource.setUrl(url);
datasource.setUsername(username);
datasource.setPassword(password);
// datasource.setDriverClassName(
// StringUtils.isEmpty(driverClassName) ?
// druidDbProperties.getDriverClassName() : driverClassName);
datasource.setInitialSize(druidDbProperties.getInitialSize());
datasource.setMinIdle(druidDbProperties.getMinIdle());
datasource.setMaxActive(druidDbProperties.getMaxActive());
datasource.setMaxWait(druidDbProperties.getMaxWait());
datasource.setTimeBetweenEvictionRunsMillis(druidDbProperties.getTimeBetweenEvictionRunsMillis());
datasource.setMinEvictableIdleTimeMillis(druidDbProperties.getMinEvictableIdleTimeMillis());
datasource.setValidationQuery(druidDbProperties.getValidationQuery());
datasource.setTestWhileIdle(druidDbProperties.isTestWhileIdle());
datasource.setTestOnBorrow(druidDbProperties.isTestOnBorrow());
datasource.setTestOnReturn(druidDbProperties.isTestOnReturn());
try {
datasource.setFilters(druidDbProperties.getFilters());
} catch (SQLException e) {
logger.error("druid configuration initialization filter", e);
}
datasource.setConnectionProperties(druidDbProperties.getConnectionProperties());
return datasource;
}
/**
* 加载默认mybatis xml配置文件,并初始化分页插件
*
* @param dataSource
* @return
* @throws Exception
*/
public SqlSessionFactory sqlSessionFactory(DataSource dataSource) throws Exception {
return createSqlSessionFactory(dataSource, "classpath:mybatis/**/*.xml");
}
/**
* 加载mybatis xml配置文件,并初始化分页插件
*
* @param dataSource 数据源
* @param mapperLocations 自定义xml配置路径
* @return
* @throws Exception
*/
public SqlSessionFactory sqlSessionFactory(DataSource dataSource, String mapperLocations) throws Exception {
return createSqlSessionFactory(dataSource, mapperLocations);
}
private SqlSessionFactory createSqlSessionFactory(DataSource dataSource, String mapperLocations) throws Exception {
SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
sqlSessionFactoryBean.setDataSource(dataSource);
// mybatis分页
PageHelper pageHelper = new PageHelper();
Properties props = new Properties();
props.setProperty("dialect", "mysql");
props.setProperty("reasonable", "true");
props.setProperty("supportMethodsArguments", "true");
props.setProperty("returnPageInfo", "check");
props.setProperty("params", "count=countSql");
pageHelper.setProperties(props); // 添加插件
sqlSessionFactoryBean.setPlugins(new Interceptor[]{pageHelper});
PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
sqlSessionFactoryBean.setMapperLocations(resolver.getResources(mapperLocations));
return sqlSessionFactoryBean.getObject();
}
}
|
3e12e034fb4badf23cfb33cdec260f61fb73e3cd | 6,360 | java | Java | src/com/powersurgepub/psmkdown/MarkdownTest.java | hbowie/psmkdown | 88da5baf18889cb43d256d2f74948ad2703e2da6 | [
"Apache-2.0"
] | null | null | null | src/com/powersurgepub/psmkdown/MarkdownTest.java | hbowie/psmkdown | 88da5baf18889cb43d256d2f74948ad2703e2da6 | [
"Apache-2.0"
] | null | null | null | src/com/powersurgepub/psmkdown/MarkdownTest.java | hbowie/psmkdown | 88da5baf18889cb43d256d2f74948ad2703e2da6 | [
"Apache-2.0"
] | null | null | null | 35.730337 | 129 | 0.702987 | 7,966 | /*
* Copyright 2013 - 2013 Herb Bowie
*
* 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.powersurgepub.psmkdown;
import com.powersurgepub.pstextio.*;
import java.io.*;
import javax.swing.*;
/**
Test the markdown routines.
@author hbowie
*/
public class MarkdownTest extends javax.swing.JFrame {
private JFileChooser chooser;
private TextLineReader lineReader = null;
/**
Creates new form MarkdownTest
*/
public MarkdownTest() {
initComponents();
}
private void fileOpen() {
chooser = new JFileChooser();
int result = chooser.showOpenDialog(this);
if (result == JFileChooser.APPROVE_OPTION) {
File mdFile = chooser.getSelectedFile();
MarkdownDoc doc = new MarkdownDoc();
lineReader = new FileLineReader (mdFile);
boolean ok = lineReader.open();
if (ok) {
String line = lineReader.readLine();
while (lineReader.isOK()
&& (! lineReader.isAtEnd())
&& line != null) {
MarkdownLine mdLine = new MarkdownLine (doc, line);
mdLine.display();
doc.display();
line = lineReader.readLine();
}
lineReader.close();
}
}
}
/**
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() {
java.awt.GridBagConstraints gridBagConstraints;
openButton = new javax.swing.JButton();
resultsScrollPane = new javax.swing.JScrollPane();
resultsTextArea = new javax.swing.JTextArea();
jMenuBar1 = new javax.swing.JMenuBar();
fileMenu = new javax.swing.JMenu();
fileOpenMenuItem = new javax.swing.JMenuItem();
editMenu = new javax.swing.JMenu();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
getContentPane().setLayout(new java.awt.GridBagLayout());
openButton.setText("Open");
openButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
openButtonActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 0;
getContentPane().add(openButton, gridBagConstraints);
resultsTextArea.setColumns(20);
resultsTextArea.setRows(5);
resultsScrollPane.setViewportView(resultsTextArea);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
getContentPane().add(resultsScrollPane, gridBagConstraints);
fileMenu.setText("File");
fileOpenMenuItem.setText("Open...");
fileOpenMenuItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
fileOpenMenuItemActionPerformed(evt);
}
});
fileMenu.add(fileOpenMenuItem);
jMenuBar1.add(fileMenu);
editMenu.setText("Edit");
jMenuBar1.add(editMenu);
setJMenuBar(jMenuBar1);
pack();
}// </editor-fold>//GEN-END:initComponents
private void openButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_openButtonActionPerformed
fileOpen();
}//GEN-LAST:event_openButtonActionPerformed
private void fileOpenMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_fileOpenMenuItemActionPerformed
fileOpen();
}//GEN-LAST:event_fileOpenMenuItemActionPerformed
/**
@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(MarkdownTest.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(MarkdownTest.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(MarkdownTest.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(MarkdownTest.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 MarkdownTest().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JMenu editMenu;
private javax.swing.JMenu fileMenu;
private javax.swing.JMenuItem fileOpenMenuItem;
private javax.swing.JMenuBar jMenuBar1;
private javax.swing.JButton openButton;
private javax.swing.JScrollPane resultsScrollPane;
private javax.swing.JTextArea resultsTextArea;
// End of variables declaration//GEN-END:variables
}
|
3e12e195980ecc6e0fa1da05d0a99105649881fc | 8,293 | java | Java | src/test/java/org/autogui/demo/NumberListDemo.java | ppp-kohe/autogui | 2f6e5b6867c5fe585f27532dbc929802ee2cf2ec | [
"Apache-2.0"
] | 6 | 2018-11-26T09:02:31.000Z | 2021-09-17T02:54:26.000Z | src/test/java/org/autogui/demo/NumberListDemo.java | ppp-kohe/autogui | 2f6e5b6867c5fe585f27532dbc929802ee2cf2ec | [
"Apache-2.0"
] | 1 | 2020-11-01T03:24:47.000Z | 2020-11-01T03:24:47.000Z | src/test/java/org/autogui/demo/NumberListDemo.java | ppp-kohe/autogui | 2f6e5b6867c5fe585f27532dbc929802ee2cf2ec | [
"Apache-2.0"
] | null | null | null | 31.652672 | 105 | 0.471361 | 7,967 | package org.autogui.demo;
import org.autogui.GuiIncluded;
import org.autogui.GuiListSelectionUpdater;
import org.autogui.swing.AutoGuiShell;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
@GuiIncluded
public class NumberListDemo {
public static void main(String[] args) {
AutoGuiShell.get().showWindow(new NumberListDemo());
}
@GuiIncluded(index = 1)
public Integers integers = new Integers();
@GuiIncluded(index = 2)
public Floats floats = new Floats();
@GuiIncluded(index = 3)
public Matrix matrix = new Matrix();
@GuiIncluded(index = 4)
public MatrixPrimitive matrixPrimitive = new MatrixPrimitive();
@GuiIncluded
public class Integers {
@GuiIncluded(index = 1)
public int start = 0;
@GuiIncluded(index = 2)
public int stride = 1;
@GuiIncluded(index = 3)
public int size = 10;
@GuiIncluded
public List<Integer> integers = new ArrayList<>();
@GuiIncluded
public void add() {
for (int i = 0 ; i < size; ++i) {
integers.add(start);
start += stride;
}
integers = new ArrayList<>(integers);
}
@GuiIncluded
public void show(List<Integer> selectedIndexes) {
StringBuilder buf = new StringBuilder();
for (int i = 0, l = selectedIndexes.size(); i < l; ++i) {
int idx = selectedIndexes.get(i);
int n = integers.get(idx);
buf.append(" [").append(idx).append("]: ").append(n);
if (i > 0 && i % 10 == 0) {
System.out.println(buf.toString());
buf = new StringBuilder();
}
}
if (buf.length() > 0) {
System.out.println(buf);
}
}
@GuiIncluded
public void delete(List<Integer> selectedIndexes) {
integers = IntStream.range(0, integers.size())
.filter(i -> !selectedIndexes.contains(i))
.mapToObj(integers::get)
.collect(Collectors.toList());
}
@GuiListSelectionUpdater(index = true)
@GuiIncluded
public List<Integer> next(List<Integer> selectedIndexes) {
System.err.println("next : " + selectedIndexes);
return selectedIndexes.stream()
.map(i -> i + 1 >= integers.size() ? 0 : i + 1)
.collect(Collectors.toList());
}
}
@GuiIncluded
public class Floats {
@GuiIncluded(index = 1)
public double start = 0;
@GuiIncluded(index = 2)
public double stride = 1;
@GuiIncluded(index = 3)
public double size = 10;
@GuiIncluded
public List<Float> floats = new ArrayList<>();
@GuiIncluded
public List<Double> doubles = new ArrayList<>();
@GuiIncluded
public void addFloats() {
for (int i = 0 ; i < size; ++i) {
floats.add((float) start);
start += stride;
}
floats = new ArrayList<>(floats);
}
@GuiIncluded
public void addDoubles() {
for (int i = 0 ; i < size; ++i) {
doubles.add(start);
start += stride;
}
doubles = new ArrayList<>(doubles);
}
@GuiIncluded
public void show(List<Integer> selectedIndexes, String propName) {
List<?> data;
if (propName.equals("floats")) {
data = floats;
} else {
data = doubles;
}
System.out.println("[" + propName + "]:");
StringBuilder buf = new StringBuilder();
for (int i = 0, l = selectedIndexes.size(); i < l; ++i) {
int idx = selectedIndexes.get(i);
Object n = data.get(idx);
buf.append(" [").append(idx).append("]: ").append(n);
if (i > 0 && i % 10 == 0) {
System.out.println(buf.toString());
buf = new StringBuilder();
}
}
if (buf.length() > 0) {
System.out.println(buf);
}
}
@GuiIncluded
public void delete(List<Integer> selectedIndexes, String propName) {
List<?> data;
if (propName.equals("floats")) {
floats = IntStream.range(0, floats.size())
.filter(i -> !selectedIndexes.contains(i))
.mapToObj(floats::get)
.collect(Collectors.toList());
} else {
doubles = IntStream.range(0, doubles.size())
.filter(i -> !selectedIndexes.contains(i))
.mapToObj(doubles::get)
.collect(Collectors.toList());
}
}
@GuiListSelectionUpdater(index = true)
@GuiIncluded
public List<Integer> next(List<Integer> selectedIndexes, String propName) {
System.err.println("next : " + selectedIndexes + " " + propName);
return selectedIndexes.stream()
.map(i -> i + 1 >= (propName.equals("floats") ? floats : doubles).size() ? 0 : i + 1)
.collect(Collectors.toList());
}
}
@GuiIncluded
public static class Matrix {
@GuiIncluded(index = 1)
public double start = 0;
@GuiIncluded(index = 2)
public double stride = 1;
@GuiIncluded(index = 3)
public int width = 10;
@GuiIncluded(index = 4)
public int height = 10;
@GuiIncluded
public List<List<Float>> matrix = new ArrayList<>();
@GuiIncluded
public void add() {
for (int i = 0; i < height; ++i) {
List<Float> row = new ArrayList<>();
for (int j = 0; j < width; ++j) {
row.add((float) start);
start += stride;
}
matrix.add(row);
}
matrix = new ArrayList<>(matrix);
}
@GuiIncluded
public void show(List<int[]> indexes) {
System.err.println("---------------- "+ indexes.size());
for (int[] idx : indexes) {
System.err.print(Arrays.toString(idx) + " : ");
if (idx.length >= 2) {
try {
System.err.println(matrix.get(idx[0]).get(idx[1]));
} catch (Exception ex) {
ex.printStackTrace();
}
} else {
System.err.println();
}
}
}
}
@GuiIncluded
public static class MatrixPrimitive {
@GuiIncluded(index = 1)
public double start = 0;
@GuiIncluded(index = 2)
public double stride = 1;
@GuiIncluded(index = 3)
public int width = 10;
@GuiIncluded(index = 4)
public int height = 10;
@GuiIncluded
public float[][] matrix = {};
@GuiIncluded
public void set() {
matrix = new float[height][width];
for (int i = 0; i < height; ++i) {
float[] row = matrix[i];
for (int j = 0; j < width; ++j) {
row[j] = ((float) start);
start += stride;
}
}
}
@GuiIncluded
public void show(List<int[]> indexes) {
System.err.println("---------------- "+ indexes.size());
for (int[] idx : indexes) {
System.err.print(Arrays.toString(idx) + " : ");
if (idx.length > 1) {
try {
System.err.println(matrix[idx[0]][idx[1]]);
} catch (Exception ex) {
ex.printStackTrace();
}
} else {
System.err.println();
}
}
}
}
}
|
3e12e298ab62e2022468eb8011fdf8a25669bc9e | 1,963 | java | Java | app/src/main/java/org/canis/aludra/service/ListCredentialsTask.java | scoir/aludra | ee7f744311aed503bdd7db9bce4759ffaaaf366b | [
"Apache-2.0"
] | 1 | 2020-10-06T14:08:02.000Z | 2020-10-06T14:08:02.000Z | app/src/main/java/org/canis/aludra/service/ListCredentialsTask.java | scoir/aludra | ee7f744311aed503bdd7db9bce4759ffaaaf366b | [
"Apache-2.0"
] | 1 | 2021-04-07T01:57:42.000Z | 2021-04-07T01:57:42.000Z | app/src/main/java/org/canis/aludra/service/ListCredentialsTask.java | scoir/aludra | ee7f744311aed503bdd7db9bce4759ffaaaf366b | [
"Apache-2.0"
] | 2 | 2020-10-06T14:08:04.000Z | 2021-04-09T12:27:30.000Z | 30.2 | 107 | 0.686704 | 7,968 | package org.canis.aludra.service;
import android.os.AsyncTask;
import org.canis.aludra.model.ConnectionRequest;
import org.canis.aludra.model.ConnectionResult;
import org.canis.aludra.model.CredentialRequest;
import org.canis.aludra.model.CredentialResult;
import java.io.IOException;
import retrofit2.Call;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
public class ListCredentialsTask extends AsyncTask<CredentialRequest, Void, CredentialResult> {
public interface ListCredentialsTaskHandler {
void HandleCredentials(CredentialResult result);
}
private final ListCredentialsTaskHandler handler;
private String cloudAgentId;
private String signature;
public ListCredentialsTask(ListCredentialsTaskHandler handler, String cloudAgentId, String signature) {
this.handler = handler;
this.cloudAgentId = cloudAgentId;
this.signature = signature;
}
@Override
protected CredentialResult doInBackground(CredentialRequest... reqs) {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("http://10.0.2.2:11004")
.addConverterFactory(GsonConverterFactory.create())
.build();
CanisService service = retrofit.create(CanisService.class);
Call<CredentialResult> call = service.ListCredentials(this.cloudAgentId, this.signature, reqs[0]);
try {
Response<CredentialResult> resp = call.execute();
if (resp.isSuccessful()) {
return resp.body();
} else {
throw new IOException(resp.errorBody().string());
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(CredentialResult result) {
super.onPostExecute(result);
this.handler.HandleCredentials(result);
}
}
|
3e12e2e80972ec853077f54c00395fd03842066e | 129 | java | Java | ProjectSourceCode/Apache Commons Math v3.5/src/test/java/org/apache/commons/math3/stat/descriptive/moment/SkewnessTest.java | yashgolwala/Software_Measurement_Team_M | 3d2aef4c0711b7a02155a42ca6b08bb6c2693d4c | [
"Unlicense"
] | null | null | null | ProjectSourceCode/Apache Commons Math v3.5/src/test/java/org/apache/commons/math3/stat/descriptive/moment/SkewnessTest.java | yashgolwala/Software_Measurement_Team_M | 3d2aef4c0711b7a02155a42ca6b08bb6c2693d4c | [
"Unlicense"
] | null | null | null | ProjectSourceCode/Apache Commons Math v3.5/src/test/java/org/apache/commons/math3/stat/descriptive/moment/SkewnessTest.java | yashgolwala/Software_Measurement_Team_M | 3d2aef4c0711b7a02155a42ca6b08bb6c2693d4c | [
"Unlicense"
] | 2 | 2019-06-24T22:57:32.000Z | 2019-06-26T16:58:52.000Z | 32.25 | 75 | 0.883721 | 7,969 | version https://git-lfs.github.com/spec/v1
oid sha256:fa3c32fd726422e8734b71ef0eed1f64d12d9e7e2743d6d9bb737b6363543d38
size 1995
|
3e12e37e30f2aa215c006d64a6a9cfb0ec4a738b | 2,637 | java | Java | gold-realtime/compute-realtime-view/src/main/java/com/platform/realtime/view/module/Message.java | yurenfangzhou/bdp-gold | 7320588bb629b63965baeb4818fda811a82d1405 | [
"Apache-2.0"
] | 13 | 2021-01-23T10:10:23.000Z | 2021-11-08T08:40:53.000Z | gold-realtime/compute-realtime-view/src/main/java/com/platform/realtime/view/module/Message.java | yurenfangzhou/bdp-gold | 7320588bb629b63965baeb4818fda811a82d1405 | [
"Apache-2.0"
] | 1 | 2021-05-14T06:59:14.000Z | 2021-05-14T06:59:14.000Z | gold-realtime/compute-realtime-view/src/main/java/com/platform/realtime/view/module/Message.java | bdpteam/bdp-gold | 4ad442fdf9d9d312c9422d262c65854544a55604 | [
"Apache-2.0"
] | 10 | 2021-01-28T15:17:57.000Z | 2022-01-24T02:54:34.000Z | 21.975 | 80 | 0.560485 | 7,970 | package com.platform.realtime.view.module;
import org.apache.commons.lang3.StringUtils;
/**
* 返回结果
*
* @author wlhbdp
*
*/
public class Message {
private final static int OK = 200;
private final static int ERROR = 500;
private final static int NO_CONTENT = 204;
private final static int BAD_REQUEST = 400;
public static class MessageEntry {
private int code;
private String msg;
public MessageEntry(int code, String msg) {
super();
this.code = code;
this.msg = msg;
}
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
}
public static class SuccessMsg extends MessageEntry {
public SuccessMsg(int code, Object object) {
super(code, "ok");
this.data = object;
}
private Object data;
public Object getData() {
return data;
}
public void setData(Object data) {
this.data = data;
}
}
public static class ErrorMsg extends MessageEntry {
public ErrorMsg(int code, String message) {
super(code, StringUtils.isEmpty(message) ? "error" : message);
}
}
public static class NoContentMsg extends MessageEntry {
public NoContentMsg(int code, String message) {
super(code, StringUtils.isEmpty(message) ? "no content" : message);
}
}
public static class BadRequestMsg extends MessageEntry {
public BadRequestMsg(int code, String message) {
super(code, StringUtils.isEmpty(message) ? "bad request" : message);
}
}
/**
* 正常返回并且有值
*
* @param result
* @return
*/
public static MessageEntry ok(Object result) {
return new SuccessMsg(OK, result);
}
/**
* 服务器发送异常
*
* @param message
* @return
*/
public static MessageEntry error(String message) {
return new ErrorMsg(ERROR, message);
}
/**
* 服务器正常,但是没有要查询的值
*
* @param message
* @return
*/
public static MessageEntry noContent(String message) {
return new NoContentMsg(NO_CONTENT, message);
}
/**
* 错误的请求
*
* @param message
* @return
*/
public static MessageEntry badRequest(String message) {
return new BadRequestMsg(BAD_REQUEST, message);
}
} |
3e12e411719fb59077698ab6b1e6cb56a71c24f3 | 2,585 | java | Java | app/src/main/java/cf/playhi/freezeyou/AskRunActivity.java | linsui/FreezeYou | 4f47d07b76f9a7d48deff03110ccc1981537e2cb | [
"Apache-2.0"
] | 76 | 2020-04-24T04:59:17.000Z | 2022-03-31T07:38:22.000Z | app/src/main/java/cf/playhi/freezeyou/AskRunActivity.java | linsui/FreezeYou | 4f47d07b76f9a7d48deff03110ccc1981537e2cb | [
"Apache-2.0"
] | 25 | 2018-07-14T01:53:54.000Z | 2020-03-08T12:37:38.000Z | app/src/main/java/cf/playhi/freezeyou/AskRunActivity.java | linsui/FreezeYou | 4f47d07b76f9a7d48deff03110ccc1981537e2cb | [
"Apache-2.0"
] | 23 | 2020-04-24T03:11:01.000Z | 2022-02-22T04:43:37.000Z | 38.58209 | 90 | 0.538491 | 7,971 | package cf.playhi.freezeyou;
import android.content.DialogInterface;
import android.os.Bundle;
import cf.playhi.freezeyou.app.FreezeYouBaseActivity;
import cf.playhi.freezeyou.utils.ApplicationInfoUtils;
import static cf.playhi.freezeyou.ThemeUtils.processSetTheme;
import static cf.playhi.freezeyou.utils.AlertDialogUtils.buildAlertDialog;
import static cf.playhi.freezeyou.utils.ApplicationIconUtils.getApplicationIcon;
import static cf.playhi.freezeyou.utils.FUFUtils.checkAndStartApp;
public class AskRunActivity extends FreezeYouBaseActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
processSetTheme(this, true);
super.onCreate(savedInstanceState);
final String pkgName = getIntent().getStringExtra("pkgName");
final String target = getIntent().getStringExtra("target");
final String tasks = getIntent().getStringExtra("tasks");
buildAlertDialog(
this,
getApplicationIcon(
this,
pkgName,
ApplicationInfoUtils.getApplicationInfoFromPkgName(pkgName, this),
true),
getResources().getString(R.string.unfreezedAndAskLaunch),
getResources().getString(R.string.notice))
.setNegativeButton(R.string.no, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
finish();
}
})
.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int ii) {
checkAndStartApp(
AskRunActivity.this,
pkgName,
target,
tasks,
null,
false
);
finish();
}
})
.setOnCancelListener(new DialogInterface.OnCancelListener() {
@Override
public void onCancel(DialogInterface dialog) {
finish();
}
})
.create()
.show();
}
@Override
protected void onPause() {
super.onPause();
finish();
}
}
|
3e12e48cf491cc57e33952cc714804a401962c36 | 504 | java | Java | richfaces-jsf-projects/Richfaces-demo-3.3.3.Final/src/org/richfaces/demo/toolBar/TbBean.java | jonathanluo/jsf | 7b5172fb8fd79fa9b485ecea968904beb14f67b9 | [
"Apache-2.0"
] | null | null | null | richfaces-jsf-projects/Richfaces-demo-3.3.3.Final/src/org/richfaces/demo/toolBar/TbBean.java | jonathanluo/jsf | 7b5172fb8fd79fa9b485ecea968904beb14f67b9 | [
"Apache-2.0"
] | null | null | null | richfaces-jsf-projects/Richfaces-demo-3.3.3.Final/src/org/richfaces/demo/toolBar/TbBean.java | jonathanluo/jsf | 7b5172fb8fd79fa9b485ecea968904beb14f67b9 | [
"Apache-2.0"
] | 1 | 2019-09-24T09:21:22.000Z | 2019-09-24T09:21:22.000Z | 24 | 64 | 0.763889 | 7,972 | package org.richfaces.demo.toolBar;
public class TbBean {
private String groupSeparator;
private String groupItemSeparator;
public String getGroupItemSeparator() {
return groupItemSeparator;
}
public void setGroupItemSeparator(String groupItemSeparator) {
this.groupItemSeparator = groupItemSeparator;
}
public String getGroupSeparator() {
return groupSeparator;
}
public void setGroupSeparator(String groupSeparator) {
this.groupSeparator = groupSeparator;
}
}
|
3e12e4a1c2376b668127f6c9cbb6de8d25b85a3c | 7,390 | java | Java | query-validator-core/src/main/java/com/codegans/sql/core/FakeConnection.java | victor-cr/query-validator | 433c0a67404104437c6d8a86209efd2a3e27cd5d | [
"MIT"
] | null | null | null | query-validator-core/src/main/java/com/codegans/sql/core/FakeConnection.java | victor-cr/query-validator | 433c0a67404104437c6d8a86209efd2a3e27cd5d | [
"MIT"
] | null | null | null | query-validator-core/src/main/java/com/codegans/sql/core/FakeConnection.java | victor-cr/query-validator | 433c0a67404104437c6d8a86209efd2a3e27cd5d | [
"MIT"
] | null | null | null | 25.221843 | 150 | 0.682138 | 7,973 | package com.codegans.sql.core;
import java.sql.*;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.Executor;
import java.util.concurrent.atomic.AtomicBoolean;
public class FakeConnection extends StatementValidatorWrapper implements Connection {
private final AtomicBoolean autoCommit;
private final AtomicBoolean readOnly;
private final DatabaseMetaData databaseMetaData;
public FakeConnection(StatementValidator validator, DatabaseMetaData databaseMetaData) {
super(validator);
this.autoCommit = new AtomicBoolean(true);
this.readOnly = new AtomicBoolean(false);
this.databaseMetaData = databaseMetaData;
}
@Override
public Statement createStatement() throws SQLException {
log.debug("Invoked: Connection.createStatement()");
return new FakeStatement(validator, this);
}
@Override
public PreparedStatement prepareStatement(String sql) throws SQLException {
log.debug("Invoked: Connection.prepareStatement(String)");
return new FakePreparedStatement(validator, this, sql);
}
@Override
public CallableStatement prepareCall(String sql) throws SQLException {
log.debug("Invoked: Connection.prepareCall(String)");
return new FakeCallableStatement(validator, this, sql);
}
@Override
public String nativeSQL(String sql) throws SQLException {
log.debug("Invoked: Connection.nativeSQL(String)");
return sql;
}
@Override
public void setAutoCommit(boolean autoCommit) throws SQLException {
log.debug("Invoked: Connection.setAutoCommit(boolean)");
this.autoCommit.set(autoCommit);
}
@Override
public boolean getAutoCommit() throws SQLException {
log.debug("Invoked: Connection.getAutoCommit()");
return this.autoCommit.get();
}
@Override
public void commit() throws SQLException {
log.debug("Invoked: Connection.commit()");
}
@Override
public void rollback() throws SQLException {
log.debug("Invoked: Connection.rollback()");
}
@Override
public DatabaseMetaData getMetaData() throws SQLException {
assertOpen();
log.debug("Invoked: Connection.getMetaData()");
return databaseMetaData;
}
@Override
public void setReadOnly(boolean readOnly) throws SQLException {
assertOpen();
log.debug("Invoked: Connection.setReadOnly(boolean)");
this.readOnly.set(readOnly);
}
@Override
public boolean isReadOnly() throws SQLException {
assertOpen();
log.debug("Invoked: Connection.isReadOnly()");
return this.readOnly.get();
}
@Override
public void setCatalog(String catalog) throws SQLException {
}
@Override
public String getCatalog() throws SQLException {
return null;
}
@Override
public void setTransactionIsolation(int level) throws SQLException {
}
@Override
public int getTransactionIsolation() throws SQLException {
return 0;
}
@Override
public SQLWarning getWarnings() throws SQLException {
return null;
}
@Override
public void clearWarnings() throws SQLException {
}
@Override
public Statement createStatement(int resultSetType, int resultSetConcurrency) throws SQLException {
return null;
}
@Override
public PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency) throws SQLException {
return null;
}
@Override
public CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency) throws SQLException {
return null;
}
@Override
public Map<String, Class<?>> getTypeMap() throws SQLException {
return null;
}
@Override
public void setTypeMap(Map<String, Class<?>> map) throws SQLException {
}
@Override
public void setHoldability(int holdability) throws SQLException {
}
@Override
public int getHoldability() throws SQLException {
return 0;
}
@Override
public Savepoint setSavepoint() throws SQLException {
return null;
}
@Override
public Savepoint setSavepoint(String name) throws SQLException {
return null;
}
@Override
public void rollback(Savepoint savepoint) throws SQLException {
}
@Override
public void releaseSavepoint(Savepoint savepoint) throws SQLException {
}
@Override
public Statement createStatement(int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException {
return null;
}
@Override
public PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException {
return null;
}
@Override
public CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException {
return null;
}
@Override
public PreparedStatement prepareStatement(String sql, int autoGeneratedKeys) throws SQLException {
return null;
}
@Override
public PreparedStatement prepareStatement(String sql, int[] columnIndexes) throws SQLException {
return null;
}
@Override
public PreparedStatement prepareStatement(String sql, String[] columnNames) throws SQLException {
return null;
}
@Override
public Clob createClob() throws SQLException {
return null;
}
@Override
public Blob createBlob() throws SQLException {
return null;
}
@Override
public NClob createNClob() throws SQLException {
return null;
}
@Override
public SQLXML createSQLXML() throws SQLException {
return null;
}
@Override
public boolean isValid(int timeout) throws SQLException {
return false;
}
@Override
public void setClientInfo(String name, String value) throws SQLClientInfoException {
}
@Override
public void setClientInfo(Properties properties) throws SQLClientInfoException {
}
@Override
public String getClientInfo(String name) throws SQLException {
return null;
}
@Override
public Properties getClientInfo() throws SQLException {
return null;
}
@Override
public Array createArrayOf(String typeName, Object[] elements) throws SQLException {
return null;
}
@Override
public Struct createStruct(String typeName, Object[] attributes) throws SQLException {
return null;
}
@Override
public void setSchema(String schema) throws SQLException {
}
@Override
public String getSchema() throws SQLException {
return null;
}
@Override
public void abort(Executor executor) throws SQLException {
}
@Override
public void setNetworkTimeout(Executor executor, int milliseconds) throws SQLException {
}
@Override
public int getNetworkTimeout() throws SQLException {
return 0;
}
@Override
public <T> T unwrap(Class<T> iface) throws SQLException {
return null;
}
@Override
public boolean isWrapperFor(Class<?> iface) throws SQLException {
return false;
}
}
|
3e12e4ae54bbd7698c00ae735168899d502ca258 | 5,615 | java | Java | handler/src/main/java/io/netty/handler/stream/ChunkedFile.java | NicoK/netty | d07d7e2b9a3795139e0b6f64e55f8ed700f8ff5c | [
"Apache-2.0"
] | 12 | 2015-12-24T02:01:44.000Z | 2020-07-28T08:34:05.000Z | handler/src/main/java/io/netty/handler/stream/ChunkedFile.java | NicoK/netty | d07d7e2b9a3795139e0b6f64e55f8ed700f8ff5c | [
"Apache-2.0"
] | 6 | 2021-12-28T03:25:29.000Z | 2022-01-08T02:09:42.000Z | handler/src/main/java/io/netty/handler/stream/ChunkedFile.java | NicoK/netty | d07d7e2b9a3795139e0b6f64e55f8ed700f8ff5c | [
"Apache-2.0"
] | 8 | 2018-05-20T00:07:13.000Z | 2019-02-22T13:29:40.000Z | 30.851648 | 107 | 0.62618 | 7,974 | /*
* Copyright 2012 The Netty Project
*
* The Netty Project licenses this file to you under the Apache License,
* version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package io.netty.handler.stream;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufAllocator;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.FileRegion;
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
/**
* A {@link ChunkedInput} that fetches data from a file chunk by chunk.
* <p>
* If your operating system supports
* <a href="http://en.wikipedia.org/wiki/Zero-copy">zero-copy file transfer</a>
* such as {@code sendfile()}, you might want to use {@link FileRegion} instead.
*/
public class ChunkedFile implements ChunkedInput<ByteBuf> {
private final RandomAccessFile file;
private final long startOffset;
private final long endOffset;
private final int chunkSize;
private long offset;
/**
* Creates a new instance that fetches data from the specified file.
*/
public ChunkedFile(File file) throws IOException {
this(file, ChunkedStream.DEFAULT_CHUNK_SIZE);
}
/**
* Creates a new instance that fetches data from the specified file.
*
* @param chunkSize the number of bytes to fetch on each
* {@link #readChunk(ChannelHandlerContext)} call
*/
public ChunkedFile(File file, int chunkSize) throws IOException {
this(new RandomAccessFile(file, "r"), chunkSize);
}
/**
* Creates a new instance that fetches data from the specified file.
*/
public ChunkedFile(RandomAccessFile file) throws IOException {
this(file, ChunkedStream.DEFAULT_CHUNK_SIZE);
}
/**
* Creates a new instance that fetches data from the specified file.
*
* @param chunkSize the number of bytes to fetch on each
* {@link #readChunk(ChannelHandlerContext)} call
*/
public ChunkedFile(RandomAccessFile file, int chunkSize) throws IOException {
this(file, 0, file.length(), chunkSize);
}
/**
* Creates a new instance that fetches data from the specified file.
*
* @param offset the offset of the file where the transfer begins
* @param length the number of bytes to transfer
* @param chunkSize the number of bytes to fetch on each
* {@link #readChunk(ChannelHandlerContext)} call
*/
public ChunkedFile(RandomAccessFile file, long offset, long length, int chunkSize) throws IOException {
if (file == null) {
throw new NullPointerException("file");
}
if (offset < 0) {
throw new IllegalArgumentException(
"offset: " + offset + " (expected: 0 or greater)");
}
if (length < 0) {
throw new IllegalArgumentException(
"length: " + length + " (expected: 0 or greater)");
}
if (chunkSize <= 0) {
throw new IllegalArgumentException(
"chunkSize: " + chunkSize +
" (expected: a positive integer)");
}
this.file = file;
this.offset = startOffset = offset;
endOffset = offset + length;
this.chunkSize = chunkSize;
file.seek(offset);
}
/**
* Returns the offset in the file where the transfer began.
*/
public long startOffset() {
return startOffset;
}
/**
* Returns the offset in the file where the transfer will end.
*/
public long endOffset() {
return endOffset;
}
/**
* Returns the offset in the file where the transfer is happening currently.
*/
public long currentOffset() {
return offset;
}
@Override
public boolean isEndOfInput() throws Exception {
return !(offset < endOffset && file.getChannel().isOpen());
}
@Override
public void close() throws Exception {
file.close();
}
@Deprecated
@Override
public ByteBuf readChunk(ChannelHandlerContext ctx) throws Exception {
return readChunk(ctx.alloc());
}
@Override
public ByteBuf readChunk(ByteBufAllocator allocator) throws Exception {
long offset = this.offset;
if (offset >= endOffset) {
return null;
}
int chunkSize = (int) Math.min(this.chunkSize, endOffset - offset);
// Check if the buffer is backed by an byte array. If so we can optimize it a bit an safe a copy
ByteBuf buf = allocator.heapBuffer(chunkSize);
boolean release = true;
try {
file.readFully(buf.array(), buf.arrayOffset(), chunkSize);
buf.writerIndex(chunkSize);
this.offset = offset + chunkSize;
release = false;
return buf;
} finally {
if (release) {
buf.release();
}
}
}
@Override
public long length() {
return endOffset - startOffset;
}
@Override
public long progress() {
return offset - startOffset;
}
}
|
3e12e638a01ef0d0e0ccab3e277bddd884b93e55 | 6,397 | java | Java | src/main/java/com/github/ayltai/hknews/parser/TheStandardParser.java | ayltai/hknews-backend | d269775877183c523d0d9aee7e6d4d4870b3d422 | [
"Apache-2.0"
] | 3 | 2020-03-03T09:27:00.000Z | 2020-12-25T06:18:57.000Z | src/main/java/com/github/ayltai/hknews/parser/TheStandardParser.java | ayltai/hknews-backend | d269775877183c523d0d9aee7e6d4d4870b3d422 | [
"Apache-2.0"
] | 101 | 2019-07-10T06:51:22.000Z | 2020-08-13T21:17:09.000Z | src/main/java/com/github/ayltai/hknews/parser/TheStandardParser.java | ayltai/hknews-backend | d269775877183c523d0d9aee7e6d4d4870b3d422 | [
"Apache-2.0"
] | null | null | null | 44.117241 | 217 | 0.660622 | 7,975 | package com.github.ayltai.hknews.parser;
import java.io.IOException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Locale;
import java.util.Objects;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.lang.NonNull;
import com.github.ayltai.hknews.data.model.Category;
import com.github.ayltai.hknews.data.model.Image;
import com.github.ayltai.hknews.data.model.Item;
import com.github.ayltai.hknews.data.model.Source;
import com.github.ayltai.hknews.data.repository.SourceRepository;
import com.github.ayltai.hknews.net.ApiServiceFactory;
import lombok.Getter;
public final class TheStandardParser extends Parser {
private static final Logger LOGGER = LoggerFactory.getLogger(TheStandardParser.class);
//region Constants
private static final String BASE_URL = "http://www.thestandard.com.hk/";
private static final String CLOSE_QUOTE = "\"";
private static final String OPEN_HREF = "<a href=\"";
private static final String OPEN_PARAGRAPH = "<p>";
private static final String CLOSE_PARAGRAPH = "</p>";
private static final String FORMAT_LONG = "dd MMM yyyy h:mm a";
private static final String FORMAT_SHORT = "dd MMM yyyy";
private static final ThreadLocal<DateFormat> DATE_FORMAT_LONG = ThreadLocal.withInitial(() -> new SimpleDateFormat(TheStandardParser.FORMAT_LONG, Locale.ENGLISH));
private static final ThreadLocal<DateFormat> DATE_FORMAT_SHORT = ThreadLocal.withInitial(() -> new SimpleDateFormat(TheStandardParser.FORMAT_SHORT, Locale.ENGLISH));
//endregion
@Getter
private final Source source;
TheStandardParser(@NonNull @lombok.NonNull final ApiServiceFactory apiServiceFactory, @NonNull @lombok.NonNull final SourceRepository sourceRepository) {
super(apiServiceFactory, sourceRepository);
this.source = sourceRepository.findByName(ParserFactory.SOURCE_THE_STANDARD);
}
@NonNull
@Override
public Collection<Item> getItems(@NonNull @lombok.NonNull final Category category) {
if (category.getUrls().isEmpty()) return Collections.emptyList();
final List<String[]> htmls = new ArrayList<>();
for (final String url : category.getUrls()) {
final String[] tokens = url.split(Pattern.quote("?"));
try {
final String[] html = StringUtils.substringsBetween(this.apiServiceFactory.create().postHtml(tokens[0], Integer.parseInt(tokens[1].split("=")[1]), 1).execute().body(), "<li class='caption'>", "</li>");
if (html == null || html.length == 0) continue;
htmls.add(html);
} catch (final IOException e) {
TheStandardParser.LOGGER.error(e.getMessage(), e);
}
}
if (htmls.isEmpty()) return Collections.emptyList();
return htmls.stream()
.map(Arrays::asList)
.flatMap(Collection::stream)
.collect(Collectors.toList())
.stream()
.map(section -> {
final String url = StringUtils.substringBetween(section, TheStandardParser.OPEN_HREF, TheStandardParser.CLOSE_QUOTE);
if (url == null) return null;
final String date = StringUtils.substringBetween(section, "<span>", "</span>");
if (date == null) return null;
try {
final Item item = new Item();
item.setTitle(StringUtils.substringBetween(StringUtils.substringBetween(section, "<h1>", "</h1>"), "\">", "</a>"));
item.setDescription(StringUtils.substringBetween(section, TheStandardParser.OPEN_PARAGRAPH, TheStandardParser.CLOSE_PARAGRAPH));
item.setUrl(TheStandardParser.BASE_URL + url);
item.setPublishDate(Parser.toSafeDate((date.length() > TheStandardParser.FORMAT_SHORT.length() ? TheStandardParser.DATE_FORMAT_LONG : TheStandardParser.DATE_FORMAT_SHORT).get().parse(date)));
item.setSource(this.getSource());
item.setCategory(category);
return item;
} catch (final ParseException e) {
TheStandardParser.LOGGER.warn(e.getMessage(), e);
}
return null;
})
.filter(Objects::nonNull)
.collect(Collectors.toCollection(ArrayList::new));
}
@NonNull
@Override
public Item getItem(@NonNull @lombok.NonNull final Item item) throws IOException {
if (item.getUrl() == null) throw new IllegalArgumentException("Item URL cannot be null");
final String html = StringUtils.substringBetween(this.apiServiceFactory.create().getHtml(item.getUrl()).execute().body(), "<div class=\"content\">", "<div class=\"related\">");
if (html != null) {
final String[] descriptions = StringUtils.substringsBetween(html, TheStandardParser.OPEN_PARAGRAPH, TheStandardParser.CLOSE_PARAGRAPH);
if (descriptions != null) item.setDescription(Stream.of(descriptions)
.reduce("", (description, content) -> description + content.trim() + "<br><br>"));
final String[] imageContainers = StringUtils.substringsBetween(html, "<figure>", "</figure>");
if (imageContainers != null) item.getImages().addAll(Stream.of(imageContainers)
.map(imageContainer -> {
final String imageUrl = StringUtils.substringBetween(imageContainer, TheStandardParser.OPEN_HREF, TheStandardParser.CLOSE_QUOTE);
if (imageUrl == null) return null;
return new Image(imageUrl, StringUtils.substringBetween(imageContainer, "<i>", "</i>"));
})
.filter(Objects::nonNull)
.collect(Collectors.toCollection(ArrayList::new)));
}
return item;
}
@Override
public void close() {
TheStandardParser.DATE_FORMAT_LONG.remove();
TheStandardParser.DATE_FORMAT_SHORT.remove();
}
}
|
3e12e73e493cc30b50e78713c2c9623ef8d80d66 | 1,174 | java | Java | spring-thunder/src/main/java/club/zhcs/thunder/listener/NutzContenxtInitListener.java | lihongwu19921215/spring-thunder | 48e7b906e5cdc956d72f52f5396a86fe690c2abe | [
"Apache-2.0"
] | null | null | null | spring-thunder/src/main/java/club/zhcs/thunder/listener/NutzContenxtInitListener.java | lihongwu19921215/spring-thunder | 48e7b906e5cdc956d72f52f5396a86fe690c2abe | [
"Apache-2.0"
] | null | null | null | spring-thunder/src/main/java/club/zhcs/thunder/listener/NutzContenxtInitListener.java | lihongwu19921215/spring-thunder | 48e7b906e5cdc956d72f52f5396a86fe690c2abe | [
"Apache-2.0"
] | null | null | null | 22.596154 | 102 | 0.742128 | 7,976 | package club.zhcs.thunder.listener;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import org.apache.log4j.PropertyConfigurator;
import org.nutz.ioc.impl.PropertiesProxy;
import org.nutz.lang.Files;
import org.nutz.resource.Scans;
/**
*
* @author admin
*
* @email upchh@example.com
*
*/
public class NutzContenxtInitListener implements ServletContextListener {
/*
* (non-Javadoc)
*
* @see
* javax.servlet.ServletContextListener#contextInitialized(javax.servlet.
* ServletContextEvent)
*/
@Override
public void contextInitialized(ServletContextEvent event) {
Scans.me().init(event.getServletContext());// 初始化nutz的Scans
String logConfigPath = "/var/config/log4j.properties"; // 线上日志配置路径
try {
if (Files.checkFile(logConfigPath) != null) {// 找到了线上配置
PropertyConfigurator.configure(new PropertiesProxy(logConfigPath).toProperties());// 那么加载线上的配置吧!!!
}
} catch (Exception e) {
}
}
/*
* (non-Javadoc)
*
* @see javax.servlet.ServletContextListener#contextDestroyed(javax.servlet.
* ServletContextEvent)
*/
@Override
public void contextDestroyed(ServletContextEvent sce) {
}
}
|
3e12e7581021391c7a69096a6b1e64e634f89290 | 1,265 | java | Java | src/Practice/RearrangePositiveAndNegativeNumbers.java | manxist256/MovingBit | 793ac93b647a888dccbd86891244ff79f0f5451e | [
"Apache-2.0"
] | 1 | 2018-12-05T12:44:13.000Z | 2018-12-05T12:44:13.000Z | src/Practice/RearrangePositiveAndNegativeNumbers.java | manxist256/MovingBit | 793ac93b647a888dccbd86891244ff79f0f5451e | [
"Apache-2.0"
] | null | null | null | src/Practice/RearrangePositiveAndNegativeNumbers.java | manxist256/MovingBit | 793ac93b647a888dccbd86891244ff79f0f5451e | [
"Apache-2.0"
] | null | null | null | 26.914894 | 79 | 0.473518 | 7,977 | /*
* 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 Practice;
import java.util.Scanner;
import java.util.Stack;
/**
*
* @author mankank
*/
public class RearrangePositiveAndNegativeNumbers {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int N = sc.nextInt();
int[] arr = new int[N];
Stack<Integer> neg = new Stack();
Stack<Integer> pos = new Stack();
for (int i = 0; i < N; i++) {
arr[i] = sc.nextInt();
if (arr[i] < 0) neg.add(arr[i]);
else pos.add(arr[i]);
}
int flag = 0, k = 0;
while (!pos.isEmpty() && !neg.isEmpty()) {
if (flag == 0) {
arr[k++] = pos.pop();
} else {
arr[k++] = neg.pop();
}
flag = flag == 0 ? 1 : 0;
}
while (!pos.isEmpty()) {
arr[k++] = pos.pop();
}
while (!neg.isEmpty()) {
arr[k++] = neg.pop();
}
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
}
}
|
3e12e76299a8f7e22f319526a6b499e2f9c4be9b | 10,055 | java | Java | plugins/actions/columnsexist/src/main/java/org/apache/hop/workflow/actions/columnsexist/ActionColumnsExist.java | henrikjan/incubator-hop | c4d05201ed61585a04678f383c80352a1423b370 | [
"Apache-2.0"
] | null | null | null | plugins/actions/columnsexist/src/main/java/org/apache/hop/workflow/actions/columnsexist/ActionColumnsExist.java | henrikjan/incubator-hop | c4d05201ed61585a04678f383c80352a1423b370 | [
"Apache-2.0"
] | null | null | null | plugins/actions/columnsexist/src/main/java/org/apache/hop/workflow/actions/columnsexist/ActionColumnsExist.java | henrikjan/incubator-hop | c4d05201ed61585a04678f383c80352a1423b370 | [
"Apache-2.0"
] | null | null | null | 34.20068 | 152 | 0.66007 | 7,978 | /*! ******************************************************************************
*
* Hop : The Hop Orchestration Platform
*
* Copyright (C) 2002-2018 by Hitachi Vantara : http://www.pentaho.com
* http://www.project-hop.org
*
*******************************************************************************
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
******************************************************************************/
package org.apache.hop.workflow.actions.columnsexist;
import org.apache.hop.core.ICheckResult;
import org.apache.hop.core.Const;
import org.apache.hop.core.Result;
import org.apache.hop.core.annotations.Action;
import org.apache.hop.core.database.Database;
import org.apache.hop.core.database.DatabaseMeta;
import org.apache.hop.core.exception.HopDatabaseException;
import org.apache.hop.core.exception.HopException;
import org.apache.hop.core.exception.HopXmlException;
import org.apache.hop.core.util.Utils;
import org.apache.hop.core.variables.IVariables;
import org.apache.hop.core.xml.XmlHandler;
import org.apache.hop.i18n.BaseMessages;
import org.apache.hop.workflow.WorkflowMeta;
import org.apache.hop.workflow.action.IAction;
import org.apache.hop.workflow.action.ActionBase;
import org.apache.hop.workflow.action.validator.ActionValidatorUtils;
import org.apache.hop.workflow.action.validator.AndValidator;
import org.apache.hop.metadata.api.IHopMetadataProvider;
import org.apache.hop.resource.ResourceEntry;
import org.apache.hop.resource.ResourceEntry.ResourceType;
import org.apache.hop.resource.ResourceReference;
import org.w3c.dom.Node;
import java.util.List;
/**
* This defines a column exists action.
*
* @author Samatar
* @since 16-06-2008
*/
@Action(
id = "COLUMNS_EXIST",
i18nPackageName = "org.apache.hop.workflow.actions.columnsexist",
name = "ActionColumnsExist.Name",
description = "ActionColumnsExist.Description",
image = "ColumnsExist.svg",
categoryDescription = "i18n:org.apache.hop.workflow:ActionCategory.Category.Conditions",
documentationUrl = "https://hop.apache.org/manual/latest/plugins/actions/columnsexist.html"
)
public class ActionColumnsExist extends ActionBase implements Cloneable, IAction {
private static final Class<?> PKG = ActionColumnsExist.class; // Needed by Translator
private String schemaname;
private String tableName;
private DatabaseMeta connection;
private String[] arguments;
public ActionColumnsExist( String n ) {
super( n, "" );
schemaname = null;
tableName = null;
connection = null;
}
public ActionColumnsExist() {
this( "" );
}
public void allocate( int nrFields ) {
arguments = new String[ nrFields ];
}
public Object clone() {
ActionColumnsExist je = (ActionColumnsExist) super.clone();
if ( arguments != null ) {
int nrFields = arguments.length;
je.allocate( nrFields );
System.arraycopy( arguments, 0, je.arguments, 0, nrFields );
}
return je;
}
@Override
public String getXml() {
StringBuilder retval = new StringBuilder( 200 );
retval.append( super.getXml() );
retval.append( " " ).append( XmlHandler.addTagValue( "tablename", tableName ) );
retval.append( " " ).append( XmlHandler.addTagValue( "schemaname", schemaname ) );
retval.append( " " ).append(
XmlHandler.addTagValue( "connection", connection == null ? null : connection.getName() ) );
retval.append( " <fields>" ).append( Const.CR );
if ( arguments != null ) {
for ( int i = 0; i < arguments.length; i++ ) {
retval.append( " <field>" ).append( Const.CR );
retval.append( " " ).append( XmlHandler.addTagValue( "name", arguments[ i ] ) );
retval.append( " </field>" ).append( Const.CR );
}
}
retval.append( " </fields>" ).append( Const.CR );
return retval.toString();
}
public void loadXml( Node entrynode, IHopMetadataProvider metadataProvider ) throws HopXmlException {
try {
super.loadXml( entrynode );
tableName = XmlHandler.getTagValue( entrynode, "tablename" );
schemaname = XmlHandler.getTagValue( entrynode, "schemaname" );
String dbname = XmlHandler.getTagValue( entrynode, "connection" );
connection = DatabaseMeta.loadDatabase( metadataProvider, dbname );
Node fields = XmlHandler.getSubNode( entrynode, "fields" );
// How many field arguments?
int nrFields = XmlHandler.countNodes( fields, "field" );
allocate( nrFields );
// Read them all...
for ( int i = 0; i < nrFields; i++ ) {
Node fnode = XmlHandler.getSubNodeByNr( fields, "field", i );
arguments[ i ] = XmlHandler.getTagValue( fnode, "name" );
}
} catch ( HopException e ) {
throw new HopXmlException( BaseMessages.getString( PKG, "ActionColumnsExist.Meta.UnableLoadXml" ), e );
}
}
public void setTablename( String tableName ) {
this.tableName = tableName;
}
public String getTablename() {
return tableName;
}
public void setSchemaname( String schemaname ) {
this.schemaname = schemaname;
}
public String getSchemaname() {
return schemaname;
}
public String[] getArguments() {
return arguments;
}
public void setArguments( String[] arguments ) {
this.arguments = arguments;
}
public void setDatabase( DatabaseMeta database ) {
this.connection = database;
}
public DatabaseMeta getDatabase() {
return connection;
}
@Override
public boolean evaluates() {
return true;
}
@Override
public boolean isUnconditional() {
return false;
}
@Override
public Result execute( Result previousResult, int nr ) {
Result result = previousResult;
result.setResult( false );
result.setNrErrors( 1 );
int nrexistcolums = 0;
int nrnotexistcolums = 0;
if ( Utils.isEmpty( tableName ) ) {
logError( BaseMessages.getString( PKG, "ActionColumnsExist.Error.TablenameEmpty" ) );
return result;
}
if ( arguments == null ) {
logError( BaseMessages.getString( PKG, "ActionColumnsExist.Error.ColumnameEmpty" ) );
return result;
}
if ( connection != null ) {
Database db = getNewDatabaseFromMeta();
db.shareVariablesWith( this );
try {
String realSchemaname = environmentSubstitute( schemaname );
String realTablename = environmentSubstitute( tableName );
db.connect();
if ( db.checkTableExists( realSchemaname, realTablename ) ) {
if ( log.isDetailed() ) {
logDetailed( BaseMessages.getString( PKG, "ActionColumnsExist.Log.TableExists", realTablename ) );
}
for ( int i = 0; i < arguments.length && !parentWorkflow.isStopped(); i++ ) {
String realColumnname = environmentSubstitute( arguments[ i ] );
if ( db.checkColumnExists( realSchemaname, realTablename, realColumnname ) ) {
if ( log.isDetailed() ) {
logDetailed( BaseMessages.getString(
PKG, "ActionColumnsExist.Log.ColumnExists", realColumnname, realTablename ) );
}
nrexistcolums++;
} else {
logError( BaseMessages.getString(
PKG, "ActionColumnsExist.Log.ColumnNotExists", realColumnname, realTablename ) );
nrnotexistcolums++;
}
}
} else {
logError( BaseMessages.getString( PKG, "ActionColumnsExist.Log.TableNotExists", realTablename ) );
}
} catch ( HopDatabaseException dbe ) {
logError( BaseMessages.getString( PKG, "ActionColumnsExist.Error.UnexpectedError", dbe.getMessage() ) );
} finally {
if ( db != null ) {
try {
db.disconnect();
} catch ( Exception e ) { /* Ignore */
}
}
}
} else {
logError( BaseMessages.getString( PKG, "ActionColumnsExist.Error.NoDbConnection" ) );
}
result.setEntryNr( nrnotexistcolums );
result.setNrLinesWritten( nrexistcolums );
// result is true only if all columns found (PDI-15801)
if ( nrexistcolums == arguments.length ) {
result.setNrErrors( 0 );
result.setResult( true );
}
return result;
}
Database getNewDatabaseFromMeta() {
return new Database( this, connection );
}
@Override
public DatabaseMeta[] getUsedDatabaseConnections() {
return new DatabaseMeta[] { connection, };
}
@Override
public List<ResourceReference> getResourceDependencies( WorkflowMeta workflowMeta ) {
List<ResourceReference> references = super.getResourceDependencies( workflowMeta );
if ( connection != null ) {
ResourceReference reference = new ResourceReference( this );
reference.getEntries().add( new ResourceEntry( connection.getHostname(), ResourceType.SERVER ) );
reference.getEntries().add( new ResourceEntry( connection.getDatabaseName(), ResourceType.DATABASENAME ) );
references.add( reference );
}
return references;
}
@Override
public void check( List<ICheckResult> remarks, WorkflowMeta workflowMeta, IVariables variables,
IHopMetadataProvider metadataProvider ) {
ActionValidatorUtils.andValidator().validate( this, "tablename", remarks, AndValidator.putValidators( ActionValidatorUtils.notBlankValidator() ) );
ActionValidatorUtils.andValidator().validate( this, "columnname", remarks, AndValidator.putValidators( ActionValidatorUtils.notBlankValidator() ) );
}
}
|
3e12e7bcbfcdec8d35d5968a3caf22e620d8b6d2 | 679 | java | Java | slime-core/src/main/java/com/github/nekolr/slime/domain/SpiderTask.java | pcncad/slime | dd20082af589a027641a8287fb0047ddf6a8c0f5 | [
"MIT"
] | 33 | 2021-05-12T01:13:50.000Z | 2022-03-23T05:56:50.000Z | slime-core/src/main/java/com/github/nekolr/slime/domain/SpiderTask.java | pcncad/slime | dd20082af589a027641a8287fb0047ddf6a8c0f5 | [
"MIT"
] | 7 | 2021-05-19T06:33:19.000Z | 2022-03-03T03:08:20.000Z | slime-core/src/main/java/com/github/nekolr/slime/domain/SpiderTask.java | pcncad/slime | dd20082af589a027641a8287fb0047ddf6a8c0f5 | [
"MIT"
] | 14 | 2021-07-11T00:02:07.000Z | 2021-12-31T08:17:40.000Z | 14.446809 | 55 | 0.600884 | 7,979 | package com.github.nekolr.slime.domain;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import javax.persistence.*;
import java.util.Date;
/**
* 爬虫任务实体类
*/
@Table(name = "slime_sp_task")
@Entity
@Getter
@Setter
@ToString
public class SpiderTask {
/**
* ID
*/
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(updatable = false)
private Long id;
/**
* 流程 ID
*/
@Column(name = "flow_id")
private Long flowId;
/**
* 开始时间
*/
@Column(name = "begin_time")
private Date beginTime;
/**
* 结束时间
*/
@Column(name = "end_time")
private Date endTime;
}
|
3e12e8aa7f8bd3c127705caebc18db7407f52169 | 2,896 | java | Java | src/test/java/net/ripe/rpki/ui/admin/TrustAnchorRequestResourceTest.java | RIPE-NCC/rpki-core | cf6293bd0481e7f926c11a1237ee92e3dc3c1ea5 | [
"BSD-3-Clause"
] | 6 | 2022-02-09T09:59:08.000Z | 2022-02-16T19:17:39.000Z | src/test/java/net/ripe/rpki/ui/admin/TrustAnchorRequestResourceTest.java | RIPE-NCC/rpki-core | cf6293bd0481e7f926c11a1237ee92e3dc3c1ea5 | [
"BSD-3-Clause"
] | null | null | null | src/test/java/net/ripe/rpki/ui/admin/TrustAnchorRequestResourceTest.java | RIPE-NCC/rpki-core | cf6293bd0481e7f926c11a1237ee92e3dc3c1ea5 | [
"BSD-3-Clause"
] | 1 | 2022-02-09T16:03:28.000Z | 2022-02-09T16:03:28.000Z | 43.223881 | 453 | 0.734116 | 7,980 | package net.ripe.rpki.ui.admin;
import net.ripe.rpki.commons.ta.domain.request.TrustAnchorRequest;
import net.ripe.rpki.commons.ta.serializers.TrustAnchorRequestSerializer;
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.wicket.util.resource.IResourceStreamWriter;
import org.junit.Before;
import org.junit.Test;
import java.io.ByteArrayOutputStream;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
public class TrustAnchorRequestResourceTest {
private TrustAnchorRequestResource subject;
private TrustAnchorRequest request;
private TrustAnchorRequestSerializer serializer;
@Before
public void setUp() {
serializer = new TrustAnchorRequestSerializer();
request = serializer.deserialize(xml);
subject = new TrustAnchorRequestResource(request);
}
@Test
public void shouldHaveXmlMimeType() {
assertEquals("application/xml", subject.getResourceStream().getContentType());
}
@Test
public void shouldHaveFileNameWithXmlExtension() {
assertTrue(subject.getFileName().endsWith(".xml"));
}
@Test
public void shouldDeserializeTheResourceBackToRequest() throws Exception {
IResourceStreamWriter sr = (IResourceStreamWriter) subject.getResourceStream();
ByteArrayOutputStream output = new ByteArrayOutputStream();
sr.write(output);
TrustAnchorRequest result = serializer.deserialize(output.toString("UTF-8"));
// Deserialized request must be identical to the original request. Due to
// lack of a proper equals implementation on TrustAnchorRequest, make
// a comparison based on reflection
assertTrue(EqualsBuilder.reflectionEquals(request, result));
}
private final String xml = "<requests.TrustAnchorRequest>\n" +
" <creationTimestamp>1610359575105</creationTimestamp>\n" +
" <taCertificatePublicationUri>rsync://localhost:10873/ta/</taCertificatePublicationUri>\n" +
" <taRequests>\n" +
" <requests.RevocationRequest>\n" +
" <requestId>3ced3f70-a2b4-42d4-9e46-2fe4cac6b4bf</requestId>\n" +
" <resourceClassName>DEFAULT</resourceClassName>\n" +
" <encodedPublicKey>MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAtZC7nbyxIqHdncRCXV6wBtBfXtMjuz0TQLd20Hunnr/982wFMqRfsBqEI4+Q/KnPV+N1rsKGhTrAzOCnISDFO5d111qOrWWd/X0T3AjoBLu2yFwtsc+2PYXxM7aAwPl1YfBsmvDjc+BlZEmPgIVLTbkYW2dXaOKVWi5CHpcbHuzox3stStSF9C2CT49N7URwL5qQ7f55BA4kQ1U1grnQR9nbFWT0HjiVIeZow+9ofRD6Io/T6+sMS2LWb3E+YMK6DCdStlYwmZEu+2HpqBjRqB7/3nfO74djpnUXLMzSFIv4x95ZFAeV0GTvLbflfTRd9G9Wa5CF5hd9zrj5OMNwAwIDAQAB</encodedPublicKey>\n" +
" </requests.RevocationRequest>\n" +
" </taRequests>\n" +
" <siaDescriptors/>\n" +
"</requests.TrustAnchorRequest>";
}
|
3e12e8b946b7ea369190eb9e109e0e3d4af41f38 | 847 | java | Java | web/src/main/java/gov/nih/nci/ctd2/dashboard/util/cnkb/CellularNetWorkElementInformation.java | floratos-lab/hipc-signature | 503e00a18773ad582e4f021d2d9afa161f7c339b | [
"BSD-3-Clause"
] | null | null | null | web/src/main/java/gov/nih/nci/ctd2/dashboard/util/cnkb/CellularNetWorkElementInformation.java | floratos-lab/hipc-signature | 503e00a18773ad582e4f021d2d9afa161f7c339b | [
"BSD-3-Clause"
] | 77 | 2019-04-08T00:41:34.000Z | 2022-02-04T21:41:41.000Z | web/src/main/java/gov/nih/nci/ctd2/dashboard/util/cnkb/CellularNetWorkElementInformation.java | floratos-lab/hipc-signature | 503e00a18773ad582e4f021d2d9afa161f7c339b | [
"BSD-3-Clause"
] | null | null | null | 21.175 | 70 | 0.72255 | 7,981 | package gov.nih.nci.ctd2.dashboard.util.cnkb;
import java.util.ArrayList;
import java.util.List;
public class CellularNetWorkElementInformation {
private String geneName = null;
private List<Integer> interactionNumlist = new ArrayList<Integer>();
public CellularNetWorkElementInformation(String geneName)
{ this.geneName = geneName;
}
public String getGeneName() {
return this.geneName;
}
public void setGeneName(String geneName) {
this.geneName = geneName;
}
public List<Integer> getInteractionNumlist() {
return this.interactionNumlist;
}
public void setInteractionNumlist(
List<Integer> interactionNumlist) {
this.interactionNumlist = interactionNumlist;
}
public boolean addInteractionNum(int number) {
return getInteractionNumlist().add(number);
}
}
|
3e12e931495923dd51ddbf8e304af38a5cdc3bf4 | 322 | java | Java | src/main/java/com/incloud/hcp/jco/dominios/dto/DominiosImports.java | CPAREDES27/TASA_BACKEND_QAS | 03353e7bc53624a3ae5dbc900c0e6f2d499d654f | [
"Apache-2.0"
] | null | null | null | src/main/java/com/incloud/hcp/jco/dominios/dto/DominiosImports.java | CPAREDES27/TASA_BACKEND_QAS | 03353e7bc53624a3ae5dbc900c0e6f2d499d654f | [
"Apache-2.0"
] | null | null | null | src/main/java/com/incloud/hcp/jco/dominios/dto/DominiosImports.java | CPAREDES27/TASA_BACKEND_QAS | 03353e7bc53624a3ae5dbc900c0e6f2d499d654f | [
"Apache-2.0"
] | null | null | null | 20.125 | 59 | 0.695652 | 7,982 | package com.incloud.hcp.jco.dominios.dto;
import java.util.List;
public class DominiosImports {
private List<DominioParams> dominios;
public List<DominioParams> getDominios() {
return dominios;
}
public void setDominios(List<DominioParams> dominios) {
this.dominios = dominios;
}
}
|
3e12e9a95d445afc1371417deea36a43a4365480 | 7,265 | java | Java | java-workers/src/main/java/com/ryanquey/podcast/dataClasses/podcast/PodcastByLanguageRecord.java | RyanQuey/java-podcast-processor | c8a9223b987b0cdc0e5dc0e98be61e646a2090d2 | [
"Unlicense"
] | 3 | 2021-04-12T02:23:23.000Z | 2021-12-07T15:15:28.000Z | java-workers/src/main/java/com/ryanquey/podcast/dataClasses/podcast/PodcastByLanguageRecord.java | RyanQuey/java-podcast-processor | c8a9223b987b0cdc0e5dc0e98be61e646a2090d2 | [
"Unlicense"
] | null | null | null | java-workers/src/main/java/com/ryanquey/podcast/dataClasses/podcast/PodcastByLanguageRecord.java | RyanQuey/java-podcast-processor | c8a9223b987b0cdc0e5dc0e98be61e646a2090d2 | [
"Unlicense"
] | null | null | null | 45.40625 | 254 | 0.713971 | 7,983 | package com.ryanquey.podcast.dataClasses.podcast;
// import com.datastax.oss.driver.api.core.cql.ResultSet;
// import com.datastax.oss.driver.api.core.cql.Row;
import com.datastax.oss.driver.api.querybuilder.term.Term;
// DSE Mapper
import com.datastax.oss.driver.api.mapper.annotations.Entity;
import com.datastax.oss.driver.api.mapper.annotations.CqlName;
import com.datastax.oss.driver.api.mapper.annotations.PartitionKey;
import com.datastax.oss.driver.api.mapper.annotations.ClusteringColumn;
import com.datastax.oss.driver.api.core.cql.BoundStatement;
import static com.datastax.oss.driver.api.querybuilder.QueryBuilder.*;
import com.ryanquey.podcast.cassandraHelpers.CassandraDb;
import com.ryanquey.podcast.dataClasses.searchQuery.SearchQueryUDT;
import com.ryanquey.podcast.helpers.DataClassesHelpers;
/*
* For one file, gets all search results and retrieves the rss feed data
*
*/
@Entity
@CqlName("podcasts_by_language")
public class PodcastByLanguageRecord extends PodcastBase {
@PartitionKey
private String language;
@ClusteringColumn(0)
private String primaryGenre;
@ClusteringColumn(1)
private String feedUrl; // rss feed url
/////////////////////////////////////////////////
// Static methods
// NOTE never set this as a static var, in case it is set incorrectly. (5/29/20)
// Does not seem to throw a helpful error if a var, but if a static method, will give helpful feedback
static public PodcastByLanguageDao getDao () {
return CassandraDb.inventoryMapper.podcastByLanguageDao("podcasts_by_language");
}
/////////////////////////////////////////////////
// constructors
// for DSE DAO
public PodcastByLanguageRecord() {};
public PodcastByLanguageRecord(Podcast podcast) {
DataClassesHelpers.copyMatchingFields(podcast, this);
};
/////////////////////////////////
// helpers for interacting with DB
public PodcastByLanguageRecord findOne () throws Exception {
if (this.language == null || this.primaryGenre == null || this.feedUrl == null) {
throw new IllegalArgumentException("all Primary keys clustering columns are required to do a search");
}
PodcastByLanguageRecord data = PodcastByLanguageRecord.getDao().findOne(this.language, this.primaryGenre, this.feedUrl);
// refresh current record's fields
DataClassesHelpers.copyMatchingFields(data, this);
return this;
}
// saves record, not appending any to collection data types.
// We will only use for this class when we've already retrieved the found_by_queries and set them on the Podcast instance
public void saveNoAppend () throws Exception {
PodcastByLanguageRecord.getDao().save(this);
}
// This is messy and less than ideal.
// Most ideal would be if they allowed a quick option on the DAO from the mapper class; this is not YET in the java driver https://community.datastax.com/questions/4980/how-can-i-append-or-prepend-to-a-collection-using.html?childToView=5016#answer-5016
// Next ideal is probably what they recommend in the above link: using query provider class. But this seems complicated and I'm just trying to learn basics here still.
// Next ideal is probably using query builder and making a custom codec.
// attempt using bound statement from the DAO:
// this one returns a bound statement with nothing bound!
/*
public void save () throws Exception {
// this should be a fully executable CQL statement, but overwrites the found_by_queries list. We want to append
BoundStatement boundSaveStatement = PodcastByLanguageRecord.getDao().buildSaveQuery(this);
// remove what was there
String oldQuery = boundSaveStatement.getPreparedStatement().getQuery();
System.out.println("original:");
System.out.println(oldQuery);
boundSaveStatement.unset("found_by_queries");
// set what we want
String query = boundSaveStatement.getPreparedStatement().getQuery();
System.out.println("about to run this from the bound safe statement");
System.out.println(query);
CassandraDb.execute(query);
}
*/
// currently doing all this since I can't figure out how to append using the default DAO stuff wihtout using @Query... And this is easier than writing out @Query
public void saveAndAppendFoundBy () throws Exception {
System.out.println("0000000000000000000000000");
System.out.println("about to persist podcast");
// not working in Elassandra
// Term ts = CassandraDb.getTimestamp();
String ts = CassandraDb.getTimestampCQL();
// currently assuming there'll only be one on a given Podcast
// TODO allow if multiple
SearchQueryUDT foundBy = this.getFoundByQueries().iterator().next();
String foundByStr = foundBy.toCQLString();
// want to create or update if exists
String query = update("podcasts_by_language")
.setColumn("owner", literal(this.getOwner()))
.setColumn("primary_genre", literal(this.getPrimaryGenre()))
.setColumn("name", literal(this.getName()))
.setColumn("image_url30", literal(this.getImageUrl30()))
.setColumn("image_url60", literal(this.getImageUrl60()))
.setColumn("image_url100", literal(this.getImageUrl100()))
.setColumn("image_url600", literal(this.getImageUrl600()))
.setColumn("api", literal(this.getApi()))
.setColumn("api_id", literal(this.getApiId()))
.setColumn("api_url", literal(this.getApiUrl()))
.setColumn("country", literal(this.getCountry()))
//.setColumn("feed_url", literal(this.getGetFeedUrl()())) // don't set because updating, so can't set any in primary key
.setColumn("genres", literal(this.getGenres())) // hoping ArrayList converts to List here;
.setColumn("api_genre_ids", literal(this.getApiGenreIds()))
//.setColumn("primary_genre", literal(this.getPrimaryGenre())) // can't update primary key
.setColumn("release_date", literal(this.getReleaseDate()))
.setColumn("explicit", literal(this.isExplicit()))
.setColumn("episode_count", literal(this.getEpisodeCount()))
//.setColumn("rss_feed", literal(this.getRssFeedStr())) // don't save this for now, is really large and since I'm printing query, hard to debug
// one curly brace set for appending to a SET type, one for the UDT itself
.append("found_by_queries", raw("{ " + foundByStr + " }"))
.setColumn("description", literal(this.getDescription()))
.setColumn("summary", literal(this.getSummary()))
.setColumn("subtitle", literal(this.getSubtitle()))
.setColumn("webmaster", literal(this.getWebmaster()))
.setColumn("owner_email", literal(this.getOwnerEmail()))
.setColumn("author", literal(this.getAuthor()))
//.setColumn("language", literal(this.getLanguage()))
.setColumn("website_url", literal(this.getWebsiteUrl()))
// not working in Elassandra
//.setColumn("updated_at", ts)
.setColumn("updated_at", raw(ts))
// only update this unique record, so set by compound primary key
.whereColumn("language").isEqualTo(literal(this.getLanguage()))
.whereColumn("feed_url").isEqualTo(literal(this.getFeedUrl()))
.asCql();
System.out.println("now executing:");
System.out.println(query);
CassandraDb.execute(query);
}
};
|
3e12eb19c2fdfb18ccb6884aeb33b58c146d2ca0 | 3,754 | java | Java | ethereum/p2p/src/main/java/org/hyperledger/besu/ethereum/p2p/rlpx/connections/PeerConnection.java | bgravenorst/besu | 6c179ba596f36afc4f46321273d359c8632436b0 | [
"Apache-2.0"
] | 702 | 2019-09-05T12:44:20.000Z | 2022-03-31T11:13:15.000Z | ethereum/p2p/src/main/java/org/hyperledger/besu/ethereum/p2p/rlpx/connections/PeerConnection.java | bgravenorst/besu | 6c179ba596f36afc4f46321273d359c8632436b0 | [
"Apache-2.0"
] | 2,114 | 2019-09-16T02:31:28.000Z | 2022-03-31T18:07:06.000Z | ethereum/p2p/src/main/java/org/hyperledger/besu/ethereum/p2p/rlpx/connections/PeerConnection.java | bgravenorst/besu | 6c179ba596f36afc4f46321273d359c8632436b0 | [
"Apache-2.0"
] | 472 | 2019-09-16T01:44:28.000Z | 2022-03-30T08:27:15.000Z | 29.793651 | 118 | 0.723761 | 7,984 | /*
* Copyright ConsenSys AG.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*
* SPDX-License-Identifier: Apache-2.0
*/
package org.hyperledger.besu.ethereum.p2p.rlpx.connections;
import org.hyperledger.besu.ethereum.p2p.peers.Peer;
import org.hyperledger.besu.ethereum.p2p.rlpx.wire.Capability;
import org.hyperledger.besu.ethereum.p2p.rlpx.wire.MessageData;
import org.hyperledger.besu.ethereum.p2p.rlpx.wire.PeerInfo;
import org.hyperledger.besu.ethereum.p2p.rlpx.wire.messages.DisconnectMessage.DisconnectReason;
import org.hyperledger.besu.plugin.data.EnodeURL;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.util.Set;
/** A P2P connection to another node. */
public interface PeerConnection {
/**
* Send given data to the connected node.
*
* @param message Data to send
* @param capability Sub-protocol to use
* @throws PeerNotConnected On attempt to send to a disconnected peer
*/
void send(Capability capability, MessageData message) throws PeerNotConnected;
/**
* Agreed capabilities between us and the peer.
*
* @return a list of shared capabilities between this node and the connected peer
*/
Set<Capability> getAgreedCapabilities();
/**
* Returns the agreed capability corresponding to given protocol.
*
* @param protocol the name of the protocol
* @return the agreed capability corresponding to this protocol, returns null if no matching
* capability is supported
*/
default Capability capability(final String protocol) {
for (final Capability cap : getAgreedCapabilities()) {
if (cap.getName().equalsIgnoreCase(protocol)) {
return cap;
}
}
return null;
}
/**
* Sends a message to the peer for the given subprotocol
*
* @param protocol the subprotocol name
* @param message the message to send
* @throws PeerNotConnected if the peer has disconnected
*/
default void sendForProtocol(final String protocol, final MessageData message)
throws PeerNotConnected {
send(capability(protocol), message);
}
/**
* Data about the peer on the other side of this connection.
*
* @return A representation of the remote peer this node is connected to.
*/
Peer getPeer();
/**
* Returns the Peer's Description.
*
* @return Peer Description
*/
PeerInfo getPeerInfo();
/**
* Immediately terminate the connection without sending a disconnect message.
*
* @param reason the reason for disconnection
* @param peerInitiated <code>true</code> if and only if the remote peer requested disconnection
*/
void terminateConnection(DisconnectReason reason, boolean peerInitiated);
/**
* Disconnect from this Peer.
*
* @param reason Reason for disconnecting
*/
void disconnect(DisconnectReason reason);
/**
* Has this connection been disconnected.
*
* @return True if the peer is disconnected
*/
boolean isDisconnected();
InetSocketAddress getLocalAddress();
InetSocketAddress getRemoteAddress();
class PeerNotConnected extends IOException {
public PeerNotConnected(final String message) {
super(message);
}
}
default EnodeURL getRemoteEnode() {
return getPeer().getEnodeURL();
}
}
|
3e12ebf3e90c03f2a4faae96ab51c8de246104e7 | 2,044 | java | Java | app/src/main/java/com/oliver/bathurst/individualproject/GCMRelay.java | OliverBathurst/Individual-Project | e8a1ca455ba93a58293f31a49d14ef783a9b2dc8 | [
"BSD-3-Clause"
] | null | null | null | app/src/main/java/com/oliver/bathurst/individualproject/GCMRelay.java | OliverBathurst/Individual-Project | e8a1ca455ba93a58293f31a49d14ef783a9b2dc8 | [
"BSD-3-Clause"
] | null | null | null | app/src/main/java/com/oliver/bathurst/individualproject/GCMRelay.java | OliverBathurst/Individual-Project | e8a1ca455ba93a58293f31a49d14ef783a9b2dc8 | [
"BSD-3-Clause"
] | null | null | null | 33.16129 | 192 | 0.622082 | 7,985 | package com.oliver.bathurst.individualproject;
import android.os.AsyncTask;
import android.os.Looper;
import org.json.JSONObject;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
/**
* Created by Oliver on 02/12/2017.
* Written by Oliver Bathurst <envkt@example.com>
*/
class GCMRelay extends AsyncTask<String[],Void,Void>{
@Override
protected Void doInBackground(String[]... strings) {
Looper.prepare();
try {
StringBuilder sb = new StringBuilder();
BufferedReader br = new BufferedReader(new InputStreamReader(new BufferedInputStream((new URL("https://oliverbathurst.github.io/web_api.txt").openConnection()).getInputStream())));
String inputLine;
while ((inputLine = br.readLine()) != null) {
sb.append(inputLine);
}
br.close();
String[] finalArr = strings[0];
HttpURLConnection conn = (HttpURLConnection) new URL("https://fcm.googleapis.com/fcm/send").openConnection();
conn.setUseCaches(false);
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Authorization", "key=" + sb.toString().trim());
conn.setRequestProperty("Content-Type", "application/json");
JSONObject json = new JSONObject();
json.put("to", finalArr[0]);
JSONObject info = new JSONObject();
info.put("message", finalArr[1]); // Notification body
json.put("data", info);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(json.toString());
wr.flush();
//wr.close();
conn.getInputStream();
conn.disconnect();
}catch(Exception ignored){}
Looper.loop();
return null;
}
}
|
3e12ed39b005e9d77b380c7ac6b641fd34e5ce53 | 12,129 | java | Java | java/micronaut-server/src/main/java/com/oracle/coherence/examples/todo/server/graphql/GraphQLFactory.java | vasac/todo-list-example | 4d11749d930dfb04d598342d6d35788cb8c00017 | [
"UPL-1.0",
"Apache-2.0",
"CC0-1.0"
] | 13 | 2020-10-02T02:55:26.000Z | 2021-12-15T01:15:25.000Z | java/micronaut-server/src/main/java/com/oracle/coherence/examples/todo/server/graphql/GraphQLFactory.java | vasac/todo-list-example | 4d11749d930dfb04d598342d6d35788cb8c00017 | [
"UPL-1.0",
"Apache-2.0",
"CC0-1.0"
] | 4 | 2021-04-09T09:07:17.000Z | 2021-12-15T10:24:08.000Z | java/micronaut-server/src/main/java/com/oracle/coherence/examples/todo/server/graphql/GraphQLFactory.java | vasac/todo-list-example | 4d11749d930dfb04d598342d6d35788cb8c00017 | [
"UPL-1.0",
"Apache-2.0",
"CC0-1.0"
] | 10 | 2020-10-27T18:43:36.000Z | 2021-12-15T01:15:27.000Z | 37.551084 | 134 | 0.567895 | 7,986 | /*
* Copyright (c) 2021 Oracle and/or its affiliates.
*
* Licensed under the Universal Permissive License v 1.0 as shown at
* https://oss.oracle.com/licenses/upl.
*/
package com.oracle.coherence.examples.todo.server.graphql;
import com.oracle.coherence.examples.todo.server.Task;
import com.tangosol.net.NamedMap;
import com.tangosol.util.Filter;
import com.tangosol.util.Filters;
import com.tangosol.util.Processors;
import graphql.GraphQL;
import graphql.language.StringValue;
import graphql.schema.Coercing;
import graphql.schema.CoercingParseLiteralException;
import graphql.schema.CoercingParseValueException;
import graphql.schema.CoercingSerializeException;
import graphql.schema.DataFetcher;
import graphql.schema.GraphQLScalarType;
import graphql.schema.GraphQLSchema;
import graphql.schema.idl.RuntimeWiring;
import graphql.schema.idl.SchemaGenerator;
import graphql.schema.idl.SchemaParser;
import graphql.schema.idl.TypeDefinitionRegistry;
import io.micronaut.coherence.annotation.Name;
import io.micronaut.context.annotation.Bean;
import io.micronaut.context.annotation.Factory;
import io.micronaut.core.io.ResourceResolver;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Collection;
import java.util.Comparator;
import java.util.Objects;
import java.util.Optional;
import java.util.function.Function;
import java.time.DateTimeException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeFormatterBuilder;
import java.time.format.DateTimeParseException;
import javax.inject.Inject;
import javax.inject.Named;
import javax.inject.Singleton;
import static java.time.format.DateTimeFormatter.ISO_LOCAL_DATE;
import static java.time.temporal.ChronoField.HOUR_OF_DAY;
import static java.time.temporal.ChronoField.MINUTE_OF_HOUR;
import static java.time.temporal.ChronoField.SECOND_OF_MINUTE;
/**
* Various bean factories for {@code GraphQL} {@link DataFetcher}s.
*/
@Factory
public class GraphQLFactory
{
@Bean
@Singleton
@Inject
public GraphQL graphQL(ResourceResolver resourceResolver,
@Named("createTask") DataFetcher<Collection<Task>> createTaskFetcher,
@Named("deleteCompletedTasks") DataFetcher<Task> deleteCompletedTasksFetcher,
@Named("deleteTask") DataFetcher<Task> deleteTaskFetcher,
@Named("updateTask") DataFetcher<Task> updateTaskFetcher,
@Named("findTask") DataFetcher<Task> findTaskFetcher,
@Named("tasks") DataFetcher<Collection<Task>> tasksFetcher)
{
// Parse the schema.
TypeDefinitionRegistry typeRegistry = new TypeDefinitionRegistry();
SchemaParser schemaParser = new SchemaParser();
typeRegistry.merge(schemaParser.parse(
new BufferedReader(new InputStreamReader(resourceResolver.getResourceAsStream("classpath:schema.graphqls").get()))));
// Create the runtime wiring.
RuntimeWiring runtimeWiring = RuntimeWiring.newRuntimeWiring()
.scalar(LOCAL_DATE_TIME)
.type("Query", typeWiring -> typeWiring.dataFetcher("findTask", findTaskFetcher))
.type("Query", typeWiring -> typeWiring.dataFetcher("tasks", tasksFetcher))
.type("Mutation", typeWiring -> typeWiring.dataFetcher("createTask", createTaskFetcher))
.type("Mutation", typeWiring -> typeWiring.dataFetcher("deleteCompletedTasks", deleteCompletedTasksFetcher))
.type("Mutation", typeWiring -> typeWiring.dataFetcher("deleteTask", deleteTaskFetcher))
.type("Mutation", typeWiring -> typeWiring.dataFetcher("updateTask", updateTaskFetcher))
.build();
// Create the executable schema.
SchemaGenerator schemaGenerator = new SchemaGenerator();
GraphQLSchema graphQLSchema = schemaGenerator.makeExecutableSchema(typeRegistry, runtimeWiring);
// Return the GraphQL bean.
return GraphQL.newGraphQL(graphQLSchema).build();
}
@Bean
@Singleton
@Named("createTask")
public DataFetcher<Task> createTasksFetcher(@Name("tasks") NamedMap<String, Task> tasks)
{
return environment ->
{
String description = environment.getArgument("description");
Objects.requireNonNull(description, "Description must be provided");
Task task = new Task(description);
tasks.put(task.getId(), task);
return task;
};
}
@Bean
@Singleton
@Named("deleteCompletedTasks")
public DataFetcher<Collection<Task>> deleteCompletedTasksFetcher(@Name("tasks") NamedMap<String, Task> tasks)
{
return environment ->
{
tasks.invokeAll(Filters.equal(Task::getCompleted, true), Processors.remove(Filters.always()));
return tasks.values();
};
}
@Bean
@Singleton
@Named("deleteTask")
public DataFetcher<Task> deleteTaskFetcher(@Name("tasks") NamedMap<String, Task> tasks)
{
return environment ->
{
String id = environment.getArgument("id");
return Optional.ofNullable(tasks.remove(id))
.orElseThrow(() -> new TaskNotFoundException(GraphQLFactory.MESSAGE + id));
};
}
@Bean
@Singleton
@Named("findTask")
public DataFetcher<Task> findTasksFetcher(@Name("tasks") NamedMap<String, Task> tasks)
{
return environment ->
{
String id = environment.getArgument("id");
return Optional.ofNullable(tasks.get(id))
.orElseThrow(() -> new TaskNotFoundException(GraphQLFactory.MESSAGE + id));
};
}
@Bean
@Singleton
@Named("tasks")
public DataFetcher<Collection<Task>> tasksFetcher(@Name("tasks") NamedMap<String, Task> tasks)
{
return environment ->
{
Boolean completed = environment.<Boolean>getArgument("completed");
Filter<Task> filter = completed == null
? Filters.always()
: Filters.equal(Task::getCompleted, completed);
return tasks.values(filter, Comparator.comparingLong(Task::getCreatedAt));
};
}
@Bean
@Singleton
@Named("updateTask")
public DataFetcher<Task> updateTaskFetcher(@Name("tasks") NamedMap<String, Task> tasks)
{
return environment ->
{
String id = environment.getArgument("id");
String description = environment.getArgument("description");
Boolean completed = environment.getArgument("completed");
try
{
return tasks.compute(id, (k, v) ->
{
Objects.requireNonNull(v);
if (description != null)
{
v.setDescription(description);
}
if (completed != null)
{
v.setCompleted(completed);
}
return v;
});
}
catch (Exception e)
{
throw new TaskNotFoundException(GraphQLFactory.MESSAGE + id);
}
};
}
private static final String MESSAGE = "Unable to find task with id ";
private static final DateTimeFormatter LOCAL_DATE_TIME_FORMATTER = new DateTimeFormatterBuilder()
.parseCaseInsensitive()
.append(ISO_LOCAL_DATE)
.appendLiteral('T')
.appendValue(HOUR_OF_DAY, 2)
.appendLiteral(':')
.appendValue(MINUTE_OF_HOUR, 2)
.optionalStart()
.appendLiteral(':')
.appendValue(SECOND_OF_MINUTE, 2)
.toFormatter();
// TODO: replace with graphql-java-extended-scalars once it become possible to use graphql-java 15+
public static final GraphQLScalarType LOCAL_DATE_TIME = GraphQLScalarType.newScalar()
.name("DateTime")
.description("A custom scalar that handles local date time")
.coercing(new Coercing<LocalDateTime, String>()
{
@Override
public String serialize(Object input)
{
LocalDateTime localDateTime;
if (input instanceof LocalDateTime)
{
localDateTime = (LocalDateTime) input;
}
else if (input instanceof String)
{
localDateTime = parseLocalDateTime(input.toString(), CoercingSerializeException::new);
}
else
{
throw new CoercingSerializeException(
"Expected something we can convert to 'java.time.LocalDateTime' but was '" + input.getClass() + "'.");
}
try
{
return LOCAL_DATE_TIME_FORMATTER.format(localDateTime);
}
catch (DateTimeException e)
{
throw new CoercingSerializeException(
"Unable to turn TemporalAccessor into LocalDateTime because of : '" + e.getMessage() + "'."
);
}
}
@Override
public LocalDateTime parseValue(Object input)
{
LocalDateTime localDateTime;
if (input instanceof LocalDateTime)
{
localDateTime = (LocalDateTime) input;
}
else if (input instanceof String)
{
localDateTime = parseLocalDateTime(input.toString(), CoercingParseValueException::new);
}
else
{
throw new CoercingParseValueException("Expected a 'String' but was '" + "typeName(input)" + "'.");
}
return localDateTime;
}
private LocalDateTime parseLocalDateTime(String s, Function<String, RuntimeException> exceptionMaker)
{
try
{
return LocalDateTime.parse(s, LOCAL_DATE_TIME_FORMATTER);
}
catch (DateTimeParseException e)
{
throw exceptionMaker.apply("Invalid RFC3339 value : '" + s + "'. because of : '" + e.getMessage() + "'");
}
}
@Override
public LocalDateTime parseLiteral(Object input)
{
if (!(input instanceof StringValue))
{
throw new CoercingParseLiteralException(
"Expected AST type 'StringValue' but was '" + input.getClass() + "'.");
}
return parseLocalDateTime(((StringValue) input).getValue(), CoercingParseLiteralException::new);
}
})
.build();
/**
* An exception indicating that a {@link Task} was not found.
*/
public static class TaskNotFoundException
extends Exception
{
/**
* Create the exception.
*
* @param message reason for the exception.
*/
public TaskNotFoundException(String message)
{
super(message);
}
}
}
|
3e12edfcd72d645580739ad0f5db48afe222e71d | 582 | java | Java | springTest/src/com/test1/Poly.java | balaSpyrus/wave11 | 3f206e9845d2a660c0c72dfd859934f4a0ff7559 | [
"MIT"
] | 1 | 2017-05-18T11:38:16.000Z | 2017-05-18T11:38:16.000Z | springTest/src/com/test1/Poly.java | balaSpyrus/wave11 | 3f206e9845d2a660c0c72dfd859934f4a0ff7559 | [
"MIT"
] | 8 | 2020-05-29T06:57:54.000Z | 2022-02-26T04:59:18.000Z | springTest/src/com/test1/Poly.java | balaSpyrus/code | 3f206e9845d2a660c0c72dfd859934f4a0ff7559 | [
"MIT"
] | 1 | 2017-01-26T14:32:13.000Z | 2017-01-26T14:32:13.000Z | 13.227273 | 75 | 0.695876 | 7,987 | package com.test1;
import java.util.List;
class Poly
{
private int sides;
private List<Description> descriptions;
public List<Description> getDescriptions()
{
return descriptions;
}
public void setDescriptions(List<Description> descriptions)
{
this.descriptions = descriptions;
}
public int getSides()
{
return sides;
}
public void setSides(int sides)
{
this.sides = sides;
}
public String draw() {
String out="";
for(Description d:descriptions)
out+=d+"\n";
return "polygon with "+getSides()+" sides drawn with descriptions \n"+out;
}
}
|
3e12ee233b0c5456aabc8b4ad519e1bd02482694 | 1,041 | java | Java | src/main/java/mutl/dialogs/UtilitiesDialog.java | iarkn/mind-util | 7a2fbb0af59b9475ab3ef4869d8b82b9a39b928a | [
"MIT"
] | 7 | 2021-08-13T11:57:19.000Z | 2022-02-11T17:52:45.000Z | src/main/java/mutl/dialogs/UtilitiesDialog.java | Receptea/mind-util | 7a2fbb0af59b9475ab3ef4869d8b82b9a39b928a | [
"MIT"
] | null | null | null | src/main/java/mutl/dialogs/UtilitiesDialog.java | Receptea/mind-util | 7a2fbb0af59b9475ab3ef4869d8b82b9a39b928a | [
"MIT"
] | 1 | 2022-01-30T14:42:52.000Z | 2022-01-30T14:42:52.000Z | 27.394737 | 124 | 0.6244 | 7,988 | package mutl.dialogs;
import arc.*;
import arc.scene.ui.*;
import arc.scene.ui.layout.*;
import mindustry.*;
import mindustry.gen.*;
import mindustry.ui.*;
import mindustry.ui.dialogs.*;
import mutl.*;
public class UtilitiesDialog extends BaseDialog {
public Table tools;
public UtilitiesDialog() {
super("@mutl.title.utilities");
tools = new Table(Tex.button);
tools.defaults().size(300f, 60f);
tools.button("@mutl.tool.unitspawner", Styles.cleart, Mutl.spawner::show).disabled(b -> !Vars.state.isGame()).row();
tools.button("@mutl.tool.display", Styles.cleart, Mutl.display::show).row();
tools.button("@mutl.tool.world", Styles.cleart, Mutl.world::show).disabled(b -> !Vars.state.isGame());
cont.table(t -> {
t.table(Tex.button, t2 -> t2.add("@mutl.header.tools")).grow();
t.button(Icon.info, Mutl.about::show).size(60f).padLeft(6f);
}).size(324f, 60f);
cont.row();
cont.add(tools);
addCloseButton();
}
}
|
3e12ee3cacf391445116ce424e82ea8fa25a1228 | 4,052 | java | Java | components/components-netsuite/components-netsuite-runtime/src/main/java/org/talend/components/netsuite/client/model/customfield/TransactionBodyCustomFieldAdapter.java | wwang-talend/components | 273af8f4ec300684c65b8afef23b96107680f8d9 | [
"Apache-2.0"
] | 53 | 2016-03-06T10:52:48.000Z | 2020-12-09T15:11:21.000Z | components/components-netsuite/components-netsuite-runtime/src/main/java/org/talend/components/netsuite/client/model/customfield/TransactionBodyCustomFieldAdapter.java | wwang-talend/components | 273af8f4ec300684c65b8afef23b96107680f8d9 | [
"Apache-2.0"
] | 1,727 | 2016-01-28T09:05:53.000Z | 2022-03-29T05:59:55.000Z | components/components-netsuite/components-netsuite-runtime/src/main/java/org/talend/components/netsuite/client/model/customfield/TransactionBodyCustomFieldAdapter.java | wwang-talend/components | 273af8f4ec300684c65b8afef23b96107680f8d9 | [
"Apache-2.0"
] | 112 | 2016-01-28T03:27:24.000Z | 2021-10-13T02:58:54.000Z | 40.929293 | 120 | 0.679171 | 7,989 | // ============================================================================
//
// Copyright (C) 2006-2018 Talend Inc. - www.talend.com
//
// This source code is available under agreement available at
// %InstallDIR%\features\org.talend.rcp.branding.%PRODUCTNAME%\%PRODUCTNAME%license.txt
//
// You should have received a copy of the agreement
// along with this program; if not, write to Talend SA
// 9 rue Pages 92150 Suresnes, France
//
// ============================================================================
package org.talend.components.netsuite.client.model.customfield;
import java.util.Map;
import org.talend.components.netsuite.client.model.BasicRecordType;
import org.talend.components.netsuite.client.model.beans.Beans;
import com.google.common.collect.ImmutableMap;
/**
* Custom field adapter for {@link BasicRecordType#TRANSACTION_BODY_CUSTOM_FIELD} type.
*/
public class TransactionBodyCustomFieldAdapter<T> extends CustomFieldAdapter<T> {
private static final String MAPPING_SALE = "bodySale";
private static final String MAPPING_PURCHASE = "bodyPurchase";
private static final String MAPPING_ASSEMBLYBUILD = "bodyAssemblyBuild";
private static final String MAPPING_CUSTOMERPAYMENT = "bodyCustomerPayment";
private static final String MAPPING_EXPENSEREPORT = "bodyExpenseReport";
private static final String MAPPING_INVENTORYADJUSTMENT = "bodyInventoryAdjustment";
private static final String MAPPING_ITEMFULFILLMENT = "bodyItemFulfillment";
private static final String MAPPING_ITEMRECEIPT = "bodyItemReceipt";
private static final String MAPPING_JOURNAL = "bodyJournal";
private static final String MAPPING_OPPORTUNITY = "bodyOpportunity";
private static final String MAPPING_TRANSFERORDER = "bodyTransferOrder";
private static final String MAPPING_VENDORPAYMENT = "bodyVendorPayment";
private static final Map<String, String> recordTypePropertyMap = ImmutableMap.<String, String>builder()
.put("assemblyBuild", MAPPING_ASSEMBLYBUILD)
.put("cashRefund", MAPPING_SALE)
.put("cashSale", MAPPING_SALE)
.put("check", MAPPING_PURCHASE)
.put("creditMemo", MAPPING_SALE)
.put("customerDeposit", MAPPING_SALE)
.put("customerPayment", MAPPING_CUSTOMERPAYMENT)
.put("customerRefund", MAPPING_SALE)
.put("deposit", MAPPING_SALE)
.put("depositApplication", MAPPING_SALE)
.put("estimate", MAPPING_SALE)
.put("expenseReport", MAPPING_EXPENSEREPORT)
.put("inventoryAdjustment", MAPPING_INVENTORYADJUSTMENT)
.put("inventoryCostRevaluation", MAPPING_INVENTORYADJUSTMENT)
.put("inventoryTransfer", MAPPING_INVENTORYADJUSTMENT)
.put("invoice", MAPPING_SALE)
.put("itemFulfillment", MAPPING_ITEMFULFILLMENT)
.put("itemReceipt", MAPPING_ITEMRECEIPT)
.put("journal", MAPPING_JOURNAL)
.put("opportunity", MAPPING_OPPORTUNITY)
.put("purchaseOrder", MAPPING_PURCHASE)
.put("returnAuthorization", MAPPING_SALE)
.put("salesOrder", MAPPING_SALE)
.put("transferOrder", MAPPING_TRANSFERORDER)
.put("vendorBill", MAPPING_PURCHASE)
.put("vendorCredit", MAPPING_PURCHASE)
.put("vendorPayment", MAPPING_VENDORPAYMENT)
.put("vendorReturnAuthorization", MAPPING_PURCHASE)
.build();
public TransactionBodyCustomFieldAdapter() {
super(BasicRecordType.TRANSACTION_BODY_CUSTOM_FIELD);
}
@Override
public boolean appliesTo(String recordType, T field) {
String propertyName = recordTypePropertyMap.get(recordType);
Boolean applies = propertyName != null ? (Boolean) Beans.getSimpleProperty(field, propertyName) : Boolean.FALSE;
return applies == null ? false : applies.booleanValue();
}
@Override
public CustomFieldRefType apply(T field) {
return getFieldType(field);
}
}
|
3e12ee6da64e971d840c20633886aa1067fe3705 | 6,606 | java | Java | src/main/java/org/smurn/jply/ElementType.java | TaehoonK/dggs_code | 2e694b07c95cb953a6752fcffef9df57989d865c | [
"MIT"
] | 2 | 2020-06-19T10:02:07.000Z | 2022-01-09T03:44:46.000Z | src/main/java/org/smurn/jply/ElementType.java | TaehoonK/dggs_code | 2e694b07c95cb953a6752fcffef9df57989d865c | [
"MIT"
] | 1 | 2021-12-18T13:43:27.000Z | 2022-01-09T03:44:05.000Z | src/main/java/org/smurn/jply/ElementType.java | TaehoonK/dggs_code | 2e694b07c95cb953a6752fcffef9df57989d865c | [
"MIT"
] | 2 | 2020-05-21T23:50:07.000Z | 2022-01-07T19:03:44.000Z | 31.759615 | 79 | 0.601574 | 7,990 | /*
* Copyright 2011 Stefan C. Mueller.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.smurn.jply;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
public final class ElementType {
/** Name of this type. */
private final String name;
/** Properties of this type. */
private final List<Property> properties;
/** Maps property names to property index. */
private final Map<String, Integer> propertyMap;
/**
* Creates an instance.
* @param name Name of the element type.
* @param properties Properties of the elements of this type.
* Must not be {@code null}.
* @throws NullPointerException if {@code name} or {@code properties} is
* {@code null}.
* @throws IllegalArgumentException if the properties don't have unique
* names.
*/
public ElementType(final String name, final List<Property> properties) {
if (name == null) {
throw new NullPointerException("name must not be null.");
}
if (properties == null) {
throw new NullPointerException("properties must not be null.");
}
this.name = name;
this.properties = Collections.unmodifiableList(
new ArrayList<Property>(properties));
HashMap<String, Integer> propertyMapTmp =
new HashMap<String, Integer>();
for (int i = 0; i < properties.size(); i++) {
propertyMapTmp.put(properties.get(i).getName(), i);
}
this.propertyMap = Collections.unmodifiableMap(propertyMapTmp);
if (propertyMap.size() != properties.size()) {
throw new IllegalArgumentException(
"properties must have unique names.");
}
}
/**
* Creates an instance.
* @param name Name of the element type.
* @param properties Properties of the elements of this type.
* @throws NullPointerException if {@code name} or {@code properties} is
* {@code null}.
* @throws IllegalArgumentException if the properties don't have unique
* names.
*/
public ElementType(final String name, final Property... properties) {
this(name, Arrays.asList(properties));
}
/**
* Gets the name of the element type.
* <p>Some names are given a specific meaning by the PLY specification and
* should only be used accordingly. See {@link ElementType}.</p>
* @return Name of the element type. Is never {@code null} or empty,
* contains only ASCII characters.
*/
public String getName() {
return name;
}
/**
* Gets all properties defined for this element type.
* @return Immutable list of properties. I never {@code null}.
*/
public List<Property> getProperties() {
return properties;
}
/**
* Gets the map that maps from property name to the index of that
* property in the {@link #getProperties()} list.
* @return Immutable map.
*/
Map<String, Integer> getPropertyMap() {
return propertyMap;
}
/**
* Represents the result of parsing the header line.
*/
static class HeaderEntry {
private final String name;
private final int count;
/**
* Creates an instance.
* @param name Name of the element type.
* @param count Number of elements of this type.
*/
public HeaderEntry(final String name, final int count) {
this.name = name;
this.count = count;
}
/**
* Gets the number of elements of the type.
* @return Number of elements.
*/
public int getCount() {
return count;
}
/**
* Gets the name of the type.
* @return Name of the type.
*/
public String getName() {
return name;
}
}
/**
* Parses a header line starting an element description.
* @param elementLine Header line.
* @return ElementType without properties.
* @throws IOException if the header line has an invalid format.
*/
static HeaderEntry parse(final String elementLine) throws IOException {
if (!elementLine.startsWith("element ")) {
throw new IOException("not an element: '"
+ elementLine + "'");
}
String definition = elementLine.substring("element ".length());
String[] parts = definition.split(" +", 2);
if (parts.length != 2) {
throw new IOException("Expected two parts in element definition: '"
+ elementLine + "'");
}
String name = parts[0];
String countStr = parts[1];
int count;
try {
count = Integer.parseInt(countStr);
}
catch (NumberFormatException e) {
throw new IOException("Invalid element entry. Not an integer: '"
+ countStr + "'.");
}
return new HeaderEntry(name, count);
}
@Override
public String toString() {
return "element " + name + " properties=" + properties;
}
@Override
public boolean equals(final Object obj) {
if (obj == null) {
return false;
}
if (obj == this) {
return true;
}
if (obj.getClass() != getClass()) {
return false;
}
ElementType rhs = (ElementType) obj;
EqualsBuilder builder = new EqualsBuilder();
builder.append(name, rhs.name);
builder.append(properties, rhs.properties);
return builder.isEquals();
}
@Override
public int hashCode() {
HashCodeBuilder builder = new HashCodeBuilder();
builder.append(name);
builder.append(properties);
return builder.toHashCode();
}
}
|
3e12ee88a788d97f204a6a9787d21ac7ca97039f | 4,449 | java | Java | SymmetricDS/symmetric-server/src/main/java/org/jumpmind/symmetric/web/RegistrationUriHandler.java | hawkwang/BeyondMDM | 588726dfa221bc9f3de7df7a2afa5bee0e213fbd | [
"Apache-2.0"
] | null | null | null | SymmetricDS/symmetric-server/src/main/java/org/jumpmind/symmetric/web/RegistrationUriHandler.java | hawkwang/BeyondMDM | 588726dfa221bc9f3de7df7a2afa5bee0e213fbd | [
"Apache-2.0"
] | 8 | 2020-09-06T02:28:34.000Z | 2022-02-26T14:11:13.000Z | SymmetricDS/symmetric-server/src/main/java/org/jumpmind/symmetric/web/RegistrationUriHandler.java | hawkwang/BeyondMDM | 588726dfa221bc9f3de7df7a2afa5bee0e213fbd | [
"Apache-2.0"
] | 2 | 2021-07-02T15:40:14.000Z | 2022-02-14T05:06:52.000Z | 43.617647 | 134 | 0.726231 | 7,991 | /**
* Licensed to JumpMind Inc under one or more contributor
* license agreements. See the NOTICE file distributed
* with this work for additional information regarding
* copyright ownership. JumpMind Inc licenses this file
* to you under the GNU General Public License, version 3.0 (GPLv3)
* (the "License"); you may not use this file except in compliance
* with the License.
*
* You should have received a copy of the GNU General Public License,
* version 3.0 (GPLv3) along with this library; if not, see
* <http://www.gnu.org/licenses/>.
*
* 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.jumpmind.symmetric.web;
import java.io.IOException;
import java.io.OutputStream;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang.StringUtils;
import org.jumpmind.symmetric.model.Node;
import org.jumpmind.symmetric.service.IParameterService;
import org.jumpmind.symmetric.service.IRegistrationService;
import org.jumpmind.symmetric.service.RegistrationRedirectException;
import org.jumpmind.symmetric.transport.http.HttpTransportManager;
/**
* Handler that delegates to the {@link IRegistrationService}
*/
public class RegistrationUriHandler extends AbstractUriHandler {
private IRegistrationService registrationService;
public RegistrationUriHandler( IParameterService parameterService,
IRegistrationService registrationService, IInterceptor... interceptors) {
super("/registration/*", parameterService, interceptors);
this.registrationService = registrationService;
}
public void handle(HttpServletRequest req, HttpServletResponse res) throws IOException,
ServletException {
Node node = transform(req);
try {
OutputStream outputStream = res.getOutputStream();
if (!registerNode(node, getHostName(req), getIpAddress(req), outputStream)) {
log.warn("{} was not allowed to register.", node);
ServletUtils.sendError(res, WebConstants.REGISTRATION_NOT_OPEN, String.format("%s was not allowed to register.",
node));
}
} catch (RegistrationRedirectException e) {
res.sendRedirect(HttpTransportManager.buildRegistrationUrl(e.getRedirectionUrl(), node));
}
}
private Node transform(HttpServletRequest req) {
Node node = new Node();
node.setNodeGroupId(ServletUtils.getParameter(req, WebConstants.NODE_GROUP_ID));
node.setSymmetricVersion(ServletUtils.getParameter(req, WebConstants.SYMMETRIC_VERSION));
node.setExternalId(ServletUtils.getParameter(req, WebConstants.EXTERNAL_ID));
String syncUrlString = ServletUtils.getParameter(req, WebConstants.SYNC_URL);
if (StringUtils.isNotBlank(syncUrlString)) {
node.setSyncUrl(syncUrlString);
}
node.setSchemaVersion(ServletUtils.getParameter(req, WebConstants.SCHEMA_VERSION));
node.setDatabaseType(ServletUtils.getParameter(req, WebConstants.DATABASE_TYPE));
node.setDatabaseVersion(ServletUtils.getParameter(req, WebConstants.DATABASE_VERSION));
node.setDeploymentType(ServletUtils.getParameter(req, WebConstants.DEPLOYMENT_TYPE));
return node;
}
protected String getHostName(HttpServletRequest req) {
String hostName = ServletUtils.getParameter(req, WebConstants.HOST_NAME);
if (StringUtils.isBlank(hostName)) {
hostName = req.getRemoteHost();
}
return hostName;
}
protected String getIpAddress(HttpServletRequest req) {
String ipAdddress = ServletUtils.getParameter(req, WebConstants.IP_ADDRESS);
if (StringUtils.isBlank(ipAdddress)) {
ipAdddress = req.getRemoteAddr();
}
return ipAdddress;
}
protected boolean registerNode(Node node, String remoteHost, String remoteAddress, OutputStream outputStream) throws IOException {
return registrationService.registerNode(node, remoteHost, remoteAddress, outputStream, true);
}
}
|
3e12f0b06218dbb87af2e817e9f54ced5ad9b52b | 69,778 | java | Java | yshop-shop/src/main/java/co/yixiang/modules/msh/service/impl/MshDemandListServiceImpl.java | yaoshengyi/serviceplatform | b03d560650ed9127ed0b1fb8f5ac68c045b256a9 | [
"Apache-2.0"
] | null | null | null | yshop-shop/src/main/java/co/yixiang/modules/msh/service/impl/MshDemandListServiceImpl.java | yaoshengyi/serviceplatform | b03d560650ed9127ed0b1fb8f5ac68c045b256a9 | [
"Apache-2.0"
] | null | null | null | yshop-shop/src/main/java/co/yixiang/modules/msh/service/impl/MshDemandListServiceImpl.java | yaoshengyi/serviceplatform | b03d560650ed9127ed0b1fb8f5ac68c045b256a9 | [
"Apache-2.0"
] | null | null | null | 49.912732 | 315 | 0.640918 | 7,992 | /**
* Copyright (C) 2018-2020
* All rights reserved, Designed By www.yixiang.co
* 注意:
* 本软件为www.yixiang.co开发研制,未经购买不得使用
* 购买后可获得全部源代码(禁止转卖、分享、上传到码云、github等开源平台)
* 一经发现盗用、分享等行为,将追究法律责任,后果自负
*/
package co.yixiang.modules.msh.service.impl;
import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletResponse;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.json.JSONUtil;
import co.yixiang.constant.ShopConstants;
import co.yixiang.constant.SystemConfigConstants;
import co.yixiang.exception.BadRequestException;
import co.yixiang.modules.api.common.Result;
import co.yixiang.modules.message.domain.MessageNotice;
import co.yixiang.modules.message.domain.MessageUser;
import co.yixiang.modules.message.service.MessageNoticeService;
import co.yixiang.modules.message.service.MessageUserService;
import co.yixiang.modules.message.service.mapper.MessageUserMapper;
import co.yixiang.modules.msh.service.dto.*;
import co.yixiang.modules.msh.service.enume.MshStatusEnum;
import co.yixiang.modules.msh.util.MshRequestUtil;
import co.yixiang.modules.shop.domain.Project;
import co.yixiang.modules.shop.domain.YxStoreProduct;
import co.yixiang.modules.shop.domain.YxSystemStore;
import co.yixiang.modules.shop.service.YxSystemStoreService;
import co.yixiang.modules.shop.service.YxUserService;
import co.yixiang.modules.shop.service.mapper.UserMapper;
import co.yixiang.modules.taibao.util.MyBeanUtils;
import co.yixiang.modules.websocket.WebSocket;
import co.yixiang.modules.yiyaobao.dto.Prescription;
import co.yixiang.modules.yiyaobao.dto.PrescriptionDetail;
import co.yixiang.mp.yiyaobao.enums.YiyaobaoPayMethodEnum;
import co.yixiang.mp.yiyaobao.enums.YiyaobaoPayTypeEnum;
import co.yixiang.mp.yiyaobao.service.dto.YiyaobaoOrderInfo;
import co.yixiang.mp.yiyaobao.service.mapper.OrdOrderMapper;
import co.yixiang.rabbitmq.send.MqProducer;
import co.yixiang.tools.utils.AppSiganatureUtils;
import co.yixiang.tools.utils.HttpUtils;
import co.yixiang.utils.FileUtil;
import co.yixiang.utils.SecurityUtils;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.pagehelper.PageHelper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageInfo;
import cn.hutool.core.date.DateUtil;
import co.yixiang.common.service.impl.BaseServiceImpl;
import co.yixiang.common.utils.QueryHelpPlus;
import co.yixiang.dozer.service.IGenerator;
import co.yixiang.modules.msh.domain.MshDemandList;
import co.yixiang.modules.msh.domain.MshDemandListFile;
import co.yixiang.modules.msh.domain.MshDemandListItem;
import co.yixiang.modules.msh.domain.MshOrder;
import co.yixiang.modules.msh.domain.MshPatientInformation;
import co.yixiang.modules.msh.domain.MshPatientListFile;
import co.yixiang.modules.msh.service.MshDemandListFileService;
import co.yixiang.modules.msh.service.MshDemandListItemService;
import co.yixiang.modules.msh.service.MshDemandListService;
import co.yixiang.modules.msh.service.MshPatientInformationService;
import co.yixiang.modules.msh.service.mapper.MshDemandListFileMapper;
import co.yixiang.modules.msh.service.mapper.MshDemandListItemMapper;
import co.yixiang.modules.msh.service.mapper.MshDemandListMapper;
import co.yixiang.modules.msh.service.mapper.MshOrderMapper;
import co.yixiang.modules.msh.service.mapper.MshPatientInformationMapper;
import co.yixiang.modules.msh.service.mapper.MshPatientListFileMapper;
import co.yixiang.modules.shop.domain.MdCountry;
import co.yixiang.modules.shop.service.mapper.MdCountryMapper;
import lombok.AllArgsConstructor;
import lombok.Data;
import org.springframework.util.CollectionUtils;
/**
* @author cq
* @date 2020-12-25
*/
@Slf4j
@Service
//@AllArgsConstructor
//@CacheConfig(cacheNames = "mshDemandList")
//@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class MshDemandListServiceImpl extends BaseServiceImpl<MshDemandListMapper, MshDemandList> implements MshDemandListService {
private static DateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
private static DateFormat dateFormatAdd = new SimpleDateFormat("yyyy-MM-dd");
@Autowired
private IGenerator generator;
@Autowired
private MshPatientInformationService mshPatientInformationService;
@Autowired
private MshDemandListItemService mshDemandListItemService;
@Autowired
private MshDemandListFileService mshDemandListFileService;
@Autowired
private MshDemandListMapper mshDemandListMapper;
@Autowired
private MshOrderMapper mshOrderMapper;
@Autowired
private MshDemandListItemMapper mshDemandListItemMapper;
@Autowired
private MshDemandListFileMapper mshDemandListFileMapper;
@Autowired
private MshPatientListFileMapper mshPatientListFileMapper;
@Autowired
private MshPatientInformationMapper mshPatientInformationMapper;
@Autowired
private MdCountryMapper mdCountryMapper;
@Autowired
private YxSystemStoreService yxSystemStoreService;
@Value("${file.path}")
private String filePath;
@Value("${file.localUrl}")
private String localUrl;
@Value("${msh.domainName}")
private String domainName;
@Value("${msh.secureKey}")
private String secureKey;
@Autowired
private MqProducer mqProducer;
@Value("${msh.delayQueueName}")
private String mshQueueName;
@Value("${yiyaobao.addSingleMshUrl}")
private String addSingleMshUrl;
@Value("${yiyaobao.apiUrlExternal}")
private String yiyaobao_apiUrl_external;
@Value("${yiyaobao.appId}")
private String appId;
@Value("${yiyaobao.appSecret}")
private String appSecret;
@Autowired
private OrdOrderMapper yiyaobaoOrdOrderMapper;
@Autowired
private WebSocket webSocket;
@Autowired
private MessageNoticeService messageNoticeService;
@Autowired
private MessageUserMapper messageUserMapper;
@Override
//@Cacheable
public Map<String, Object> queryAll(MshDemandListQueryCriteria criteria, Pageable pageable) {
getMshPage(criteria,pageable);
PageInfo<MshDemandListDto> page = new PageInfo<>(selectMshDemandListList(criteria));
Map<String, Object> map = new LinkedHashMap<>(2);
map.put("content", generator.convert(page.getList(), MshDemandListDto.class));
map.put("totalElements", page.getTotal());
return map;
}
public void getMshPage(MshDemandListQueryCriteria criteria,Pageable pageable) {
String order=null;
if(pageable.getSort()!=null){
order= pageable.getSort().toString();
order=order.replace(":","");
if(StringUtils.isEmpty(criteria.getOrderBy())){
order="create_time desc";
}else{
order=criteria.getOrderBy();
}
}
PageHelper.startPage(pageable.getPageNumber()+1, pageable.getPageSize(),order);
}
public List<MshDemandListDto> selectMshDemandListList(MshDemandListQueryCriteria criteria) {
List<MshDemandListDto> list = mshDemandListMapper.selectMshDemandLists(criteria);
//更新订单状态文字
//0:待审核;1:审核通过;2:审核不通过;3:已发货;4:已完成;5:已退货;
// for(int i = 0; i<list.size(); i++){
// for (int j = 0; j < list.get(i).getOrderList().size(); j++) {
// if("0".equals(list.get(i).getOrderList().get(j).getOrderStatus())){
// list.get(i).getOrderList().get(j).setOrderStatusStr("待审核");
// }else if("1".equals(list.get(i).getOrderList().get(j).getOrderStatus())){
// list.get(i).getOrderList().get(j).setOrderStatusStr("审核通过");
// }else if("2".equals(list.get(i).getOrderList().get(j).getOrderStatus())){
// list.get(i).getOrderList().get(j).setOrderStatusStr("审核不通过");
// }else if("3".equals(list.get(i).getOrderList().get(j).getOrderStatus())){
// list.get(i).getOrderList().get(j).setOrderStatusStr("已发货");
// }else if("4".equals(list.get(i).getOrderList().get(j).getOrderStatus())){
// list.get(i).getOrderList().get(j).setOrderStatusStr("已完成");
// }else if("5".equals(list.get(i).getOrderList().get(j).getOrderStatus())){
// list.get(i).getOrderList().get(j).setOrderStatusStr("已退货");
// }else if("6".equals(list.get(i).getOrderList().get(j).getOrderStatus())){
// list.get(i).getOrderList().get(j).setOrderStatusStr("驳回");
// }else{
// list.get(i).getOrderList().get(j).setOrderStatusStr("");
// }
// }
// }
return list;
}
@Override
//@Cacheable
public List<MshDemandListDto> queryAll(MshDemandListQueryCriteria criteria) {
return selectMshDemandListList(criteria);
}
@Override
public void download(List<MshDemandListDto> all, HttpServletResponse response) throws IOException {
List<Map<String, Object>> list = new ArrayList<>();
for (MshDemandListDto mshDemandList : all) {
Map<String, Object> map = new LinkedHashMap<>();
map.put("MSH Member ID", mshDemandList.getMemberId());
map.put("患者姓名", mshDemandList.getPatientname());
map.put("手机号", mshDemandList.getPhone());
map.put("省", mshDemandList.getProvince());
map.put("市", mshDemandList.getCity());
map.put("区", mshDemandList.getDistrict());
map.put("详细地址", mshDemandList.getDetail());
map.put("添加时间", mshDemandList.getCreateTime());
list.add(map);
}
FileUtil.downloadExcel(list, response);
}
@Override
public ServiceResult<Boolean> createmshDemandList(JSONObject jsonObject) {
ServiceResult<Boolean> serviceResult = new ServiceResult<>();
String jsonStr = jsonObject.toString();
MshDemandListForCreateDto mshDemandListForCreateDto = JSONObject.parseObject(jsonStr, MshDemandListForCreateDto.class);
//患者表信息
MshPatientInformation mshPatientInformation = mshDemandListForCreateDto.getMshPatientInformation();
//需求单附件表其他
List<MshDemandListFile> mshDemandListFileList = mshDemandListForCreateDto.getMshDemandListFileList();
//需求单附件表申请表
List<MshDemandListFile> mshDemandListFileListApplication = mshDemandListForCreateDto.getMshDemandListFileListApplication();
//需求单附件表处方照片 (医疗文件照片)
List<MshDemandListFile> mshDemandListFileListPicUrl = mshDemandListForCreateDto.getMshDemandListFileListPicUrl();
//需求单患者信息附件表
List<MshPatientListFile> mshPatientListFileList = mshDemandListForCreateDto.getMshPatientListFileList();
//需求单子表
List<MshDemandListItem> mshDemandListItemList = mshDemandListForCreateDto.getMshDemandListItemList();
// //获取省市区的name
// QueryWrapper<MdCountry> queryWrapper = new QueryWrapper<>();
// queryWrapper.eq("CODE", mshPatientInformation.getProvinceCode());
// String province = mdCountryMapper.selectList(queryWrapper).get(0).getName();
//
// queryWrapper = new QueryWrapper<>();
// queryWrapper.eq("CODE", mshPatientInformation.getCityCode());
// String city = mdCountryMapper.selectList(queryWrapper).get(0).getName();
//
// queryWrapper = new QueryWrapper<>();
// queryWrapper.eq("CODE", mshPatientInformation.getDistrictCode());
// String district = mdCountryMapper.selectList(queryWrapper).get(0).getName();
//获取省市区的name
String province = null;
String city = null;
String district = null;
QueryWrapper<MdCountry> queryWrapper = null;
if (mshPatientInformation.getProvinceCode() != null && !("".equals(mshPatientInformation.getProvinceCode()))) {
queryWrapper = new QueryWrapper<>();
queryWrapper.eq("CODE", mshPatientInformation.getProvinceCode());
province = mdCountryMapper.selectList(queryWrapper).get(0).getName();
}
if (mshPatientInformation.getCityCode() != null && !("".equals(mshPatientInformation.getCityCode()))) {
queryWrapper = new QueryWrapper<>();
queryWrapper.eq("CODE", mshPatientInformation.getCityCode());
city = mdCountryMapper.selectList(queryWrapper).get(0).getName();
}
if (mshPatientInformation.getDistrictCode() != null && !("".equals(mshPatientInformation.getDistrictCode()))) {
queryWrapper = new QueryWrapper<>();
queryWrapper.eq("CODE", mshPatientInformation.getDistrictCode());
district = mdCountryMapper.selectList(queryWrapper).get(0).getName();
}
//校验是否存在该手机号,存在即更新,不存在插入
MshPatientInformation mpi = mshPatientInformationService.getOne(new QueryWrapper<MshPatientInformation>().eq("phone", mshPatientInformation.getPhone()).eq("delete_status", 0));
if (mpi != null) {
//更新患者表信息
mshPatientInformation.setProvince(province);
mshPatientInformation.setCity(city);
mshPatientInformation.setDistrict(district);
mshPatientInformation.setId(mpi.getId());
mshPatientInformationService.updateById(mshPatientInformation);
} else {
//插入患者表信息
mshPatientInformation.setProvince(province);
mshPatientInformation.setCity(city);
mshPatientInformation.setDistrict(district);
mshPatientInformation.setAddTime(DateUtil.date().toTimestamp());
boolean patientFlag = mshPatientInformationService.save(mshPatientInformation);
if (!patientFlag) {
serviceResult.setOk(false);
serviceResult.setMsg("插入患者表信息失败!");
return serviceResult;
}
}
//患者附件信息表全删全插
if (mshPatientListFileList.get(0).getPatientId() != null) {
QueryWrapper<MshPatientListFile> deleteQueryWrapper = new QueryWrapper<>();
deleteQueryWrapper.eq("patient_id", mshPatientListFileList.get(0).getPatientId());
mshPatientListFileMapper.delete(deleteQueryWrapper);
}
//插入患者附件表信息
for (int i = 0; i < mshPatientListFileList.size(); i++) {
mshPatientListFileList.get(i).setPatientId(mshPatientInformation.getId());
mshPatientListFileList.get(i).setType("身份证或护照");
int num = mshPatientListFileMapper.insert(mshPatientListFileList.get(i));
if (num == 0) {
serviceResult.setOk(false);
serviceResult.setMsg("插入需求单患者附件信息失败!");
return serviceResult;
}
}
String username = SecurityUtils.getUsername();
Long maxId = mshDemandListMapper.findMaxId(dateFormat.format(new Date()));
String demandNo = "";
if (maxId != null) {
maxId=maxId+1;
demandNo = "XXSY" +maxId;
} else {
demandNo = "XXSY" + dateFormat.format(new Date()) + String.format("%05d", 1);
}
//插入需求单主表信息
MshDemandList mshDemandList = new MshDemandList();
mshDemandList.setPatientname(mshPatientInformation.getPatientname());
mshDemandList.setPhone(mshPatientInformation.getPhone());
if (mshDemandListFileListPicUrl.size() > 0) {
mshDemandList.setPicUrl(mshDemandListFileListPicUrl.get(0).getFileUrl());
}
mshDemandList.setProvince(province);
mshDemandList.setCity(city);
mshDemandList.setDistrict(district);
mshDemandList.setProvinceCode(mshPatientInformation.getProvinceCode());
mshDemandList.setCityCode(mshPatientInformation.getCityCode());
mshDemandList.setDistrictCode(mshPatientInformation.getDistrictCode());
mshDemandList.setDetail(mshPatientInformation.getDetail());
mshDemandList.setCreateTime(DateUtil.date().toTimestamp());
mshDemandList.setPatientId(mshPatientInformation.getId());
mshDemandList.setSaveStatus(1);
mshDemandList.setMemberId(mshPatientInformation.getMemberId());
mshDemandList.setSource("线下");
mshDemandList.setDemandNo(demandNo);
mshDemandList.setCreateUser(username);
mshDemandList.setCompany(mshPatientInformation.getCompany());
mshDemandList.setVip(mshPatientInformation.getVip());
mshDemandList.setPerCustoService(mshPatientInformation.getPerCustoService());
mshDemandList.setPerCustoServiceEmail(mshPatientInformation.getPerCustoServiceEmail());
mshDemandList.setPatientEmail(mshPatientInformation.getPatientEmail());
mshDemandList.setDiseaseName(mshPatientInformation.getDiseaseName());
mshDemandList.setFileHospital(mshPatientInformation.getFileHospital());
mshDemandList.setFileDate(mshPatientInformation.getFileDate());
mshDemandList.setReceivingName(mshPatientInformation.getReceivingName());
mshDemandList.setRelationship(mshPatientInformation.getRelationship());
mshDemandList.setReceivingPhone(mshPatientInformation.getReceivingPhone());
int num = mshDemandListMapper.insert(mshDemandList);
if (num == 0) {
serviceResult.setOk(false);
serviceResult.setMsg("插入需求单主表信息失败!");
return serviceResult;
}
//插入需求单附件表信息
for (int i = 0; i < mshDemandListFileList.size(); i++) {
mshDemandListFileList.get(i).setDemandListId(mshDemandList.getId());
mshDemandListFileList.get(i).setType("其他");
boolean mshDemandListFileFlag = mshDemandListFileService.save(mshDemandListFileList.get(i));
if (!mshDemandListFileFlag) {
serviceResult.setOk(false);
serviceResult.setMsg("插入需求单附件表信息失败!");
return serviceResult;
}
}
//插入需求单附件表信息
for (int i = 0; i < mshDemandListFileListApplication.size(); i++) {
mshDemandListFileListApplication.get(i).setDemandListId(mshDemandList.getId());
mshDemandListFileListApplication.get(i).setType("申请表");
boolean mshDemandListFileFlag = mshDemandListFileService.save(mshDemandListFileListApplication.get(i));
if (!mshDemandListFileFlag) {
serviceResult.setOk(false);
serviceResult.setMsg("插入需求单附件表信息失败!");
return serviceResult;
}
}
//插入需求单附件表信息
for (int i = 0; i < mshDemandListFileListPicUrl.size(); i++) {
mshDemandListFileListPicUrl.get(i).setDemandListId(mshDemandList.getId());
mshDemandListFileListPicUrl.get(i).setType("医疗文件照片");
boolean mshDemandListFileFlag = mshDemandListFileService.save(mshDemandListFileListPicUrl.get(i));
if (!mshDemandListFileFlag) {
serviceResult.setOk(false);
serviceResult.setMsg("插入需求单附件表信息失败!");
return serviceResult;
}
}
//插入需求单详细表信息
for(int i = 0; i<mshDemandListItemList.size(); i++){
mshDemandListItemList.get(i).setDemandListId(mshDemandList.getId());
boolean mshDemandListItemFlag = mshDemandListItemService.save(mshDemandListItemList.get(i));
if(!mshDemandListItemFlag){
serviceResult.setOk(false);
serviceResult.setMsg("插入需求单详细表信息失败!");
return serviceResult;
}
}
serviceResult.setOk(true);
return serviceResult;
}
@Override
public ServiceResult<Boolean> createmshDemandListForSave(JSONObject jsonObject) {
ServiceResult<Boolean> serviceResult = new ServiceResult<>();
String jsonStr = jsonObject.toString();
MshDemandListForCreateDto mshDemandListForCreateDto = JSONObject.parseObject(jsonStr, MshDemandListForCreateDto.class);
//患者表信息
MshPatientInformation mshPatientInformation = mshDemandListForCreateDto.getMshPatientInformation();
//需求单附件表其他
List<MshDemandListFile> mshDemandListFileList = mshDemandListForCreateDto.getMshDemandListFileList();
//需求单附件表申请表
List<MshDemandListFile> mshDemandListFileListApplication = mshDemandListForCreateDto.getMshDemandListFileListApplication();
//需求单附件表处方照片 (医疗文件照片)
List<MshDemandListFile> mshDemandListFileListPicUrl = mshDemandListForCreateDto.getMshDemandListFileListPicUrl();
//需求单患者信息附件表
List<MshPatientListFile> mshPatientListFileList = mshDemandListForCreateDto.getMshPatientListFileList();
//需求单子表
List<MshDemandListItem> mshDemandListItemList = mshDemandListForCreateDto.getMshDemandListItemList();
//新增或修改FLAG
String flag = mshDemandListForCreateDto.getFlag();
//需求单ID
Integer id = mshDemandListForCreateDto.getId();
//保存状态
Integer saveStatus = mshDemandListForCreateDto.getSaveStatus();
//获取省市区的name
String province = null;
String city = null;
String district = null;
QueryWrapper<MdCountry> queryWrapper = null;
if (mshPatientInformation.getProvinceCode() != null && !("".equals(mshPatientInformation.getProvinceCode()))) {
queryWrapper = new QueryWrapper<>();
queryWrapper.eq("CODE", mshPatientInformation.getProvinceCode());
province = mdCountryMapper.selectList(queryWrapper).get(0).getName();
}
if (mshPatientInformation.getCityCode() != null && !("".equals(mshPatientInformation.getCityCode()))) {
queryWrapper = new QueryWrapper<>();
queryWrapper.eq("CODE", mshPatientInformation.getCityCode());
city = mdCountryMapper.selectList(queryWrapper).get(0).getName();
}
if (mshPatientInformation.getDistrictCode() != null && !("".equals(mshPatientInformation.getDistrictCode()))) {
queryWrapper = new QueryWrapper<>();
queryWrapper.eq("CODE", mshPatientInformation.getDistrictCode());
district = mdCountryMapper.selectList(queryWrapper).get(0).getName();
}
//判断新增还是修改逻辑
if ("0".equals(flag)) {
//新增
//校验是否存在该手机号,存在即更新,不存在插入
MshPatientInformation mpi = null;
if (mshPatientInformation.getPhone() == null || "".equals(mshPatientInformation.getPhone())) {
mpi = null;
} else {
mpi = mshPatientInformationService.getOne(new QueryWrapper<MshPatientInformation>().eq("phone", mshPatientInformation.getPhone()).eq("delete_status", 0));
}
//判断手机号是否为空,为空时插入一条新的患者数据,不为空需要校验手机是否存在
if (StringUtils.isEmpty(mshPatientInformation.getPhone())) {
//插入患者表信息
mshPatientInformation.setProvince(province);
mshPatientInformation.setCity(city);
mshPatientInformation.setDistrict(district);
mshPatientInformation.setAddTime(DateUtil.date().toTimestamp());
boolean patientFlag = mshPatientInformationService.save(mshPatientInformation);
if (!patientFlag) {
serviceResult.setOk(false);
serviceResult.setMsg("插入患者表信息失败!");
return serviceResult;
}
} else {
if (mpi != null) {
//更新患者表信息
mshPatientInformation.setProvince(province);
mshPatientInformation.setCity(city);
mshPatientInformation.setDistrict(district);
mshPatientInformation.setId(mpi.getId());
mshPatientInformationService.updateById(mshPatientInformation);
} else {
//插入患者表信息
mshPatientInformation.setProvince(province);
mshPatientInformation.setCity(city);
mshPatientInformation.setDistrict(district);
mshPatientInformation.setAddTime(DateUtil.date().toTimestamp());
boolean patientFlag = mshPatientInformationService.save(mshPatientInformation);
if (!patientFlag) {
serviceResult.setOk(false);
serviceResult.setMsg("插入患者表信息失败!");
return serviceResult;
}
}
}
//患者附件信息表全删全插
if (mpi != null) {
QueryWrapper<MshPatientListFile> deleteQueryWrapper = new QueryWrapper<>();
deleteQueryWrapper.eq("patient_id", mpi.getId());
mshPatientListFileMapper.delete(deleteQueryWrapper);
}
//插入患者附件表信息
for (int i = 0; i < mshPatientListFileList.size(); i++) {
mshPatientListFileList.get(i).setPatientId(mshPatientInformation.getId());
mshPatientListFileList.get(i).setType("身份证或护照");
int num = mshPatientListFileMapper.insert(mshPatientListFileList.get(i));
if (num == 0) {
serviceResult.setOk(false);
serviceResult.setMsg("插入需求单患者附件信息失败!");
return serviceResult;
}
}
String username = SecurityUtils.getUsername();
Long maxId = mshDemandListMapper.findMaxId(dateFormat.format(new Date()));
String demandNo = "";
if (maxId != null) {
maxId=maxId+1;
demandNo = "XXSY" +maxId;
} else {
demandNo = "XXSY" + dateFormat.format(new Date()) + String.format("%05d", 1);
}
//插入需求单主表信息
MshDemandList mshDemandList = new MshDemandList();
mshDemandList.setPatientname(mshPatientInformation.getPatientname());
mshDemandList.setPhone(mshPatientInformation.getPhone());
if (mshDemandListFileListPicUrl.size() > 0) {
mshDemandList.setPicUrl(mshDemandListFileListPicUrl.get(0).getFileUrl());
}
mshDemandList.setProvince(province);
mshDemandList.setCity(city);
mshDemandList.setDistrict(district);
mshDemandList.setProvinceCode(mshPatientInformation.getProvinceCode());
mshDemandList.setCityCode(mshPatientInformation.getCityCode());
mshDemandList.setDistrictCode(mshPatientInformation.getDistrictCode());
mshDemandList.setDetail(mshPatientInformation.getDetail());
mshDemandList.setCreateTime(DateUtil.date().toTimestamp());
mshDemandList.setPatientId(mshPatientInformation.getId());
mshDemandList.setSaveStatus(saveStatus);
mshDemandList.setMemberId(mshPatientInformation.getMemberId());
mshDemandList.setSource("线下");
mshDemandList.setDemandNo(demandNo);
mshDemandList.setCreateUser(username);
mshDemandList.setCompany(mshPatientInformation.getCompany());
mshDemandList.setVip(mshPatientInformation.getVip());
mshDemandList.setPerCustoService(mshPatientInformation.getPerCustoService());
mshDemandList.setPerCustoServiceEmail(mshPatientInformation.getPerCustoServiceEmail());
mshDemandList.setPatientEmail(mshPatientInformation.getPatientEmail());
mshDemandList.setDiseaseName(mshPatientInformation.getDiseaseName());
mshDemandList.setFileHospital(mshPatientInformation.getFileHospital());
mshDemandList.setFileDate(mshPatientInformation.getFileDate());
mshDemandList.setReceivingName(mshPatientInformation.getReceivingName());
mshDemandList.setRelationship(mshPatientInformation.getRelationship());
mshDemandList.setReceivingPhone(mshPatientInformation.getReceivingPhone());
int num = mshDemandListMapper.insert(mshDemandList);
if (num == 0) {
serviceResult.setOk(false);
serviceResult.setMsg("插入需求单主表信息失败!");
return serviceResult;
}
//插入需求单附件表信息
for (int i = 0; i < mshDemandListFileList.size(); i++) {
mshDemandListFileList.get(i).setDemandListId(mshDemandList.getId());
mshDemandListFileList.get(i).setType("其他");
boolean mshDemandListFileFlag = mshDemandListFileService.save(mshDemandListFileList.get(i));
if (!mshDemandListFileFlag) {
serviceResult.setOk(false);
serviceResult.setMsg("插入需求单附件表信息失败!");
return serviceResult;
}
}
//插入需求单附件表信息
for (int i = 0; i < mshDemandListFileListApplication.size(); i++) {
mshDemandListFileListApplication.get(i).setDemandListId(mshDemandList.getId());
mshDemandListFileListApplication.get(i).setType("申请表");
boolean mshDemandListFileFlag = mshDemandListFileService.save(mshDemandListFileListApplication.get(i));
if (!mshDemandListFileFlag) {
serviceResult.setOk(false);
serviceResult.setMsg("插入需求单附件表信息失败!");
return serviceResult;
}
}
//插入需求单附件表信息
for (int i = 0; i < mshDemandListFileListPicUrl.size(); i++) {
mshDemandListFileListPicUrl.get(i).setDemandListId(mshDemandList.getId());
mshDemandListFileListPicUrl.get(i).setType("医疗文件照片");
boolean mshDemandListFileFlag = mshDemandListFileService.save(mshDemandListFileListPicUrl.get(i));
if (!mshDemandListFileFlag) {
serviceResult.setOk(false);
serviceResult.setMsg("插入需求单附件表信息失败!");
return serviceResult;
}
}
//插入需求单详细表信息
for(int i = 0; i<mshDemandListItemList.size(); i++){
mshDemandListItemList.get(i).setDemandListId(mshDemandList.getId());
boolean mshDemandListItemFlag = mshDemandListItemService.save(mshDemandListItemList.get(i));
if(!mshDemandListItemFlag){
serviceResult.setOk(false);
serviceResult.setMsg("插入需求单详细表信息失败!");
return serviceResult;
}
}
serviceResult.setOk(true);
return serviceResult;
} else {
//修改
//查询上次录入的数据手机号是否为空
MshPatientInformation mpi1 = mshPatientInformationService.getOne(new QueryWrapper<MshPatientInformation>().eq("id", mshPatientInformation.getId()).eq("delete_status", 0));
//查询当前手机号是否存在
MshPatientInformation mpi2 = null;
if (mshPatientInformation.getPhone() == null || "".equals(mshPatientInformation.getPhone())) {
mpi2 = null;
} else {
mpi2 = mshPatientInformationService.getOne(new QueryWrapper<MshPatientInformation>().eq("phone", mshPatientInformation.getPhone()).eq("delete_status", 0));
}
//判断当前传入手机号是否为空
if (mshPatientInformation.getPhone() == null || "".equals(mshPatientInformation.getPhone())) {
//当前传入手机号为空
//判断上次手机号是否为空
if (mpi1 != null && (mpi1.getPhone() == null || "".equals(mpi1.getPhone()))) {
//更新患者表信息
mshPatientInformation.setProvince(province);
mshPatientInformation.setCity(city);
mshPatientInformation.setDistrict(district);
mshPatientInformation.setId(mpi1.getId());
mshPatientInformationService.updateById(mshPatientInformation);
} else {
//插入患者表信息
mshPatientInformation.setId(null);
mshPatientInformation.setProvince(province);
mshPatientInformation.setCity(city);
mshPatientInformation.setDistrict(district);
mshPatientInformation.setAddTime(DateUtil.date().toTimestamp());
boolean patientFlag = mshPatientInformationService.save(mshPatientInformation);
if (!patientFlag) {
serviceResult.setOk(false);
serviceResult.setMsg("插入患者表信息失败!");
return serviceResult;
}
}
} else {
//当前传入手机号不为空
//判断上次手机号是否为空
if (mpi1 != null && (mpi1.getPhone() == null || "".equals(mpi1.getPhone()))) {
//上次录入的手机号为空
if (mpi2 != null) {
//更新患者表信息
mshPatientInformation.setProvince(province);
mshPatientInformation.setCity(city);
mshPatientInformation.setDistrict(district);
mshPatientInformation.setId(mpi2.getId());
mshPatientInformationService.updateById(mshPatientInformation);
//删除之前插入的空的患者数据
QueryWrapper<MshPatientInformation> deleteQueryWrapper = new QueryWrapper<>();
deleteQueryWrapper.eq("id", mpi1.getId());
mshPatientInformationMapper.delete(deleteQueryWrapper);
} else {
//更新患者表信息
mshPatientInformation.setProvince(province);
mshPatientInformation.setCity(city);
mshPatientInformation.setDistrict(district);
mshPatientInformation.setId(mpi1.getId());
mshPatientInformationService.updateById(mshPatientInformation);
}
} else {
if (mpi2 != null) {
//更新患者表信息
mshPatientInformation.setProvince(province);
mshPatientInformation.setCity(city);
mshPatientInformation.setDistrict(district);
mshPatientInformation.setId(mpi2.getId());
mshPatientInformationService.updateById(mshPatientInformation);
} else {
//插入患者表信息
mshPatientInformation.setId(null);
mshPatientInformation.setProvince(province);
mshPatientInformation.setCity(city);
mshPatientInformation.setDistrict(district);
mshPatientInformation.setAddTime(DateUtil.date().toTimestamp());
boolean patientFlag = mshPatientInformationService.save(mshPatientInformation);
if (!patientFlag) {
serviceResult.setOk(false);
serviceResult.setMsg("插入患者表信息失败!");
return serviceResult;
}
}
}
}
//更新需求单主表信息
MshDemandList mshDemandList = new MshDemandList();
mshDemandList.setId(id);
mshDemandList.setPatientId(mshPatientInformation.getId());
mshDemandList.setSaveStatus(saveStatus);
//线下开单且 保存状态为保存状态
// if (!(StringUtils.isNotEmpty(mshDemandListForCreateDto.getSource()) &&
// (mshDemandListForCreateDto.getSource().equals("APP")
// || mshDemandListForCreateDto.getSource().equals("Wechat"))) && (saveStatus == 0 || saveStatus==1)) {
// }
//
// if (saveStatus == 0 || saveStatus == 3 || saveStatus==1) {
mshDemandList.setPatientname(mshPatientInformation.getPatientname());
mshDemandList.setPhone(mshPatientInformation.getPhone());
mshDemandList.setMemberId(mshPatientInformation.getMemberId());
mshDemandList.setCompany(mshPatientInformation.getCompany());
mshDemandList.setVip(mshPatientInformation.getVip());
mshDemandList.setPatientEmail(mshPatientInformation.getPatientEmail());
mshDemandList.setDiseaseName(mshPatientInformation.getDiseaseName());
mshDemandList.setFileHospital(mshPatientInformation.getFileHospital());
mshDemandList.setFileDate(mshPatientInformation.getFileDate());
mshDemandList.setPerCustoService(mshPatientInformation.getPerCustoService());
mshDemandList.setPerCustoServiceEmail(mshPatientInformation.getPerCustoServiceEmail());
mshDemandList.setReceivingName(mshPatientInformation.getReceivingName());
mshDemandList.setRelationship(mshPatientInformation.getRelationship());
mshDemandList.setReceivingPhone(mshPatientInformation.getReceivingPhone());
mshDemandList.setDetail(mshPatientInformation.getDetail());
mshDemandList.setProvince(province);
mshDemandList.setCity(city);
mshDemandList.setDistrict(district);
mshDemandList.setProvinceCode(mshPatientInformation.getProvinceCode());
mshDemandList.setCityCode(mshPatientInformation.getCityCode());
mshDemandList.setDistrictCode(mshPatientInformation.getDistrictCode());
// }
mshDemandList.setUpdateTime(new Date());
mshDemandListMapper.updateById(mshDemandList);
//对需求单附件表,患者附件表,需求单详细表信息进行全删全插
//删除需求单详细表信息
QueryWrapper<MshDemandListItem> deleteQueryWrapper = new QueryWrapper<>();
deleteQueryWrapper.eq("demand_list_id", id);
mshDemandListItemMapper.delete(deleteQueryWrapper);
//插入需求单详细表信息
for(int i = 0; i<mshDemandListItemList.size(); i++){
mshDemandListItemList.get(i).setDemandListId(id);
log.info("mshDemandListItemList:"+ JSON.toJSONString(mshDemandListItemList.get(i)));
boolean mshDemandListItemFlag = mshDemandListItemService.save(mshDemandListItemList.get(i));
if(!mshDemandListItemFlag){
serviceResult.setOk(false);
serviceResult.setMsg("插入需求单详细表信息失败!");
return serviceResult;
}
}
//删除需求单附件表
QueryWrapper<MshDemandListFile> deleteQueryWrapper2 = new QueryWrapper<>();
deleteQueryWrapper2.eq("demand_list_id", id);
mshDemandListFileMapper.delete(deleteQueryWrapper2);
//插入需求单附件表信息
for (int i = 0; i < mshDemandListFileList.size(); i++) {
mshDemandListFileList.get(i).setDemandListId(id);
mshDemandListFileList.get(i).setType("其他");
boolean mshDemandListFileFlag = mshDemandListFileService.save(mshDemandListFileList.get(i));
if (!mshDemandListFileFlag) {
serviceResult.setOk(false);
serviceResult.setMsg("插入需求单附件表信息失败!");
return serviceResult;
}
}
//插入需求单附件表信息
for (int i = 0; i < mshDemandListFileListApplication.size(); i++) {
mshDemandListFileListApplication.get(i).setDemandListId(mshDemandList.getId());
mshDemandListFileListApplication.get(i).setType("申请表");
boolean mshDemandListFileFlag = mshDemandListFileService.save(mshDemandListFileListApplication.get(i));
if (!mshDemandListFileFlag) {
serviceResult.setOk(false);
serviceResult.setMsg("插入需求单附件表信息失败!");
return serviceResult;
}
}
//插入需求单附件表信息
for (int i = 0; i < mshDemandListFileListPicUrl.size(); i++) {
mshDemandListFileListPicUrl.get(i).setDemandListId(mshDemandList.getId());
mshDemandListFileListPicUrl.get(i).setType("医疗文件照片");
boolean mshDemandListFileFlag = mshDemandListFileService.save(mshDemandListFileListPicUrl.get(i));
if (!mshDemandListFileFlag) {
serviceResult.setOk(false);
serviceResult.setMsg("插入需求单附件表信息失败!");
return serviceResult;
}
}
//删除患者附件信息
QueryWrapper<MshPatientListFile> deleteQueryWrapper3 = new QueryWrapper<>();
deleteQueryWrapper3.eq("patient_id", mpi1.getId());
mshPatientListFileMapper.delete(deleteQueryWrapper3);
//插入患者附件表信息
for (int i = 0; i < mshPatientListFileList.size(); i++) {
mshPatientListFileList.get(i).setPatientId(mshPatientInformation.getId());
mshPatientListFileList.get(i).setType("身份证或护照");
int num = mshPatientListFileMapper.insert(mshPatientListFileList.get(i));
if (num == 0) {
serviceResult.setOk(false);
serviceResult.setMsg("插入需求单患者附件信息失败!");
return serviceResult;
}
}
}
serviceResult.setOk(true);
return serviceResult;
}
@Override
public ServiceResult<Integer> checkDeleteById(Integer[] ids) {
ServiceResult<Integer> serviceResult = new ServiceResult<>();
//查询订单表中是否存在该需求单
for (Integer it : ids) {
QueryWrapper<MshOrder> queryWrapper = new QueryWrapper<>();
queryWrapper.eq("demand_list_id", it);
List<MshOrder> mshOrderList = mshOrderMapper.selectList(queryWrapper);
if (mshOrderList != null && mshOrderList.size() > 0) {
serviceResult.setOk(false);
serviceResult.setData(it);
serviceResult.setMsg("需求单号" + it + "已生成订单");
return serviceResult;
}
}
serviceResult.setOk(true);
return serviceResult;
}
@Override
public ServiceResult<Boolean> deleteById(Integer[] ids) {
ServiceResult<Boolean> serviceResult = new ServiceResult<>();
//删除需求单主表及子表信息
for (Integer it : ids) {
//需求单主表
mshDemandListMapper.deleteById(it);
//需求单子表
QueryWrapper<MshDemandListItem> queryWrapper1 = new QueryWrapper<>();
queryWrapper1.eq("demand_list_id", it);
mshDemandListItemMapper.delete(queryWrapper1);
//需求单附件表
QueryWrapper<MshDemandListFile> queryWrapper2 = new QueryWrapper<>();
queryWrapper2.eq("demand_list_id", it);
mshDemandListFileMapper.delete(queryWrapper2);
}
serviceResult.setOk(true);
return serviceResult;
}
@Override
public Map<String, Object> getMshDemandListdDetails(Integer id) {
Map<String, Object> map = new LinkedHashMap<>(5);
MshDemandList mshDemandList = mshDemandListMapper.findById(id);
map.put("MshDemandListInfo", mshDemandList);
//需求单附件信息
QueryWrapper<MshDemandListFile> queryWrapper = new QueryWrapper<>();
queryWrapper.eq("demand_list_id", id);
queryWrapper.orderByAsc("type");
map.put("MshDemandListFileList", mshDemandListFileMapper.selectList(queryWrapper));
//查询患者相关信息
QueryWrapper<MshPatientInformation> queryWrapper3 = new QueryWrapper<>();
queryWrapper3.eq("id", mshDemandList.getPatientId());
List<MshPatientInformation> list3 = mshPatientInformationMapper.selectList(queryWrapper3);
map.put("MshPatientInformation", list3);
QueryWrapper<MshPatientListFile> queryWrapper4 = new QueryWrapper<>();
if (list3 != null && list3.size() > 0) {
queryWrapper4.eq("patient_id", list3.get(0).getId());
map.put("MshPatientListFileList", mshPatientListFileMapper.selectList(queryWrapper4));
} else {
map.put("MshPatientListFileList", null);
}
//查询需求单明细
QueryWrapper<MshDemandListItem> queryWrapper5 = new QueryWrapper<>();
queryWrapper5.eq("demand_list_id", id);
List<MshDemandListItem> list4 = mshDemandListItemMapper.selectList(queryWrapper5);
map.put("mshDemandListItemList", list4);
YxSystemStore yxSystemStore = yxSystemStoreService.getOne(new LambdaQueryWrapper<YxSystemStore>().eq(YxSystemStore::getName, ShopConstants.STORENAME_GUANGZHOU_CLOUD), false);
map.put("storeInfo", yxSystemStore);
return map;
}
@Override
public MshDemandListAuditDto getMshDemandListAuditInfo(Integer id) {
MshDemandList mshDemandList = mshDemandListMapper.findById(id);
MshDemandListAuditDto mshDemandListDto = generator.convert(mshDemandList, MshDemandListAuditDto.class);
List<MshOrderDto> mshOrderDtos = mshOrderMapper.getMshOrderByDemandListId(id);
List<MshOrderAuditDto> mshOrderAuditDtos = generator.convert(mshOrderDtos, MshOrderAuditDto.class);
for (MshOrderAuditDto mshOrderDto : mshOrderAuditDtos) {
if ("0".equals(mshOrderDto.getOrderStatus())) {
mshOrderDto.setOrderStatusStr("");
} else if ("1".equals(mshOrderDto.getOrderStatus())) {
mshOrderDto.setOrderStatusStr("审核通过");
} else if ("2".equals(mshOrderDto.getOrderStatus())) {
mshOrderDto.setOrderStatusStr("审核不通过");
} else if ("3".equals(mshOrderDto.getOrderStatus())) {
mshOrderDto.setOrderStatusStr("审核通过");
} else if ("4".equals(mshOrderDto.getOrderStatus())) {
mshOrderDto.setOrderStatusStr("审核通过");
} else if ("5".equals(mshOrderDto.getOrderStatus())) {
mshOrderDto.setOrderStatusStr("审核通过");
} else if ("6".equals(mshOrderDto.getOrderStatus())) {
mshOrderDto.setOrderStatusStr("驳回");
} else {
mshOrderDto.setOrderStatusStr("");
}
}
mshDemandListDto.setMshOrderAuditDtos(mshOrderAuditDtos);
return mshDemandListDto;
}
@Override
public void updateMshDemandList(MshDemandList resources) {
MshDemandList mshDemandList= mshDemandListMapper.selectById(resources.getId());
if(("APP".equals(mshDemandList.getSource()) || "Wechat".equals(mshDemandList.getSource())) && mshDemandList.getAuditStatus().equals(MshStatusEnum.AuditStatus.QX.getCode()) ){
throw new BadRequestException("需求单来源为:"+mshDemandList.getSource()+",不能取消。");
}
if(resources.getAuditStatus()!=null && (resources.getAuditStatus()==1 || resources.getAuditStatus()==2 || resources.getAuditStatus()==6)){
String username = SecurityUtils.getUsername();
resources.setAuditName(username);
resources.setAuditTime(new Timestamp(System.currentTimeMillis()));
}
resources.setUpdateTime(new Date());
mshDemandListMapper.updateById(resources);
if (resources.getSaveStatus()==2) {
if(resources.getAuditStatus()==1){
List<MshOrderDto> list= mshOrderMapper.getMshOrderByDemandListId(resources.getId());
if(!CollectionUtils.isEmpty(list)){
for (MshOrderDto mshOrderDto : list) {
if(mshOrderDto.getOrderStatus().equals("6")){
// if(ShopConstants.STORENAME_GUANGZHOU_CLOUD.equals(mshOrderDto.getDrugstoreName())){
//设置处方字段
String prescriptionNo = mshOrderDto.getId() + "_msh";
Prescription pres = new Prescription();
pres.setOrderId(mshOrderDto.getYiyaobaoId());
// 收货信息
pres.setAddress(mshDemandList.getDetail());
pres.setProvinceName(mshDemandList.getProvince());
pres.setCityName(mshDemandList.getCity());
pres.setDistrictName(mshDemandList.getDistrict());
pres.setReceiver(mshDemandList.getPatientname());
pres.setReceiverMobile(mshDemandList.getPhone());
pres.setName(mshDemandList.getPatientname());
pres.setHospitalName("益药商城");
pres.setPrescripNo(prescriptionNo);
String url = yiyaobao_apiUrl_external + addSingleMshUrl;
String requestBody = JSONUtil.parseObj(pres).toString(); //
try {
long timestamp = System.currentTimeMillis(); // 生成签名时间戳
Map<String, String> headers = new HashMap<String, String>();
headers.put("ACCESS_APPID", appId); // 设置APP
headers.put("ACCESS_TIMESTAMP", String.valueOf(timestamp)); // 设置签名时间戳
String ACCESS_SIGANATURE = AppSiganatureUtils
.createSiganature(requestBody, appId, appSecret,
timestamp);
headers.put("ACCESS_SIGANATURE", ACCESS_SIGANATURE); // 生成并设置签名
log.info("ACCESS_APPID={}",appId);
log.info("ACCESS_TIMESTAMP={}",String.valueOf(timestamp));
log.info("ACCESS_SIGANATURE={}",ACCESS_SIGANATURE);
log.info("url={}",url);
log.info("requestBody={}",requestBody);
String result = HttpUtils.postJsonHttps(url, requestBody,
headers); // 发起调用
log.info("下发益药宝订单,结果:{}" ,result);
cn.hutool.json.JSONObject object = JSONUtil.parseObj(result);
if(object.getBool("success")) {
MshOrder order= MyBeanUtils.convert(mshOrderDto, MshOrder.class);
order.setOrderStatus("0");
mshOrderMapper.updateById(order);
YiyaobaoOrderInfo yiyaobaoOrderInfo = new YiyaobaoOrderInfo();
yiyaobaoOrderInfo.setOrderSource("32");
yiyaobaoOrderInfo.setPrsNo(prescriptionNo);
yiyaobaoOrderInfo.setPayMethod(YiyaobaoPayMethodEnum.payMethod_21.getValue()); // 金融支付
yiyaobaoOrderInfo.setPayResult("10"); // 已支付
yiyaobaoOrderInfo.setPayTime(DateUtil.formatDateTime(new Date()));
yiyaobaoOrderInfo.setPayType(YiyaobaoPayTypeEnum.payType_40.getValue());
// 更新益药宝订单的信息
yiyaobaoOrdOrderMapper.updateYiyaobaoOrderInfoByPrescripNo(yiyaobaoOrderInfo);
}
} catch (Exception e) {
e.printStackTrace();
}
}
// }
}
}
udpateMshDemandListAuditStatus(resources.getId().toString());
}
//消息队列
mqProducer.sendDelayQueue(mshQueueName,resources.getId().toString(),2000);
}
}
@Override
public List<String> getMshDemandAllAuditPerson() {
return mshDemandListMapper.getMshDemandAllAuditPerson();
}
@Override
public List<String> getMshDemandAllVip() {
return mshDemandListMapper.getMshDemandAllVip();
}
@Override
public void sendDemandListInfo(String id) {
MshDemandList demandList = mshDemandListMapper.selectById(id);
if("线下".equals(demandList.getSource())){
}else{
List<MshOrderDto> mshOrderDtos= mshOrderMapper.getMshOrderByDemandListId(demandList.getId());
MshDemandListDto mshDemandListDto = generator.convert(demandList, MshDemandListDto.class);
mshDemandListDto.setOrderList(mshOrderDtos);
QueryWrapper<MshPatientListFile> queryWrapper4 = new QueryWrapper<>();
queryWrapper4.eq("patient_id", demandList.getPatientId());
List<MshPatientListFile> mshPatientListFiles= mshPatientListFileMapper.selectList(queryWrapper4);
List<String> IdCardImages = CollectionUtils.isEmpty(mshPatientListFiles)?new ArrayList<>():mshPatientListFiles.stream().map(MshPatientListFile::getFileUrl).collect(Collectors.toList());
QueryWrapper<MshDemandListFile> queryWrapper = new QueryWrapper<>();
queryWrapper.eq("demand_list_id", demandList.getId());
queryWrapper.orderByAsc("type");
List<MshDemandListFile> mshDemandListFiles= mshDemandListFileMapper.selectList(queryWrapper);
List<MshDemandListFile> mshDemandDocumentsResultList = mshDemandListFiles.stream().filter(MshDemandListFile -> Objects.equals(MshDemandListFile.getType(),"医疗文件照片") || Objects.equals(MshDemandListFile.getType(),"病例") || Objects.equals(MshDemandListFile.getType(),"处方照片") ).collect(Collectors.toList());
List<String> medicalDocumentsImages = CollectionUtils.isEmpty(mshDemandDocumentsResultList)?new ArrayList<>():mshDemandDocumentsResultList.stream().map(MshDemandListFile::getFileUrl).collect(Collectors.toList());
List<MshDemandListFile> mshOtherImagesResultList = mshDemandListFiles.stream().filter(MshDemandListFile -> Objects.equals(MshDemandListFile.getType(),"其他")).collect(Collectors.toList());
List<String> OtherImagesImages = CollectionUtils.isEmpty(mshOtherImagesResultList)?new ArrayList<>():mshOtherImagesResultList.stream().map(MshDemandListFile::getFileUrl).collect(Collectors.toList());
mshDemandListDto.setIdCardImages(IdCardImages);
mshDemandListDto.setMedicalDocumentsImages(medicalDocumentsImages);
mshDemandListDto.setOtherImages(OtherImagesImages);
try {
JSONObject jsonObject=JSONObject.parseObject(MshRequestUtil.syncOrderDetail(domainName,secureKey,mshDemandListDto));
if(jsonObject==null || !jsonObject.get("code").equals("200")){
// throw new BadRequestException("同步失败");
}
} catch (Exception ex) {
ex.printStackTrace();
throw new BadRequestException(ex.getMessage());
}
}
}
@Override
public MshDemandList udpateMshDemandListAuditStatus(String id){
MshDemandList demandList = mshDemandListMapper.selectById(Integer.valueOf(id));
List<MshOrderDto> mshOrderDtos= mshOrderMapper.getMshOrderByDemandListId(demandList.getId());
Integer a,b,c,d,e,f,g;
a=b=c=d=e=f=g=0;
if(!CollectionUtils.isEmpty(mshOrderDtos)){
List<String> reason = mshOrderDtos.stream().map(MshOrderDto::getAuditReasons).filter(x -> StringUtils.isNotEmpty(x)).collect(Collectors.toList());
for (MshOrderDto mshOrderDto : mshOrderDtos) {
if(Integer.valueOf(mshOrderDto.getOrderStatus()) == MshStatusEnum.OrderStatus.DSH.getCode()){
a++;
}
if(Integer.valueOf(mshOrderDto.getOrderStatus()) == MshStatusEnum.OrderStatus.SHTG.getCode()){
b++;
}
if(Integer.valueOf(mshOrderDto.getOrderStatus()) == MshStatusEnum.OrderStatus.SHBTG.getCode()){
c++;
}
if(Integer.valueOf(mshOrderDto.getOrderStatus()) == MshStatusEnum.OrderStatus.YFH.getCode()){
d++;
}
if(Integer.valueOf(mshOrderDto.getOrderStatus()) == MshStatusEnum.OrderStatus.YWC.getCode()){
e++;
}
if(Integer.valueOf(mshOrderDto.getOrderStatus()) == MshStatusEnum.OrderStatus.YTH.getCode()){
f++;
}
if(Integer.valueOf(mshOrderDto.getOrderStatus()) == MshStatusEnum.OrderStatus.BH.getCode()){
g++;
}
}
// 需求单下所有订单都为待审核时,需求单状态=客服审核通过
if(a>mshOrderDtos.size()){
demandList.setAuditStatus(MshStatusEnum.AuditStatus.KFSHTG.getCode());
}
//无待审核有订单驳回时,需求单状态=药剂师驳回
if(a==0 && g>0){
demandList.setAuditStatus(MshStatusEnum.AuditStatus.BH.getCode());
demandList.setSaveStatus(MshStatusEnum.SaveStatus.BH.getCode());
}
//需求单下无待审核订单无订单驳回且有通过时,需求单状态=药剂师审核通过
if(a==0 && g==0 && (b>0 || d>0 || e>0 || f>0)){
demandList.setAuditStatus(MshStatusEnum.AuditStatus.YJSSHTG.getCode());
}
//无待审核订单无订单通过且无订单驳回时,需求单状态=药剂师审核不通过
if(c>0 && b==0 && d==0 && e==0 && f==0 && g==0 && a==0 && g==0){
demandList.setAuditStatus(MshStatusEnum.AuditStatus.YJSSHBTG.getCode());
if(mshOrderDtos.size()==1){
demandList.setCancelReason(MshStatusEnum.CancelReason.getCancelReason(mshOrderDtos.get(0).getAuditReasons())==null?mshOrderDtos.get(0).getAuditReasons():MshStatusEnum.CancelReason.getCancelReason(mshOrderDtos.get(0).getAuditReasons()).getCode());
}else{
Set set = new HashSet();
set.addAll(reason); // 将list所有元素添加到set中 set集合特性会自动去重复
reason.clear();
reason.addAll(set); // 将list清空并将set中的所有元素添加到list中
if(reason.size()>1){
demandList.setCancelReason(MshStatusEnum.CancelReason.reason_1.getCode());
}else{
demandList.setCancelReason(MshStatusEnum.CancelReason.getCancelReason(mshOrderDtos.get(0).getAuditReasons())==null?mshOrderDtos.get(0).getAuditReasons():MshStatusEnum.CancelReason.getCancelReason(mshOrderDtos.get(0).getAuditReasons()).getCode());
}
}
}
demandList.setUpdateTime(new Date());
mshDemandListMapper.updateById(demandList);
}
return demandList;
}
@Override
public void reportDowload(HttpServletResponse response,MshDemandListQueryCriteria criteria) throws IOException {
List<Map<String, Object>> list = new ArrayList<>();
List<Map<String, Object>> mapList = mshDemandListMapper.reportList(criteria);
for (Map<String, Object> map : mapList) {
Map<String, Object> linkedHashMap = new LinkedHashMap<>();
linkedHashMap.put("患者姓名",map.get("患者姓名"));
linkedHashMap.put("患者地址",map.get("患者地址"));
linkedHashMap.put("患者电话",map.get("患者电话"));
linkedHashMap.put("MSH member id",map.get("MSH member id"));
linkedHashMap.put("需求单号",map.get("需求单号"));
linkedHashMap.put("需求单生成日期",map.get("需求单生成日期"));
linkedHashMap.put("SKU",map.get("SKU"));
linkedHashMap.put("商品名",map.get("商品名"));
linkedHashMap.put("通用名",map.get("通用名"));
linkedHashMap.put("药品规格",map.get("药品规格"));
linkedHashMap.put("数量",map.get("数量"));
linkedHashMap.put("生产厂家",map.get("生产厂家"));
linkedHashMap.put("需求单价格",map.get("需求单价格"));
linkedHashMap.put("销售订单号",map.get("销售订单号"));
linkedHashMap.put("订单状态",map.get("订单状态"));
linkedHashMap.put("发货日期",map.get("发货日期"));
linkedHashMap.put("已发货数量",map.get("已发货数量"));
linkedHashMap.put("快递单号",map.get("快递单号"));
linkedHashMap.put("发票号",map.get("发票号"));
list.add(linkedHashMap);
}
FileUtil.downloadExcel(list, response);
}
@Override
public void addMshDemandList(MshDemandDto mshDemandDto) {
MshDemandList mshDemandList= mshDemandListMapper.findByDemandNo(mshDemandDto.getDemandNo());
if(mshDemandList!=null){
throw new BadRequestException(HttpStatus.SERVICE_UNAVAILABLE,"报文体中demandNo:"+mshDemandDto.getDemandNo()+",在上药系统已存在。");
}
MshPatientInformation mshPatientInformation = new MshPatientInformation();
mshPatientInformation.setPatientname(mshDemandDto.getPatientName());
mshPatientInformation.setPhone(mshDemandDto.getPatientPhone());
mshPatientInformation.setProvince(mshDemandDto.getProvinceName());
mshPatientInformation.setCity(mshDemandDto.getCityName());
mshPatientInformation.setDistrict(mshDemandDto.getDistrictName());
mshPatientInformation.setProvinceCode(mshDemandDto.getProvinceCode());
mshPatientInformation.setCityCode(mshDemandDto.getCityCode());
mshPatientInformation.setDistrictCode(mshDemandDto.getDistrictCode());
mshPatientInformation.setDetail(mshDemandDto.getAddress());
mshPatientInformation.setAddTime(DateUtil.date().toTimestamp());
mshPatientInformation.setDeleteStatus(0);
mshPatientInformation.setMemberId(mshDemandDto.getMermberId());
mshPatientInformation.setReceivingName(mshDemandDto.getConsigneeName());
mshPatientInformation.setRelationship(mshDemandDto.getRelation());
mshPatientInformation.setReceivingPhone(mshDemandDto.getConsigneePhone());
mshPatientInformation.setCompany(mshDemandDto.getCompanyShortName());
mshPatientInformation.setVip(mshDemandDto.getVipFlag());
mshPatientInformation.setPerCustoService(mshDemandDto.getCustomerService());
mshPatientInformation.setPerCustoServiceEmail(mshDemandDto.getCustomerServiceEmail());
mshPatientInformation.setPatientEmail(mshDemandDto.getPatientEmail());
mshPatientInformation.setDiseaseName(mshDemandDto.getDiseaseName());
mshPatientInformation.setFileHospital(mshDemandDto.getHospitalName());
try {
mshPatientInformation.setFileDate(StringUtils.isEmpty(mshDemandDto.getDocumentDate())?null:dateFormatAdd.parse(mshDemandDto.getDocumentDate()));
} catch (ParseException e) {
e.printStackTrace();
}
//新增患者
MshPatientInformation information = mshPatientInformationService.getOne(new QueryWrapper<MshPatientInformation>().eq("phone", mshDemandDto.getPatientPhone()).eq("delete_status", 0));
if(information!=null){
mshPatientInformation.setId(information.getId());
mshPatientInformationService.updateById(mshPatientInformation);
}else{
mshPatientInformationService.save(mshPatientInformation);
}
List<String> IdCardImages= mshDemandDto.getIdCardImages();
List<MshPatientListFile> mshPatientListFiles=new ArrayList<>();
for (String idCardImage : IdCardImages) {
MshPatientListFile mshPatientListFile=new MshPatientListFile();
mshPatientListFile.setType("身份证或护照");
mshPatientListFile.setPatientId(mshPatientInformation.getId());
mshPatientListFile.setFileType("image/jpeg");
mshPatientListFile.setFileUrl(idCardImage);
mshPatientListFiles.add(mshPatientListFile);
}
//患者附件信息表全删全插
QueryWrapper<MshPatientListFile> deleteQueryWrapper = new QueryWrapper<>();
deleteQueryWrapper.eq("patient_id", mshPatientInformation.getId());
mshPatientListFileMapper.delete(deleteQueryWrapper);
//插入患者附件表信息
for (int i = 0; i < mshPatientListFiles.size(); i++) {
mshPatientListFileMapper.insert(mshPatientListFiles.get(i));
}
List<String> medicalDocumentsImages=mshDemandDto.getMedicalDocumentsImages();
mshDemandList = new MshDemandList();
mshDemandList.setPatientname(mshPatientInformation.getPatientname());
mshDemandList.setPhone(mshPatientInformation.getPhone());
if (medicalDocumentsImages.size() > 0) {
mshDemandList.setPicUrl(medicalDocumentsImages.get(0));
}
mshDemandList.setProvince(mshPatientInformation.getProvince());
mshDemandList.setCity(mshPatientInformation.getCity());
mshDemandList.setDistrict(mshPatientInformation.getDistrict());
mshDemandList.setProvinceCode(mshPatientInformation.getProvinceCode());
mshDemandList.setCityCode(mshPatientInformation.getCityCode());
mshDemandList.setDistrictCode(mshPatientInformation.getDistrictCode());
mshDemandList.setDetail(mshPatientInformation.getDetail());
mshDemandList.setCreateTime(DateUtil.date().toTimestamp());
mshDemandList.setPatientId(mshPatientInformation.getId());
mshDemandList.setSaveStatus(0);
mshDemandList.setMemberId(mshPatientInformation.getMemberId());
mshDemandList.setSource(mshDemandDto.getSource());
mshDemandList.setDemandNo(mshDemandDto.getDemandNo());
mshDemandList.setCreateUser(mshDemandDto.getMaker());
mshDemandList.setCompany(mshPatientInformation.getCompany());
mshDemandList.setVip(mshPatientInformation.getVip());
mshDemandList.setPerCustoService(mshPatientInformation.getPerCustoService());
mshDemandList.setPerCustoServiceEmail(mshPatientInformation.getPerCustoServiceEmail());
mshDemandList.setPatientEmail(mshPatientInformation.getPatientEmail());
mshDemandList.setDiseaseName(mshPatientInformation.getDiseaseName());
mshDemandList.setFileHospital(mshPatientInformation.getFileHospital());
mshDemandList.setFileDate(mshPatientInformation.getFileDate());
mshDemandList.setReceivingName(mshPatientInformation.getReceivingName());
mshDemandList.setRelationship(mshPatientInformation.getRelationship());
mshDemandList.setReceivingPhone(mshPatientInformation.getReceivingPhone());
int num = mshDemandListMapper.insert(mshDemandList);
if(num>0){
List<MshDemandListFile> mshDemandListFiles=new ArrayList<>();
for (String medicalDocumentsImage : medicalDocumentsImages) {
MshDemandListFile mshDemandListFile=new MshDemandListFile();
mshDemandListFile.setType("医疗文件照片");
mshDemandListFile.setFileUrl(medicalDocumentsImage);
mshDemandListFile.setDemandListId(mshDemandList.getId());
mshDemandListFile.setFileType("image/jpeg");
mshDemandListFiles.add(mshDemandListFile);
}
List<String> otherImages= mshDemandDto.getOtherImages();
for (String otherImage : otherImages) {
MshDemandListFile mshDemandListFile=new MshDemandListFile();
mshDemandListFile.setType("其他");
mshDemandListFile.setFileUrl(otherImage);
mshDemandListFile.setDemandListId(mshDemandList.getId());
mshDemandListFile.setFileType("image/jpeg");
mshDemandListFiles.add(mshDemandListFile);
}
List<String> applyImages= mshDemandDto.getApplyImages();
for (String otherImage : applyImages) {
MshDemandListFile mshDemandListFile=new MshDemandListFile();
mshDemandListFile.setType("申请表");
mshDemandListFile.setFileUrl(otherImage);
mshDemandListFile.setDemandListId(mshDemandList.getId());
mshDemandListFile.setFileType("image/jpeg");
mshDemandListFiles.add(mshDemandListFile);
}
mshDemandListFileService.saveBatch(mshDemandListFiles);
}
QueryWrapper queryWrapper = new QueryWrapper<MessageUser>();
queryWrapper.apply(" send_dept = {0} ","msh");
List<MessageUser> messageUsers = messageUserMapper.selectList(queryWrapper);
if(!CollectionUtils.isEmpty(messageUsers)){
for (MessageUser messageUser : messageUsers) {
MessageNotice resources=new MessageNotice();
resources.setUserId(messageUser.getUserId());
resources.setCreateTime(new Timestamp(System.currentTimeMillis()));
resources.setMessage("有新的线上需求单,请及时处理,需求单号为【"+mshDemandList.getDemandNo()+"】");
resources.setTitle("msh需求单");
messageNoticeService.save(resources);
if(!messageUser.getUserId().equals("ALL")){
webSocket.pushMessage(messageUser.getUserId(),"您有一笔新的需求单,请及时处理,需求单号为【"+mshDemandList.getDemandNo()+"】");
}else{
webSocket.pushMessage("您有一笔新的需求单,请及时处理,需求单号为【"+mshDemandList.getDemandNo()+"】");
}
}
}
}
public static void main(String[] args) {
System.out.println(MshStatusEnum.OrderStatus.DSH.getCode());
System.out.println(Integer.parseInt("0")==MshStatusEnum.OrderStatus.DSH.getCode());
}
}
|
3e12f0f36142dcc43c0dfc49aaeb23c11c7410d4 | 2,155 | java | Java | Java Programming: Solving problems with Software/week2/geneCount/PartI.java | manparvesh/coursera-OOP-java | ba2580d882045d2bdd020bc07a8430817cfe4fb6 | [
"MIT"
] | 1 | 2019-01-29T08:55:12.000Z | 2019-01-29T08:55:12.000Z | Java Programming: Solving problems with Software/week2/geneCount/PartI.java | manparvesh/coursera-OOP-java | ba2580d882045d2bdd020bc07a8430817cfe4fb6 | [
"MIT"
] | null | null | null | Java Programming: Solving problems with Software/week2/geneCount/PartI.java | manparvesh/coursera-OOP-java | ba2580d882045d2bdd020bc07a8430817cfe4fb6 | [
"MIT"
] | 3 | 2019-06-30T14:52:40.000Z | 2020-05-21T08:35:39.000Z | 29.121622 | 79 | 0.47239 | 7,993 | import edu.duke.*;
/**
* Write a description of PartI here.
*
* @author (your name)
* @version (a version number or a date)
*/
public class PartI {
int findStopCodon(String dna , int startIndex , String stopCodon){
dna = dna.toUpperCase();
stopCodon = stopCodon.toUpperCase();
int endIndex = dna.indexOf(stopCodon,startIndex+3);
while(endIndex != -1){
if((endIndex-startIndex)%3 == 0){
return endIndex ;
}
endIndex = dna.indexOf(stopCodon,endIndex+1);
}
return -1 ;
}
String findGene(String dna , int startIndex ){
//int startIndex = dna.indexOf("ATG",startSearch);
if(startIndex != -1){
int taa = findStopCodon(dna ,startIndex ,"TAA");
int tga = findStopCodon(dna ,startIndex ,"TGA");
int tag = findStopCodon(dna ,startIndex ,"TAG");
int minOne = -1 ;
if( taa == -1 || (tga != -1 && tga < taa)){
minOne = tga ;
}
else{
minOne = taa ;
}
if( minOne == -1 || (tag != -1 && tag < minOne)){
minOne = tag ;
}
if(minOne != -1){
return dna.substring(startIndex , minOne+3);
}
else{
return "";
}
}
else{
return "";
}
}
StorageResource getAllGenes(String dna){
int currentIndex = dna.indexOf("ATG");
StorageResource x = new StorageResource();
while(currentIndex != -1){
String gene = findGene(dna , currentIndex);
if(!gene.isEmpty()){
x.add(gene);
currentIndex = dna.indexOf("ATG",currentIndex + gene.length());
}
else{
currentIndex = dna.indexOf("ATG",currentIndex + 1);
}
}
return x ;
}
void testing(){
StorageResource z = getAllGenes("ATGTAAGATGCCCTAGT");
for(String x : z.data()){
System.out.println(x);
}
}
} |
3e12f0fe6c210bd5b99dc869830da461cff961f1 | 3,446 | java | Java | src/main/java/com/tencentcloudapi/tsf/v20180326/models/UpdateApiTimeoutsRequest.java | githubWangbo/tencentcloud-sdk-java | c490a478c4cd6d0a262c7b72c2e65af7578377cf | [
"Apache-2.0"
] | 416 | 2018-05-16T03:36:25.000Z | 2022-03-31T03:48:52.000Z | src/main/java/com/tencentcloudapi/tsf/v20180326/models/UpdateApiTimeoutsRequest.java | githubWangbo/tencentcloud-sdk-java | c490a478c4cd6d0a262c7b72c2e65af7578377cf | [
"Apache-2.0"
] | 117 | 2018-05-03T07:11:06.000Z | 2022-03-09T11:07:55.000Z | src/main/java/com/tencentcloudapi/tsf/v20180326/models/UpdateApiTimeoutsRequest.java | githubWangbo/tencentcloud-sdk-java | c490a478c4cd6d0a262c7b72c2e65af7578377cf | [
"Apache-2.0"
] | 236 | 2018-05-10T03:15:09.000Z | 2022-03-05T02:17:51.000Z | 26.921875 | 89 | 0.625943 | 7,994 | /*
* Copyright (c) 2017-2018 THL A29 Limited, a Tencent company. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.tencentcloudapi.tsf.v20180326.models;
import com.tencentcloudapi.common.AbstractModel;
import com.google.gson.annotations.SerializedName;
import com.google.gson.annotations.Expose;
import java.util.HashMap;
public class UpdateApiTimeoutsRequest extends AbstractModel{
/**
* API ID 列表
*/
@SerializedName("ApiIds")
@Expose
private String [] ApiIds;
/**
* 开启/禁用,enabled/disabled
*/
@SerializedName("UsableStatus")
@Expose
private String UsableStatus;
/**
* 超时时间,单位毫秒,开启API超时时,必填
*/
@SerializedName("Timeout")
@Expose
private Long Timeout;
/**
* Get API ID 列表
* @return ApiIds API ID 列表
*/
public String [] getApiIds() {
return this.ApiIds;
}
/**
* Set API ID 列表
* @param ApiIds API ID 列表
*/
public void setApiIds(String [] ApiIds) {
this.ApiIds = ApiIds;
}
/**
* Get 开启/禁用,enabled/disabled
* @return UsableStatus 开启/禁用,enabled/disabled
*/
public String getUsableStatus() {
return this.UsableStatus;
}
/**
* Set 开启/禁用,enabled/disabled
* @param UsableStatus 开启/禁用,enabled/disabled
*/
public void setUsableStatus(String UsableStatus) {
this.UsableStatus = UsableStatus;
}
/**
* Get 超时时间,单位毫秒,开启API超时时,必填
* @return Timeout 超时时间,单位毫秒,开启API超时时,必填
*/
public Long getTimeout() {
return this.Timeout;
}
/**
* Set 超时时间,单位毫秒,开启API超时时,必填
* @param Timeout 超时时间,单位毫秒,开启API超时时,必填
*/
public void setTimeout(Long Timeout) {
this.Timeout = Timeout;
}
public UpdateApiTimeoutsRequest() {
}
/**
* NOTE: Any ambiguous key set via .set("AnyKey", "value") will be a shallow copy,
* and any explicit key, i.e Foo, set via .setFoo("value") will be a deep copy.
*/
public UpdateApiTimeoutsRequest(UpdateApiTimeoutsRequest source) {
if (source.ApiIds != null) {
this.ApiIds = new String[source.ApiIds.length];
for (int i = 0; i < source.ApiIds.length; i++) {
this.ApiIds[i] = new String(source.ApiIds[i]);
}
}
if (source.UsableStatus != null) {
this.UsableStatus = new String(source.UsableStatus);
}
if (source.Timeout != null) {
this.Timeout = new Long(source.Timeout);
}
}
/**
* Internal implementation, normal users should not use it.
*/
public void toMap(HashMap<String, String> map, String prefix) {
this.setParamArraySimple(map, prefix + "ApiIds.", this.ApiIds);
this.setParamSimple(map, prefix + "UsableStatus", this.UsableStatus);
this.setParamSimple(map, prefix + "Timeout", this.Timeout);
}
}
|
3e12f1bec16176ae6b6ca21bed1734dfa0d29886 | 6,093 | java | Java | src/com/cladonia/xml/designer/SubstitutionSelectionDialog.java | HiltonRoscoe/exchangerxml | 6da3871f1094633bd98c95fd3f404cfbf805fe43 | [
"ClArtistic"
] | 6 | 2021-01-31T21:22:32.000Z | 2021-07-13T04:52:24.000Z | src/com/cladonia/xml/designer/SubstitutionSelectionDialog.java | HiltonRoscoe/exchangerxml | 6da3871f1094633bd98c95fd3f404cfbf805fe43 | [
"ClArtistic"
] | 8 | 2021-01-08T20:49:50.000Z | 2021-06-27T23:14:03.000Z | src/com/cladonia/xml/designer/SubstitutionSelectionDialog.java | HiltonRoscoe/exchangerxml | 6da3871f1094633bd98c95fd3f404cfbf805fe43 | [
"ClArtistic"
] | null | null | null | 26.606987 | 107 | 0.645823 | 7,995 | /*
* $Id: SubstitutionSelectionDialog.java,v 1.5 2005/04/29 12:39:57 gmcgoldrick Exp $
*
* Copyright (C) 2002, Cladonia Ltd. All rights reserved.
*
* This software is the proprietary information of Cladonia Ltd.
* Use is subject to license terms.
*/
package com.cladonia.xml.designer;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.Vector;
import javax.swing.AbstractListModel;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.border.EmptyBorder;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import com.cladonia.schema.SchemaElement;
import com.cladonia.xngreditor.XngrDialog;
//import com.cladonia.schema.XMLSchema;
/**
* A dialog that takes in a list of schema elements and allows
* the user to select a element.
*
* @version $Revision: 1.5 $, $Date: 2005/04/29 12:39:57 $
* @author Dogsbay
*/
public class SubstitutionSelectionDialog extends XngrDialog {
private static final boolean DEBUG = false;
private static final Dimension SIZE = new Dimension( 230, 300);
private JList list = null;
//private QLabel text = null;
private ElementListModel model = null;
/**
* Creates a modal dialog that allows the user to select a
* substitution element.
*
* @param parent the parent frame.
*/
public SubstitutionSelectionDialog( JFrame parent) {
super( parent,true);
//try {
// LicenseManager licenseManager = LicenseManager.getInstance();
// licenseManager.isValid( com.cladonia.license.KeyGenerator.generate(2), "Exchanger XML Editor");
//} catch (Exception x) {
// System.exit(0);
// return;
//}
setResizable( false);
setTitle( "Select Substitution", "Select Substitution");
setDialogDescription( "Select a Substitution element.");
list = new JList();
list.addMouseListener( new MouseAdapter() {
public void mouseReleased( MouseEvent e) {
int index = list.getSelectedIndex();
if ( index != -1) { // A row is selected...
if ( e.getClickCount() == 2) {
cancelled = false;
hide();
//setVisible(false);
}
}
}
});
list.addListSelectionListener(new ListSelectionListener() {
public void valueChanged(ListSelectionEvent arg0) {
int selected = list.getSelectedIndex();
if(selected>-1) {
list.ensureIndexIsVisible(selected);
}
}
});
/*text = new QLabel();
text.setLines( 3);
text.setText( "Select an element that should be used to Substitute:");
text.setHorizontalAlignment( QLabel.LEFT);*/
//removed for xngr-dialog
/*
okButton = new JButton("OK");
cancelButton = new JButton("Cancel");
okButton.addActionListener( new ActionListener() {
public void actionPerformed( ActionEvent e) {
cancelled = false;
setVisible(false);
}
});
cancelButton.addActionListener( new ActionListener() {
public void actionPerformed( ActionEvent e) {
cancelled = true;
setVisible(false);
}
});
addWindowListener( new WindowAdapter() {
public void windowClosing( WindowEvent e) {
cancelled = true;
setVisible(false);
}
});
JPanel buttonPanel = new JPanel( new FlowLayout( FlowLayout.CENTER));
buttonPanel.setBorder( new EmptyBorder( 5, 0, 3, 0));
buttonPanel.add( okButton);
buttonPanel.add( cancelButton);
cancelButton.setFont( cancelButton.getFont().deriveFont( Font.PLAIN));
getRootPane().setDefaultButton( okButton);
*/ JPanel mainPanel = new JPanel( new BorderLayout());
//mainPanel.add( text, BorderLayout.NORTH);
JScrollPane scrollPane = new JScrollPane( list,
JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
mainPanel.add( scrollPane, BorderLayout.CENTER);
mainPanel.setBorder( new EmptyBorder( 5, 5, 5, 5));
//mainPanel.add( buttonPanel, BorderLayout.SOUTH);
this.setContentPane( mainPanel);
pack();
//setSize( new Dimension( SIZE.width, getSize().height));
setLocationRelativeTo( parent);
}
/**
* Set the schema.
*
* @param schema the schema with the root elements.
*/
public void setElement( SchemaElement element) {
Vector substitutes = element.getSubstituteElements();
if ( substitutes != null) {
model = new ElementListModel( substitutes);
list.setModel( model);
list.setSelectedIndex( 0);
}
}
/**
* Returns the URL of the document.
*
* @return the URL of the document
*/
public SchemaElement getSelectedElement() {
int index = list.getSelectedIndex();
if ( index != -1) {
return model.getElement( index);
} else {
return model.getElement( 0);
}
}
class ElementListModel extends AbstractListModel {
Vector elements = null;
public ElementListModel( Vector list) {
elements = new Vector();
for ( int i = 0; i < list.size(); i++) {
SchemaElement element = (SchemaElement)list.elementAt(i);
// Find out where to insert the element...
int index = -1;
for ( int j = 0; j < elements.size() && index == -1; j++) {
// Compare alphabeticaly
if ( element.getName().compareToIgnoreCase( ((SchemaElement)elements.elementAt(j)).getName()) <= 0) {
index = j;
}
}
if ( index != -1) {
elements.insertElementAt( element, index);
} else {
elements.addElement( element);
}
}
}
public int getSize() {
if ( elements != null) {
return elements.size();
}
return 0;
}
public Object getElementAt( int i) {
return ((SchemaElement)elements.elementAt( i)).getName();
}
public SchemaElement getElement( int i) {
return (SchemaElement)elements.elementAt( i);
}
}
}
|
3e12f1f8fdb5f4f16402c966b334febe0b5de361 | 3,998 | java | Java | AndroidUIDemos/app/src/main/java/org/mazhuang/androiduidemos/activity/ScaleTypeTestActivity.java | mzlogin/android-ui-demos | fb5626158cdc0562b3e61ae80be8ffebdac56291 | [
"MIT"
] | 7 | 2016-10-22T05:20:14.000Z | 2019-04-16T08:47:05.000Z | AndroidUIDemos/app/src/main/java/org/mazhuang/androiduidemos/activity/ScaleTypeTestActivity.java | mzlogin/android-ui-demos | fb5626158cdc0562b3e61ae80be8ffebdac56291 | [
"MIT"
] | 2 | 2016-04-20T09:09:36.000Z | 2021-02-19T09:14:41.000Z | AndroidUIDemos/app/src/main/java/org/mazhuang/androiduidemos/activity/ScaleTypeTestActivity.java | mzlogin/android-ui-demos | fb5626158cdc0562b3e61ae80be8ffebdac56291 | [
"MIT"
] | null | null | null | 37.018519 | 97 | 0.647324 | 7,996 | package org.mazhuang.androiduidemos.activity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.SparseArray;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import org.mazhuang.androiduidemos.R;
/**
* Created by mazhuang on 2016/11/8.
*/
public class ScaleTypeTestActivity extends BaseActivity {
private ImageView mImageView;
private EditText mWidthEdit;
private EditText mHeightEdit;
private int mImageViewWidth;
private int mImageViewHeight;
private int mDefaultSize = 200;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_scale_type_test);
initViews();
}
private void initViews() {
mImageView = (ImageView) findViewById(R.id.image);
mWidthEdit = (EditText) findViewById(R.id.view_width);
mHeightEdit = (EditText) findViewById(R.id.view_height);
TextWatcher textWatcher = new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
ViewGroup.LayoutParams lp = mImageView.getLayoutParams();
if (lp != null) {
try {
mImageViewWidth = Integer.valueOf(mWidthEdit.getText().toString());
} catch (NumberFormatException e) {
mImageViewWidth = mDefaultSize;
}
try {
mImageViewHeight = Integer.valueOf(mHeightEdit.getText().toString());
} catch (NumberFormatException e) {
mImageViewHeight = mDefaultSize;
}
lp.width = mImageViewWidth;
lp.height = mImageViewHeight;
mImageView.setLayoutParams(lp);
}
}
};
mWidthEdit.addTextChangedListener(textWatcher);
mHeightEdit.addTextChangedListener(textWatcher);
Spinner scaleTypeSpinner = (Spinner) findViewById(R.id.scale_type);
final ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
R.array.scale_type, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
scaleTypeSpinner.setAdapter(adapter);
final SparseArray<ImageView.ScaleType> scaleTypeArray = new SparseArray<>();
scaleTypeArray.put(0, ImageView.ScaleType.MATRIX);
scaleTypeArray.put(1, ImageView.ScaleType.FIT_XY);
scaleTypeArray.put(2, ImageView.ScaleType.FIT_START);
scaleTypeArray.put(3, ImageView.ScaleType.FIT_CENTER);
scaleTypeArray.put(4, ImageView.ScaleType.FIT_END);
scaleTypeArray.put(5, ImageView.ScaleType.CENTER);
scaleTypeArray.put(6, ImageView.ScaleType.CENTER_CROP);
scaleTypeArray.put(7, ImageView.ScaleType.CENTER_INSIDE);
scaleTypeSpinner.setSelection(scaleTypeArray.indexOfValue(mImageView.getScaleType()));
scaleTypeSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
ImageView.ScaleType type = scaleTypeArray.get(position);
mImageView.setScaleType(type);
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
}
|
3e12f32ab451bceb8646e40be2a082be9bb0b771 | 12,205 | java | Java | src/main/java/frc/robot/subsystems/Vision.java | team2485/frc-2022 | 4cb5fdd2abc1b6189156cc8961c3c0551265f7b0 | [
"BSD-3-Clause"
] | 5 | 2022-01-16T04:05:04.000Z | 2022-03-04T23:17:43.000Z | src/main/java/frc/robot/subsystems/Vision.java | team2485/frc-2022 | 4cb5fdd2abc1b6189156cc8961c3c0551265f7b0 | [
"BSD-3-Clause"
] | null | null | null | src/main/java/frc/robot/subsystems/Vision.java | team2485/frc-2022 | 4cb5fdd2abc1b6189156cc8961c3c0551265f7b0 | [
"BSD-3-Clause"
] | 1 | 2022-01-17T17:05:02.000Z | 2022-01-17T17:05:02.000Z | 34.971347 | 157 | 0.634576 | 7,997 | package frc.robot.subsystems;
import static frc.robot.Constants.FieldConstants.*;
import static frc.robot.Constants.VisionConstants.*;
import edu.wpi.first.math.geometry.Rotation2d;
import edu.wpi.first.math.geometry.Translation2d;
import edu.wpi.first.networktables.EntryListenerFlags;
import edu.wpi.first.networktables.NetworkTableInstance;
import edu.wpi.first.util.datalog.DoubleArrayLogEntry;
import edu.wpi.first.wpilibj.DataLogManager;
import edu.wpi.first.wpilibj.DriverStation;
import edu.wpi.first.wpilibj.Timer;
import edu.wpi.first.wpilibj2.command.SubsystemBase;
import frc.team2485.WarlordsLib.math.CircleFitter;
import io.github.oblarg.oblog.Loggable;
import io.github.oblarg.oblog.annotations.*;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Consumer;
import org.photonvision.PhotonCamera;
import org.photonvision.common.hardware.VisionLEDMode;
import org.photonvision.targeting.PhotonPipelineResult;
import org.photonvision.targeting.PhotonTrackedTarget;
import org.photonvision.targeting.TargetCorner;
/**
* Much of this class is based on FRC 6328's vision code:
* https://github.com/Mechanical-Advantage/RobotCode2022/blob/f4fec2247e47195467eccd504fe44c674e45786a/src/main/java/frc/robot/subsystems/vision/Vision.java
*/
public class Vision extends SubsystemBase implements Loggable {
private PhotonCamera m_camera = new PhotonCamera(kCameraName);
public enum LEDSetMode {
kAlwaysOn,
kAlwaysOff,
kAuto
}
@Log private boolean m_LEDsOn = false;
private LEDSetMode m_LEDSetMode = LEDSetMode.kAuto;
private boolean m_forceLEDs = false;
private Consumer<TimestampedTranslation2d> m_translationConsumer;
private double m_lastCaptureTimestamp = 0.0;
private double m_imageCaptureTimestamp;
private double[] m_cornerX = new double[] {};
private double[] m_cornerY = new double[] {};
private Timer m_targetGraceTimer = new Timer(); // times amount of time since target loss
DoubleArrayLogEntry m_target1TopLeftCornerLog =
new DoubleArrayLogEntry(DataLogManager.getLog(), "/vision/target1/topLeft");
DoubleArrayLogEntry m_target1TopRightCornerLog =
new DoubleArrayLogEntry(DataLogManager.getLog(), "/vision/target1/topRight");
DoubleArrayLogEntry m_target1BottomLeftCornerLog =
new DoubleArrayLogEntry(DataLogManager.getLog(), "/vision/target1/bottomLeft");
DoubleArrayLogEntry m_target1BottomRightCornerLog =
new DoubleArrayLogEntry(DataLogManager.getLog(), "/vision/target1/bottomRight");
public Vision() {
m_targetGraceTimer.start();
NetworkTableInstance.getDefault()
.getEntry("/photonvision/" + kCameraName + "/latencyMillis")
.addListener(
event -> {
PhotonPipelineResult result = m_camera.getLatestResult();
double timestamp = Timer.getFPGATimestamp() - (result.getLatencyMillis() / 1000.0);
List<Double> cornerXList = new ArrayList<>();
List<Double> cornerYList = new ArrayList<>();
for (PhotonTrackedTarget target : result.getTargets()) {
for (TargetCorner corner : target.getCorners()) {
cornerXList.add(corner.x);
cornerYList.add(corner.y);
}
}
synchronized (this) {
m_imageCaptureTimestamp = timestamp;
m_cornerX = cornerXList.stream().mapToDouble(Double::doubleValue).toArray();
m_cornerY = cornerYList.stream().mapToDouble(Double::doubleValue).toArray();
}
},
EntryListenerFlags.kUpdate);
}
public void setLEDMode(LEDSetMode mode) {
this.m_LEDSetMode = mode;
}
@Log.ToString(name = "LED Set Mode", tabName = "RobotContainer")
public LEDSetMode getLEDSetMode() {
return m_LEDSetMode;
}
/**
* If current LED mode is Auto, turn to AlwaysOff. If current LED mode is AlwaysOff, turn to
* AlwaysOn. If current LED mode is AlwaysOn, turn to Auto.
*/
public void cycleLEDMode() {
System.out.println("Led mode: " + m_LEDSetMode);
switch (m_LEDSetMode) {
case kAuto:
this.setLEDMode(LEDSetMode.kAlwaysOff);
break;
case kAlwaysOff:
this.setLEDMode(LEDSetMode.kAlwaysOn);
break;
case kAlwaysOn:
this.setLEDMode(LEDSetMode.kAuto);
break;
default:
this.setLEDMode(LEDSetMode.kAuto);
break;
}
}
/** Use to enable LEDs continuously while override is "Auto" */
public void setForceLeds(boolean on) {
m_forceLEDs = on;
}
private void setLEDs(boolean enabled) {
m_camera.setLED(enabled ? VisionLEDMode.kOn : VisionLEDMode.kOff);
}
public void setTranslationConsumer(Consumer<TimestampedTranslation2d> consumer) {
m_translationConsumer = consumer;
}
@Override
public void periodic() {
// count targets if LEDs on
int targetCount = m_LEDsOn ? m_cornerX.length / 4 : 0;
// System.out.println("Target Count: " + targetCount);
// Update LED idle state
// Reset grace timer if targets found
if (targetCount > 0) {
m_targetGraceTimer.reset();
}
// Blink if no target found for more than grace period
boolean idleOn =
m_targetGraceTimer.get() < kTargetGraceSecs
|| Timer.getFPGATimestamp() % kBlinkPeriodSecs < kBlinkLengthSecs;
// Update LED mode based on supplier/idle state/DS state
switch (m_LEDSetMode) {
case kAlwaysOn:
m_LEDsOn = true;
break;
case kAlwaysOff:
m_LEDsOn = false;
break;
case kAuto:
if (m_forceLEDs) {
m_LEDsOn = true;
} else if (DriverStation.isDisabled()) {
m_LEDsOn = false;
} else if (DriverStation.isAutonomous()) {
m_LEDsOn = true;
} else {
m_LEDsOn = idleOn;
}
break;
default:
m_LEDsOn = false;
break;
}
this.setLEDs(m_LEDsOn);
// Don't update translation if no new image
if (m_imageCaptureTimestamp == m_lastCaptureTimestamp) {
return;
}
m_lastCaptureTimestamp = m_imageCaptureTimestamp;
// If we have enough targets, calculate camera to target translation
if (targetCount >= kMinTargetCount) {
List<Translation2d> cameraToTargetTranslations = new ArrayList<>();
for (int targetIndex = 0; targetIndex < targetCount; targetIndex++) {
List<Translation2d> corners = new ArrayList<>();
double totalX = 0.0, totalY = 0.0; // for averaging
for (int i = targetIndex * 4; i < targetIndex * 4 + 4; i++) {
if (i < m_cornerX.length && i < m_cornerY.length) {
// add x and y of corner to our translation matrix
corners.add(new Translation2d(m_cornerX[i], m_cornerY[i]));
totalX += m_cornerX[i];
totalY += m_cornerY[i];
}
}
Translation2d targetAvg = new Translation2d(totalX / 4, totalY / 4);
corners = sortCorners(corners, targetAvg);
for (int i = 0; i < corners.size(); i++) {
Translation2d cornerTranslation =
solveCameraToTargetTranslation(
corners.get(i), i < 2 ? kVisionTargetHeightUpper : kVisionTargetHeightLower);
if (cornerTranslation != null) {
cameraToTargetTranslations.add(cornerTranslation);
}
}
if (targetIndex == 0) {
m_target1TopLeftCornerLog.append(
new double[] {corners.get(0).getX(), corners.get(0).getY()});
m_target1TopRightCornerLog.append(
new double[] {corners.get(1).getX(), corners.get(1).getY()});
m_target1BottomLeftCornerLog.append(
new double[] {corners.get(2).getX(), corners.get(2).getY()});
m_target1BottomRightCornerLog.append(
new double[] {corners.get(3).getX(), corners.get(3).getY()});
}
}
if (cameraToTargetTranslations.size() >= kMinTargetCount * 4) {
Translation2d cameraToTargetCenterTranslation =
CircleFitter.fit(kVisionTargetRadius, cameraToTargetTranslations, kCircleFitPrecision);
m_translationConsumer.accept(
new TimestampedTranslation2d(
m_imageCaptureTimestamp - kExtraLatencySecs, cameraToTargetCenterTranslation));
}
}
}
/**
* Sorts list of corners to be in order: top left, top right, bottom left, bottom right
*
* @return
*/
private static List<Translation2d> sortCorners(
List<Translation2d> corners, Translation2d average) {
// Find top corners
Integer topLeftIndex = null;
Integer topRightIndex = null;
double minPosRads = Math.PI;
double minNegRads = Math.PI;
for (int i = 0; i < corners.size(); i++) {
Translation2d corner = corners.get(i);
double angleRad =
new Rotation2d(corner.getX() - average.getX(), average.getY() - corner.getY())
.minus(Rotation2d.fromDegrees(90))
.getRadians();
if (angleRad > 0) {
if (angleRad < minPosRads) {
minPosRads = angleRad;
topLeftIndex = i;
}
} else {
if (Math.abs(angleRad) < minNegRads) {
minNegRads = Math.abs(angleRad);
topRightIndex = i;
}
}
}
Integer lowerIndex1 = null, lowerIndex2 = null;
// Find lower corners (don't need left or right)
for (int i = 0; i < corners.size(); i++) {
boolean alreadySaved = false;
if (topLeftIndex != null) {
if (topLeftIndex.equals(i)) {
alreadySaved = true;
}
}
if (topRightIndex != null) {
if (topRightIndex.equals(i)) {
alreadySaved = true;
}
}
if (!alreadySaved) {
if (lowerIndex1 == null) {
lowerIndex1 = i;
} else {
lowerIndex2 = i;
}
}
}
// Produce final list
List<Translation2d> sortedCorners = new ArrayList();
if (topLeftIndex != null) {
sortedCorners.add(corners.get(topLeftIndex));
}
if (topRightIndex != null) {
sortedCorners.add(corners.get(topRightIndex));
}
if (lowerIndex1 != null) {
sortedCorners.add(corners.get(lowerIndex1));
}
if (lowerIndex2 != null) {
sortedCorners.add(corners.get(lowerIndex2));
}
return sortedCorners;
}
private Translation2d solveCameraToTargetTranslation(Translation2d corner, double targetHeight) {
double xPixels = corner.getX();
double yPixels = corner.getY();
// Robot frame of reference. Scaled -1 to 1.
double nY = -(xPixels - (double) kCameraPixelsX / 2) / ((double) kCameraPixelsX / 2);
double nZ = -(yPixels - (double) kCameraPixelsX / 2) / ((double) kCameraPixelsX / 2);
Translation2d xzPlaneTranslation =
new Translation2d(1, kCameraViewportRatioH / 2.0 * nZ).rotateBy(kCameraPitch);
double x = xzPlaneTranslation.getX();
double y = kCameraViewportRatioW / 2.0 * nY; // Y viewport from horizontal
double z = xzPlaneTranslation.getY();
double heightLensToTarget = kLensHeightMeters - targetHeight;
if ((z < 0.0) == (heightLensToTarget > 0.0)) {
double scaling = heightLensToTarget / -z;
double distanceLensToTarget = Math.hypot(x, y) * scaling;
Rotation2d targetPitchFromLens = new Rotation2d(x, y);
return new Translation2d(
distanceLensToTarget * targetPitchFromLens.getCos(),
distanceLensToTarget * targetPitchFromLens.getSin());
}
return null;
}
public static class TimestampedTranslation2d {
public final double timestamp;
public final Translation2d translation;
public TimestampedTranslation2d(double timestamp, Translation2d translation) {
this.timestamp = timestamp;
this.translation = translation;
}
}
}
|
3e12f3ed17dfadb50bf2c62bac983cfb723c2e87 | 612 | java | Java | src/main/java/idawi/ProgressRatio.java | lhogie/idawi | bee4750a67b68d4080c2945b71f85d2226afbeb8 | [
"Apache-2.0"
] | null | null | null | src/main/java/idawi/ProgressRatio.java | lhogie/idawi | bee4750a67b68d4080c2945b71f85d2226afbeb8 | [
"Apache-2.0"
] | null | null | null | src/main/java/idawi/ProgressRatio.java | lhogie/idawi | bee4750a67b68d4080c2945b71f85d2226afbeb8 | [
"Apache-2.0"
] | null | null | null | 16.540541 | 56 | 0.624183 | 7,998 | package idawi;
public class ProgressRatio extends ProgressInformation {
long target, progress;
public ProgressRatio(long target, long progress) {
this.target = target;
this.progress = progress;
}
public ProgressRatio() {
this(1, 0);
}
public double ratio() {
if (completed()) {
return 1;
}
else {
return progress / (double) target;
}
}
public boolean completed() {
return progress >= target;
}
@Override
public String toString() {
if (completed()) {
return "completed " + target + "/" + target;
}
else {
return (((int) (10000 * ratio())) / 100d) + "%";
}
}
} |
3e12f595c91c5641a5d5a0a4aba268fb03bbc1c5 | 1,621 | java | Java | sample-app/src/main/java/com/alimuzaffar/sample/widgets/AnimatedEditTextWidgetsActivity.java | josemg08/AnimatedEditText | db040ea037db8cb5ba5936822ff95bfa210e04fe | [
"Apache-2.0"
] | 487 | 2016-03-18T14:20:59.000Z | 2022-03-02T12:29:23.000Z | sample-app/src/main/java/com/alimuzaffar/sample/widgets/AnimatedEditTextWidgetsActivity.java | josemg08/AnimatedEditText | db040ea037db8cb5ba5936822ff95bfa210e04fe | [
"Apache-2.0"
] | 10 | 2016-03-23T12:39:54.000Z | 2019-10-25T17:43:06.000Z | sample-app/src/main/java/com/alimuzaffar/sample/widgets/AnimatedEditTextWidgetsActivity.java | josemg08/AnimatedEditText | db040ea037db8cb5ba5936822ff95bfa210e04fe | [
"Apache-2.0"
] | 62 | 2016-03-21T15:06:03.000Z | 2020-11-16T08:06:47.000Z | 32.42 | 125 | 0.703886 | 7,999 | package com.alimuzaffar.sample.widgets;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import com.alimuzaffar.lib.widgets.AnimatedEditText;
import com.alimuzaffar.lib.widgets.TextDrawable;
public class AnimatedEditTextWidgetsActivity extends AppCompatActivity {
private AnimatedEditText mTxtPopIn;
private AnimatedEditText mTxtBottomUp;
private AnimatedEditText mTxtRightIn;
private AnimatedEditText mTxtMiddleUp;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edit_text);
mTxtPopIn = (AnimatedEditText) findViewById(R.id.txt_pop_in);
mTxtBottomUp = (AnimatedEditText) findViewById(R.id.txt_bottom_up);
mTxtRightIn = (AnimatedEditText) findViewById(R.id.txt_right_in);
mTxtMiddleUp = (AnimatedEditText) findViewById(R.id.txt_middle_up);
EditText regular = (EditText) findViewById(R.id.txt_regular);
if (regular != null) {
regular.setCompoundDrawables(new TextDrawable(regular, "+61 "), null, new TextDrawable(regular, "\u2605"), null);
}
}
public void onClick_clear(View view) {
toggle(mTxtPopIn);
toggle(mTxtBottomUp);
toggle(mTxtRightIn);
toggle(mTxtMiddleUp);
}
public void toggle(AnimatedEditText v) {
if (TextUtils.isEmpty(v.getText())) {
v.setText("Hello World");
} else {
v.setText(null);
}
}
}
|
3e12f621a9427d770085671d517fc0ae402b8141 | 1,307 | java | Java | spring5_demo01/src/test/java/org/lxyqaq/spring5/TestSpring5.java | lxyqaq/SpringStudy | ae30298a7a30413f77e33018a3b1a45580b422ca | [
"Apache-2.0"
] | null | null | null | spring5_demo01/src/test/java/org/lxyqaq/spring5/TestSpring5.java | lxyqaq/SpringStudy | ae30298a7a30413f77e33018a3b1a45580b422ca | [
"Apache-2.0"
] | null | null | null | spring5_demo01/src/test/java/org/lxyqaq/spring5/TestSpring5.java | lxyqaq/SpringStudy | ae30298a7a30413f77e33018a3b1a45580b422ca | [
"Apache-2.0"
] | null | null | null | 23.890909 | 96 | 0.693303 | 8,000 | package org.lxyqaq.spring5;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;
/**
* @ClassName TestSpring5
* @Description TODO
* @Author lxyqaq @Email efpyi@example.com
* @Date 2021/1/1 17:53
* @Version 1.0
*/
public class TestSpring5 {
@Test
public void testAdd() {
//1.加载spring配置文件
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("bean1.xml");
//2.获取配置创建的对象
User user = applicationContext.getBean("user", User.class);
System.out.println(user);
user.add();
}
@Test
public void testBook1() {
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("bean1.xml");
Book book = applicationContext.getBean("book", Book.class);
System.out.println(book);
book.testDemo();
}
@Test
public void testOrders1() {
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("bean1.xml");
Orders orders = applicationContext.getBean("orders", Orders.class);
System.out.println(orders);
orders.ordersTest();
}
}
|
3e12f7602e75025b1164733ae5584425355a6cc8 | 623 | java | Java | ForgePluginBukkit/src/main/java/com/earth2me/minecraft/forgeplugin/util/Strings.java | Zenexer/ForgePlugin | d9d4010fc2d766dcdc85043aea6b5ef2e651a75c | [
"Unlicense"
] | 5 | 2017-05-20T02:32:37.000Z | 2021-04-03T08:42:45.000Z | ForgePluginBukkit/src/main/java/com/earth2me/minecraft/forgeplugin/util/Strings.java | Zenexer/ForgePlugin | d9d4010fc2d766dcdc85043aea6b5ef2e651a75c | [
"Unlicense"
] | 2 | 2018-07-02T17:08:29.000Z | 2019-12-31T01:15:05.000Z | ForgePluginBukkit/src/main/java/com/earth2me/minecraft/forgeplugin/util/Strings.java | Zenexer/ForgePlugin | d9d4010fc2d766dcdc85043aea6b5ef2e651a75c | [
"Unlicense"
] | 4 | 2018-03-19T18:19:17.000Z | 2020-09-05T12:59:53.000Z | 18.878788 | 66 | 0.600321 | 8,001 | package com.earth2me.minecraft.forgeplugin.util;
public final class Strings
{
private Strings()
{
}
public String join(final String delimiter, final String... args)
{
if (args == null || args.length < 1)
{
return "";
}
int length = delimiter.length() * (args.length - 1);
for (String string : args)
{
length += string.length();
}
final StringBuilder builder = new StringBuilder(length);
builder.append(args[0]);
for (int i = 1; i < args.length; i++)
{
builder.append(delimiter).append(args[i]);
}
return builder.toString().intern();
}
}
|
3e12f76ea93b4dc689272a0d7386d3adb661af22 | 571 | java | Java | mxlib.api/src/main/java/io/github/karlatemp/mxlib/classmodel/Nameable.java | Karlatemp/mxlib | c04d532ad177463dbc0647654bf30224eaa01da3 | [
"MIT"
] | 5 | 2021-01-30T05:26:15.000Z | 2021-08-31T06:11:06.000Z | mxlib.api/src/main/java/io/github/karlatemp/mxlib/classmodel/Nameable.java | Karlatemp/mxlib | c04d532ad177463dbc0647654bf30224eaa01da3 | [
"MIT"
] | 2 | 2021-05-15T15:44:37.000Z | 2021-06-15T14:45:44.000Z | mxlib.api/src/main/java/io/github/karlatemp/mxlib/classmodel/Nameable.java | Karlatemp/mxlib | c04d532ad177463dbc0647654bf30224eaa01da3 | [
"MIT"
] | 1 | 2021-05-15T15:42:24.000Z | 2021-05-15T15:42:24.000Z | 27.333333 | 99 | 0.74216 | 8,002 | /*
* Copyright (c) 2018-2021 Karlatemp. All rights reserved.
* @author Karlatemp <lyhxr@example.com> <https://github.com/Karlatemp>
*
* MXLib/MXLib.mxlib-api.main/Nameable.java
*
* Use of this source code is governed by the MIT license that can be found via the following link.
*
* https://github.com/Karlatemp/MxLib/blob/master/LICENSE
*/
package io.github.karlatemp.mxlib.classmodel;
import org.jetbrains.annotations.Contract;
import org.jetbrains.annotations.NotNull;
public interface Nameable {
@Contract(pure = true)
@NotNull String getName();
}
|
3e12f88ac0516be340f4560d964c260f80746874 | 4,328 | java | Java | core/src/main/java/com/digiquest/core/battle/dm20/DM20RomFactory.java | cfogrady/digiquest | 615adb13389a543dc808c5f37ab388fd29b12ac6 | [
"MIT"
] | null | null | null | core/src/main/java/com/digiquest/core/battle/dm20/DM20RomFactory.java | cfogrady/digiquest | 615adb13389a543dc808c5f37ab388fd29b12ac6 | [
"MIT"
] | null | null | null | core/src/main/java/com/digiquest/core/battle/dm20/DM20RomFactory.java | cfogrady/digiquest | 615adb13389a543dc808c5f37ab388fd29b12ac6 | [
"MIT"
] | null | null | null | 46.537634 | 183 | 0.660351 | 8,003 | package com.digiquest.core.battle.dm20;
import com.digiquest.core.digimon.Digimon;
import com.github.cfogrady.dcom.digimon.Attribute;
import com.github.cfogrady.dcom.digimon.Stage;
import com.github.cfogrady.dcom.digimon.dm20.DM20Attack;
import com.github.cfogrady.dcom.digimon.dm20.DM20IndexEntry;
import com.github.cfogrady.dcom.digimon.dm20.DM20Operation;
import com.github.cfogrady.dcom.digimon.dm20.DM20Rom;
import lombok.extern.slf4j.Slf4j;
import java.util.*;
import java.util.stream.Collectors;
@Slf4j
public class DM20RomFactory {
public static final int MAX_ATTACK_LEVEL = 14;
private final Map<Stage, List<DM20IndexEntry>> indexEntriesByStage;
public DM20RomFactory(List<DM20IndexEntry> dm20IndexEntries) {
indexEntriesByStage = buildMapFromIndexEntryList(dm20IndexEntries);
}
public static Map<Stage, List<DM20IndexEntry>> buildMapFromIndexEntryList(List<DM20IndexEntry> dm20IndexEntries) {
HashMap<Stage, List<DM20IndexEntry>> indexEntriesByStage = new HashMap<>();
dm20IndexEntries.forEach(entry -> {
if(!indexEntriesByStage.containsKey(entry.getStage())) {
List<DM20IndexEntry> stageList = new ArrayList<>();
stageList.add(entry);
indexEntriesByStage.put(entry.getStage(), stageList);
} else {
indexEntriesByStage.get(entry.getStage()).add(entry);
}
});
// Order the entries
for(Stage stage : indexEntriesByStage.keySet()) {
indexEntriesByStage.get(stage).sort(Comparator.comparingInt(DM20IndexEntry::getPower));
}
return indexEntriesByStage;
}
public Set<Integer> getPowersAtStage(Stage stage) {
return indexEntriesByStage.get(stage).stream().map(DM20IndexEntry::getPower).collect(Collectors.toSet());
}
public DM20IndexEntry getIndexForStageAndPower(Stage stage, int power) {
Optional<DM20IndexEntry> matchingIndexEntry = indexEntriesByStage.get(stage).stream().filter(entry -> entry.getPower() == power).findFirst();
if(matchingIndexEntry.isEmpty()) {
throw new IllegalArgumentException("Given power is not valid for any monster on the DM20");
}
return matchingIndexEntry.get();
}
public DM20IndexEntry getIndexForStageAndRelativePower(Stage stage, double relativePower) {
if(relativePower > 1.0 || relativePower < 0.0) {
throw new IllegalArgumentException("Relative power out of bounds. Must be between 0 and 1");
}
List<DM20IndexEntry> entriesForStage = indexEntriesByStage.get(stage);
int index = (int) Math.round((entriesForStage.size()-1) * relativePower);
return entriesForStage.get(index);
}
public DM20Rom createDM20Rom(Digimon digimon, float attackLevel) {
int attack = Math.round(attackLevel * MAX_ATTACK_LEVEL);
return createDM20Rom(digimon, attack);
}
public DM20Rom createDM20Rom(Digimon digimon, int attack, int strength) {
DM20IndexEntry indexEntry = getIndexForStageAndRelativePower(digimon.getStage(), digimon.getDefaultStageStrength());
return createDM20Rom(digimon.getName(), digimon.getStage(), digimon.getAttribute(), indexEntry, attack, strength, digimon.getStrongAttackDM20(), digimon.getWeakAttackDM20());
}
public DM20Rom createDM20Rom(String name, Stage stage, Attribute attribute, DM20IndexEntry indexEntry, int attack, int strength, DM20Attack strongAttack, DM20Attack weakAttack) {
int strengthPower = strength * 4;
DM20Rom rom = DM20Rom.builder()
.attack(attack)
.name(name.substring(0, 4).toCharArray())
.initiator(false)
.operation(DM20Operation.BATTLE)
.version(0)
.firstDigimon(DM20Rom.DigiStats.builder()
.attribute(attribute)
.index(indexEntry.getIndex())
.power(indexEntry.getPower() + strengthPower)
.strongShot(strongAttack.ordinal())
.weakShot(weakAttack.ordinal())
.build())
.build();
return rom;
}
}
|
3e12f8a178a9f3d44207bd01312f6a0df15064bc | 1,291 | java | Java | src/main/java/org/primeframework/mvc/control/FreeMarkerBodyProxy.java | prime-framework/prime-mvc | cb655ed5c20d989f1508aac4b9f549d9cb644285 | [
"Apache-2.0"
] | 3 | 2015-02-27T05:10:47.000Z | 2020-04-19T20:19:53.000Z | src/main/java/org/primeframework/mvc/control/FreeMarkerBodyProxy.java | prime-framework/prime-mvc | cb655ed5c20d989f1508aac4b9f549d9cb644285 | [
"Apache-2.0"
] | 8 | 2020-11-09T18:37:33.000Z | 2022-03-09T16:27:28.000Z | src/main/java/org/primeframework/mvc/control/FreeMarkerBodyProxy.java | prime-framework/prime-mvc | cb655ed5c20d989f1508aac4b9f549d9cb644285 | [
"Apache-2.0"
] | 2 | 2016-05-25T17:24:19.000Z | 2019-07-30T23:00:02.000Z | 26.895833 | 68 | 0.708753 | 8,004 | /*
* Copyright (c) 2001-2007, Inversoft Inc., All Rights Reserved
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the specific
* language governing permissions and limitations under the License.
*/
package org.primeframework.mvc.control;
import java.io.Writer;
import org.primeframework.mvc.PrimeException;
import freemarker.template.TemplateDirectiveBody;
/**
* This class is a proxy for the FreeMarker directive body.
*
* @author Brian Pontarelli
*/
public class FreeMarkerBodyProxy implements Body {
private final TemplateDirectiveBody body;
public FreeMarkerBodyProxy(TemplateDirectiveBody body) {
this.body = body;
}
/**
* {@inheritDoc}
*/
public void render(Writer writer) {
if (body != null) {
try {
body.render(writer);
} catch (Exception e) {
throw new PrimeException(e);
}
}
}
} |
3e12f8e7a400a86ad4bce7670d44a6ea27d59b7b | 5,095 | java | Java | app/src/main/java/org/wikipedia/edit/EditHandler.java | ramesh-kr/apps-android-wikipedia | 95dc57b795f538770fef07ee93f61455c37c14fd | [
"Apache-2.0"
] | 1 | 2019-10-18T22:51:52.000Z | 2019-10-18T22:51:52.000Z | app/src/main/java/org/wikipedia/edit/EditHandler.java | ramesh-kr/apps-android-wikipedia | 95dc57b795f538770fef07ee93f61455c37c14fd | [
"Apache-2.0"
] | 2 | 2020-07-17T09:40:17.000Z | 2021-05-09T07:26:00.000Z | app/src/main/java/org/wikipedia/edit/EditHandler.java | ramesh-kr/apps-android-wikipedia | 95dc57b795f538770fef07ee93f61455c37c14fd | [
"Apache-2.0"
] | 1 | 2019-12-16T12:42:29.000Z | 2019-12-16T12:42:29.000Z | 44.304348 | 120 | 0.682041 | 8,005 | package org.wikipedia.edit;
import android.content.Intent;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.widget.PopupMenu;
import org.json.JSONObject;
import org.wikipedia.Constants;
import org.wikipedia.R;
import org.wikipedia.WikipediaApp;
import org.wikipedia.analytics.ProtectedEditAttemptFunnel;
import org.wikipedia.auth.AccountUtil;
import org.wikipedia.bridge.CommunicationBridge;
import org.wikipedia.descriptions.DescriptionEditUtil;
import org.wikipedia.page.Page;
import org.wikipedia.page.PageFragment;
import org.wikipedia.page.Section;
import org.wikipedia.util.DimenUtil;
import org.wikipedia.util.log.L;
public class EditHandler implements CommunicationBridge.JSEventListener {
public static final int RESULT_REFRESH_PAGE = 1;
private final PageFragment fragment;
private ProtectedEditAttemptFunnel funnel;
private Page currentPage;
public EditHandler(PageFragment fragment, CommunicationBridge bridge) {
this.fragment = fragment;
bridge.addListener("editSectionClicked", this);
}
public void setPage(Page page) {
this.currentPage = page;
this.funnel = new ProtectedEditAttemptFunnel(WikipediaApp.getInstance(), page.getTitle().getWikiSite());
}
public void startEditingSection(int sectionID, @Nullable String highlightText) {
if (!currentPage.getPageProperties().canEdit()) {
showUneditableDialog();
return;
}
if (sectionID < 0 || sectionID >= currentPage.getSections().size()) {
L.w("Attempting to edit a mismatched section ID.");
return;
}
Section section = currentPage.getSections().get(sectionID);
Intent intent = new Intent(fragment.getActivity(), EditSectionActivity.class);
intent.setAction(EditSectionActivity.ACTION_EDIT_SECTION);
intent.putExtra(EditSectionActivity.EXTRA_SECTION_ID, section.getId());
intent.putExtra(EditSectionActivity.EXTRA_SECTION_HEADING, section.getHeading());
intent.putExtra(EditSectionActivity.EXTRA_TITLE, currentPage.getTitle());
intent.putExtra(EditSectionActivity.EXTRA_PAGE_PROPS, currentPage.getPageProperties());
intent.putExtra(EditSectionActivity.EXTRA_HIGHLIGHT_TEXT, highlightText);
fragment.startActivityForResult(intent, Constants.ACTIVITY_REQUEST_EDIT_SECTION);
}
public void showUneditableDialog() {
new AlertDialog.Builder(fragment.requireActivity())
.setCancelable(false)
.setTitle(R.string.page_protected_can_not_edit_title)
.setMessage(AccountUtil.isLoggedIn()
? R.string.page_protected_can_not_edit
: R.string.page_protected_can_not_edit_anon)
.setPositiveButton(R.string.protected_page_warning_dialog_ok_button_text, null)
.show();
funnel.log(currentPage.getPageProperties().getEditProtectionStatus());
}
@Override
public void onMessage(String messageType, JSONObject messagePayload) {
if (!fragment.isAdded()) {
return;
}
if (messageType.equals("editSectionClicked")) {
if (messagePayload.has("mainPencilClicked") && DescriptionEditUtil.isEditAllowed(currentPage)) {
View tempView = new View(fragment.requireContext());
tempView.setX(DimenUtil.dpToPx(messagePayload.optInt("x")));
tempView.setY(DimenUtil.dpToPx(messagePayload.optInt("y")) - fragment.getWebView().getScrollY());
((ViewGroup) fragment.getView()).addView(tempView);
PopupMenu menu = new PopupMenu(fragment.requireContext(), tempView, 0, 0, R.style.PagePopupMenu);
menu.getMenuInflater().inflate(R.menu.menu_page_header_edit, menu.getMenu());
menu.setOnMenuItemClickListener(new EditMenuClickListener());
menu.setOnDismissListener(menu1 -> ((ViewGroup) fragment.getView()).removeView(tempView));
menu.show();
} else if (messagePayload.has("editDescriptionClicked") && DescriptionEditUtil.isEditAllowed(currentPage)) {
fragment.verifyBeforeEditingDescription(null);
} else {
startEditingSection(messagePayload.optInt("sectionID"), null);
}
}
}
private class EditMenuClickListener implements PopupMenu.OnMenuItemClickListener {
@Override
public boolean onMenuItemClick(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_page_header_edit_description:
fragment.verifyBeforeEditingDescription(null);
return true;
case R.id.menu_page_header_edit_lead_section:
startEditingSection(0, null);
return true;
default:
return false;
}
}
}
}
|
3e12f90cc36fcca9592856cb5b1b9bf9850a53da | 4,157 | java | Java | core/camel-management/src/test/java/org/apache/camel/management/ManagedRouteStopAndFailTest.java | apiloqbc/camel | b5969c10c7eb59aec971c43853378629984b0766 | [
"Apache-2.0"
] | null | null | null | core/camel-management/src/test/java/org/apache/camel/management/ManagedRouteStopAndFailTest.java | apiloqbc/camel | b5969c10c7eb59aec971c43853378629984b0766 | [
"Apache-2.0"
] | 1 | 2022-03-31T14:32:11.000Z | 2022-03-31T14:32:11.000Z | core/camel-management/src/test/java/org/apache/camel/management/ManagedRouteStopAndFailTest.java | apiloqbc/camel | b5969c10c7eb59aec971c43853378629984b0766 | [
"Apache-2.0"
] | null | null | null | 38.137615 | 128 | 0.69834 | 8,006 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.management;
import java.util.Set;
import javax.management.MBeanServer;
import javax.management.ObjectName;
import org.apache.camel.Route;
import org.apache.camel.ServiceStatus;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.spi.RouteError;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.DisabledOnOs;
import org.junit.jupiter.api.condition.OS;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
@DisabledOnOs(OS.AIX)
public class ManagedRouteStopAndFailTest extends ManagementTestSupport {
@Test
public void testStopAndFailRoute() throws Exception {
// fire a message to get it running
getMockEndpoint("mock:result").expectedMessageCount(1);
template.sendBody("direct:start", "Hello World");
assertMockEndpointsSatisfied();
MBeanServer mbeanServer = getMBeanServer();
Set<ObjectName> set = mbeanServer.queryNames(new ObjectName("*:type=routes,*"), null);
assertEquals(1, set.size());
ObjectName on = set.iterator().next();
boolean registered = mbeanServer.isRegistered(on);
assertEquals(true, registered, "Should be registered");
String uri = (String) mbeanServer.getAttribute(on, "EndpointUri");
// the route has this starting endpoint uri
assertEquals("direct://start", uri);
// should be started
String state = (String) mbeanServer.getAttribute(on, "State");
assertEquals(ServiceStatus.Started.name(), state, "Should be started");
String uptime = (String) mbeanServer.getAttribute(on, "Uptime");
assertNotNull(uptime);
log.info("Uptime: {}", uptime);
long uptimeMillis = (Long) mbeanServer.getAttribute(on, "UptimeMillis");
assertTrue(uptimeMillis > 0);
String routeId = (String) mbeanServer.getAttribute(on, "RouteId");
mbeanServer.invoke(on, "stopAndFail", null, null);
registered = mbeanServer.isRegistered(on);
assertEquals(true, registered, "Should be registered");
// should be stopped, eg its removed
state = (String) mbeanServer.getAttribute(on, "State");
assertEquals(ServiceStatus.Stopped.name(), state, "Should be stopped");
uptime = (String) mbeanServer.getAttribute(on, "Uptime");
assertEquals("", uptime);
uptimeMillis = (Long) mbeanServer.getAttribute(on, "UptimeMillis");
assertEquals(0, uptimeMillis);
Route route = context.getRoute(routeId);
RouteError re = route.getLastError();
Assertions.assertNotNull(re);
Assertions.assertTrue(re.isUnhealthy());
Assertions.assertEquals(RouteError.Phase.STOP, re.getPhase());
Assertions.assertEquals("Route " + routeId + " is forced stopped and marked as failed", re.getException().getMessage());
}
@Override
protected RouteBuilder createRouteBuilder() throws Exception {
return new RouteBuilder() {
@Override
public void configure() throws Exception {
from("direct:start").delayer(10).to("log:foo").to("mock:result");
}
};
}
}
|
3e12f9a86862a7acdbcc793a8aaa4c3df6806954 | 889 | java | Java | Platform/Plugins/com.tle.platform.common/src/com/tle/core/plugins/SerializedBeanLocator.java | infiniticg/equella | 75ddd69bca3a94e213705dcfe90cf7077cc89872 | [
"Apache-2.0"
] | 1 | 2018-07-25T02:34:16.000Z | 2018-07-25T02:34:16.000Z | Platform/Plugins/com.tle.platform.common/src/com/tle/core/plugins/SerializedBeanLocator.java | infiniticg/equella | 75ddd69bca3a94e213705dcfe90cf7077cc89872 | [
"Apache-2.0"
] | null | null | null | Platform/Plugins/com.tle.platform.common/src/com/tle/core/plugins/SerializedBeanLocator.java | infiniticg/equella | 75ddd69bca3a94e213705dcfe90cf7077cc89872 | [
"Apache-2.0"
] | 1 | 2018-04-11T20:31:51.000Z | 2018-04-11T20:31:51.000Z | 24.027027 | 84 | 0.737908 | 8,007 | /*
* Copyright 2017 Apereo
*
* 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.tle.core.plugins;
import java.io.Serializable;
public class SerializedBeanLocator<T extends Serializable> implements BeanLocator<T>
{
private final T object;
public SerializedBeanLocator(T object)
{
this.object = object;
}
@Override
public T get()
{
return object;
}
}
|
3e12f9b6a752508080d382cfec459e73e7baa9b0 | 351 | java | Java | src/swai/location/data/Coordinate.java | swaiing/dripster-ws | e0ed4481c0efa18899091662fbfffac5d64888b9 | [
"MIT"
] | null | null | null | src/swai/location/data/Coordinate.java | swaiing/dripster-ws | e0ed4481c0efa18899091662fbfffac5d64888b9 | [
"MIT"
] | null | null | null | src/swai/location/data/Coordinate.java | swaiing/dripster-ws | e0ed4481c0efa18899091662fbfffac5d64888b9 | [
"MIT"
] | null | null | null | 16.714286 | 55 | 0.740741 | 8,008 | package swai.location.data;
public class Coordinate {
private final double latitude;
private final double longitude;
public Coordinate(double latitude, double longitude) {
this.latitude = latitude;
this.longitude = longitude;
}
public double getLatitude() {
return latitude;
}
public double getLongitude() {
return longitude;
}
} |
3e12fa1a8a22b4c3ef4bb94bc8f654e0439ac788 | 3,732 | java | Java | src/com/leidos/optimizer/OptimizerFileReader.java | OSADP/DFW-FRATIS-AOP | 1b22eed18f38511ac3f18a62d9a0cb99df4e8b98 | [
"Apache-2.0"
] | null | null | null | src/com/leidos/optimizer/OptimizerFileReader.java | OSADP/DFW-FRATIS-AOP | 1b22eed18f38511ac3f18a62d9a0cb99df4e8b98 | [
"Apache-2.0"
] | null | null | null | src/com/leidos/optimizer/OptimizerFileReader.java | OSADP/DFW-FRATIS-AOP | 1b22eed18f38511ac3f18a62d9a0cb99df4e8b98 | [
"Apache-2.0"
] | null | null | null | 26.657143 | 74 | 0.632637 | 8,009 | /**
Copyright 2015 Leidos Corp
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.leidos.optimizer;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import com.leidos.optimizer.data.ContainerMove;
import com.leidos.optimizer.data.Move;
import com.leidos.optimizer.data.Terminal;
public class OptimizerFileReader {
private String[] excludeList = new String[]{"CRAFTMADE INTL"};
public List<Move> readFile(String fileName) throws IOException{
List<Move> legMoves = new ArrayList<Move>();
File f = new File(fileName);
BufferedReader br = new BufferedReader(new FileReader(f));
String s = br.readLine();
s = br.readLine();
while (s != null) {
s = s.replaceAll("\"", "");
String[] line = s.split(",");
// Move m = new ContainerMove();
if(!isExcluded(line[3]) && !isExcluded(line[8])){
ContainerMove l = new ContainerMove();
l.setId(line[0]);
if(line.length > 29){
l.setContainerNumber(line[29]);
}
Terminal ft = new Terminal();
ft.setName(line[3]);
ft.setCity(line[5]);
ft.setState(line[6]);
ft.setZip(line[7]);
l.setFromTerminal(ft);
Terminal t = new Terminal();
t.setName(line[8]);
t.setCity(line[10]);
t.setState(line[11]);
t.setZip(line[12]);
l.setToTerminal(t);
l.setLegNumber(line[14]);
if (line[19] != null && !"".equals(line[19])
&& line[19].indexOf(':') > 0) {
l.setApptStart(Integer.parseInt(line[19].replaceAll(":", "")));
}
if (line[20] != null && !"".equals(line[20])) {
l.setApptEnd(Integer.parseInt(line[20].replaceAll(":", "")));
}
legMoves.add(l);
}
s = br.readLine();
}
return legMoves;
}
public List<Move> readEmptyFile(String fileName) throws IOException{
List<Move> legMoves = new ArrayList<Move>();
File f = new File(fileName);
BufferedReader br = new BufferedReader(new FileReader(f));
String s = br.readLine();
s = br.readLine();
while (s != null) {
s = s.replaceAll("\"", "");
String[] line = s.split(",");
// Move m = new ContainerMove();
if(!isExcluded(line[3]) && !isExcluded(line[8])){
ContainerMove l = new ContainerMove();
l.setId(line[0]);
if(line.length > 30){
l.setContainerNumber(line[30]);
}
Terminal ft = new Terminal();
ft.setName(line[3]);
ft.setCity(line[5]);
ft.setState(line[6]);
ft.setZip(line[7]);
l.setFromTerminal(ft);
Terminal t = new Terminal();
t.setName(line[8]);
t.setCity(line[10]);
t.setState(line[11]);
t.setZip(line[12]);
l.setToTerminal(t);
l.setLegNumber(line[14]);
if (line[19] != null && !"".equals(line[19])
&& line[19].indexOf(':') > 0) {
l.setApptStart(Integer.parseInt(line[19].replaceAll(":", "")));
}
if (line[20] != null && !"".equals(line[20])) {
l.setApptEnd(Integer.parseInt(line[20].replaceAll(":", "")));
}
legMoves.add(l);
}
s = br.readLine();
}
return legMoves;
}
private boolean isExcluded(String name){
for(String s:excludeList){
if(s.equalsIgnoreCase(name)){
return true;
}
}
return false;
}
}
|
3e12fa3340314361b47cc784fc26c27ef175a3e8 | 8,797 | java | Java | BLE_Cane_App/app/src/main/java/com/example/juan/ble_cane/IdActivity.java | joaquinballesteros/Smart-Cane | 6143562b1b34c87cb5118422393d3fdb361f47e2 | [
"CC-BY-4.0"
] | 1 | 2019-03-21T13:11:05.000Z | 2019-03-21T13:11:05.000Z | BLE_Cane_App/app/src/main/java/com/example/juan/ble_cane/IdActivity.java | joaquinballesteros/Smart-Cane | 6143562b1b34c87cb5118422393d3fdb361f47e2 | [
"CC-BY-4.0"
] | null | null | null | BLE_Cane_App/app/src/main/java/com/example/juan/ble_cane/IdActivity.java | joaquinballesteros/Smart-Cane | 6143562b1b34c87cb5118422393d3fdb361f47e2 | [
"CC-BY-4.0"
] | 1 | 2022-02-09T13:03:41.000Z | 2022-02-09T13:03:41.000Z | 36.201646 | 140 | 0.560532 | 8,010 | package com.example.juan.ble_cane;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.support.design.widget.TextInputEditText;
import android.support.design.widget.TextInputLayout;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.Toast;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
public class IdActivity extends AppCompatActivity {
private TextInputEditText editTextId;
private TextInputEditText editTextAge;
private TextInputLayout textInputId;
private TextInputLayout textInputAge;
private RadioButton radiobtnMale, radiobtnFemale,radiobtnRight, radiobtnLeft;
private Button btnSave, btnRaw, btnAct;
SimpleDateFormat dateStr = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
String fullPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Cane";
File dir;
File subdir;
OutputStream fOut;
File file;
String fDate;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_id);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
editTextId = (TextInputEditText) findViewById(R.id.editTextId);
editTextAge = (TextInputEditText) findViewById(R.id.editTextAge);
textInputId = (TextInputLayout) findViewById(R.id.text_input_layout_id);
textInputAge = (TextInputLayout) findViewById(R.id.text_input_layout_age);
radiobtnMale = (RadioButton) findViewById(R.id.male_radio_btn);
radiobtnFemale = (RadioButton) findViewById(R.id.female_radio_btn);
radiobtnRight = (RadioButton) findViewById(R.id.right_radio_btn);
radiobtnLeft = (RadioButton) findViewById(R.id.left_radio_btn);
btnSave = (Button) findViewById(R.id.buttonValidate);
btnRaw = (Button) findViewById(R.id.buttonRaw);
btnAct = (Button) findViewById(R.id.buttonActivity);
btnRaw.setEnabled(false);
btnAct.setEnabled(false);
try {
String nameSubdir;
int max = 0;
int temp;
dir = new File(fullPath);
if (!dir.exists()) {
dir.mkdirs();
} else {
File f = new File(fullPath);
File[] files = f.listFiles();
for(int i=0; i<files.length; i++) {
nameSubdir = files[i].toString();
nameSubdir = nameSubdir.replace(fullPath + "/@", "");
temp = Integer.valueOf(nameSubdir);
if (temp > max){
max = temp;
}
}
int index = Integer.valueOf(max) + 1;
editTextId.setText(String.valueOf(index));
}
} catch(Exception e) {
e.printStackTrace();
}
btnSave.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View view){
String strGender, strLaterality, strPaciente;
if(validate()){
if(radiobtnFemale.isChecked()){
strGender = "Female";
} else {
strGender = "Male";
}
if(radiobtnRight.isChecked()){
strLaterality = "Right";
} else {
strLaterality = "Left";
}
try {
subdir = new File(fullPath + "/@" + editTextId.getText());
if (!subdir.exists()) {
subdir.mkdirs();
}
fOut = null;
Date fileDate = new Date();
fDate = dateStr.format(fileDate)+".txt";
file = new File(fullPath + "/@" + editTextId.getText(), fDate);
file.createNewFile();
fOut = new FileOutputStream(file, true);
strPaciente = "ID: " + editTextId.getText() + "\n" + "Age: " + editTextAge.getText() + "\n" + "Gender: " + strGender
+ "\n" + "Laterality: " + strLaterality + "\n\n";
fOut.write(strPaciente.getBytes());
} catch (Exception e){
Log.e ("saveToExternalStorage()", e.getMessage());
}
try {
fOut.flush();
fOut.close();
} catch (IOException e) {
e.printStackTrace();
}
Toast.makeText(getApplicationContext(), "Pacient data saved", Toast.LENGTH_SHORT).show();
btnSave.setEnabled(false);
btnRaw.setEnabled(true);
btnAct.setEnabled(true);
}
}
});
btnAct.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View view){
launchActivity();
}
});
btnRaw.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View view){
launchRaw();
}
});
}
private void launchActivity(){
Intent intentAct = new Intent(this, BLEDataActivity.class);
intentAct.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intentAct.putExtra("textName", fDate);
intentAct.putExtra("textId", "/@" + editTextId.getText());
startActivity(intentAct);
finish();
}
private void launchRaw(){
Intent intentRaw = new Intent(this, RawActivity.class);
intentRaw.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intentRaw.putExtra("textName", fDate);
intentRaw.putExtra("textId", "/@" + editTextId.getText());
startActivity(intentRaw);
finish();
}
private boolean validate() {
String idError = null;
boolean validId, validAge, validGender, validLat;
if (TextUtils.isEmpty(editTextId.getText())) {
idError = getString(R.string.mandatory);
validId = false;
} else {
validId = true;
}
toggleTextInputLayoutError(textInputId, idError);
String ageError = null;
if (TextUtils.isEmpty(editTextAge.getText())) {
ageError = getString(R.string.mandatory);
validAge = false;
} else {
validAge = true;
}
toggleTextInputLayoutError(textInputAge, ageError);
if(!radiobtnFemale.isChecked() && !radiobtnMale.isChecked()){
radiobtnFemale.setError("Selec Item");
validGender = false;
} else {
radiobtnFemale.setError(null);
validGender = true;
}
if(!radiobtnRight.isChecked() && !radiobtnLeft.isChecked()){
radiobtnLeft.setError("Selec Item");
validLat = false;
} else {
radiobtnLeft.setError(null);
validLat = true;
}
clearFocus();
if(!validAge || !validGender || !validId || !validLat){
return false;
} else{
return true;
}
}
/**
* Display/hides TextInputLayout error.
*
* @param msg the message, or null to hide
*/
private static void toggleTextInputLayoutError(@NonNull TextInputLayout textInputLayout,
String msg) {
textInputLayout.setError(msg);
if (msg == null) {
textInputLayout.setErrorEnabled(false);
} else {
textInputLayout.setErrorEnabled(true);
}
}
private void clearFocus() {
View view = this.getCurrentFocus();
if (view != null && view instanceof EditText) {
InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context
.INPUT_METHOD_SERVICE);
inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(), 0);
view.clearFocus();
}
}
}
|
3e12fa3f22d0c80e3d32118c362163a78c578564 | 210 | java | Java | src/main/g8/src/main/java/$package__packaged$/app/Application.java | ldaume/java-guice-app | 0bca7c2f1579e09ff9582366df3cd4bae46c178a | [
"MIT"
] | null | null | null | src/main/g8/src/main/java/$package__packaged$/app/Application.java | ldaume/java-guice-app | 0bca7c2f1579e09ff9582366df3cd4bae46c178a | [
"MIT"
] | null | null | null | src/main/g8/src/main/java/$package__packaged$/app/Application.java | ldaume/java-guice-app | 0bca7c2f1579e09ff9582366df3cd4bae46c178a | [
"MIT"
] | null | null | null | 15 | 42 | 0.62381 | 8,011 | package $package$.app;
/**
* Executes the underlying application.
*
* @author leonard Daume
*/
public interface Application {
/**
* The entry point to the application.
*/
void start();
}
|
3e12fb451e0fbce6584eeed55c6928908d240866 | 3,769 | java | Java | src/test/java/org/jboss/community/sbs/plugin/jira/RemoteJiraManagerTest.java | jbossorg/jive-jira | 1b0eb5877e05707c1cb58c1a5b2a8297ebc47433 | [
"Apache-2.0"
] | null | null | null | src/test/java/org/jboss/community/sbs/plugin/jira/RemoteJiraManagerTest.java | jbossorg/jive-jira | 1b0eb5877e05707c1cb58c1a5b2a8297ebc47433 | [
"Apache-2.0"
] | 1 | 2015-01-07T14:04:20.000Z | 2015-01-07T14:04:20.000Z | src/test/java/org/jboss/community/sbs/plugin/jira/RemoteJiraManagerTest.java | jbossorg/jive-jira | 1b0eb5877e05707c1cb58c1a5b2a8297ebc47433 | [
"Apache-2.0"
] | null | null | null | 42.829545 | 158 | 0.660122 | 8,012 | /*
* JBoss, Home of Professional Open Source
* Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors
* as indicated by the @authors tag. All rights reserved.
*/
package org.jboss.community.sbs.plugin.jira;
import java.io.IOException;
import java.net.URISyntaxException;
import java.util.HashMap;
import java.util.Map;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class RemoteJiraManagerTest {
public static void main(String[] args) throws URISyntaxException, IOException {
String jiraBase = "https://issues.stage.jboss.org";
// System.out.println("build number:" + client.getMetadataClient().getServerInfo().claim().getBuildNumber());
// /rest/api/2/issue/ORG-2779
BasicAuthRestTemplate restTemplate = new BasicAuthRestTemplate("lkrzyzanek", "PASSWORD");
//
// ResponseEntity<JsonNode> issue = restTemplate.getForEntity(jiraBase + "/rest/api/2/issue/ORG-2779?fields=customfield_12310010", JsonNode.class);
//
// JsonNode values = issue.getBody().findValue("customfield_12310010");
// if (values != null && values.isArray() && values.size() > 0) {
//
// System.out.println(values.get(0).textValue());
// }
Map<String, Object> fields = new HashMap<>();
fields.put("customfield_12310010", "http://localhost:8080/docs/DOC-1001\nhttp://localhost:8080/docs/DOC-1011");
Map<String, Object> params = new HashMap<>();
params.put("fields", fields);
restTemplate.put(jiraBase + "/rest/api/2/issue/ORG-2779?notifyUsers=false",
params);
// ResponseEntity<JsonNode> resonse = restTemplate.getForEntity(
// jiraBase + "/rest/api/2/search?jql=updated >= -30m"
// + "&fields=customfield_12310010&fields=status",
// JsonNode.class);
//
// System.out.println(resonse.getBody().get("issues").findValue("statusCategory").get("key").asText());
// HttpResponse<JsonNode> response = Unirest.get(jiraBase + "/rest/api/2/issue/ORG-2779")
// .queryString("fields", "summary")
// .basicAuth("lkrzyzanek", "fuyJL71vp1")
// .asJson();
// System.out.println(response);
System.out.println("DONE");
}
@Test
public void testNormalizeJiraForumReference() {
RemoteJiraManager manager = new RemoteJiraManagerImpl();
assertEquals("http://seamframework.org/Community/AnotherInterceptorProblem",
manager.normalizeJiraForumReference("http://seamframework.org/Community/AnotherInterceptorProblem"));
assertEquals("https://developer.jboss.org/message/577806",
manager.normalizeJiraForumReference("https://developer.jboss.org/message/577806"));
assertEquals(
"http://netty-forums-and-mailing-lists.685743.n2.nabble.com/Netty-3-2-3-Final-released-tp5669985.html",
manager
.normalizeJiraForumReference("http://netty-forums-and-mailing-lists.685743.n2.nabble.com/Netty-3-2-3-Final-released-tp5669985.html"));
assertEquals("https://developer.jboss.org/message/550657#550657",
manager.normalizeJiraForumReference("https://developer.jboss.org/message/550657#550657"));
/* No more supported URL from nukes forums
assertEquals("https://community.jboss.org/thread/39512?tstart=0",
manager.normalizeJiraForumReference("http://www.jboss.org/index.html?module=bb&op=viewtopic&t=152864"));
*/
assertEquals("https://developer.jboss.org/wiki/SecureTheJmxConsole",
manager.normalizeJiraForumReference("http://www.jboss.org/community/docs/DOC-12190"));
}
}
|
3e12fb47519c2b25309cecbb8f53c850c7457b48 | 9,856 | java | Java | activemq-unit-tests/src/test/java/org/apache/activemq/store/StoreOrderTest.java | gemmellr/activemq | 5bd2abf85dbda14bf41f54d09af4866e814f931f | [
"Apache-2.0"
] | 2,073 | 2015-01-01T15:27:57.000Z | 2022-03-31T09:08:51.000Z | activemq-unit-tests/src/test/java/org/apache/activemq/store/StoreOrderTest.java | gemmellr/activemq | 5bd2abf85dbda14bf41f54d09af4866e814f931f | [
"Apache-2.0"
] | 338 | 2015-01-05T17:50:20.000Z | 2022-03-31T17:46:12.000Z | activemq-unit-tests/src/test/java/org/apache/activemq/store/StoreOrderTest.java | gemmellr/activemq | 5bd2abf85dbda14bf41f54d09af4866e814f931f | [
"Apache-2.0"
] | 1,498 | 2015-01-03T10:58:42.000Z | 2022-03-28T05:11:21.000Z | 35.970803 | 107 | 0.649858 | 8,013 | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.activemq.store;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import javax.jms.ConnectionFactory;
import javax.jms.Destination;
import javax.jms.MessageConsumer;
import javax.jms.MessageProducer;
import javax.jms.Session;
import javax.jms.TextMessage;
import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.activemq.broker.BrokerService;
import org.apache.activemq.broker.region.policy.PolicyEntry;
import org.apache.activemq.broker.region.policy.PolicyMap;
import org.apache.activemq.command.ActiveMQQueue;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
// https://issues.apache.org/activemq/browse/AMQ-2594
public abstract class StoreOrderTest {
private static final Logger LOG = LoggerFactory.getLogger(StoreOrderTest.class);
protected BrokerService broker;
private ActiveMQConnection connection;
public Destination destination = new ActiveMQQueue("StoreOrderTest?consumer.prefetchSize=0");
protected abstract void setPersistentAdapter(BrokerService brokerService) throws Exception;
protected void dumpMessages() throws Exception {}
public class TransactedSend implements Runnable {
private CountDownLatch readyForCommit;
private CountDownLatch firstDone;
private boolean first;
private Session session;
private MessageProducer producer;
public TransactedSend(CountDownLatch readyForCommit,
CountDownLatch firstDone, boolean b) throws Exception {
this.readyForCommit = readyForCommit;
this.firstDone = firstDone;
this.first = b;
session = connection.createSession(true, Session.SESSION_TRANSACTED);
producer = session.createProducer(destination);
}
public void run() {
try {
if (!first) {
firstDone.await(30, TimeUnit.SECONDS);
}
producer.send(session.createTextMessage(first ? "first" : "second"));
if (first) {
firstDone.countDown();
}
readyForCommit.countDown();
} catch (Exception e) {
e.printStackTrace();
fail("unexpected ex on run " + e);
}
}
public void commit() throws Exception {
session.commit();
session.close();
}
}
@Before
public void setup() throws Exception {
broker = createBroker();
initConnection();
}
public void initConnection() throws Exception {
ConnectionFactory connectionFactory = new ActiveMQConnectionFactory("vm://localhost?create=false");
connection = (ActiveMQConnection) connectionFactory.createConnection();
connection.setWatchTopicAdvisories(false);
connection.start();
}
@After
public void stopBroker() throws Exception {
if (connection != null) {
connection.close();
}
if (broker != null) {
broker.stop();
}
}
@Test
public void testCompositeSendReceiveAfterRestart() throws Exception {
destination = new ActiveMQQueue("StoreOrderTest,SecondStoreOrderTest");
enqueueOneMessage();
LOG.info("restart broker");
stopBroker();
broker = createRestartedBroker();
dumpMessages();
initConnection();
destination = new ActiveMQQueue("StoreOrderTest");
assertNotNull("got one message from first dest", receiveOne());
dumpMessages();
destination = new ActiveMQQueue("SecondStoreOrderTest");
assertNotNull("got one message from second dest", receiveOne());
}
@Test
public void validateUnorderedTxCommit() throws Exception {
Executor executor = Executors.newCachedThreadPool();
CountDownLatch readyForCommit = new CountDownLatch(2);
CountDownLatch firstDone = new CountDownLatch(1);
TransactedSend first = new TransactedSend(readyForCommit, firstDone, true);
TransactedSend second = new TransactedSend(readyForCommit, firstDone, false);
executor.execute(first);
executor.execute(second);
assertTrue("both started", readyForCommit.await(20, TimeUnit.SECONDS));
LOG.info("commit out of order");
// send interleaved so sequence id at time of commit could be reversed
second.commit();
// force usage over the limit before second commit to flush cache
enqueueOneMessage();
// can get lost in the cursor as it is behind the last sequenceId that was cached
first.commit();
LOG.info("send/commit done..");
dumpMessages();
String received1, received2, received3 = null;
if (true) {
LOG.info("receive and rollback...");
Session session = connection.createSession(true, Session.SESSION_TRANSACTED);
received1 = receive(session);
received2 = receive(session);
received3 = receive(session);
assertEquals("second", received1);
assertEquals("middle", received2);
assertEquals("first", received3);
session.rollback();
session.close();
}
LOG.info("restart broker");
stopBroker();
broker = createRestartedBroker();
initConnection();
if (true) {
LOG.info("receive and rollback after restart...");
Session session = connection.createSession(true, Session.SESSION_TRANSACTED);
received1 = receive(session);
received2 = receive(session);
received3 = receive(session);
assertEquals("second", received1);
assertEquals("middle", received2);
assertEquals("first", received3);
session.rollback();
session.close();
}
LOG.info("receive and ack each message");
received1 = receiveOne();
received2 = receiveOne();
received3 = receiveOne();
assertEquals("second", received1);
assertEquals("middle", received2);
assertEquals("first", received3);
}
private void enqueueOneMessage() throws Exception {
Session session = connection.createSession(true, Session.SESSION_TRANSACTED);
MessageProducer producer = session.createProducer(destination);
producer.send(session.createTextMessage("middle"));
session.commit();
session.close();
}
private String receiveOne() throws Exception {
Session session = connection.createSession(true, Session.SESSION_TRANSACTED);
String received = receive(session);
session.commit();
session.close();
return received;
}
private String receive(Session session) throws Exception {
MessageConsumer consumer = session.createConsumer(destination);
String result = null;
TextMessage message = (TextMessage) consumer.receive(5000);
if (message != null) {
LOG.info("got message: " + message);
result = message.getText();
}
consumer.close();
return result;
}
protected BrokerService createBroker() throws Exception {
boolean deleteMessagesOnStartup = true;
return startBroker(deleteMessagesOnStartup);
}
protected BrokerService createRestartedBroker() throws Exception {
boolean deleteMessagesOnStartup = false;
return startBroker(deleteMessagesOnStartup);
}
protected BrokerService startBroker(boolean deleteMessagesOnStartup) throws Exception {
BrokerService newBroker = new BrokerService();
configureBroker(newBroker);
newBroker.setDeleteAllMessagesOnStartup(deleteMessagesOnStartup);
newBroker.start();
return newBroker;
}
protected void configureBroker(BrokerService brokerService) throws Exception {
setPersistentAdapter(brokerService);
brokerService.setAdvisorySupport(false);
PolicyMap map = new PolicyMap();
PolicyEntry defaultEntry = new PolicyEntry();
defaultEntry.setMemoryLimit(1024*3);
defaultEntry.setCursorMemoryHighWaterMark(68);
defaultEntry.setExpireMessagesPeriod(0);
map.setDefaultEntry(defaultEntry);
brokerService.setDestinationPolicy(map);
}
}
|
3e12fba7f0640dba20a8306e33d2e7d058766fe1 | 497 | java | Java | src/main/java/io/ytong/stanfordalgorithm/c1w1/Solution.java | David-Tong/stanford-algorithm-specialization | 5e6d19ed71efc35093ffa01218809a4a4379413e | [
"Apache-2.0"
] | null | null | null | src/main/java/io/ytong/stanfordalgorithm/c1w1/Solution.java | David-Tong/stanford-algorithm-specialization | 5e6d19ed71efc35093ffa01218809a4a4379413e | [
"Apache-2.0"
] | null | null | null | src/main/java/io/ytong/stanfordalgorithm/c1w1/Solution.java | David-Tong/stanford-algorithm-specialization | 5e6d19ed71efc35093ffa01218809a4a4379413e | [
"Apache-2.0"
] | null | null | null | 24.85 | 68 | 0.647887 | 8,014 | package io.ytong.stanfordalgorithm.c1w1;
public class Solution {
private Helper helper = new Helper();
public String multiply(String num1, String num2) throws Exception {
String result = "";
for(int j=num2.length()-1; j>=0; j--) {
char ch = num2.charAt(j);
String temp = helper.stringMultiply(String.valueOf(ch), num1);
int padding = num2.length() - j;
for (int i=1; i<padding; i++) {
temp += "0";
}
result = helper.stringAdd(result, temp);
}
return result;
}
}
|
3e12fc38570c6ac24ba037c2118da8b8063692bf | 311 | java | Java | fhir-registry/src/main/java/com/ibm/fhir/registry/spi/FHIRRegistryResourceProvider.java | kant/FHIR | fb1d933e3b37b556160bb8252b161d349a038bb9 | [
"Apache-2.0"
] | null | null | null | fhir-registry/src/main/java/com/ibm/fhir/registry/spi/FHIRRegistryResourceProvider.java | kant/FHIR | fb1d933e3b37b556160bb8252b161d349a038bb9 | [
"Apache-2.0"
] | null | null | null | fhir-registry/src/main/java/com/ibm/fhir/registry/spi/FHIRRegistryResourceProvider.java | kant/FHIR | fb1d933e3b37b556160bb8252b161d349a038bb9 | [
"Apache-2.0"
] | null | null | null | 20.733333 | 59 | 0.768489 | 8,015 | /*
* (C) Copyright IBM Corp. 2019
*
* SPDX-License-Identifier: Apache-2.0
*/
package com.ibm.fhir.registry.spi;
import java.util.Collection;
import com.ibm.fhir.registry.resource.FHIRRegistryResource;
public interface FHIRRegistryResourceProvider {
Collection<FHIRRegistryResource> getResources();
} |
3e12fcb4337b36a3aa90f250daf1696f9199d694 | 17,010 | java | Java | app/src/main/java/ca/brocku/kt13nh/Student_Connect/qa_components/QaDisplay.java | RonnyMBrock/StudentConnect | 60abe5f38cc6875430c1cf64d653e0afedb8dcb6 | [
"MIT"
] | null | null | null | app/src/main/java/ca/brocku/kt13nh/Student_Connect/qa_components/QaDisplay.java | RonnyMBrock/StudentConnect | 60abe5f38cc6875430c1cf64d653e0afedb8dcb6 | [
"MIT"
] | null | null | null | app/src/main/java/ca/brocku/kt13nh/Student_Connect/qa_components/QaDisplay.java | RonnyMBrock/StudentConnect | 60abe5f38cc6875430c1cf64d653e0afedb8dcb6 | [
"MIT"
] | null | null | null | 40.987952 | 98 | 0.614051 | 8,016 | package ca.brocku.kt13nh.Student_Connect.qa_components;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.provider.OpenableColumns;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Editable;
import android.text.InputFilter;
import android.text.TextWatcher;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.bumptech.glide.Glide;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.ChildEventListener;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import ca.brocku.kt13nh.Student_Connect.R;
import ca.brocku.kt13nh.Student_Connect.chatroom_components.Chatroom;
import ca.brocku.kt13nh.Student_Connect.chatroom_components.ChatroomSettings;
public class QaDisplay extends AppCompatActivity {
public static final String ANONYMOUS = "anonymous";
public static final int DEFAULT_MSG_LENGTH_LIMIT = 2048;
private static final int RC_PHOTO_PICKER = 2;
private static final int RC_FILE_PICKER = 1212;
private static final int RC_SETTINGS = 1;
private ListView mAnswerListView;
private AnswerAdapter mAnswerAdapter;
private ImageButton mPhotoPickerButton;
private ImageButton mFilePickerButton;
private EditText mAnswerEditText;
private Button mSendButton;
private String displayName;
private String mUsername;
private FirebaseDatabase mFirebaseDatabase;
private DatabaseReference mDatabaseReference;
private DatabaseReference mCurrentUserReference;
private DatabaseReference mAnswersDatabaseReference;
private ChildEventListener mChildEventListener;
private FirebaseStorage mFirebaseStorage;
private StorageReference mImagesStorageReference;
private StorageReference mFilesStorageReference;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_qa_display);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
Intent intent = getIntent();
setTitle(intent.getStringExtra("title"));
initializeFirebaseComponents();
attachDatabaseReadListener();
initializeComponents();
attachListeners();
}
@Override
/**
* shows report button when an answer is selected
*/
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenu.ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
if (v.getId() == R.id.answersListView) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.report_menu, menu);
}
}
@Override
/**
* incrementing report counter for the user whose commented was reported
*/
public boolean onContextItemSelected(MenuItem item) {
AdapterView.AdapterContextMenuInfo info =
(AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
String userToReport = ((Answer) mAnswerListView.getItemAtPosition((int) info.id))
.getUser();
switch (item.getItemId()) {
case R.id.report:
if (mUsername.equals(userToReport))
Toast.makeText(QaDisplay.this, "You cannot report yourself",
Toast.LENGTH_SHORT);
else {
String userToReportFirstName = userToReport.split(" ")[0];
mCurrentUserReference.getParent()
.child("first_name").equalTo(userToReportFirstName).getRef()
.child("last_name");
}
return true;
default:
return super.onContextItemSelected(item);
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.chatroom_settings, menu);
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
finish();
return true;
case R.id.chatSettings:
//Goes to settings page
Intent settingsIntent = new Intent(QaDisplay.this,
QaDisplaySettings.class);
if (displayName.equals(ANONYMOUS))
settingsIntent.putExtra("anonymous", true);
else
settingsIntent.putExtra("anonymous", false);
startActivityForResult(settingsIntent, RC_SETTINGS);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
@Override
/**
* Opens picture/file selecter when file upload or picture upload is pressed
*/
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == RC_SETTINGS) {
//Sets display name to anonymous if user selected Post As Anonymous
if (data.getBooleanExtra("anonymous", false) == true)
displayName = ANONYMOUS;
else
displayName = mUsername;
} else if (requestCode == RC_PHOTO_PICKER) {
Uri selectedImageUri = data.getData();
//Get a reference to store file at Images/<FILENAME>
StorageReference imageRef = mImagesStorageReference.child(
selectedImageUri.getLastPathSegment());
//Upload file to Firebase storage
imageRef.putFile(selectedImageUri).addOnSuccessListener(this,
new OnSuccessListener<UploadTask.TaskSnapshot>() {
@Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Uri downloadUrl = taskSnapshot.getDownloadUrl();
Answer answer = new Answer(null, displayName,
downloadUrl.toString(), null, null);
mAnswersDatabaseReference.push().setValue(answer);
}
});
} else if (requestCode == RC_FILE_PICKER) {
Uri selectedFileUri = data.getData();
String uriString = selectedFileUri.toString();
//Find the name of the file selected by the user
File myFile = new File(uriString);
String displayName = null;
if (uriString.startsWith("content://")) {
Cursor cursor = null;
try {
cursor = this.getContentResolver().query(selectedFileUri, null,
null, null,
null);
if (cursor != null && cursor.moveToFirst()) {
displayName = cursor.getString(cursor.getColumnIndex
(OpenableColumns.DISPLAY_NAME));
}
} finally {
cursor.close();
}
} else if (uriString.startsWith("file://")) {
displayName = myFile.getName();
}
//Get a reference to store file at Files/<FILENAME>
final String fileName = displayName;
StorageReference fileRef = mFilesStorageReference.child(
selectedFileUri.getLastPathSegment());
final String uploadedBy = this.displayName;
//Add answer object containing the user, name of the selected file, and the url to
// its location in Firebase Storage to the database
fileRef.putFile(selectedFileUri).addOnSuccessListener(this,
new OnSuccessListener<UploadTask.TaskSnapshot>() {
@Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Uri downloadUrl = taskSnapshot.getDownloadUrl();
Answer answer = new Answer(null, uploadedBy, null,
fileName, downloadUrl.toString());
mAnswersDatabaseReference.push().setValue(answer);
}
});
}
}
}
/**
* Initializes all Firebase components like DatabaseReferences, FirebaseStorage etc.
*/
private void initializeFirebaseComponents() {
mFirebaseDatabase = FirebaseDatabase.getInstance();
mDatabaseReference = mFirebaseDatabase.getReference();
mFirebaseStorage = FirebaseStorage.getInstance();
FirebaseUser currentUser = FirebaseAuth.getInstance().getCurrentUser();
mCurrentUserReference = mDatabaseReference.child("User").child(currentUser.getUid());
String questionID = getIntent().getStringExtra("questionID");
mAnswersDatabaseReference = mDatabaseReference.child("Questions")
.child(questionID).child("answers");
mImagesStorageReference = mFirebaseStorage.getReference().child("Images");
mFilesStorageReference = mFirebaseStorage.getReference().child("Files");
}
/**
* Initializes all TextViews, ListViews, Buttons etc
*/
private void initializeComponents() {
//Set question details at top of activity
TextView mAskerTextView = (TextView) findViewById(R.id.askerTextView);
TextView mQuestionTimeTextView = (TextView) findViewById(R.id.questionTimeTextView);
TextView mQuestionTextView = (TextView) findViewById(R.id.questionTextView);
Intent intent = getIntent();
mAskerTextView.setText(intent.getStringExtra("askedBy"));
mQuestionTimeTextView.setText(intent.getStringExtra("time"));
mQuestionTextView.setText(intent.getStringExtra("description"));
String imageUrl = intent.getStringExtra("imageUrl");
if (!imageUrl.equals("")) {
ImageView photoImageView = (ImageView) findViewById(R.id.questionImageView);
photoImageView.setVisibility(View.VISIBLE);
Glide.with(photoImageView.getContext())
.load(imageUrl)
.into(photoImageView);
}
// Initialize references to views
mAnswerListView = (ListView) findViewById(R.id.answersListView);
mPhotoPickerButton = (ImageButton) findViewById(R.id.qaPhotoPickerButton);
mFilePickerButton = (ImageButton) findViewById(R.id.qaFilePickerButton);
mAnswerEditText = (EditText) findViewById(R.id.answerEditText);
mSendButton = (Button) findViewById(R.id.qaSendButton);
// Initialize answers ListView and its adapter
List<Answer> answers = new ArrayList<>();
mAnswerAdapter = new AnswerAdapter(this, R.layout.item_answer, answers);
mAnswerListView.setAdapter(mAnswerAdapter);
}
/**
* Attaches the child event listener to the answers table in the database.
* When a new answer is added to the answers for the current question, the qa view is
* updated to contain the new answer
*/
private void attachDatabaseReadListener() {
if (mChildEventListener == null) {
mChildEventListener = new ChildEventListener() {
@Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
Answer answer = dataSnapshot.getValue(Answer.class);
mAnswerAdapter.add(answer);
}
@Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
}
@Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
@Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
};
mAnswersDatabaseReference.addChildEventListener(mChildEventListener);
}
}
/**
* Attaches all other listeners to components in the activity
*/
private void attachListeners() {
mCurrentUserReference.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
mUsername = dataSnapshot.child("first_name").getValue().toString() + " " +
dataSnapshot.child("last_name").getValue().toString();
displayName = mUsername;
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
//Selecting an answer in the answer list view will give the option to report
mAnswerListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
view.showContextMenu();
}
});
// ImagePickerButton shows an image picker to upload a image for an answer
mPhotoPickerButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// TODO: Fire an intent to show an image picker
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("image/jpeg");
intent.putExtra(Intent.EXTRA_LOCAL_ONLY, true);
startActivityForResult(Intent.createChooser(intent, "Complete action using"),
RC_PHOTO_PICKER);
}
});
mFilePickerButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
// TODO: Fire an intent to show an image picker
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("application/*");
intent.putExtra(Intent.EXTRA_LOCAL_ONLY, true);
startActivityForResult(Intent.createChooser(intent, "Complete action using"),
RC_FILE_PICKER);
}
});
// Enable Send button when there's text to send
mAnswerEditText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
@Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
if (charSequence.toString().trim().length() > 0) {
mSendButton.setEnabled(true);
} else {
mSendButton.setEnabled(false);
}
}
@Override
public void afterTextChanged(Editable editable) {
}
});
//limit answer to character limit defined by DEFAULT_MSG_LENGTH_LIMIT
mAnswerEditText.setFilters(new InputFilter[]
{new InputFilter.LengthFilter(DEFAULT_MSG_LENGTH_LIMIT)});
// Send button sends a answer and clears the EditText
mSendButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Answer answer = new Answer(mAnswerEditText.getText().toString(), displayName,
null, null, null);
mAnswersDatabaseReference.push().setValue(answer);
// Clear input box
mAnswerEditText.setText("");
}
});
}
}
|
3e12fd33fa07181c3327a0582c429d43169ba4ef | 6,054 | java | Java | zc-elasticsearch-spring-boot-starter/src/main/java/com/zhengcheng/data/elasticsearch/metadata/DocumentInfoHelper.java | zhangquansheng/zhengcheng-parent | 401d6fc8be86c23e977bf6ff82ca0e0cc75dd41c | [
"Apache-2.0"
] | 5 | 2020-08-20T06:37:06.000Z | 2021-02-25T05:42:59.000Z | zc-elasticsearch-spring-boot-starter/src/main/java/com/zhengcheng/data/elasticsearch/metadata/DocumentInfoHelper.java | zhangquansheng/zhengcheng-parent | 401d6fc8be86c23e977bf6ff82ca0e0cc75dd41c | [
"Apache-2.0"
] | 3 | 2021-07-02T18:55:13.000Z | 2022-03-08T03:34:45.000Z | zc-elasticsearch-spring-boot-starter/src/main/java/com/zhengcheng/data/elasticsearch/metadata/DocumentInfoHelper.java | zhangquansheng/zhengcheng-parent | 401d6fc8be86c23e977bf6ff82ca0e0cc75dd41c | [
"Apache-2.0"
] | 1 | 2022-03-08T03:02:53.000Z | 2022-03-08T03:02:53.000Z | 29.105769 | 112 | 0.595144 | 8,017 | package com.zhengcheng.data.elasticsearch.metadata;
import cn.hutool.core.util.ReflectUtil;
import cn.hutool.core.util.StrUtil;
import com.zhengcheng.data.elasticsearch.annotations.Document;
import com.zhengcheng.data.elasticsearch.annotations.Id;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.ClassUtils;
import java.lang.reflect.Field;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
/**
* 文档反射信息辅助类
*
* @author quansheng1.zhang
* @since 2021/6/16 11:08
*/
@Slf4j
public class DocumentInfoHelper {
/**
* 储存反射类文档信息
*/
private static final Map<Class<?>, DocumentInfo> DOCUMENT_INFO_CACHE = new ConcurrentHashMap<>();
/**
* 默认序列化版本uid
*/
private static final String SERIAL_VERSION_UID = "serialVersionUID";
/**
* <p>
* 获取实体映射文档信息
* </p>
*
* @param clazz 反射实体类
* @return 数据库文档反射信息
*/
public static DocumentInfo getDocumentInfo(Class<?> clazz) {
if (clazz == null || clazz == String.class) {
return null;
}
DocumentInfo documentInfo = DOCUMENT_INFO_CACHE.get(ClassUtils.getUserClass(clazz));
if (null != documentInfo) {
return documentInfo;
}
// 尝试获取父类缓存
Class<?> currentClass = clazz;
while (null == documentInfo && Object.class != currentClass) {
currentClass = currentClass.getSuperclass();
documentInfo = DOCUMENT_INFO_CACHE.get(ClassUtils.getUserClass(currentClass));
}
if (documentInfo != null) {
DOCUMENT_INFO_CACHE.put(ClassUtils.getUserClass(clazz), documentInfo);
}
return documentInfo;
}
/**
* <p>
* 实体类反射获取文档信息【初始化】
* </p>
*
* @param clazz 反射实体类
* @return 数据库文档反射信息
*/
public synchronized static DocumentInfo initDocumentInfo(Class<?> clazz) {
DocumentInfo documentInfo = DOCUMENT_INFO_CACHE.get(clazz);
if (documentInfo != null) {
return documentInfo;
}
/* 没有获取到缓存信息,则初始化 */
documentInfo = new DocumentInfo(clazz);
/* 初始化文档索引相关 */
initDocumentIndex(clazz, documentInfo);
/* 初始化字段相关 */
initTableFields(clazz, documentInfo);
/* 放入缓存 */
DOCUMENT_INFO_CACHE.put(clazz, documentInfo);
return documentInfo;
}
/**
* <p>
* 初始化 文档数据库类型,文档索引名
* </p>
*
* @param clazz 实体类
* @param documentInfo 数据库文档反射信息
*/
private static void initDocumentIndex(Class<?> clazz, DocumentInfo documentInfo) {
Document document = clazz.getAnnotation(Document.class);
if (document != null) {
documentInfo.setIndexName(document.indexName());
documentInfo.setIndexType(document.indexType());
documentInfo.setIndexNumberOfShards(document.shards());
documentInfo.setIndexNumberOfReplicas(document.replicas());
documentInfo.setAnalyzer(document.analyzer());
documentInfo.setSearchAnalyzer(document.searchAnalyzer());
}
}
/**
* <p>
* 初始化 文档主键,文档字段
* </p>
*
* @param clazz 实体类
* @param documentInfo 数据库文档反射信息
*/
public static void initTableFields(Class<?> clazz, DocumentInfo documentInfo) {
Field[] list = ReflectUtil.getFields(clazz);
// 是否存在 @Id 注解
boolean existId = isExistId(Arrays.asList(list));
if (!existId) {
log.warn("请使用 @Id 标记 id 主键");
throw new RuntimeException();
}
List<DocumentFieldInfo> fieldList = new ArrayList<>();
for (Field field : list) {
if (StrUtil.equalsIgnoreCase(SERIAL_VERSION_UID, field.getName())) {
continue;
}
/* 文档 ID 初始化 */
Id id = field.getAnnotation(Id.class);
if (id != null) {
initIndexIdWithoutAnnotation(documentInfo, field, clazz.getName());
continue;
}
/* 有 @Field 注解的字段初始化 */
if (initDocumentFieldWithAnnotation(fieldList, field)) {
continue;
}
/* 无 @Field 注解的字段初始化 */
fieldList.add(new DocumentFieldInfo(field));
}
/* 字段列文档,不可变集合 */
documentInfo.setFieldList(Collections.unmodifiableList(fieldList));
}
/**
* <p>
* 文档主键属性初始化
* </p>
*
* @param documentInfo 文档信息
* @param field 字段
* @param className 类名称
*/
private static void initIndexIdWithoutAnnotation(DocumentInfo documentInfo, Field field, String className) {
if (StrUtil.isNotEmpty(documentInfo.getKeyProperty())) {
log.error("@Id can't more than one in Class: {}.", className);
throw new RuntimeException();
}
if (!String.class.equals(field.getType())) {
log.error("@Id only String type is supported in Class: {}.", className);
throw new RuntimeException();
}
final String property = field.getName();
documentInfo.setKeyProperty(property).setKeyType(field.getType());
}
/**
* <p>
* 字段属性初始化
* </p>
*
* @param fieldList 字段列文档
* @return true 继续下一个属性判断,返回 continue;
*/
private static boolean initDocumentFieldWithAnnotation(List<DocumentFieldInfo> fieldList, Field field) {
/* 获取注解属性,自定义字段 */
com.zhengcheng.data.elasticsearch.annotations.Field documentField =
field.getAnnotation(com.zhengcheng.data.elasticsearch.annotations.Field.class);
if (Objects.isNull(documentField)) {
return false;
}
fieldList.add(new DocumentFieldInfo(field, documentField));
return true;
}
/**
* <p>
* 判断主键注解是否存在
* </p>
*
* @param list 字段列文档
* @return true 为存在 @Id 注解;
*/
public static boolean isExistId(List<Field> list) {
return list.stream().anyMatch(field -> field.isAnnotationPresent(Id.class));
}
}
|
3e12fd90d26820c734e6482b75aa5e8c44d8f2de | 370 | java | Java | app/src/androidTest/java/tv/ismar/daisy/module/detailpage/sample/ApplicationTest.java | JasonFengIce/DetailPageModule | 8638c613c49451f2a4dd4ef25aa55f642621bfc4 | [
"Apache-2.0"
] | null | null | null | app/src/androidTest/java/tv/ismar/daisy/module/detailpage/sample/ApplicationTest.java | JasonFengIce/DetailPageModule | 8638c613c49451f2a4dd4ef25aa55f642621bfc4 | [
"Apache-2.0"
] | null | null | null | app/src/androidTest/java/tv/ismar/daisy/module/detailpage/sample/ApplicationTest.java | JasonFengIce/DetailPageModule | 8638c613c49451f2a4dd4ef25aa55f642621bfc4 | [
"Apache-2.0"
] | null | null | null | 28.461538 | 93 | 0.756757 | 8,018 | package tv.ismar.daisy.module.detailpage.sample;
import android.app.Application;
import android.test.ApplicationTestCase;
/**
* <a href="http://d.android.com/tools/testing/testing_android.html">Testing Fundamentals</a>
*/
public class ApplicationTest extends ApplicationTestCase<Application> {
public ApplicationTest() {
super(Application.class);
}
} |
3e12fd9851dcfa035b8968eebc31daebe71d7b79 | 32,032 | java | Java | qpid-jms-client/src/test/java/org/apache/qpid/jms/integration/ConnectionIntegrationTest.java | acidburn0zzz/qpid-jms | 9258e899c22718875a25e37817f76c9994398646 | [
"Apache-2.0"
] | 2 | 2017-11-29T09:20:03.000Z | 2017-11-29T09:20:05.000Z | qpid-jms-client/src/test/java/org/apache/qpid/jms/integration/ConnectionIntegrationTest.java | acidburn0zzz/qpid-jms | 9258e899c22718875a25e37817f76c9994398646 | [
"Apache-2.0"
] | 1 | 2021-02-08T21:26:29.000Z | 2021-02-08T21:26:29.000Z | qpid-jms-client/src/test/java/org/apache/qpid/jms/integration/ConnectionIntegrationTest.java | Acidburn0zzz/qpid-jms | 9258e899c22718875a25e37817f76c9994398646 | [
"Apache-2.0"
] | null | null | null | 41.492228 | 183 | 0.660027 | 8,019 | /*
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.qpid.jms.integration;
import static org.apache.qpid.jms.provider.amqp.AmqpSupport.NETWORK_HOST;
import static org.apache.qpid.jms.provider.amqp.AmqpSupport.OPEN_HOSTNAME;
import static org.apache.qpid.jms.provider.amqp.AmqpSupport.PORT;
import static org.hamcrest.CoreMatchers.containsString;
import static org.hamcrest.Matchers.allOf;
import static org.hamcrest.Matchers.arrayContaining;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasEntry;
import static org.hamcrest.Matchers.notNullValue;
import static org.hamcrest.Matchers.nullValue;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.io.IOException;
import java.net.URI;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.ExceptionListener;
import javax.jms.IllegalStateException;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.MessageProducer;
import javax.jms.Queue;
import javax.jms.Session;
import org.apache.qpid.jms.JmsConnection;
import org.apache.qpid.jms.JmsConnectionFactory;
import org.apache.qpid.jms.JmsDefaultConnectionListener;
import org.apache.qpid.jms.provider.ProviderRedirectedException;
import org.apache.qpid.jms.provider.amqp.AmqpSupport;
import org.apache.qpid.jms.test.QpidJmsTestCase;
import org.apache.qpid.jms.test.Wait;
import org.apache.qpid.jms.test.testpeer.TestAmqpPeer;
import org.apache.qpid.jms.test.testpeer.basictypes.AmqpError;
import org.apache.qpid.jms.test.testpeer.basictypes.ConnectionError;
import org.apache.qpid.jms.test.testpeer.matchers.CoordinatorMatcher;
import org.apache.qpid.jms.util.MetaDataSupport;
import org.apache.qpid.proton.amqp.Binary;
import org.apache.qpid.proton.amqp.Symbol;
import org.apache.qpid.proton.amqp.UnsignedInteger;
import org.apache.qpid.proton.amqp.transaction.TxnCapability;
import org.apache.qpid.proton.engine.impl.AmqpHeader;
import org.hamcrest.Matcher;
import org.junit.Test;
public class ConnectionIntegrationTest extends QpidJmsTestCase {
private final IntegrationTestFixture testFixture = new IntegrationTestFixture();
@Test(timeout = 20000)
public void testCreateAndCloseConnection() throws Exception {
try (TestAmqpPeer testPeer = new TestAmqpPeer();) {
Connection connection = testFixture.establishConnecton(testPeer);
testPeer.expectClose();
connection.close();
}
}
@Test(timeout = 10000)
public void testCreateConnectionToNonSaslPeer() throws Exception {
doConnectionWithUnexpectedHeaderTestImpl(AmqpHeader.HEADER);
}
@Test(timeout = 10000)
public void testCreateConnectionToNonAmqpPeer() throws Exception {
byte[] responseHeader = new byte[] { 'N', 'O', 'T', '-', 'A', 'M', 'Q', 'P' };
doConnectionWithUnexpectedHeaderTestImpl(responseHeader);
}
private void doConnectionWithUnexpectedHeaderTestImpl(byte[] responseHeader) throws Exception, IOException {
try (TestAmqpPeer testPeer = new TestAmqpPeer();) {
testPeer.expectHeader(AmqpHeader.SASL_HEADER, responseHeader);
ConnectionFactory factory = new JmsConnectionFactory("amqp://localhost:" + testPeer.getServerPort());
try {
factory.createConnection("guest", "guest");
fail("Expected connection creation to fail");
} catch (JMSException jmse) {
assertThat(jmse.getMessage(), containsString("SASL header mismatch"));
}
}
}
@Test(timeout = 20000)
public void testCloseConnectionTimesOut() throws Exception {
try (TestAmqpPeer testPeer = new TestAmqpPeer();) {
JmsConnection connection = (JmsConnection) testFixture.establishConnecton(testPeer);
connection.setCloseTimeout(500);
testPeer.expectClose(false);
connection.start();
assertNotNull("Connection should not be null", connection);
connection.close();
testPeer.waitForAllHandlersToComplete(1000);
}
}
@Test(timeout = 20000)
public void testCloseConnectionCompletesWhenConnectionDropsBeforeResponse() throws Exception {
try (TestAmqpPeer testPeer = new TestAmqpPeer();) {
JmsConnection connection = (JmsConnection) testFixture.establishConnecton(testPeer);
testPeer.expectClose(false);
testPeer.dropAfterLastHandler();
connection.start();
assertNotNull("Connection should not be null", connection);
connection.close();
testPeer.waitForAllHandlersToComplete(1000);
}
}
@Test(timeout = 20000)
public void testCreateConnectionWithClientId() throws Exception {
try (TestAmqpPeer testPeer = new TestAmqpPeer();) {
Connection connection = testFixture.establishConnecton(testPeer, false, null, null, null, true);
testPeer.expectClose();
connection.close();
}
}
@Test(timeout = 20000)
public void testCreateAutoAckSession() throws Exception {
try (TestAmqpPeer testPeer = new TestAmqpPeer();) {
Connection connection = testFixture.establishConnecton(testPeer);
testPeer.expectBegin();
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
assertNotNull("Session should not be null", session);
testPeer.expectClose();
connection.close();
}
}
@Test(timeout = 20000)
public void testCreateAutoAckSessionByDefault() throws Exception {
try (TestAmqpPeer testPeer = new TestAmqpPeer();) {
Connection connection = testFixture.establishConnecton(testPeer);
testPeer.expectBegin();
Session session = connection.createSession();
assertNotNull("Session should not be null", session);
testPeer.expectClose();
connection.close();
}
}
@Test(timeout = 20000)
public void testCreateAutoAckSessionUsingAckModeOnlyMethod() throws Exception {
try (TestAmqpPeer testPeer = new TestAmqpPeer();) {
Connection connection = testFixture.establishConnecton(testPeer);
testPeer.expectBegin();
Session session = connection.createSession(Session.AUTO_ACKNOWLEDGE);
assertNotNull("Session should not be null", session);
testPeer.expectClose();
connection.close();
}
}
@Test(timeout = 20000)
public void testCreateTransactedSession() throws Exception {
try (TestAmqpPeer testPeer = new TestAmqpPeer();) {
Connection connection = testFixture.establishConnecton(testPeer);
testPeer.expectBegin();
// Expect the session, with an immediate link to the transaction coordinator
// using a target with the expected capabilities only.
CoordinatorMatcher txCoordinatorMatcher = new CoordinatorMatcher();
txCoordinatorMatcher.withCapabilities(arrayContaining(TxnCapability.LOCAL_TXN));
testPeer.expectSenderAttach(txCoordinatorMatcher, false, false);
// First expect an unsettled 'declare' transfer to the txn coordinator, and
// reply with a declared disposition state containing the txnId.
Binary txnId = new Binary(new byte[]{ (byte) 1, (byte) 2, (byte) 3, (byte) 4});
testPeer.expectDeclare(txnId);
testPeer.expectDischarge(txnId, true);
testPeer.expectClose();
Session session = connection.createSession(true, Session.SESSION_TRANSACTED);
assertNotNull("Session should not be null", session);
connection.close();
}
}
@Test(timeout = 20000)
public void testCreateTransactedSessionUsingAckModeOnlyMethod() throws Exception {
try (TestAmqpPeer testPeer = new TestAmqpPeer();) {
Connection connection = testFixture.establishConnecton(testPeer);
testPeer.expectBegin();
// Expect the session, with an immediate link to the transaction coordinator
// using a target with the expected capabilities only.
CoordinatorMatcher txCoordinatorMatcher = new CoordinatorMatcher();
txCoordinatorMatcher.withCapabilities(arrayContaining(TxnCapability.LOCAL_TXN));
testPeer.expectSenderAttach(txCoordinatorMatcher, false, false);
// First expect an unsettled 'declare' transfer to the txn coordinator, and
// reply with a declared disposition state containing the txnId.
Binary txnId = new Binary(new byte[]{ (byte) 1, (byte) 2, (byte) 3, (byte) 4});
testPeer.expectDeclare(txnId);
testPeer.expectDischarge(txnId, true);
testPeer.expectClose();
Session session = connection.createSession(Session.SESSION_TRANSACTED);
assertNotNull("Session should not be null", session);
connection.close();
}
}
@Test(timeout = 20000)
public void testCreateTransactedSessionFailsWhenNoDetachResponseSent() throws Exception {
try (TestAmqpPeer testPeer = new TestAmqpPeer();) {
Connection connection = testFixture.establishConnecton(testPeer);
((JmsConnection) connection).setRequestTimeout(500);
testPeer.expectBegin();
// Expect the session, with an immediate link to the transaction coordinator
// using a target with the expected capabilities only.
CoordinatorMatcher txCoordinatorMatcher = new CoordinatorMatcher();
txCoordinatorMatcher.withCapabilities(arrayContaining(TxnCapability.LOCAL_TXN));
testPeer.expectSenderAttach(notNullValue(), txCoordinatorMatcher, true, true, false, 0, null, null);
testPeer.expectDetach(true, false, false);
// Expect the AMQP session to be closed due to the JMS session creation failure.
testPeer.expectEnd();
try {
connection.createSession(true, Session.SESSION_TRANSACTED);
fail("Session create should have failed.");
} catch (JMSException ex) {
// Expected
}
testPeer.expectClose();
connection.close();
testPeer.waitForAllHandlersToComplete(1000);
}
}
@Test(timeout = 20000)
public void testRemotelyCloseConnectionDuringSessionCreation() throws Exception {
final String BREAD_CRUMB = "ErrorMessageBreadCrumb";
try (TestAmqpPeer testPeer = new TestAmqpPeer();) {
Connection connection = testFixture.establishConnecton(testPeer);
// Expect the begin, then explicitly close the connection with an error
testPeer.expectBegin(notNullValue(), false);
testPeer.remotelyCloseConnection(true, AmqpError.NOT_ALLOWED, BREAD_CRUMB);
try {
connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
fail("Expected exception to be thrown");
} catch (JMSException jmse) {
// Expected
assertNotNull("Expected exception to have a message", jmse.getMessage());
assertTrue("Expected breadcrumb to be present in message", jmse.getMessage().contains(BREAD_CRUMB));
}
testPeer.waitForAllHandlersToComplete(3000);
connection.close();
}
}
@Test(timeout = 20000)
public void testRemotelyDropConnectionDuringSessionCreation() throws Exception {
try (TestAmqpPeer testPeer = new TestAmqpPeer();) {
Connection connection = testFixture.establishConnecton(testPeer);
// Expect the begin, then drop connection without without a close frame.
testPeer.expectBegin(notNullValue(), false);
testPeer.dropAfterLastHandler();
try {
connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
fail("Expected exception to be thrown");
} catch (JMSException jmse) {
// Expected
}
testPeer.waitForAllHandlersToComplete(3000);
connection.close();
}
}
@Test(timeout = 20000)
public void testConnectionPropertiesContainExpectedMetaData() throws Exception {
try (TestAmqpPeer testPeer = new TestAmqpPeer();) {
Matcher<?> connPropsMatcher = allOf(hasEntry(AmqpSupport.PRODUCT, MetaDataSupport.PROVIDER_NAME),
hasEntry(AmqpSupport.VERSION, MetaDataSupport.PROVIDER_VERSION),
hasEntry(AmqpSupport.PLATFORM, MetaDataSupport.PLATFORM_DETAILS));
testPeer.expectSaslAnonymous();
testPeer.expectOpen(connPropsMatcher, null, false);
testPeer.expectBegin();
ConnectionFactory factory = new JmsConnectionFactory("amqp://localhost:" + testPeer.getServerPort() + "?jms.clientID=foo");
Connection connection = factory.createConnection();
testPeer.waitForAllHandlersToComplete(1000);
assertNull(testPeer.getThrowable());
testPeer.expectClose();
connection.close();
}
}
@Test(timeout = 20000)
public void testMaxFrameSizeOptionCommunicatedInOpen() throws Exception {
int frameSize = 39215;
doMaxFrameSizeOptionTestImpl(frameSize, UnsignedInteger.valueOf(frameSize));
}
@Test(timeout = 20000)
public void testMaxFrameSizeOptionCommunicatedInOpenDefault() throws Exception {
doMaxFrameSizeOptionTestImpl(-1, UnsignedInteger.MAX_VALUE);
}
private void doMaxFrameSizeOptionTestImpl(int uriOption, UnsignedInteger transmittedValue) throws JMSException, InterruptedException, Exception, IOException {
try (TestAmqpPeer testPeer = new TestAmqpPeer();) {
testPeer.expectSaslLayerDisabledConnect(equalTo(transmittedValue));
// Each connection creates a session for managing temporary destinations etc
testPeer.expectBegin();
String uri = "amqp://localhost:" + testPeer.getServerPort() + "?amqp.saslLayer=false&amqp.maxFrameSize=" + uriOption;
ConnectionFactory factory = new JmsConnectionFactory(uri);
Connection connection = factory.createConnection();
connection.start();
testPeer.waitForAllHandlersToComplete(3000);
assertNull(testPeer.getThrowable());
testPeer.expectClose();
connection.close();
}
}
@Test(timeout = 20000)
public void testAmqpHostnameSetByDefault() throws Exception {
doAmqpHostnameTestImpl("localhost", false, equalTo("localhost"));
}
@Test(timeout = 20000)
public void testAmqpHostnameSetByVhostOption() throws Exception {
String vhost = "myAmqpHost";
doAmqpHostnameTestImpl(vhost, true, equalTo(vhost));
}
@Test(timeout = 20000)
public void testAmqpHostnameNotSetWithEmptyVhostOption() throws Exception {
doAmqpHostnameTestImpl("", true, nullValue());
}
private void doAmqpHostnameTestImpl(String amqpHostname, boolean setHostnameOption, Matcher<?> hostnameMatcher) throws JMSException, InterruptedException, Exception, IOException {
try (TestAmqpPeer testPeer = new TestAmqpPeer();) {
testPeer.expectSaslAnonymous();
testPeer.expectOpen(null, hostnameMatcher, false);
// Each connection creates a session for managing temporary destinations etc
testPeer.expectBegin();
String uri = "amqp://localhost:" + testPeer.getServerPort();
if(setHostnameOption) {
uri += "?amqp.vhost=" + amqpHostname;
}
ConnectionFactory factory = new JmsConnectionFactory(uri);
Connection connection = factory.createConnection();
// Set a clientID to provoke the actual AMQP connection process to occur.
connection.setClientID("clientName");
testPeer.waitForAllHandlersToComplete(1000);
assertNull(testPeer.getThrowable());
testPeer.expectClose();
connection.close();
}
}
@Test(timeout = 20000)
public void testRemotelyEndConnectionListenerInvoked() throws Exception {
try (TestAmqpPeer testPeer = new TestAmqpPeer();) {
final CountDownLatch done = new CountDownLatch(1);
// Don't set a ClientId, so that the underlying AMQP connection isn't established yet
Connection connection = testFixture.establishConnecton(testPeer, false, null, null, null, false);
// Tell the test peer to close the connection when executing its last handler
testPeer.remotelyCloseConnection(true);
// Add the exception listener
connection.setExceptionListener(new ExceptionListener() {
@Override
public void onException(JMSException exception) {
done.countDown();
}
});
// Trigger the underlying AMQP connection
connection.start();
assertTrue("Connection should report failure", done.await(5, TimeUnit.SECONDS));
testPeer.waitForAllHandlersToComplete(1000);
connection.close();
}
}
@Test(timeout = 20000)
public void testRemotelyEndConnectionWithRedirect() throws Exception {
try (TestAmqpPeer testPeer = new TestAmqpPeer();) {
final CountDownLatch done = new CountDownLatch(1);
final AtomicReference<JMSException> asyncError = new AtomicReference<JMSException>();
final String redirectVhost = "vhost";
final String redirectNetworkHost = "localhost";
final int redirectPort = 5677;
// Don't set a ClientId, so that the underlying AMQP connection isn't established yet
Connection connection = testFixture.establishConnecton(testPeer, false, null, null, null, false);
// Tell the test peer to close the connection when executing its last handler
Map<Symbol, Object> errorInfo = new HashMap<Symbol, Object>();
errorInfo.put(OPEN_HOSTNAME, redirectVhost);
errorInfo.put(NETWORK_HOST, redirectNetworkHost);
errorInfo.put(PORT, 5677);
testPeer.remotelyCloseConnection(true, ConnectionError.REDIRECT, "Connection redirected", errorInfo);
// Add the exception listener
connection.setExceptionListener(new ExceptionListener() {
@Override
public void onException(JMSException exception) {
asyncError.set(exception);
done.countDown();
}
});
// Trigger the underlying AMQP connection
connection.start();
assertTrue("Connection should report failure", done.await(5, TimeUnit.SECONDS));
assertTrue(asyncError.get() instanceof JMSException);
assertTrue(asyncError.get().getCause() instanceof ProviderRedirectedException);
ProviderRedirectedException redirect = (ProviderRedirectedException) asyncError.get().getCause();
URI redirectionURI = redirect.getRedirectionURI();
assertNotNull(redirectionURI);
assertTrue(redirectVhost, redirectionURI.getQuery().contains("amqp.vhost=" + redirectVhost));
assertEquals(redirectNetworkHost, redirectionURI.getHost());
assertEquals(redirectPort, redirectionURI.getPort());
testPeer.waitForAllHandlersToComplete(1000);
connection.close();
}
}
@Test(timeout = 20000)
public void testRemotelyEndConnectionWithSessionWithConsumer() throws Exception {
final String BREAD_CRUMB = "ErrorMessage";
try (TestAmqpPeer testPeer = new TestAmqpPeer();) {
final Connection connection = testFixture.establishConnecton(testPeer);
testPeer.expectBegin();
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
// Create a consumer, then remotely end the connection afterwards.
testPeer.expectReceiverAttach();
testPeer.expectLinkFlow();
testPeer.remotelyCloseConnection(true, AmqpError.RESOURCE_LIMIT_EXCEEDED, BREAD_CRUMB);
Queue queue = session.createQueue("myQueue");
MessageConsumer consumer = session.createConsumer(queue);
testPeer.waitForAllHandlersToComplete(1000);
assertTrue("connection never closed.", Wait.waitFor(new Wait.Condition() {
@Override
public boolean isSatisified() throws Exception {
return !((JmsConnection) connection).isConnected();
}
}, 10000, 10));
try {
connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
fail("Expected ISE to be thrown due to being closed");
} catch (IllegalStateException jmsise) {
String message = jmsise.getCause().getMessage();
assertTrue(message.contains(AmqpError.RESOURCE_LIMIT_EXCEEDED.toString()));
assertTrue(message.contains(BREAD_CRUMB));
}
// Verify the session is now marked closed
try {
session.getAcknowledgeMode();
fail("Expected ISE to be thrown due to being closed");
} catch (IllegalStateException jmsise) {
String message = jmsise.getCause().getMessage();
assertTrue(message.contains(AmqpError.RESOURCE_LIMIT_EXCEEDED.toString()));
assertTrue(message.contains(BREAD_CRUMB));
}
// Verify the consumer is now marked closed
try {
consumer.getMessageListener();
fail("Expected ISE to be thrown due to being closed");
} catch (IllegalStateException jmsise) {
String message = jmsise.getCause().getMessage();
assertTrue(message.contains(AmqpError.RESOURCE_LIMIT_EXCEEDED.toString()));
assertTrue(message.contains(BREAD_CRUMB));
}
// Try closing them explicitly, should effectively no-op in client.
// The test peer will throw during close if it sends anything.
consumer.close();
session.close();
connection.close();
}
}
@Test(timeout = 20000)
public void testRemotelyEndConnectionWithSessionWithProducerWithSendWaitingOnCredit() throws Exception {
final String BREAD_CRUMB = "ErrorMessageBreadCrumb";
try (TestAmqpPeer testPeer = new TestAmqpPeer();) {
Connection connection = testFixture.establishConnecton(testPeer);
testPeer.expectBegin();
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
// Expect producer creation, don't give it credit.
testPeer.expectSenderAttachWithoutGrantingCredit();
// Producer has no credit so the send should block waiting for it.
testPeer.remotelyCloseConnection(true, AmqpError.RESOURCE_LIMIT_EXCEEDED, BREAD_CRUMB, 50);
Queue queue = session.createQueue("myQueue");
final MessageProducer producer = session.createProducer(queue);
Message message = session.createTextMessage("myMessage");
try {
producer.send(message);
fail("Expected exception to be thrown");
} catch (JMSException jmse) {
// Expected
assertNotNull("Expected exception to have a message", jmse.getMessage());
assertTrue("Expected breadcrumb to be present in message", jmse.getMessage().contains(BREAD_CRUMB));
}
connection.close();
testPeer.waitForAllHandlersToComplete(3000);
}
}
@Test(timeout = 20000)
public void testCreateConnectionWithServerSendingPreemptiveData() throws Exception {
boolean sendServerSaslHeaderPreEmptively = true;
try (TestAmqpPeer testPeer = new TestAmqpPeer(null, false, sendServerSaslHeaderPreEmptively);) {
// Don't use test fixture, handle the connection directly to control sasl behaviour
testPeer.expectSaslAnonymousWithPreEmptiveServerHeader();
testPeer.expectOpen();
testPeer.expectBegin();
JmsConnectionFactory factory = new JmsConnectionFactory("amqp://localhost:" + testPeer.getServerPort());
Connection connection = factory.createConnection();
connection.start();
testPeer.expectClose();
connection.close();
}
}
@Test(timeout = 20000)
public void testDontAwaitClientIDBeforeOpen() throws Exception {
try (TestAmqpPeer testPeer = new TestAmqpPeer();) {
String uri = "amqp://localhost:" + testPeer.getServerPort() + "?jms.awaitClientID=false";
testPeer.expectSaslAnonymous();
testPeer.expectOpen();
testPeer.expectBegin();
ConnectionFactory factory = new JmsConnectionFactory(uri);
Connection connection = factory.createConnection();
// Verify that all handlers complete, i.e. the awaitClientID=false option
// setting was effective in provoking the AMQP Open immediately even
// though it has no ClientID and we haven't used the Connection.
testPeer.waitForAllHandlersToComplete(3000);
testPeer.expectClose();
connection.close();
testPeer.waitForAllHandlersToComplete(1000);
}
}
@Test(timeout = 20000)
public void testWaitForClientIDDoesNotOpenUntilPromptedWithSetClientID() throws Exception {
doTestWaitForClientIDDoesNotOpenUntilPrompted(true);
}
@Test(timeout = 20000)
public void testWaitForClientIDDoesNotOpenUntilPromptedWithStart() throws Exception {
doTestWaitForClientIDDoesNotOpenUntilPrompted(false);
}
private void doTestWaitForClientIDDoesNotOpenUntilPrompted(boolean setClientID) throws Exception {
try (TestAmqpPeer testPeer = new TestAmqpPeer();) {
String uri = "amqp://localhost:" + testPeer.getServerPort() + "?jms.awaitClientID=true";
testPeer.expectSaslAnonymous();
ConnectionFactory factory = new JmsConnectionFactory(uri);
Connection connection = factory.createConnection();
testPeer.waitForAllHandlersToComplete(1000);
testPeer.expectOpen();
testPeer.expectBegin();
if (setClientID) {
connection.setClientID("client-id");
} else {
connection.start();
}
testPeer.expectClose();
connection.close();
testPeer.waitForAllHandlersToComplete(2000);
}
}
@Test(timeout = 20000)
public void testUseDaemonThreadURIOption() throws Exception {
doUseDaemonThreadTestImpl(null);
doUseDaemonThreadTestImpl(false);
doUseDaemonThreadTestImpl(true);
}
private void doUseDaemonThreadTestImpl(Boolean useDaemonThread) throws Exception {
try (TestAmqpPeer testPeer = new TestAmqpPeer();) {
String remoteURI = "amqp://localhost:" + testPeer.getServerPort();
if (useDaemonThread != null) {
remoteURI += "?jms.useDaemonThread=" + useDaemonThread;
}
testPeer.expectSaslAnonymous();
testPeer.expectOpen();
testPeer.expectBegin();
final CountDownLatch connectionEstablished = new CountDownLatch(1);
final AtomicBoolean daemonThread = new AtomicBoolean(false);
ConnectionFactory factory = new JmsConnectionFactory(remoteURI);
JmsConnection connection = (JmsConnection) factory.createConnection();
connection.addConnectionListener(new JmsDefaultConnectionListener() {
@Override
public void onConnectionEstablished(URI remoteURI) {
// Record whether the thread is daemon or not
daemonThread.set(Thread.currentThread().isDaemon());
connectionEstablished.countDown();
}
});
connection.start();
assertTrue("Connection established callback didn't trigger", connectionEstablished.await(5, TimeUnit.SECONDS));
testPeer.expectClose();
connection.close();
testPeer.waitForAllHandlersToComplete(2000);
if (useDaemonThread == null) {
// Expect default to be false when not configured
assertFalse(daemonThread.get());
} else {
// Else expect to match the URI option value
assertEquals(useDaemonThread, daemonThread.get());
}
}
}
@Test(timeout = 20000)
public void testConnectionWithPreemptiveServerOpen() throws Exception {
try (TestAmqpPeer testPeer = new TestAmqpPeer();) {
// Ensure the Connection awaits a ClientID being set or not, giving time for the preemptive server Open
String uri = "amqp://localhost:" + testPeer.getServerPort() + "?jms.awaitClientID=true";
testPeer.expectSaslAnonymousWithServerAmqpHeaderSentPreemptively();
testPeer.sendPreemptiveServerAmqpHeader();
testPeer.sendPreemptiveServerOpenFrame();
// Then expect the clients header to arrive, but defer responding since the servers was already sent.
testPeer.expectHeader(AmqpHeader.HEADER, null);
ConnectionFactory factory = new JmsConnectionFactory(uri);
Connection connection = factory.createConnection();
// Then expect the clients Open frame to arrive, but defer responding since the servers was already sent
// before the clients AMQP connection open is provoked.
testPeer.expectOpen(null, null, true);
testPeer.expectBegin();
Thread.sleep(10); // Gives a little more time for the preemptive Open to actually arrive.
// Use the connection to provoke the Open
connection.setClientID("client-id");
testPeer.expectClose();
connection.close();
testPeer.waitForAllHandlersToComplete(2000);
}
}
}
|
3e12fda573f088ecd4b83329fd73b051a7a181dc | 379 | java | Java | Framework_Project/atguigu-atcf/common/src/test/java/com/juyss/util/Md5Test.java | juyss/workspace | 6005307287200ce5c208f02ff307409d0d34a5e5 | [
"MulanPSL-1.0"
] | null | null | null | Framework_Project/atguigu-atcf/common/src/test/java/com/juyss/util/Md5Test.java | juyss/workspace | 6005307287200ce5c208f02ff307409d0d34a5e5 | [
"MulanPSL-1.0"
] | 1 | 2020-09-14T07:46:05.000Z | 2020-09-14T07:46:05.000Z | Framework_Project/atguigu-atcf/common/src/test/java/com/juyss/util/Md5Test.java | juyss/workspace | 6005307287200ce5c208f02ff307409d0d34a5e5 | [
"MulanPSL-1.0"
] | null | null | null | 16.478261 | 49 | 0.641161 | 8,020 | package com.juyss.util;
import org.junit.Test;
/**
* @author ShmeBluk
* @version 1.0
* @ClassName: Md5Test
* @Desc: 测试MD5加密工具类
* @package com.juyss.util
* @project atguigu-CrowdFunding
* @date 2020/10/11 23:50
*/
public class Md5Test {
@Test
public void MD5Test(){
String digest = MD5Util.digest("102850");
System.out.println(digest);
}
}
|
3e12fdcaa64b4d1a90ed7b864f33964ca5a58968 | 6,760 | java | Java | build-info-extractor/src/main/java/org/jfrog/build/extractor/clientConfiguration/client/ArtifactoryXrayClient.java | liron-shalom/build-info | c7725d16a5ee2a458ca1ae096dd792f00ed12550 | [
"Apache-2.0"
] | null | null | null | build-info-extractor/src/main/java/org/jfrog/build/extractor/clientConfiguration/client/ArtifactoryXrayClient.java | liron-shalom/build-info | c7725d16a5ee2a458ca1ae096dd792f00ed12550 | [
"Apache-2.0"
] | null | null | null | build-info-extractor/src/main/java/org/jfrog/build/extractor/clientConfiguration/client/ArtifactoryXrayClient.java | liron-shalom/build-info | c7725d16a5ee2a458ca1ae096dd792f00ed12550 | [
"Apache-2.0"
] | null | null | null | 41.728395 | 145 | 0.660207 | 8,021 | package org.jfrog.build.extractor.clientConfiguration.client;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.NullArgumentException;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.entity.StringEntity;
import org.apache.http.util.EntityUtils;
import org.jfrog.build.api.util.Log;
import org.jfrog.build.client.PreemptiveHttpClient;
import org.jfrog.build.client.artifactoryXrayResponse.ArtifactoryXrayResponse;
import java.io.IOException;
/**
* Created by romang on 1/1/17.
*/
public class ArtifactoryXrayClient extends ArtifactoryBaseClient {
private static final String SCAN_BUILD_URL = "/api/xray/scanBuild";
/**
* Retrying to resume the scan 5 times after a stable connection
*/
private static final int XRAY_SCAN_RETRY_CONSECUTIVE_RETRIES = 5;
/**
* Expecting \r\n every 30 seconds
*/
private static final int XRAY_SCAN_CONNECTION_TIMEOUT_SECS = 90;
/**
* 30 seconds sleep between retry
*/
private static final int XRAY_SCAN_SLEEP_BETWEEN_RETRIES_MILLIS = 30000;
/**
* Fatal error code from Xray
*/
private static final String XRAY_FATAL_FAIL_STATUS = "-1";
/**
* ArtifactoryXrayClient manages retry mechanism, http-client's mechanism is not required
*/
private static final int HTTP_CLIENT_RETRIES = 0;
public ArtifactoryXrayClient(String artifactoryUrl, String username, String password, Log logger) {
super(artifactoryUrl, username, password, logger);
setConnectionRetries(HTTP_CLIENT_RETRIES);
}
public ArtifactoryXrayResponse xrayScanBuild(String buildName, String buildNumber, String context) throws IOException, InterruptedException {
StringEntity entity = new StringEntity("{\"buildName\":\"" + buildName + "\",\"buildNumber\":\"" + buildNumber +
"\",\"context\":\"" + context + "\"}");
entity.setContentType("application/json");
String scanUrl = artifactoryUrl + SCAN_BUILD_URL;
HttpPost httpPost = new HttpPost(scanUrl);
httpPost.setEntity(entity);
return execute(httpPost);
}
/**
* Stable connection is a connection which was connected successfully for at least @stableConnectionMillis.
*
* @param lastConnectionAttemptMillis
* @return
*/
private boolean isStableConnection(long lastConnectionAttemptMillis) {
final long stableConnectionMillis = (XRAY_SCAN_CONNECTION_TIMEOUT_SECS + 10) * 1000;
return lastConnectionAttemptMillis + stableConnectionMillis < System.currentTimeMillis();
}
private ArtifactoryXrayResponse parseXrayScanResponse(HttpResponse response) throws IOException {
if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
throw new IOException("Artifactory response: " + response.getStatusLine().getReasonPhrase());
}
ObjectMapper mapper = new ObjectMapper();
String content = IOUtils.toString(response.getEntity().getContent(), "UTF-8");
JsonNode result;
try {
result = mapper.readTree(content);
if (result == null) {
throw new NullArgumentException("Received empty content from Artifactory");
}
} catch (Exception ex) {
// Throwing XrayErrorException since the retry-mechanism should not reset the retries-count in such error.
throw new XrayErrorException(String.format("Failed processing scan response: %s\n%s", ex.toString(), content));
}
if (result.get("errors") != null) {
String resultStr = result.get("errors").toString();
for (JsonNode error : result.get("errors")) {
if (error.get("status").toString().equals(XRAY_FATAL_FAIL_STATUS)) {
throw new RuntimeException("Artifactory response: " + resultStr);
}
}
throw new XrayErrorException("Artifactory response: " + resultStr);
}
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
return mapper.treeToValue(result, ArtifactoryXrayResponse.class);
}
private ArtifactoryXrayResponse execute(HttpRequestBase httpRequest) throws InterruptedException, IOException {
PreemptiveHttpClient client = httpClient.getHttpClient(XRAY_SCAN_CONNECTION_TIMEOUT_SECS);
int retryNum = 0;
long lastConnectionAttemptMillis = 0;
HttpResponse response = null;
while (true) {
try {
lastConnectionAttemptMillis = System.currentTimeMillis();
retryNum++;
response = client.execute(httpRequest);
return parseXrayScanResponse(response);
} catch (XrayErrorException e) {
handleException(retryNum, e);
} catch (IOException e) {
if (isStableConnection(lastConnectionAttemptMillis)) {
// Interruption may happen when build is aborted in the CI Server.
if (Thread.currentThread().isInterrupted()) {
throw new InterruptedException("Operation interrupted.");
}
retryNum = 0;
continue;
}
handleException(retryNum, e);
} finally {
releaseResponse(httpRequest, response);
}
}
}
private void releaseResponse(HttpRequestBase httpRequest, HttpResponse response) {
if (response != null) {
try {
EntityUtils.consume(response.getEntity());
} catch (IOException e) {
// Ignore
}
}
httpRequest.releaseConnection();
}
private void handleException(int retryNum, IOException e) throws InterruptedException, IOException {
if (XRAY_SCAN_RETRY_CONSECUTIVE_RETRIES <= retryNum) {
throw e;
}
log.warn("Xray scan connection lost: " + e.getMessage() + ", attempting to reconnect...");
// Sleeping before trying to reconnect.
Thread.sleep(XRAY_SCAN_SLEEP_BETWEEN_RETRIES_MILLIS);
}
/**
* Private exception class, signals that Xray-response returned from Artifactory contained an error.
*/
private class XrayErrorException extends IOException {
private XrayErrorException(String message) {
super(message);
}
}
}
|
3e12ff4b36651aeff553caa30642278d4162419e | 1,350 | java | Java | src/test/java/net/openhft/chronicle/wire/method/DefaultMethodHandlingTest.java | pthariensflame/Chronicle-Wire | 17dd7a922bbce01fb0c33258b3bc8c2370dd2fa6 | [
"Apache-2.0"
] | 273 | 2015-01-16T23:14:39.000Z | 2022-03-24T08:12:34.000Z | src/test/java/net/openhft/chronicle/wire/method/DefaultMethodHandlingTest.java | pthariensflame/Chronicle-Wire | 17dd7a922bbce01fb0c33258b3bc8c2370dd2fa6 | [
"Apache-2.0"
] | 334 | 2015-08-11T21:59:09.000Z | 2022-03-30T19:00:53.000Z | src/test/java/net/openhft/chronicle/wire/method/DefaultMethodHandlingTest.java | pthariensflame/Chronicle-Wire | 17dd7a922bbce01fb0c33258b3bc8c2370dd2fa6 | [
"Apache-2.0"
] | 121 | 2015-01-16T23:14:42.000Z | 2022-03-04T04:54:20.000Z | 31.395349 | 91 | 0.662222 | 8,022 | package net.openhft.chronicle.wire.method;
import net.openhft.chronicle.bytes.Bytes;
import net.openhft.chronicle.bytes.MethodReader;
import net.openhft.chronicle.core.Mocker;
import net.openhft.chronicle.wire.TextWire;
import net.openhft.chronicle.wire.WireTestCommon;
import org.junit.Test;
import java.io.StringWriter;
import static org.junit.Assert.*;
interface WithDefault {
void method1(String text);
default void method2(String text2) {
throw new UnsupportedOperationException();
}
}
public class DefaultMethodHandlingTest extends WireTestCommon {
@Test
public void withDefault() {
TextWire wire = new TextWire(Bytes.allocateElasticOnHeap());
WithDefault withDefault = wire.methodWriter(WithDefault.class);
withDefault.method1("one");
withDefault.method2("two");
assertEquals("method1: one\n" +
"...\n" +
"method2: two\n" +
"...\n", wire.toString());
StringWriter sw = new StringWriter();
MethodReader reader = wire.methodReader(Mocker.logging(WithDefault.class, "", sw));
assertTrue(reader.readOne());
assertTrue(reader.readOne());
assertFalse(reader.readOne());
assertEquals("method1[one]\n" +
"method2[two]\n", sw.toString().replace("\r", ""));
}
}
|
3e12ff89e0c91d81f1003756dc0e0e38ed34531c | 4,146 | java | Java | modules/web/src/com/haulmont/cuba/web/app/folders/SaveSetWindow.java | cuba-platform/cuba-thesis | 09ae6b584537f89e458a6a70c9344b3f47d9a8c4 | [
"Apache-2.0"
] | 2 | 2020-02-21T08:17:10.000Z | 2020-07-27T08:24:47.000Z | modules/web/src/com/haulmont/cuba/web/app/folders/SaveSetWindow.java | cuba-platform/cuba-thesis | 09ae6b584537f89e458a6a70c9344b3f47d9a8c4 | [
"Apache-2.0"
] | null | null | null | modules/web/src/com/haulmont/cuba/web/app/folders/SaveSetWindow.java | cuba-platform/cuba-thesis | 09ae6b584537f89e458a6a70c9344b3f47d9a8c4 | [
"Apache-2.0"
] | 2 | 2020-02-21T08:17:12.000Z | 2020-09-22T20:02:02.000Z | 36.690265 | 115 | 0.620598 | 8,023 | /*
* Copyright (c) 2008-2013 Haulmont. All rights reserved.
* Use is subject to license terms, see http://www.cuba-platform.com/license for details.
*/
package com.haulmont.cuba.web.app.folders;
import com.haulmont.cuba.core.global.*;
import com.haulmont.cuba.gui.components.*;
import com.haulmont.cuba.gui.components.filter.UserSetHelper;
import com.haulmont.cuba.security.entity.SearchFolder;
import com.haulmont.cuba.web.AppUI;
import java.util.Map;
import java.util.Set;
/**
* @author devyatkin
* @version $Id$
*/
public class SaveSetWindow extends AbstractWindow {
private Set ids;
private String componentPath;
private String componentId;
private String entityType;
private String entityClass;
private CubaFoldersPane foldersPane;
private LookupField foldersSelect;
private String query;
@Override
public void init(Map<String, Object> params) {
super.init(params);
getDialogParams().setWidthAuto();
ids = (Set) params.get("items");
componentPath = (String) params.get("componentPath");
componentId = (String) params.get("componentId");
entityType = (String) params.get("entityType");
foldersPane = (CubaFoldersPane) params.get("foldersPane");
entityClass = (String) params.get("entityClass");
query = (String) params.get("query");
foldersSelect = getComponent("folderSelect");
Button createBtn = getComponentNN("createNew");
Button insertBtn = getComponentNN("insertBtn");
insertBtn.setAction(new InsertAction());
createBtn.setAction(new CreateSetAction());
}
private class InsertAction extends AbstractAction {
protected InsertAction() {
super("InsertAction");
}
@Override
public void actionPerform(Component component) {
SearchFolder folder = foldersSelect.getValue();
if (folder == null) {
showNotification(getMessage("saveSetWindow.notSelected"), NotificationType.TRAY);
return;
}
String filterXml = folder.getFilterXml();
folder.setFilterXml(UserSetHelper.addEntities(filterXml, ids));
foldersPane.saveFolder(folder);
foldersPane.refreshFolders();
close(COMMIT_ACTION_ID, true);
}
}
private class CreateSetAction extends AbstractAction {
protected CreateSetAction() {
super("CreateSetAction");
}
@Override
public void actionPerform(Component component) {
QueryParser parser = QueryTransformerFactory.createParser(query);
String entityAlias = parser.getEntityAlias(entityType);
String filterXml = UserSetHelper.generateSetFilter(ids, entityClass, componentId, entityAlias);
Metadata metadata = AppBeans.get(Metadata.NAME);
final SearchFolder folder = metadata.create(SearchFolder.class);
UserSessionSource sessionSource = AppBeans.get(UserSessionSource.NAME);
folder.setUser(sessionSource.getUserSession().getUser());
folder.setName("");
folder.setFilterXml(filterXml);
folder.setFilterComponentId(componentPath);
folder.setEntityType(entityType);
folder.setIsSet(true);
Runnable commitHandler = new Runnable() {
@Override
public void run() {
foldersPane.saveFolder(folder);
foldersPane.refreshFolders();
}
};
final FolderEditWindow window = AppFolderEditWindow.create(false, false, folder, null, commitHandler);
AppUI.getCurrent().addWindow(window);
window.addCloseListener(new com.vaadin.ui.Window.CloseListener() {
@Override
public void windowClose(com.vaadin.ui.Window.CloseEvent e) {
close(COMMIT_ACTION_ID);
}
});
}
}
} |
3e130079e3b961215c6faee52a0a4d9ba774fc43 | 2,462 | java | Java | ham/simpledns/src/main/java/org/kendar/SimpleDns.java | kendarorg/HttpAnsweringMachine | 9659fe92844500dce8a7b910a956cb26dba87237 | [
"MIT"
] | 2 | 2022-01-17T07:45:16.000Z | 2022-03-16T22:01:35.000Z | ham/simpledns/src/main/java/org/kendar/SimpleDns.java | kendarorg/HttpAnsweringMachine | 9659fe92844500dce8a7b910a956cb26dba87237 | [
"MIT"
] | 39 | 2022-01-20T14:23:42.000Z | 2022-03-31T12:06:47.000Z | ham/simpledns/src/main/java/org/kendar/SimpleDns.java | kendarorg/HttpAnsweringMachine | 9659fe92844500dce8a7b910a956cb26dba87237 | [
"MIT"
] | 1 | 2022-03-07T22:31:59.000Z | 2022-03-07T22:31:59.000Z | 35.681159 | 95 | 0.71974 | 8,024 | package org.kendar;
import org.kendar.dns.configurations.DnsConfig;
import org.kendar.servers.JsonConfiguration;
import org.kendar.servers.config.GlobalConfig;
import org.kendar.servers.dns.DnsMultiResolver;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import org.springframework.core.env.Environment;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Locale;
@SuppressWarnings("SpringJavaAutowiredFieldsWarningInspection")
@SpringBootApplication
public class SimpleDns implements CommandLineRunner {
@Autowired private ApplicationContext applicationContext;
@Autowired private Environment environment;
public static void main(String[] args) {
// SpringApplication.run(SimpleDns.class, args);
SpringApplication app = new SpringApplication(SimpleDns.class);
app.setLazyInitialization(true);
app.run(args);
}
@SuppressWarnings("InfiniteLoopStatement") @Override
public void run(String... args) {
var configuration = applicationContext.getBean(JsonConfiguration.class);
try {
DnsConfig config = new DnsConfig();
config.setExtraServers(new ArrayList<>());
config.setActive(true);
config.setBlocked(new ArrayList<>());
config.getBlocked().add("wpad.*");
config.getBlocked().add("*.trafficmanager.net");
config.setPort(53);
GlobalConfig global = new GlobalConfig();
global.setLocalAddress("localhost");
configuration.setConfiguration(global);
configuration.setConfiguration(config);
} catch (Exception e) {
e.printStackTrace();
}
var resolver =
(DnsMultiResolver) applicationContext.getBean(DnsMultiResolver.class);
resolver.noResponseCaching();
var dnsServer =
(org.kendar.dns.DnsServer) applicationContext.getBean(org.kendar.dns.DnsServer.class);
dnsServer.setBlocker((a)-> a.substring(0,1).toUpperCase(Locale.ROOT)+a.substring(1));
dnsServer.setDnsRunnable((a,b,c)->{return new HttpDnsRunnable(a,b,c);});
while (true) {
try {
dnsServer.run();
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
}
}
}
|
3e1300cc10b90af303f770bd2afea1b9ec083dc8 | 853 | java | Java | src/main/java/iot/jcypher/database/DBType.java | ashr123/jcypher | d1191cb1e485220829f5f631ed3fd7820e4aeafb | [
"Apache-2.0"
] | 91 | 2015-03-05T15:54:23.000Z | 2021-10-29T19:18:37.000Z | src/main/java/iot/jcypher/database/DBType.java | ashr123/jcypher | d1191cb1e485220829f5f631ed3fd7820e4aeafb | [
"Apache-2.0"
] | 58 | 2015-07-07T11:35:13.000Z | 2020-05-27T08:53:39.000Z | src/main/java/iot/jcypher/database/DBType.java | ashr123/jcypher | d1191cb1e485220829f5f631ed3fd7820e4aeafb | [
"Apache-2.0"
] | 23 | 2015-08-12T19:06:15.000Z | 2021-06-10T08:50:51.000Z | 38.772727 | 76 | 0.595545 | 8,025 | /************************************************************************
* Copyright (c) 2014 IoT-Solutions e.U.
*
* 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 iot.jcypher.database;
public enum DBType {
REMOTE, EMBEDDED, IN_MEMORY
}
|
3e1300df9d2d50d5f2594e8b4426af3b78bc1c44 | 1,479 | java | Java | src/main/java/com/spring/auth/role/infrastructure/repositories/DeleteRoleRepository.java | diegotobalina/auth | ea9c9b66c9892a6952872835e5cf9ef8859a68f0 | [
"MIT"
] | null | null | null | src/main/java/com/spring/auth/role/infrastructure/repositories/DeleteRoleRepository.java | diegotobalina/auth | ea9c9b66c9892a6952872835e5cf9ef8859a68f0 | [
"MIT"
] | null | null | null | src/main/java/com/spring/auth/role/infrastructure/repositories/DeleteRoleRepository.java | diegotobalina/auth | ea9c9b66c9892a6952872835e5cf9ef8859a68f0 | [
"MIT"
] | null | null | null | 36.975 | 78 | 0.817444 | 8,026 | package com.spring.auth.role.infrastructure.repositories;
import com.spring.auth.events.ports.PublishRoleDeletedEventPort;
import com.spring.auth.exceptions.application.NotFoundException;
import com.spring.auth.role.infrastructure.repositories.ports.DeleteRolePort;
import com.spring.auth.role.infrastructure.repositories.ports.FindRolePort;
import com.spring.auth.role.domain.Role;
import com.spring.auth.role.domain.RoleJpa;
import com.spring.auth.role.domain.RoleMapper;
import com.spring.auth.role.infrastructure.repositories.jpa.RoleRepositoryJpa;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
/** @author diegotobalina created on 24/06/2020 */
@Repository
@AllArgsConstructor
public class DeleteRoleRepository implements DeleteRolePort {
private RoleRepositoryJpa roleRepositoryJpa;
private FindRolePort findRolePort;
private PublishRoleDeletedEventPort publishRoleDeletedEventPort;
@Override
@Transactional(rollbackFor = Exception.class)
public Role delete(Role role) {
RoleJpa roleJpa = RoleMapper.parse(role);
roleRepositoryJpa.deleteById(roleJpa.getId());
Role deletedRole = RoleMapper.parse(roleJpa);
publishRoleDeletedEventPort.publish(deletedRole);
return deletedRole;
}
@Override
public Role delete(String roleId) throws NotFoundException {
Role role = findRolePort.findById(roleId);
return delete(role);
}
}
|
3e1301342546c273023c59c8bc429a2971b8929a | 3,466 | java | Java | SpineTools-Java/src/org/warlock/spine/messaging/ITKTrunkHandler.java | DamianJMurphy/SpineTools-Java | 550e14526829fdd30ff4691f0439798c67329ade | [
"Apache-2.0"
] | 4 | 2015-11-24T15:34:04.000Z | 2022-02-17T03:59:16.000Z | SpineTools-Java/src/org/warlock/spine/messaging/ITKTrunkHandler.java | DamianJMurphy/SpineTools-Java | 550e14526829fdd30ff4691f0439798c67329ade | [
"Apache-2.0"
] | null | null | null | SpineTools-Java/src/org/warlock/spine/messaging/ITKTrunkHandler.java | DamianJMurphy/SpineTools-Java | 550e14526829fdd30ff4691f0439798c67329ade | [
"Apache-2.0"
] | 4 | 2016-01-05T15:01:23.000Z | 2022-02-17T03:56:02.000Z | 38.711111 | 121 | 0.686567 | 8,027 | /*
Copyright 2014 Health and Social Care Information Centre
Solution Assurance <efpyi@example.com>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package org.warlock.spine.messaging;
import org.warlock.itk.distributionenvelope.DistributionEnvelope;
import java.util.HashMap;
/**
* Implementation of the SpineEbXmlHandler interface, specifically for the ITK Trunk
* message. The Connection Manager automatically makes an instance of this class and
* sets it as the handler for ITK Trunk messages.
*
* The class implements its own handler mechanism for processing received ITK distribution
* envelopes, that is the equivalent of the MHS's mechanism. It creates an instance of
* DefaultFileSaveDistributionEnvelopeHandler when instantiated itself, and uses this to
* handle received ITK messages unless a specific handler is registered against the received
* ITK service.
*
* @author Damian Murphy <efpyi@example.com>
*/
public class ITKTrunkHandler
implements SpineEbXmlHandler
{
private static final int ITKATTACHMENT = 0;
private static final String LOGSOURCE = "ITKTrunkHandler";
private HashMap<String, DistributionEnvelopeHandler> handlers = null;
private DefaultFileSaveDistributionEnvelopeHandler defaultHandler = null;
private Exception bootException = null;
public ITKTrunkHandler()
{
handlers = new HashMap<>();
try {
defaultHandler = new DefaultFileSaveDistributionEnvelopeHandler();
}
catch (java.io.FileNotFoundException e) {
bootException = e;
}
}
/**
* Register an instance of a handler, against the given ITK service.
*
* @param s ITK service name
* @param h Instance of a DistributionEnvelopeHandler implementation.
*/
public void addHandler(String s, DistributionEnvelopeHandler h)
{
handlers.put(s, h);
}
@Override
public void handle(EbXmlMessage m)
throws Exception
{
if (bootException != null)
throw new Exception("Boot exception in ITK Trunk handler", bootException);
// Note that we assume that this is a good enough ITK Trunk message at this point
// because if it wasn't, the attempt to make the ITKDE attachment would have failed
// when the EbXmlMessage was parsed off the network. If it *does* throw a ClassCastException,
// let it because something else has gone wrong in the code.
//
ITKDistributionEnvelopeAttachment a = (ITKDistributionEnvelopeAttachment)m.getAttachments().get(ITKATTACHMENT);
DistributionEnvelope d = a.getDistributionEnvelope();
DistributionEnvelopeHandler h = handlers.get(d.getService());
if (h == null) {
defaultHandler.handle(d);
} else {
h.handle(d);
}
}
}
|
3e130142720eed129bbfc658608a1774ad2c049a | 2,477 | java | Java | breeze-protobuf/src/test/java/com/weibo/test/proto/Gender.java | lion2luo/breeze | 6270b3357cdd42551a66f0afaaadf7f704fec3fd | [
"Apache-2.0"
] | 4 | 2019-07-19T19:51:59.000Z | 2020-12-07T07:36:34.000Z | breeze-protobuf/src/test/java/com/weibo/test/proto/Gender.java | lion2luo/breeze | 6270b3357cdd42551a66f0afaaadf7f704fec3fd | [
"Apache-2.0"
] | null | null | null | breeze-protobuf/src/test/java/com/weibo/test/proto/Gender.java | lion2luo/breeze | 6270b3357cdd42551a66f0afaaadf7f704fec3fd | [
"Apache-2.0"
] | 2 | 2019-04-04T05:30:24.000Z | 2020-10-30T02:59:15.000Z | 23.590476 | 68 | 0.64675 | 8,028 | // Generated by the protocol buffer compiler. DO NOT EDIT!
// source: user.proto
package com.weibo.test.proto;
/**
* Protobuf enum {@code proto.Gender}
*/
public enum Gender
implements com.google.protobuf.ProtocolMessageEnum {
/**
* <code>Man = 0;</code>
*/
Man(0),
/**
* <code>Woman = 1;</code>
*/
Woman(1),
UNRECOGNIZED(-1),
;
/**
* <code>Man = 0;</code>
*/
public static final int Man_VALUE = 0;
/**
* <code>Woman = 1;</code>
*/
public static final int Woman_VALUE = 1;
public final int getNumber() {
if (this == UNRECOGNIZED) {
throw new IllegalArgumentException(
"Can't get the number of an unknown enum value.");
}
return value;
}
/**
* @deprecated Use {@link #forNumber(int)} instead.
*/
@Deprecated
public static Gender valueOf(int value) {
return forNumber(value);
}
public static Gender forNumber(int value) {
switch (value) {
case 0: return Man;
case 1: return Woman;
default: return null;
}
}
public static com.google.protobuf.Internal.EnumLiteMap<Gender>
internalGetValueMap() {
return internalValueMap;
}
private static final com.google.protobuf.Internal.EnumLiteMap<
Gender> internalValueMap =
new com.google.protobuf.Internal.EnumLiteMap<Gender>() {
public Gender findValueByNumber(int number) {
return Gender.forNumber(number);
}
};
public final com.google.protobuf.Descriptors.EnumValueDescriptor
getValueDescriptor() {
return getDescriptor().getValues().get(ordinal());
}
public final com.google.protobuf.Descriptors.EnumDescriptor
getDescriptorForType() {
return getDescriptor();
}
public static final com.google.protobuf.Descriptors.EnumDescriptor
getDescriptor() {
return com.weibo.test.proto.UserProto.getDescriptor()
.getEnumTypes().get(0);
}
private static final Gender[] VALUES = values();
public static Gender valueOf(
com.google.protobuf.Descriptors.EnumValueDescriptor desc) {
if (desc.getType() != getDescriptor()) {
throw new IllegalArgumentException(
"EnumValueDescriptor is not for this type.");
}
if (desc.getIndex() == -1) {
return UNRECOGNIZED;
}
return VALUES[desc.getIndex()];
}
private final int value;
private Gender(int value) {
this.value = value;
}
// @@protoc_insertion_point(enum_scope:proto.Gender)
}
|
3e130194ba2b42170f76c39b39432f7a2f793022 | 390 | java | Java | modules/jooby-spec/src/test/java/apps/SimilarSig.java | auxiliaire/jooby | 49c0a1dbd30b2b17717192a5e3410486f33e67de | [
"Apache-2.0"
] | null | null | null | modules/jooby-spec/src/test/java/apps/SimilarSig.java | auxiliaire/jooby | 49c0a1dbd30b2b17717192a5e3410486f33e67de | [
"Apache-2.0"
] | null | null | null | modules/jooby-spec/src/test/java/apps/SimilarSig.java | auxiliaire/jooby | 49c0a1dbd30b2b17717192a5e3410486f33e67de | [
"Apache-2.0"
] | null | null | null | 15.6 | 46 | 0.489744 | 8,029 | package apps;
import org.jooby.Jooby;
public class SimilarSig extends Jooby {
{
// doc1
get("/1", () -> {
SomeLambda l = new SomeLambda();
Object value = l.get("/x", req -> "Hi");
return value;
});
// doc2
get("/2", () -> {
SomeLambda l = new SomeLambda();
Object value = l.get("/x", req -> "Hi");
return value;
});
}
}
|
3e1302842f7c0b0d9a58efa3cd15be910b233753 | 12,881 | java | Java | customfont/src/main/java/com/kevadiyakrunalk/customfont/util/CustomFontUtils.java | Krunal-Kevadiya/CustomFont | 5894ba5d0ae52225fd606c6b302186e376164869 | [
"Apache-2.0"
] | null | null | null | customfont/src/main/java/com/kevadiyakrunalk/customfont/util/CustomFontUtils.java | Krunal-Kevadiya/CustomFont | 5894ba5d0ae52225fd606c6b302186e376164869 | [
"Apache-2.0"
] | null | null | null | customfont/src/main/java/com/kevadiyakrunalk/customfont/util/CustomFontUtils.java | Krunal-Kevadiya/CustomFont | 5894ba5d0ae52225fd606c6b302186e376164869 | [
"Apache-2.0"
] | null | null | null | 34.07672 | 168 | 0.608726 | 8,030 | package com.kevadiyakrunalk.customfont.util;
import android.content.Context;
import android.content.res.AssetManager;
import android.content.res.Resources;
import android.content.res.TypedArray;
import android.graphics.Paint;
import android.graphics.Typeface;
import android.text.Editable;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.widget.TextView;
import com.kevadiyakrunalk.customfont.CustomFontConfig;
/**
* The type Calligraphy utils.
*/
public final class CustomFontUtils {
/**
* The constant ANDROID_ATTR_TEXT_APPEARANCE.
*/
public static final int[] ANDROID_ATTR_TEXT_APPEARANCE = new int[]{android.R.attr.textAppearance};
/**
* Apply typeface span char sequence.
*
* @param s the s
* @param typeface the typeface
* @return the char sequence
*/
public static CharSequence applyTypefaceSpan(CharSequence s, Typeface typeface) {
if (s != null && s.length() > 0) {
if (!(s instanceof Spannable)) {
s = new SpannableString(s);
}
((Spannable) s).setSpan(TypefaceUtils.getSpan(typeface), 0, s.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
}
return s;
}
/**
* Apply font to text view boolean.
*
* @param textView the text view
* @param typeface the typeface
* @return the boolean
*/
public static boolean applyFontToTextView(final TextView textView, final Typeface typeface) {
return applyFontToTextView(textView, typeface, false);
}
/**
* Apply font to text view boolean.
*
* @param textView the text view
* @param typeface the typeface
* @param deferred the deferred
* @return the boolean
*/
public static boolean applyFontToTextView(final TextView textView, final Typeface typeface, boolean deferred) {
if (textView == null || typeface == null) return false;
textView.setPaintFlags(textView.getPaintFlags() | Paint.SUBPIXEL_TEXT_FLAG | Paint.ANTI_ALIAS_FLAG);
textView.setTypeface(typeface);
if (deferred) {
textView.setText(applyTypefaceSpan(textView.getText(), typeface), TextView.BufferType.SPANNABLE);
textView.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
applyTypefaceSpan(s, typeface);
}
});
}
return true;
}
/**
* Apply font to text view boolean.
*
* @param context the context
* @param textView the text view
* @param filePath the file path
* @return the boolean
*/
public static boolean applyFontToTextView(final Context context, final TextView textView, final String filePath) {
return applyFontToTextView(context, textView, filePath, false);
}
/**
* Apply font to text view boolean.
*
* @param context the context
* @param textView the text view
* @param filePath the file path
* @param deferred the deferred
* @return the boolean
*/
public static boolean applyFontToTextView(final Context context, final TextView textView, final String filePath, boolean deferred) {
if (textView == null || context == null) return false;
final AssetManager assetManager = context.getAssets();
final Typeface typeface = TypefaceUtils.load(assetManager, filePath);
return applyFontToTextView(textView, typeface, deferred);
}
/**
* Apply font to text view.
*
* @param context the context
* @param textView the text view
* @param config the config
*/
public static void applyFontToTextView(final Context context, final TextView textView, final CustomFontConfig config) {
applyFontToTextView(context, textView, config, false);
}
/**
* Apply font to text view.
*
* @param context the context
* @param textView the text view
* @param config the config
* @param deferred the deferred
*/
public static void applyFontToTextView(final Context context, final TextView textView, final CustomFontConfig config, boolean deferred) {
if (context == null || textView == null || config == null) return;
if (!config.isFontSet()) return;
applyFontToTextView(context, textView, config.getFontPath(), deferred);
}
/**
* Apply font to text view.
*
* @param context the context
* @param textView the text view
* @param config the config
* @param textViewFont the text view font
*/
public static void applyFontToTextView(final Context context, final TextView textView, final CustomFontConfig config, final String textViewFont) {
applyFontToTextView(context, textView, config, textViewFont, false);
}
/**
* Apply font to text view.
*
* @param context the context
* @param textView the text view
* @param config the config
* @param textViewFont the text view font
* @param deferred the deferred
*/
public static void applyFontToTextView(final Context context, final TextView textView, final CustomFontConfig config, final String textViewFont, boolean deferred) {
if (context == null || textView == null || config == null) return;
if (!TextUtils.isEmpty(textViewFont) && applyFontToTextView(context, textView, textViewFont, deferred)) {
return;
}
applyFontToTextView(context, textView, config, deferred);
}
/**
* Pull font path from view string.
*
* @param context the context
* @param attrs the attrs
* @param attributeId the attribute id
* @return the string
*/
public static String pullFontPathFromView(Context context, AttributeSet attrs, int[] attributeId) {
if (attributeId == null || attrs == null)
return null;
final String attributeName;
try {
attributeName = context.getResources().getResourceEntryName(attributeId[0]);
} catch (Resources.NotFoundException e) {
// invalid attribute ID
return null;
}
final int stringResourceId = attrs.getAttributeResourceValue(null, attributeName, -1);
return stringResourceId > 0
? context.getString(stringResourceId)
: attrs.getAttributeValue(null, attributeName);
}
/**
* Pull font path from style string.
*
* @param context the context
* @param attrs the attrs
* @param attributeId the attribute id
* @return the string
*/
public static String pullFontPathFromStyle(Context context, AttributeSet attrs, int[] attributeId) {
if (attributeId == null || attrs == null)
return null;
final TypedArray typedArray = context.obtainStyledAttributes(attrs, attributeId);
if (typedArray != null) {
try {
// First defined attribute
String fontFromAttribute = typedArray.getString(0);
if (!TextUtils.isEmpty(fontFromAttribute)) {
return fontFromAttribute;
}
} catch (Exception ignore) {
// Failed for some reason.
} finally {
typedArray.recycle();
}
}
return null;
}
/**
* Pull font path from text appearance string.
*
* @param context the context
* @param attrs the attrs
* @param attributeId the attribute id
* @return the string
*/
public static String pullFontPathFromTextAppearance(final Context context, AttributeSet attrs, int[] attributeId) {
if (attributeId == null || attrs == null) {
return null;
}
int textAppearanceId = -1;
final TypedArray typedArrayAttr = context.obtainStyledAttributes(attrs, ANDROID_ATTR_TEXT_APPEARANCE);
if (typedArrayAttr != null) {
try {
textAppearanceId = typedArrayAttr.getResourceId(0, -1);
} catch (Exception ignored) {
// Failed for some reason
return null;
} finally {
typedArrayAttr.recycle();
}
}
final TypedArray textAppearanceAttrs = context.obtainStyledAttributes(textAppearanceId, attributeId);
if (textAppearanceAttrs != null) {
try {
return textAppearanceAttrs.getString(0);
} catch (Exception ignore) {
// Failed for some reason.
return null;
} finally {
textAppearanceAttrs.recycle();
}
}
return null;
}
/**
* Pull font path from theme string.
*
* @param context the context
* @param styleAttrId the style attr id
* @param attributeId the attribute id
* @return the string
*/
public static String pullFontPathFromTheme(Context context, int styleAttrId, int[] attributeId) {
if (styleAttrId == -1 || attributeId == null)
return null;
final Resources.Theme theme = context.getTheme();
final TypedValue value = new TypedValue();
theme.resolveAttribute(styleAttrId, value, true);
final TypedArray typedArray = theme.obtainStyledAttributes(value.resourceId, attributeId);
try {
String font = typedArray.getString(0);
return font;
} catch (Exception ignore) {
// Failed for some reason.
return null;
} finally {
typedArray.recycle();
}
}
/**
* Pull font path from theme string.
*
* @param context the context
* @param styleAttrId the style attr id
* @param subStyleAttrId the sub style attr id
* @param attributeId the attribute id
* @return the string
*/
public static String pullFontPathFromTheme(Context context, int styleAttrId, int subStyleAttrId, int[] attributeId) {
if (styleAttrId == -1 || attributeId == null)
return null;
final Resources.Theme theme = context.getTheme();
final TypedValue value = new TypedValue();
theme.resolveAttribute(styleAttrId, value, true);
int subStyleResId = -1;
final TypedArray parentTypedArray = theme.obtainStyledAttributes(value.resourceId, new int[]{subStyleAttrId});
try {
subStyleResId = parentTypedArray.getResourceId(0, -1);
} catch (Exception ignore) {
// Failed for some reason.
return null;
} finally {
parentTypedArray.recycle();
}
if (subStyleResId == -1) return null;
final TypedArray subTypedArray = context.obtainStyledAttributes(subStyleResId, attributeId);
if (subTypedArray != null) {
try {
return subTypedArray.getString(0);
} catch (Exception ignore) {
// Failed for some reason.
return null;
} finally {
subTypedArray.recycle();
}
}
return null;
}
private static Boolean sToolbarCheck = null;
private static Boolean sAppCompatViewCheck = null;
/**
* Can check for v 7 toolbar boolean.
*
* @return the boolean
*/
public static boolean canCheckForV7Toolbar() {
if (sToolbarCheck == null) {
try {
Class.forName("android.support.v7.widget.Toolbar");
sToolbarCheck = Boolean.TRUE;
} catch (ClassNotFoundException e) {
sToolbarCheck = Boolean.FALSE;
}
}
return sToolbarCheck;
}
/**
* Can add v 7 app compat views boolean.
*
* @return the boolean
*/
public static boolean canAddV7AppCompatViews() {
if (sAppCompatViewCheck == null) {
try {
Class.forName("android.support.v7.widget.AppCompatTextView");
sAppCompatViewCheck = Boolean.TRUE;
} catch (ClassNotFoundException e) {
sAppCompatViewCheck = Boolean.FALSE;
}
}
return sAppCompatViewCheck;
}
private CustomFontUtils() {
}
}
|
3e13049eb4dc8ac34bccdd8955ded170cdcea465 | 1,111 | java | Java | src/com/edasaki/rpg/commands/console/AdRewardCommand.java | edasaki/ZentrelaRPG | 08166c834ab11f8ee1b2e01a23f98cad9614d1ef | [
"MIT"
] | 12 | 2017-02-22T10:00:13.000Z | 2021-06-11T10:48:28.000Z | src/com/edasaki/rpg/commands/console/AdRewardCommand.java | TommyAlmeida/ZentrelaRPG | 08166c834ab11f8ee1b2e01a23f98cad9614d1ef | [
"MIT"
] | null | null | null | src/com/edasaki/rpg/commands/console/AdRewardCommand.java | TommyAlmeida/ZentrelaRPG | 08166c834ab11f8ee1b2e01a23f98cad9614d1ef | [
"MIT"
] | 18 | 2017-02-22T14:39:42.000Z | 2021-06-27T08:46:59.000Z | 29.236842 | 92 | 0.674167 | 8,031 | package com.edasaki.rpg.commands.console;
import org.bukkit.ChatColor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import com.edasaki.rpg.PlayerDataRPG;
import com.edasaki.rpg.commands.RPGAbstractCommand;
import com.edasaki.rpg.rewards.RewardsManager;
public class AdRewardCommand extends RPGAbstractCommand {
public AdRewardCommand(String... commandNames) {
super(commandNames);
}
@Override
public void execute(CommandSender sender, String[] args) {
String s = args[0];
Player target = plugin.getServer().getPlayerExact(s);
if (target != null && target.isOnline() && plugin.getPD(target) != null) {
// PlayerData pd = plugin.getPD(target);
RewardsManager.givePoints(target.getName(), 1);
} else {
sender.sendMessage(ChatColor.RED + "Could not find online player '" + s + "'.");
}
}
@Override
public void executePlayer(Player p, PlayerDataRPG pd, String[] args) {
}
@Override
public void executeConsole(CommandSender sender, String[] args) {
}
}
|
3e13066c3b38b3bc51a23a0fd3c017a89323484e | 2,637 | java | Java | app/src/test/java/sw19/moring03/paint/HeartTest.java | sw19-tug/morning03 | 1780596a7c8635758d78b2d426698d8999988e63 | [
"MIT"
] | 1 | 2019-03-20T08:07:09.000Z | 2019-03-20T08:07:09.000Z | app/src/test/java/sw19/moring03/paint/HeartTest.java | sw19-tug/morning03 | 1780596a7c8635758d78b2d426698d8999988e63 | [
"MIT"
] | 39 | 2019-03-19T11:15:54.000Z | 2019-06-18T07:35:21.000Z | app/src/test/java/sw19/moring03/paint/HeartTest.java | sw19-tug/morning03 | 1780596a7c8635758d78b2d426698d8999988e63 | [
"MIT"
] | null | null | null | 29.3 | 121 | 0.6697 | 8,032 | package sw19.moring03.paint;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.mockito.junit.MockitoJUnitRunner;
import sw19.moring03.paint.tools.HeartTool;
import sw19.moring03.paint.utils.PointF;
import static junit.framework.TestCase.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
@RunWith(MockitoJUnitRunner.class)
public class HeartTest {
private Canvas canvas;
private Paint paint;
@Before
public void startUp() {
canvas = new Canvas();
paint = new Paint();
}
@Test
public void testHeartSimple() {
HeartTool tool = new HeartTool(Color.BLACK, 10);
assertEquals(Color.BLACK, tool.getColor());
assertEquals(10, tool.getStrokeWidth());
tool.addPoint(new PointF(15, 15));
tool.addPoint(new PointF(30, 30));
tool.addPoint(new PointF(60, 60));
assertTrue(tool.draw(canvas, paint));
}
@Test
public void testInvalidHeart() {
HeartTool tool = new HeartTool(Color.BLACK, 10);
tool.addPoint(new PointF(10, 10));
assertFalse(tool.draw(canvas, paint));
}
@Test
public void testDrawHeart() {
int expectedPaths = 1;
int expectedCircles = 2;
HeartTool tool = new HeartTool(Color.BLACK, 10);
tool.addPoint(new PointF(10, 10));
tool.addPoint(new PointF(20, 20));
canvas = Mockito.mock(Canvas.class);
tool.draw(canvas, paint);
Mockito.verify(canvas, Mockito.times(expectedPaths)).drawPath(Mockito.any(Path.class), Mockito.any(Paint.class));
Mockito.verify(canvas, Mockito.times(expectedCircles)).drawCircle(Mockito.anyFloat(), Mockito.anyFloat(),
Mockito.anyFloat(), Mockito.any(Paint.class));
}
@Test
public void testDrawInvertedHeart() {
int expectedPaths = 1;
int expectedCircles = 2;
HeartTool tool = new HeartTool(Color.BLACK, 10);
tool.addPoint(new PointF(30, 30));
tool.addPoint(new PointF(10, 10));
canvas = Mockito.mock(Canvas.class);
tool.draw(canvas, paint);
Mockito.verify(canvas, Mockito.times(expectedPaths)).drawPath(Mockito.any(Path.class), Mockito.any(Paint.class));
Mockito.verify(canvas, Mockito.times(expectedCircles)).drawCircle(Mockito.anyFloat(), Mockito.anyFloat(),
Mockito.anyFloat(), Mockito.any(Paint.class));
}
} |
3e1306f0e8965109401c22bd391f51d8e2a9a274 | 9,275 | java | Java | dac/daemon/src/main/java/com/dremio/dac/cmd/ExportProfiles.java | geetek/dremio-oss | 812c7f32f9437df52b1d7bd8d5c45f9a79b6e9d2 | [
"Apache-2.0"
] | 1,085 | 2017-07-19T15:08:38.000Z | 2022-03-29T13:35:07.000Z | dac/daemon/src/main/java/com/dremio/dac/cmd/ExportProfiles.java | geetek/dremio-oss | 812c7f32f9437df52b1d7bd8d5c45f9a79b6e9d2 | [
"Apache-2.0"
] | 20 | 2017-07-19T20:16:27.000Z | 2021-12-02T10:56:25.000Z | dac/daemon/src/main/java/com/dremio/dac/cmd/ExportProfiles.java | geetek/dremio-oss | 812c7f32f9437df52b1d7bd8d5c45f9a79b6e9d2 | [
"Apache-2.0"
] | 398 | 2017-07-19T18:12:58.000Z | 2022-03-30T09:37:40.000Z | 39.135021 | 155 | 0.719245 | 8,033 | /*
* Copyright (C) 2017-2019 Dremio Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.dremio.dac.cmd;
import java.io.IOException;
import java.security.GeneralSecurityException;
import java.time.LocalDateTime;
import java.time.OffsetDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.Optional;
import com.beust.jcommander.IStringConverter;
import com.beust.jcommander.JCommander;
import com.beust.jcommander.Parameter;
import com.beust.jcommander.ParameterException;
import com.beust.jcommander.Parameters;
import com.dremio.dac.resource.ExportProfilesParams;
import com.dremio.dac.resource.ExportProfilesParams.ExportFormatType;
import com.dremio.dac.resource.ExportProfilesParams.WriteFileMode;
import com.dremio.dac.resource.ExportProfilesResource;
import com.dremio.dac.resource.ExportProfilesStats;
import com.dremio.dac.server.DACConfig;
import com.dremio.dac.server.admin.profile.ProfilesExporter;
import com.dremio.datastore.LocalKVStoreProvider;
import com.dremio.datastore.api.LegacyKVStoreProvider;
import com.google.common.annotations.VisibleForTesting;
/**
* Local date time parser.
*/
class LocalDateTimeConverter implements IStringConverter<LocalDateTime> {
@Override
public LocalDateTime convert(String value) {
String dateFormat = "yyyy-MM-dd";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern(dateFormat + "'T'HH[:mm[:ss]]");
if (value.length() == dateFormat.length()) {
//see https://stackoverflow.com/quetions/27454025/unable-to-obtain-localdatetime-from-temporalaccessor-when-parsing-localdatetime
value += "T00"; // add hours to a string to make sure that parse will not fail for date string without time
}
return LocalDateTime.parse(value, formatter);
}
}
/**
* Export profiles command.
*/
@AdminCommand(value = "export-profiles", description = "Exports profiles of jobs from Dremio")
public class ExportProfiles {
/**
* Command line options for export profiles
*/
@Parameters(separators = "=")
static final class ExportProfilesOptions {
@Parameter(names={"-h", "--help"}, description="show usage", help=true)
private boolean help = false;
@Parameter(names= {"--output"}, description="Path to generate profile chunks." +
"Example: /tmp/profiles/", required = true)
private String outputFilePath = null;
@Parameter(names= {"--write-mode"}, description="Specifies how we should handle a case, when target file already exists.")
private WriteFileMode writeMode = WriteFileMode.FAIL_IF_EXISTS;
@Parameter(names= {"--from"}, description="Export profiles beginning from this date inclusively (job_end_time >= toDate)." +
"Example: 2011-12-03T10:15:30 ", converter = LocalDateTimeConverter.class)
private LocalDateTime fromDate = null;
@Parameter(names= {"--to"}, description="Export profiles ending by this date exclusively (job_end_time < toDate)." +
"Example: 2011-12-03T10:15:30", converter = LocalDateTimeConverter.class)
private LocalDateTime toDate = null;
@Parameter(names= {"-u", "--user"}, description="username (admin). Is required for online mode [--online]")
private String userName = null;
@Parameter(names= {"-p", "--password"}, description="password. Is required for online mode [--online]", password=true)
private String password = null;
@Parameter(names= {"-a", "--accept-all"}, description="accept all ssl certificates")
private boolean acceptAll = false;
@Parameter(names= {"--size"}, description="Chunk size for each zip file", hidden = true)
private int chunkSize = 10;
@Parameter(names= {"--local-path"}, description="Default local path to export", hidden = true)
private String localPath = null;
@Parameter(names= {"--format"}, description="Format in which profiles should be exported. .JSON and .ZIP(default) are supported.")
private ExportFormatType outputFormatType = ExportFormatType.ZIP;
@Parameter(names= {"-l", "--local-attach"}, description="Attach locally to Dremio JVM to authenticate user. Not compatible with user/password options")
private boolean localAttach = false;
@Parameter(names= {"-o", "--offline"}, description="Append this option to use offline export.")
private boolean offlineMode = false;
}
private static boolean isTimeSet = true;
public static void main(String[] args)
throws Exception {
final ExportProfilesOptions options = new ExportProfilesOptions();
JCommander jc = JCommander.newBuilder().addObject(options).build();
jc.setProgramName("dremio-admin export-profiles");
try {
jc.parse(args);
} catch (ParameterException p) {
AdminLogger.log(p.getMessage());
jc.usage();
System.exit(1);
}
if(options.help) {
jc.usage();
System.exit(0);
}
if (options.localAttach && (options.userName != null || options.password != null)){
AdminLogger.log("Do not pass username or password when running in local-attach mode");
jc.usage();
System.exit(1);
}
setTime(options);
setPath(options);
final DACConfig dacConfig = DACConfig.newConfig();
if (!dacConfig.isMaster) {
throw new UnsupportedOperationException("Profile export should be ran on master node.");
}
if (options.localAttach) {
String[] attachArg = {"export-profiles", getAPIExportParams(options).toParamString()};
try {
DremioAttach.main(attachArg);
} catch (NoClassDefFoundError error) {
AdminLogger.log("A JDK is required to use local-attach mode. Please make sure JAVA_HOME is correctly configured");
}
} else {
if (options.offlineMode) {
exportOffline(options, dacConfig);
}else {
if (options.userName == null) {
options.userName = System.console().readLine("username: ");
}
if (options.password == null) {
char[] pwd = System.console().readPassword("password: ");
options.password = new String(pwd);
}
exportOnline(options, options.userName, options.password, options.acceptAll, dacConfig);
}
}
}
private static Long getMilliseconds(LocalDateTime date, ZoneOffset zoneOffset) {
return date == null ? null : date.toInstant(zoneOffset).toEpochMilli();
}
static ExportProfilesParams getAPIExportParams(ExportProfilesOptions options) {
ZoneOffset zoneOffset = OffsetDateTime.now().getOffset();
return new ExportProfilesParams(options.outputFilePath, options.writeMode,
getMilliseconds(options.fromDate, zoneOffset),
getMilliseconds(options.toDate, zoneOffset),
options.outputFormatType,
options.chunkSize);
}
private static void exportOnline(ExportProfilesOptions options, String userName, String password, boolean acceptAll, DACConfig dacConfig)
throws IOException, GeneralSecurityException {
final WebClient client = new WebClient(dacConfig, userName, password, !acceptAll);
AdminLogger.log(client.buildPost(ExportProfilesStats.class, "/export-profiles", getAPIExportParams(options))
.retrieveStats(options.fromDate, options.toDate, isTimeSet));
}
private static void exportOffline(ExportProfilesOptions options, DACConfig dacConfig)
throws Exception {
Optional<LocalKVStoreProvider> providerOptional = CmdUtils.getKVStoreProvider(dacConfig.getConfig());
if (!providerOptional.isPresent()) {
AdminLogger.log("No database found. Profiles are not exported");
return;
}
try (LocalKVStoreProvider kvStoreProvider = providerOptional.get()) {
kvStoreProvider.start();
exportOffline(options, kvStoreProvider.asLegacy());
}
}
static void exportOffline(ExportProfilesOptions options, LegacyKVStoreProvider provider)
throws Exception {
ProfilesExporter exporter = ExportProfilesResource.getExporter(getAPIExportParams(options));
AdminLogger.log(exporter.export(provider).retrieveStats(options.fromDate, options.toDate, isTimeSet));
}
@VisibleForTesting
static void setPath(ExportProfilesOptions options) {
if (options.outputFilePath == null) {
options.outputFilePath = options.localPath;
}
}
@VisibleForTesting
static void setTime(ExportProfilesOptions options) {
if (options.toDate == null) {
options.toDate = LocalDateTime.now();
isTimeSet = false;
}
if (options.fromDate == null) {
options.fromDate = options.toDate.minusDays(30);
isTimeSet = false;
}
if (!options.fromDate.isBefore(options.toDate)) {
throw new ParameterException(String.format("'from' parameter (%s) should be less than 'to' parameter (%s)",
options.fromDate, options.toDate));
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.