hexsha
stringlengths 40
40
| size
int64 8
1.04M
| content
stringlengths 8
1.04M
| avg_line_length
float64 2.24
100
| max_line_length
int64 4
1k
| alphanum_fraction
float64 0.25
0.97
|
---|---|---|---|---|---|
05483fc224ee2b9f8295aa00438b7add648f0e42 | 2,205 | package cn.edu.nju.software.pinpoint.statistics.controller;
import cn.edu.nju.software.pinpoint.statistics.entity.common.JSONResult;
import cn.edu.nju.software.pinpoint.statistics.utils.FileUtil;
import cn.edu.nju.software.pinpoint.statistics.utils.cors.CorsConfigure;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.util.ClassUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.util.HashMap;
import java.util.Map;
@CrossOrigin
//@RestController
@Api(value = "文件上传接口")
@RequestMapping(value = "/api")
@Controller
public class FileUploadController{
@Value("${filepath}")
private String path;
/*
* 获取file.html页面
*/
@RequestMapping(value ="file",method = RequestMethod.GET)
public String file(){
return "/file";
}
//处理文件上传
@RequestMapping(value = "/upload", method = RequestMethod.POST)
@ApiOperation(value = "文件上传", notes = "返回状态200成功")
@ResponseBody
public JSONResult uploadImg(@RequestParam("file") MultipartFile file,
HttpServletRequest request) {
String contentType = file.getContentType(); //图片文件类型
String fileName = file.getOriginalFilename(); //图片名字
//文件存放路径
if(StringUtils.isEmpty(path))
path = ClassUtils.getDefaultClassLoader().getResource("").getPath();
// String filePath = "/Users/yaya/Desktop/upload/";
String filePath = path+"/upload/";
System.out.println("======: "+path);
//调用文件处理类FileUtil,处理文件,将文件写入指定位置
try {
FileUtil.uploadFile(file.getBytes(), filePath, fileName);
} catch (Exception e) {
// TODO: handle exception
}
Map<String, String> result = new HashMap<String, String>();
result.put("path", filePath + fileName);
// 返回图片的存放路径
return JSONResult.ok(result);
}
}
| 31.956522 | 80 | 0.685261 |
c9268bb72060d7e3eea09f1c5271d3abdad51a16 | 2,033 | /*
* Copyright (c) 2018 AITIA International Inc.
*
* This work is part of the Productive 4.0 innovation project, which receives grants from the
* European Commissions H2020 research and innovation programme, ECSEL Joint Undertaking
* (project no. 737459), the free state of Saxony, the German Federal Ministry of Education and
* national funding authorities from involved countries.
*/
package eu.arrowhead.common.filter;
import eu.arrowhead.common.exception.ErrorMessage;
import eu.arrowhead.common.exception.ExceptionType;
import javax.annotation.Priority;
import javax.ws.rs.Priorities;
import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.container.ContainerRequestFilter;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import javax.ws.rs.ext.Provider;
@Provider
@Priority(Priorities.ENTITY_CODER)
public class EmptyPayloadFilter implements ContainerRequestFilter {
@Override
public void filter(ContainerRequestContext requestContext) {
String method = requestContext.getMethod();
int contentLength = requestContext.getLength();
if ((method.equals("POST") || method.equals("PUT")) && contentLength == 0) {
ErrorMessage em = new ErrorMessage(
"Message body is null (unusual for POST/PUT request)! If you truly want to send an empty payload, try sending empty brackets: {} for "
+ "JSONObject, [] for JSONArray.", 400, ExceptionType.BAD_PAYLOAD, requestContext.getUriInfo().getAbsolutePath().toString());
requestContext.abortWith(Response.status(Status.BAD_REQUEST).entity(em).build());
}
if ((method.equals(("GET")) || method.equals("DELETE")) && contentLength > 0) {
ErrorMessage em = new ErrorMessage("Message body is not null (unusual for GET/DELETE request)!", 400, ExceptionType.BAD_PAYLOAD,
requestContext.getUriInfo().getAbsolutePath().toString());
requestContext.abortWith(Response.status(Status.BAD_REQUEST).entity(em).build());
}
}
}
| 44.195652 | 144 | 0.735366 |
bb2aee63f806ac42c2127cfcfa67eb0674173c52 | 1,075 | package org.knowm.xchange.bittrex.dto.marketdata;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.ArrayList;
public class BittrexMarketSummariesResponse {
private final boolean success;
private final String message;
private final ArrayList<BittrexMarketSummary> marketSummaries;
public BittrexMarketSummariesResponse(
@JsonProperty("success") boolean success,
@JsonProperty("message") String message,
@JsonProperty("result") ArrayList<BittrexMarketSummary> result) {
super();
this.success = success;
this.message = message;
this.marketSummaries = result;
}
public boolean isSuccess() {
return success;
}
public String getMessage() {
return message;
}
public ArrayList<BittrexMarketSummary> getMarketSummaries() {
return marketSummaries;
}
@Override
public String toString() {
return "BittrexMarketSummariesResponse [success="
+ success
+ ", message="
+ message
+ ", marketSummaries="
+ marketSummaries
+ "]";
}
}
| 21.5 | 71 | 0.693953 |
6b9a912b5c5a683e84fb8ab4f1dc133e147d9f5d | 269 | package gaia3d.persistence;
import org.springframework.stereotype.Repository;
/**
* 공통 처리
* @author jeongdae
*
*/
@Repository
public interface CommonMapper {
/**
* 테이블 존재 유무 체크
* @param tableName
* @return
*/
Boolean isTableExist(String tableName);
}
| 12.809524 | 49 | 0.69145 |
0af1de251059b309abbcbbc888b5a7db6dd46714 | 5,595 | package com.tzutalin.dlibtest;
import android.Manifest;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import com.dexafree.materialList.card.Card;
import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.UiThread;
import org.androidannotations.annotations.ViewById;
import java.util.List;
import hugo.weaving.DebugLog;
import timber.log.Timber;
@EActivity(R.layout.activity_main)
public class MainActivity extends AppCompatActivity {
private static final int REQUEST_CODE_PERMISSION = 2;
private static final String TAG = "MainActivity";
// Storage Permissions
private static String[] PERMISSIONS_REQ = {
Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.WRITE_EXTERNAL_STORAGE,
Manifest.permission.CAMERA
};
protected String mTestImgPath;
// UI
@ViewById(R.id.fab_cam)
protected FloatingActionButton mFabCamActionBt;
@ViewById(R.id.toolbar)
protected Toolbar mToolbar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setSupportActionBar(mToolbar);
// Just use hugo to print log
isExternalStorageWritable();
isExternalStorageReadable();
// For API 23+ you need to request the read/write permissions even if they are already in your manifest.
int currentapiVersion = android.os.Build.VERSION.SDK_INT;
if (currentapiVersion >= Build.VERSION_CODES.M) {
verifyPermissions(this);
}
//we set "noDetection" as default detectionMode
SharedPreferences mSharedPreferences = getSharedPreferences("userInfo", MODE_PRIVATE);
SharedPreferences.Editor edit = mSharedPreferences.edit();
edit.putString("detectionMode", "eyesBlinkDetection");
edit.apply();
}
@AfterViews
protected void setupUI() {
mToolbar.setTitle(getString(R.string.app_name));
}
@Click({R.id.fab_cam})
protected void launchCameraPreview() {
startActivity(new Intent(this, CameraActivity.class));
}
/**
* Checks if the app has permission to write to device storage or open camera
* If the app does not has permission then the user will be prompted to grant permission
*/
@DebugLog
private static boolean verifyPermissions(Activity activity) {
// Check if we have write permission
int write_permission = ActivityCompat.checkSelfPermission(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE);
int read_persmission = ActivityCompat.checkSelfPermission(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE);
int camera_permission = ActivityCompat.checkSelfPermission(activity, Manifest.permission.CAMERA);
if (write_permission != PackageManager.PERMISSION_GRANTED ||
read_persmission != PackageManager.PERMISSION_GRANTED ||
camera_permission != PackageManager.PERMISSION_GRANTED) {
// We don't have permission so prompt the user
ActivityCompat.requestPermissions(
activity,
PERMISSIONS_REQ,
REQUEST_CODE_PERMISSION
);
return false;
} else {
return true;
}
}
/* Checks if external storage is available for read and write */
@DebugLog
private boolean isExternalStorageWritable() {
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
return true;
}
return false;
}
/* Checks if external storage is available to at least read */
@DebugLog
private boolean isExternalStorageReadable() {
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state) ||
Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
return true;
}
return false;
}
@DebugLog
protected void demoStaticImage() {
if (mTestImgPath != null) {
Timber.tag(TAG).d("demoStaticImage() launch a task to det");
} else {
Timber.tag(TAG).d("demoStaticImage() mTestImgPath is null, go to gallery");
}
}
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
if (requestCode == REQUEST_CODE_PERMISSION) {
demoStaticImage();
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
}
private ProgressDialog mDialog;
@UiThread
protected void addCardListView(List<Card> cardrets) {
}
@UiThread
protected void showDiaglog() {
mDialog = ProgressDialog.show(MainActivity.this, "Wait", "Face detection", true);
}
@UiThread
protected void dismissDialog() {
if (mDialog != null) {
mDialog.dismiss();
}
}
}
| 33.502994 | 120 | 0.687578 |
a7768d0ae3f745c4380601dfcab35e7df9919457 | 12,564 | /*
* Copyright 2013 Twitter, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.squareup.okhttp.internal.spdy;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
/**
* This class was originally composed from the following classes in
* <a href="https://github.com/twitter/hpack">Twitter Hpack</a>.
* <ul>
* <li>{@code com.twitter.hpack.HuffmanEncoder}</li>
* <li>{@code com.twitter.hpack.HuffmanDecoder}</li>
* <li>{@code com.twitter.hpack.HpackUtil}</li>
* </ul>
*/
class Huffman {
enum Codec {
REQUEST(REQUEST_CODES, REQUEST_CODE_LENGTHS),
RESPONSE(RESPONSE_CODES, RESPONSE_CODE_LENGTHS);
private final Node root = new Node();
private final int[] codes;
private final byte[] lengths;
/**
* @param codes Index designates the symbol this code represents.
* @param lengths Index designates the symbol this code represents.
*/
Codec(int[] codes, byte[] lengths) {
buildTree(codes, lengths);
this.codes = codes;
this.lengths = lengths;
}
void encode(byte[] data, OutputStream out) throws IOException {
long current = 0;
int n = 0;
for (int i = 0; i < data.length; i++) {
int b = data[i] & 0xFF;
int code = codes[b];
int nbits = lengths[b];
current <<= nbits;
current |= code;
n += nbits;
while (n >= 8) {
n -= 8;
out.write(((int) (current >> n)));
}
}
if (n > 0) {
current <<= (8 - n);
current |= (0xFF >>> n);
out.write((int) current);
}
}
int encodedLength(byte[] bytes) {
long len = 0;
for (int i = 0; i < bytes.length; i++) {
int b = bytes[i] & 0xFF;
len += lengths[b];
}
return (int) ((len + 7) >> 3);
}
byte[] decode(byte[] buf) throws IOException {
// FIXME
ByteArrayOutputStream baos = new ByteArrayOutputStream();
Node node = root;
int current = 0;
int nbits = 0;
for (int i = 0; i < buf.length; i++) {
int b = buf[i] & 0xFF;
current = (current << 8) | b;
nbits += 8;
while (nbits >= 8) {
int c = (current >>> (nbits - 8)) & 0xFF;
node = node.children[c];
if (node.children == null) {
// terminal node
baos.write(node.symbol);
nbits -= node.terminalBits;
node = root;
} else {
// non-terminal node
nbits -= 8;
}
}
}
while (nbits > 0) {
int c = (current << (8 - nbits)) & 0xFF;
node = node.children[c];
if (node.children != null || node.terminalBits > nbits) {
break;
}
baos.write(node.symbol);
nbits -= node.terminalBits;
node = root;
}
return baos.toByteArray();
}
private void buildTree(int[] codes, byte[] lengths) {
for (int i = 0; i < lengths.length; i++) {
addCode(i, codes[i], lengths[i]);
}
}
private void addCode(int sym, int code, byte len) {
Node terminal = new Node(sym, len);
Node current = root;
while (len > 8) {
len -= 8;
int i = ((code >>> len) & 0xFF);
if (current.children == null) {
throw new IllegalStateException("invalid dictionary: prefix not unique");
}
if (current.children[i] == null) {
current.children[i] = new Node();
}
current = current.children[i];
}
int shift = 8 - len;
int start = (code << shift) & 0xFF;
int end = 1 << shift;
for (int i = start; i < start + end; i++) {
current.children[i] = terminal;
}
}
}
private static final class Node {
// Null if terminal.
private final Node[] children;
// Terminal nodes have a symbol.
private final int symbol;
// Number of bits represented in the terminal node.
private final int terminalBits;
/** Construct an internal node. */
Node() {
this.children = new Node[256];
this.symbol = 0; // Not read.
this.terminalBits = 0; // Not read.
}
/**
* Construct a terminal node.
*
* @param symbol symbol the node represents
* @param bits length of Huffman code in bits
*/
Node(int symbol, int bits) {
this.children = null;
this.symbol = symbol;
int b = bits & 0x07;
this.terminalBits = b == 0 ? 8 : b;
}
}
// Appendix C: Huffman Codes For Requests
// http://tools.ietf.org/html/draft-ietf-httpbis-header-compression-05#appendix-C
private static final int[] REQUEST_CODES = {
0x7ffffba, 0x7ffffbb, 0x7ffffbc, 0x7ffffbd, 0x7ffffbe, 0x7ffffbf, 0x7ffffc0, 0x7ffffc1,
0x7ffffc2, 0x7ffffc3, 0x7ffffc4, 0x7ffffc5, 0x7ffffc6, 0x7ffffc7, 0x7ffffc8, 0x7ffffc9,
0x7ffffca, 0x7ffffcb, 0x7ffffcc, 0x7ffffcd, 0x7ffffce, 0x7ffffcf, 0x7ffffd0, 0x7ffffd1,
0x7ffffd2, 0x7ffffd3, 0x7ffffd4, 0x7ffffd5, 0x7ffffd6, 0x7ffffd7, 0x7ffffd8, 0x7ffffd9, 0xe8,
0xffc, 0x3ffa, 0x7ffc, 0x7ffd, 0x24, 0x6e, 0x7ffe, 0x7fa, 0x7fb, 0x3fa, 0x7fc, 0xe9, 0x25,
0x4, 0x0, 0x5, 0x6, 0x7, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x1ec, 0xea, 0x3fffe, 0x2d,
0x1fffc, 0x1ed, 0x3ffb, 0x6f, 0xeb, 0xec, 0xed, 0xee, 0x70, 0x1ee, 0x1ef, 0x1f0, 0x1f1, 0x3fb,
0x1f2, 0xef, 0x1f3, 0x1f4, 0x1f5, 0x1f6, 0x1f7, 0xf0, 0xf1, 0x1f8, 0x1f9, 0x1fa, 0x1fb, 0x1fc,
0x3fc, 0x3ffc, 0x7ffffda, 0x1ffc, 0x3ffd, 0x2e, 0x7fffe, 0x8, 0x2f, 0x9, 0x30, 0x1, 0x31,
0x32, 0x33, 0xa, 0x71, 0x72, 0xb, 0x34, 0xc, 0xd, 0xe, 0xf2, 0xf, 0x10, 0x11, 0x35, 0x73,
0x36, 0xf3, 0xf4, 0xf5, 0x1fffd, 0x7fd, 0x1fffe, 0xffd, 0x7ffffdb, 0x7ffffdc, 0x7ffffdd,
0x7ffffde, 0x7ffffdf, 0x7ffffe0, 0x7ffffe1, 0x7ffffe2, 0x7ffffe3, 0x7ffffe4, 0x7ffffe5,
0x7ffffe6, 0x7ffffe7, 0x7ffffe8, 0x7ffffe9, 0x7ffffea, 0x7ffffeb, 0x7ffffec, 0x7ffffed,
0x7ffffee, 0x7ffffef, 0x7fffff0, 0x7fffff1, 0x7fffff2, 0x7fffff3, 0x7fffff4, 0x7fffff5,
0x7fffff6, 0x7fffff7, 0x7fffff8, 0x7fffff9, 0x7fffffa, 0x7fffffb, 0x7fffffc, 0x7fffffd,
0x7fffffe, 0x7ffffff, 0x3ffff80, 0x3ffff81, 0x3ffff82, 0x3ffff83, 0x3ffff84, 0x3ffff85,
0x3ffff86, 0x3ffff87, 0x3ffff88, 0x3ffff89, 0x3ffff8a, 0x3ffff8b, 0x3ffff8c, 0x3ffff8d,
0x3ffff8e, 0x3ffff8f, 0x3ffff90, 0x3ffff91, 0x3ffff92, 0x3ffff93, 0x3ffff94, 0x3ffff95,
0x3ffff96, 0x3ffff97, 0x3ffff98, 0x3ffff99, 0x3ffff9a, 0x3ffff9b, 0x3ffff9c, 0x3ffff9d,
0x3ffff9e, 0x3ffff9f, 0x3ffffa0, 0x3ffffa1, 0x3ffffa2, 0x3ffffa3, 0x3ffffa4, 0x3ffffa5,
0x3ffffa6, 0x3ffffa7, 0x3ffffa8, 0x3ffffa9, 0x3ffffaa, 0x3ffffab, 0x3ffffac, 0x3ffffad,
0x3ffffae, 0x3ffffaf, 0x3ffffb0, 0x3ffffb1, 0x3ffffb2, 0x3ffffb3, 0x3ffffb4, 0x3ffffb5,
0x3ffffb6, 0x3ffffb7, 0x3ffffb8, 0x3ffffb9, 0x3ffffba, 0x3ffffbb, 0x3ffffbc, 0x3ffffbd,
0x3ffffbe, 0x3ffffbf, 0x3ffffc0, 0x3ffffc1, 0x3ffffc2, 0x3ffffc3, 0x3ffffc4, 0x3ffffc5,
0x3ffffc6, 0x3ffffc7, 0x3ffffc8, 0x3ffffc9, 0x3ffffca, 0x3ffffcb, 0x3ffffcc, 0x3ffffcd,
0x3ffffce, 0x3ffffcf, 0x3ffffd0, 0x3ffffd1, 0x3ffffd2, 0x3ffffd3, 0x3ffffd4, 0x3ffffd5,
0x3ffffd6, 0x3ffffd7, 0x3ffffd8, 0x3ffffd9, 0x3ffffda, 0x3ffffdb
};
private static final byte[] REQUEST_CODE_LENGTHS = {
27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
27, 27, 27, 27, 27, 27, 27, 27, 27, 8, 12, 14, 15, 15, 6, 7, 15, 11, 11, 10, 11, 8, 6, 5, 4,
5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 9, 8, 18, 6, 17, 9, 14, 7, 8, 8, 8, 8, 7, 9, 9, 9, 9, 10, 9, 8,
9, 9, 9, 9, 9, 8, 8, 9, 9, 9, 9, 9, 10, 14, 27, 13, 14, 6, 19, 5, 6, 5, 6, 4, 6, 6, 6, 5, 7,
7, 5, 6, 5, 5, 5, 8, 5, 5, 5, 6, 7, 6, 8, 8, 8, 17, 11, 17, 12, 27, 27, 27, 27, 27, 27, 27,
27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
27, 27, 27, 27, 27, 27, 27, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26,
26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26,
26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26,
26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26,
26, 26, 26, 26, 26, 26, 26
};
// Appendix D: Huffman Codes For Responses
// http://tools.ietf.org/html/draft-ietf-httpbis-header-compression-05#appendix-D
private static final int[] RESPONSE_CODES = {
0x1ffffbc, 0x1ffffbd, 0x1ffffbe, 0x1ffffbf, 0x1ffffc0, 0x1ffffc1, 0x1ffffc2, 0x1ffffc3,
0x1ffffc4, 0x1ffffc5, 0x1ffffc6, 0x1ffffc7, 0x1ffffc8, 0x1ffffc9, 0x1ffffca, 0x1ffffcb,
0x1ffffcc, 0x1ffffcd, 0x1ffffce, 0x1ffffcf, 0x1ffffd0, 0x1ffffd1, 0x1ffffd2, 0x1ffffd3,
0x1ffffd4, 0x1ffffd5, 0x1ffffd6, 0x1ffffd7, 0x1ffffd8, 0x1ffffd9, 0x1ffffda, 0x1ffffdb, 0x0,
0xffa, 0x6a, 0x1ffa, 0x3ffc, 0x1ec, 0x3f8, 0x1ffb, 0x1ed, 0x1ee, 0xffb, 0x7fa, 0x22, 0x23,
0x24, 0x6b, 0x1, 0x2, 0x3, 0x8, 0x9, 0xa, 0x25, 0x26, 0xb, 0xc, 0xd, 0x1ef, 0xfffa, 0x6c,
0x1ffc, 0xffc, 0xfffb, 0x6d, 0xea, 0xeb, 0xec, 0xed, 0xee, 0x27, 0x1f0, 0xef, 0xf0, 0x3f9,
0x1f1, 0x28, 0xf1, 0xf2, 0x1f2, 0x3fa, 0x1f3, 0x29, 0xe, 0x1f4, 0x1f5, 0xf3, 0x3fb, 0x1f6,
0x3fc, 0x7fb, 0x1ffd, 0x7fc, 0x7ffc, 0x1f7, 0x1fffe, 0xf, 0x6e, 0x2a, 0x2b, 0x10, 0x6f, 0x70,
0x71, 0x2c, 0x1f8, 0x1f9, 0x72, 0x2d, 0x2e, 0x2f, 0x30, 0x1fa, 0x31, 0x32, 0x33, 0x34, 0x73,
0xf4, 0x74, 0xf5, 0x1fb, 0xfffc, 0x3ffd, 0xfffd, 0xfffe, 0x1ffffdc, 0x1ffffdd, 0x1ffffde,
0x1ffffdf, 0x1ffffe0, 0x1ffffe1, 0x1ffffe2, 0x1ffffe3, 0x1ffffe4, 0x1ffffe5, 0x1ffffe6,
0x1ffffe7, 0x1ffffe8, 0x1ffffe9, 0x1ffffea, 0x1ffffeb, 0x1ffffec, 0x1ffffed, 0x1ffffee,
0x1ffffef, 0x1fffff0, 0x1fffff1, 0x1fffff2, 0x1fffff3, 0x1fffff4, 0x1fffff5, 0x1fffff6,
0x1fffff7, 0x1fffff8, 0x1fffff9, 0x1fffffa, 0x1fffffb, 0x1fffffc, 0x1fffffd, 0x1fffffe,
0x1ffffff, 0xffff80, 0xffff81, 0xffff82, 0xffff83, 0xffff84, 0xffff85, 0xffff86, 0xffff87,
0xffff88, 0xffff89, 0xffff8a, 0xffff8b, 0xffff8c, 0xffff8d, 0xffff8e, 0xffff8f, 0xffff90,
0xffff91, 0xffff92, 0xffff93, 0xffff94, 0xffff95, 0xffff96, 0xffff97, 0xffff98, 0xffff99,
0xffff9a, 0xffff9b, 0xffff9c, 0xffff9d, 0xffff9e, 0xffff9f, 0xffffa0, 0xffffa1, 0xffffa2,
0xffffa3, 0xffffa4, 0xffffa5, 0xffffa6, 0xffffa7, 0xffffa8, 0xffffa9, 0xffffaa, 0xffffab,
0xffffac, 0xffffad, 0xffffae, 0xffffaf, 0xffffb0, 0xffffb1, 0xffffb2, 0xffffb3, 0xffffb4,
0xffffb5, 0xffffb6, 0xffffb7, 0xffffb8, 0xffffb9, 0xffffba, 0xffffbb, 0xffffbc, 0xffffbd,
0xffffbe, 0xffffbf, 0xffffc0, 0xffffc1, 0xffffc2, 0xffffc3, 0xffffc4, 0xffffc5, 0xffffc6,
0xffffc7, 0xffffc8, 0xffffc9, 0xffffca, 0xffffcb, 0xffffcc, 0xffffcd, 0xffffce, 0xffffcf,
0xffffd0, 0xffffd1, 0xffffd2, 0xffffd3, 0xffffd4, 0xffffd5, 0xffffd6, 0xffffd7, 0xffffd8,
0xffffd9, 0xffffda, 0xffffdb, 0xffffdc
};
private static final byte[] RESPONSE_CODE_LENGTHS = {
25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
25, 25, 25, 25, 25, 25, 25, 25, 25, 4, 12, 7, 13, 14, 9, 10, 13, 9, 9, 12, 11, 6, 6, 6, 7, 4,
4, 4, 5, 5, 5, 6, 6, 5, 5, 5, 9, 16, 7, 13, 12, 16, 7, 8, 8, 8, 8, 8, 6, 9, 8, 8, 10, 9, 6, 8,
8, 9, 10, 9, 6, 5, 9, 9, 8, 10, 9, 10, 11, 13, 11, 15, 9, 17, 5, 7, 6, 6, 5, 7, 7, 7, 6, 9, 9,
7, 6, 6, 6, 6, 9, 6, 6, 6, 6, 7, 8, 7, 8, 9, 16, 14, 16, 16, 25, 25, 25, 25, 25, 25, 25, 25,
25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
25, 25, 25, 25, 25, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
24, 24, 24, 24, 24, 24
};
}
| 44.871429 | 100 | 0.611748 |
ca19a072bd9f484e5b202cf68facd2c206f05a61 | 1,553 | package org.langxf.javalab.collection;
import org.openjdk.jmh.annotations.*;
import org.openjdk.jmh.infra.Blackhole;
import org.openjdk.jmh.runner.Runner;
import org.openjdk.jmh.runner.RunnerException;
import org.openjdk.jmh.runner.options.Options;
import org.openjdk.jmh.runner.options.OptionsBuilder;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
/**
* @author Langxf
* 测试完成时间
* 预热 2 轮,每次 1s
* 测试 5 轮,每次 3s
* fork 1 个线程
* 每个测试线程一个实例
*/
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@Warmup(iterations = 2, time = 1, timeUnit = TimeUnit.SECONDS)
@Measurement(iterations = 5, time = 3, timeUnit = TimeUnit.SECONDS)
@Fork(1)
@State(Scope.Thread)
public class TestMapCapacity {
static final int SIZE = 1024;
public static void main(String[] args) throws RunnerException {
// 启动基准测试 & 要导入的测试类
Options opt = new OptionsBuilder()
.include(TestMapCapacity.class.getSimpleName())
.build();
new Runner(opt).run();
}
@Benchmark
public void noSizeTest(Blackhole blackhole) {
Map map = new HashMap(SIZE);
for (int i = 0; i < SIZE; i++) {
map.put(i, i);
}
// 为了避免 JIT 忽略未被使用的结果
blackhole.consume(map);
}
@Benchmark
public void setSizeTest(Blackhole blackhole) {
Map map = new HashMap(1367);
for (int i = 0; i < SIZE; i++) {
map.put(i, i);
}
// 为了避免 JIT 忽略未被使用的结果
blackhole.consume(map);
}
}
| 26.322034 | 67 | 0.643271 |
82d211eeea98d2f46ef509ae89daf780f52eda20 | 689 | package com.stackDigest.stackDigest.beans.database;
import javax.persistence.*;
@Entity(name = "userd_seen")
@Table(indexes =
{
@Index(columnList = "id,seen",name = "user_id_seen")
})
public class UserD_seen {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int pkey;
@Column(columnDefinition = "VARCHAR(64)")
private String id;
@Column
private int seen;
public UserD_seen() {}
public UserD_seen(String id, int seen) {
this.id = id;
this.seen = seen;
}
public int getPkey() {
return pkey;
}
public void setPkey(int pkey) {
this.pkey = pkey;
}
}
| 19.138889 | 68 | 0.597968 |
b14598fae56c888a8cbad184ed7c63aa8827d12a | 32,926 | package com.matrixdev.game.apimanagerlib.web;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.Toast;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonSyntaxException;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.ByteArrayInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Type;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import javax.net.ssl.HttpsURLConnection;
/**
* Created by milin on 11-Nov-15.
*/
public class ApiManager {
SQLiteDatabase sqldb;
Context context;
ServerResponseListener serverResponseListener;
private Boolean jsonParsing;
private Type classTypeForJson;
private HashMap<String, String> headerParams;
public ApiManager(Context context, ServerResponseListener serverResponseListener) {
this.context = context;
this.serverResponseListener = serverResponseListener;
}
public ApiManager(Context context, ServerResponseListener serverResponseListener, SQLiteDatabase sqldb) {
this.sqldb = sqldb;
this.context = context;
this.serverResponseListener = serverResponseListener;
}
public void setHeadersParams(HashMap<String, String> headerParams) {
this.headerParams = headerParams;
}
private void performJsonParsing(String TAG, String response, Type type) {
jsonParsing = false;
classTypeForJson = null;
if (response != null) {
Gson gson = new GsonBuilder().create();
//JsonReader reader = new JsonReader(new StringReader(response));
//reader.setLenient(true);
try {
Object responseObject = gson.fromJson(response, type);
serverResponseListener.positiveResponse(TAG, responseObject);
} catch (JsonSyntaxException jse) {
jse.printStackTrace();
String errorString;
errorString = "error For Developer: Some Issue in Json Syntax. Unable to parse it";
Log.d("----err jsonString:", response);
Log.d("----err json:", jse.getMessage());
serverResponseListener.negativeResponse(TAG, errorString);
return;
} catch (Exception e) {
e.printStackTrace();
String errorString;
errorString = "error For Developer: Some general exception in creating objects from returned json";
Log.d("----err jsonString:", response);
Log.d("----err json:", e.getMessage());
serverResponseListener.negativeResponse(TAG, errorString);
}
// means server response is null
} else {
String errorString;
errorString = "error Response = null";
serverResponseListener.negativeResponse(TAG, errorString);
}
}
public void getStringPostResponse(String TAG, String Url) {
final Post post = new Post(TAG, Url);
if (!isNetworkConnected()) {
Toast.makeText(context, "No Internet Access", Toast.LENGTH_LONG).show();
return;
}
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
post.execute();
}
});
thread.start();
}
public void getStringPostResponse(String TAG, String Url, HashMap<String, String> arr) {
final Post post = new Post(TAG, Url, arr);
if (!isNetworkConnected()) {
Toast.makeText(context, "No Internet Access", Toast.LENGTH_LONG).show();
return;
}
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
post.execute();
}
});
thread.start();
}
private class Post extends AsyncTask<Void, Void, String> {
private String TAG;
String Url;
int errorFlag = 0;
HashMap<String, String> params;
Post(String TAG, String Url) {
this.TAG = TAG;
this.Url = Url;
}
Post(String TAG, String Url, HashMap<String, String> arr) {
this.Url = Url;
this.params = arr;
this.TAG = TAG;
}
@Override
public void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
Log.d("----post result", result);
if (errorFlag == 0) {
Log.d("----Call : ", "positive");
if (jsonParsing != null && jsonParsing)
performJsonParsing(TAG, result, classTypeForJson);
else
serverResponseListener.positiveResponse(TAG, result);
} else {
Log.d("----Call : ", "negative");
serverResponseListener.negativeResponse(TAG, result);
}
}
@Override
protected String doInBackground(Void... params) {
// TODO Auto-generated method stub
String responseStr = "";
HashMap<String, String> nameValuePair = new HashMap<>();
nameValuePair.put("", "");
URL url = null;
try {
url = new URL(Url);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
if (headerParams != null) {
applyHeaders(urlConnection);
}
urlConnection.setRequestMethod("POST");
// urlConnection.setConnectTimeout(5000);
urlConnection.setDoInput(true);
urlConnection.setDoOutput(true);
OutputStream sendingStream = urlConnection.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(sendingStream, "UTF-8"));
if (this.params == null)
writer.write(getQuery(nameValuePair));
else
writer.write(getQuery(this.params));
writer.flush();
writer.close();
sendingStream.close();
int responseCode = urlConnection.getResponseCode();
if (responseCode == HttpsURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_CREATED) {
String line;
BufferedReader br = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
while ((line = br.readLine()) != null) {
responseStr += line;
}
} else {
responseStr = "Reponse Code : " + responseCode + "(" + urlConnection.getResponseMessage() + ")";
errorFlag = 1;
}
} catch (MalformedURLException e) {
e.printStackTrace();
errorFlag = 1;
responseStr = e.getMessage();
} catch (IOException e) {
e.printStackTrace();
errorFlag = 1;
responseStr = e.getMessage();
}
Log.d("----post response", responseStr);
headerParams = null;
return filter(responseStr);
}
}
void intiate(String tableName) {
String Query = "PRAGMA table_info(" + tableName + ")";
Cursor my_cursor = sqldb.rawQuery(Query, null);
int pos = 0;
String Q = "insert into " + tableName + " values (";
for (int i = 0; i < my_cursor.getCount(); i++) {
my_cursor.moveToPosition(i);
if (i != 0) {
Q += ",";
}
String type = my_cursor.getString(my_cursor.getColumnIndex("type"));
if (type.contains("char")) {
Q += "''";
} else if (type.contains("date")) {
Q += "'0-0-0'";
} else
Q += "0";
}
Q += ");";
sqldb.execSQL(Q);
}
public int createDbXmlFromWeb(String stringResponse, String tableName) {
try {
if (sqldb == null || tableName == null) {
Toast.makeText(context, "Must include database in class constructor.", Toast.LENGTH_LONG).show();
return 1;
}
XmlPullParserFactory xmlFactoryObject = XmlPullParserFactory.newInstance();
XmlPullParser myParser = xmlFactoryObject.newPullParser();
myParser.setInput(new ByteArrayInputStream(stringResponse.getBytes()), null);
Cursor cs = sqldb.rawQuery("Select * from " + tableName, null);
if (cs.getCount() != 0)
sqldb.execSQL("delete from " + tableName);
intiate(tableName);
//sqldb.execSQL("insert into empl values(0,'a','a',0,'0-0-0',0,0,0);");
cs = sqldb.rawQuery("Select * from " + tableName, null);
cs.moveToFirst();
System.out.println("-----#" + cs.getCount());
int colno = 0;
String row = "Insert into " + tableName + " values (";
int event = myParser.getEventType();
while (event != XmlPullParser.END_DOCUMENT) {
String name = myParser.getName();
switch (event) {
case XmlPullParser.START_TAG:
break;
case XmlPullParser.TEXT:
name = myParser.getText();
case XmlPullParser.END_TAG:
if (name.equalsIgnoreCase("record")) {
colno = 0;
row += ");";
sqldb.execSQL(row);
row = "Insert into " + tableName + " values (";
}
if (!name.equalsIgnoreCase("record") && !name.equalsIgnoreCase(tableName)) {
if (colno != 0)
row += " , ";
if (cs.getType(colno) == Cursor.FIELD_TYPE_INTEGER || cs.getType(colno) == Cursor.FIELD_TYPE_FLOAT || cs.getType(colno) == Cursor.FIELD_TYPE_NULL)
row += name;
else
row += " ' " + name + " ' ";
colno++;
myParser.next();
}
break;
}
System.out.println("----" + name);
event = myParser.next();
}
String col = cs.getColumnName(0);
cs.moveToFirst();
String val = cs.getString(0);
sqldb.execSQL("delete from " + tableName + " where " + col + " = " + val);
return 0;
} catch (XmlPullParserException e) {
e.printStackTrace();
Toast.makeText(context, "Error in parsing" + e.getMessage(), Toast.LENGTH_LONG).show();
Log.d("----xmlParsing", "Error in parsing" + e.getMessage());
return 1;
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(context, "Error in parsing", Toast.LENGTH_LONG).show();
Log.d("----xmlParsing", "Error in parsing" + e.getMessage());
return 1;
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(context, "Error in parsing", Toast.LENGTH_LONG).show();
Log.d("----xmlParsing", "Error in parsing" + e.getMessage());
return 1;
}
}
public void sendFile(String TAG, String Url, HashMap<String, File> fileParams, HashMap<String, String> params) {
PostFile post = new PostFile(TAG, Url, fileParams, params);
if (!isNetworkConnected()) {
Toast.makeText(context, "No Internet Access", Toast.LENGTH_LONG).show();
return;
}
post.execute();
}
private class PostFile extends AsyncTask<Void, Void, String> {
private HashMap<String, File> fileParams;
String Url;
String TAG;
String filePath;
String fileName;
File file;
private int errorFlag = 0;
HashMap<String, String> params;
public PostFile(String TAG, String url, HashMap<String, File> fileParams, HashMap<String, String> params) {
this.Url = url;
this.TAG = TAG;
this.params = params;
this.fileParams = fileParams;
if (fileParams == null) {
Toast.makeText(context, "NO files to send", Toast.LENGTH_LONG).show();
this.cancel(true);
}
}
@Override
public void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
Log.d("----post result", result);
if (errorFlag == 0) {
Log.d("----Call : ", "positive");
if (jsonParsing != null && jsonParsing)
performJsonParsing(TAG, result, classTypeForJson);
else
serverResponseListener.positiveResponse(TAG, result);
} else {
Log.d("----Call : ", "negative");
serverResponseListener.negativeResponse(TAG, result);
}
}
@Override
protected String doInBackground(Void... params) {
// TODO Auto-generated method stub
String boundary = "===" + System.currentTimeMillis() + "===";
String lineEnd = "\r\n";
String twoHyphens = "--";
HashMap<String, String> nameValuePair = new HashMap<String, String>(2);
nameValuePair.put("", "");
String contentDisposition = "Content-Disposition: form-data;";
String contentTypeFile = "Content-Type: application/octet-stream";
String responseStr = "";
URL url = null;
try {
url = new URL(Url);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
if (headerParams != null) {
applyHeaders(urlConnection);
}
urlConnection.setDoInput(true);
urlConnection.setDoOutput(true);
urlConnection.setUseCaches(false);
urlConnection.setRequestMethod("POST");
//urlConnection.setRequestProperty("Connection", "Keep-Alive");
//urlConnection.setRequestProperty("Cache-Control", "no-cache");
urlConnection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
urlConnection.setRequestProperty("uploaded_file", "file");
if (fileParams.size() == 0) {
responseStr = "No File Provided";
errorFlag = 1;
return "";
}
DataOutputStream writer = new DataOutputStream(urlConnection.getOutputStream());
writer.flush();
StringBuffer requestBody = new StringBuffer();
for (Map.Entry<String, File> fileParam : fileParams.entrySet()) {
writer.writeBytes(lineEnd);
writer.writeBytes(twoHyphens + boundary + lineEnd);
writer.writeBytes(contentDisposition);
writer.writeBytes(String.format("name=%s;", fileParam.getKey()));
writer.writeBytes(String.format("filename='%s';", fileParam.getValue().getName()));
//writer.writeBytes(";" + lineEnd);
writer.writeBytes(lineEnd);
writer.writeBytes(contentTypeFile);
writer.writeBytes(lineEnd);
writer.writeBytes(lineEnd);
/* byte[] data = new byte[(int) fileParam.getValue().length()];
try {
new FileInputStream(fileParam.getValue()).read(data);
writer.writeBytes(new String(data));
} catch (Exception e) {
e.printStackTrace();
errorFlag = 1;
responseStr = e.getMessage();
}
*/
writer.write(fullyReadFileToBytes(fileParam.getValue()));
writer.writeBytes(lineEnd);
writer.writeBytes(lineEnd);
writer.writeBytes(twoHyphens + boundary);
}
for (Map.Entry<String, String> param : this.params.entrySet()) {
writer.writeBytes(lineEnd);
writer.writeBytes(contentDisposition);
writer.writeBytes(String.format("name=%s", param.getKey()));
//writer.writeBytes(";" + lineEnd);
writer.writeBytes(lineEnd);
writer.writeBytes(lineEnd);
writer.writeBytes(param.getValue());
writer.writeBytes(lineEnd);
writer.writeBytes(twoHyphens + boundary);
}
writer.writeBytes(twoHyphens + lineEnd);
/*
if (this.params == null)
writer.writeBytes(getQuery2(nameValuePair));
else
writer.writeBytes(getQuery2(this.params));
*/
Log.d("----request", requestBody.toString());
Log.d("----request", "");
//writer.writeBytes(requestBody.toString());
writer.close();
int responseCode = urlConnection.getResponseCode();
if (responseCode == HttpsURLConnection.HTTP_OK) {
String line;
BufferedReader br = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
while ((line = br.readLine()) != null) {
responseStr += line;
}
} else {
responseStr = "Reponse Code : " + responseCode + "(" + urlConnection.getResponseMessage() + ")";
errorFlag = 1;
}
} catch (IOException e) {
e.printStackTrace();
errorFlag = 1;
responseStr = e.getMessage();
} catch (Exception e) {
e.printStackTrace();
errorFlag = 1;
responseStr = e.getMessage();
}
headerParams = null;
return filter(responseStr);
}
}
public void getFile(String TAG, String Url, HashMap<String, String> params, String saveFilePath, String saveFileName) {
final GetFile post = new GetFile(TAG, Url, params, saveFilePath, saveFileName);
if (!isNetworkConnected()) {
Toast.makeText(context, "No Internet Access", Toast.LENGTH_LONG).show();
return;
}
post.execute();
}
private class GetFile extends AsyncTask<Void, Void, String> {
String Url;
String TAG;
File saveFile;
String saveFilePath;
String saveFileName;
HashMap<String, String> params;
private int errorFlag = 0;
public GetFile(String TAG, String Url, HashMap<String, String> params, String saveFilePath, String saveFileName) {
this.Url = Url;
this.TAG = TAG;
this.params = params;
this.saveFilePath = saveFilePath;
this.saveFileName = saveFileName;
if (this.params == null)
Log.d("----", "empty params");
if (saveFilePath == null || saveFilePath.length() == 0 || saveFileName == null || saveFileName.length() == 0)
Toast.makeText(context, "Field can't left be null", Toast.LENGTH_LONG).show();
else
this.saveFile = new File(this.saveFilePath, saveFileName);
}
@Override
public void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
if (errorFlag == 0) {
Log.d("----Call : ", "positive");
if (jsonParsing != null && jsonParsing)
performJsonParsing(TAG, result, classTypeForJson);
else
serverResponseListener.positiveResponse(TAG, result);
} else {
Log.d("----Call : ", "negative");
serverResponseListener.negativeResponse(TAG, result);
}
}
@Override
protected String doInBackground(Void... params) {
// TODO Auto-generated method stub
String responseStr = "";
HashMap<String, String> nameValuePair = new HashMap<String, String>();
nameValuePair.put("", "");
URL url = null;
try {
url = new URL(Url);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
if (headerParams != null) {
applyHeaders(urlConnection);
}
urlConnection.setRequestMethod("POST");
urlConnection.setDoInput(true);
urlConnection.setDoOutput(true);
OutputStream sendingStream = urlConnection.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(sendingStream, "UTF-8"));
if (this.params == null)
writer.write(getQuery(nameValuePair));
else
writer.write(getQuery(this.params));
writer.flush();
writer.close();
sendingStream.close();
if (urlConnection.getHeaderField("Content-Type").toString().trim().equals("text/html")) {
String line;
BufferedReader br = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
while ((line = br.readLine()) != null) {
responseStr += line;
}
return responseStr;
}
int responseCode = urlConnection.getResponseCode();
if (responseCode == HttpsURLConnection.HTTP_OK) {
InputStream in = urlConnection.getInputStream();
Log.d("----1", saveFilePath);
Log.d("----2", String.valueOf(new File(saveFilePath).mkdir()));
Log.d("----3", String.valueOf(saveFile.createNewFile()));
OutputStream fileOutput = new FileOutputStream(saveFile);
BufferedOutputStream bufferedFileOutput = new BufferedOutputStream(fileOutput);
byte[] buf = new byte[1024];
int len;
int progressLen = 0;
long totalLen = urlConnection.getContentLength();
while ((len = in.read(buf)) > 0) {
progressLen += len;
Log.d("----download progress", String.valueOf(progressLen * 100 / totalLen) + "%");
bufferedFileOutput.write(buf, 0, len);
}
bufferedFileOutput.flush();
bufferedFileOutput.close();
in.close();
responseStr = "Download Completed";
} else {
responseStr = "Response Code : " + responseCode + "(" + urlConnection.getResponseMessage() + ")";
errorFlag = 1;
}
} catch (MalformedURLException e) {
e.printStackTrace();
errorFlag = 1;
responseStr = e.getMessage();
} catch (IOException e) {
e.printStackTrace();
errorFlag = 1;
responseStr = e.getMessage();
}
headerParams = null;
return filter(responseStr);
}
}
public void getStringGetResponse(String TAG, String Url) {
final Get get = new Get(TAG, Url);
if (!isNetworkConnected()) {
Toast.makeText(context, "No Internet Access", Toast.LENGTH_LONG).show();
return;
}
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
get.execute();
}
});
thread.start();
}
public void getStringGetResponse(String TAG, String Url, HashMap<String, String> params) {
final Get get = new Get(TAG, Url, params);
if (!isNetworkConnected()) {
Toast.makeText(context, "No Internet Access", Toast.LENGTH_LONG).show();
return;
}
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
get.execute();
}
});
thread.start();
}
private class Get extends AsyncTask<Void, Void, String> {
private String TAG;
String Url;
int errorFlag = 0;
HashMap<String, String> params;
Get(String TAG, String Url) {
this.TAG = TAG;
this.Url = Url;
params = null;
}
Get(String TAG, String Url, HashMap<String, String> params) {
this.Url = Url;
this.params = params;
this.TAG = TAG;
}
@Override
public void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
Log.d("----get result", result);
if (errorFlag == 0) {
Log.d("----Call : ", "positive");
if (jsonParsing != null && jsonParsing)
performJsonParsing(TAG, result, classTypeForJson);
else
serverResponseListener.positiveResponse(TAG, result);
} else {
Log.d("----Call : ", "negative");
serverResponseListener.negativeResponse(TAG, result);
}
}
@Override
protected String doInBackground(Void... params) {
// TODO Auto-generated method stub
String responseStr = "";
URL url = null;
try {
if (this.params != null)
Url += urlEncodeUTF8(this.params);
url = new URL(Url);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
if (headerParams != null) {
applyHeaders(urlConnection);
}
urlConnection.setRequestMethod("GET");
// urlConnection.setDoInput(true);
// urlConnection.setDoOutput(true);
int responseCode = urlConnection.getResponseCode();
if (responseCode == HttpsURLConnection.HTTP_OK) {
String line;
BufferedReader br = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
while ((line = br.readLine()) != null) {
responseStr += line;
}
} else {
responseStr = "Reponse Code : " + responseCode + "(" + urlConnection.getResponseMessage() + ")";
errorFlag = 1;
}
} catch (MalformedURLException e) {
e.printStackTrace();
errorFlag = 1;
responseStr = e.getMessage();
} catch (IOException e) {
e.printStackTrace();
errorFlag = 1;
responseStr = e.getMessage();
}
Log.d("----get response", responseStr);
headerParams = null;
return filter(responseStr);
}
}
private String filter(String response) {
response = response.split("<!-- Hosting24 Analytics Code -->")[0];
response = response.replace("<html>", "");
response = response.replace("</html>", "");
response = response.trim();
return response;
}
private String getQuery(HashMap<String, String> params) throws UnsupportedEncodingException {
StringBuilder result = new StringBuilder();
boolean first = true;
for (Map.Entry<String, String> pair : params.entrySet()) {
if (first)
first = false;
else
result.append("&");
result.append(URLEncoder.encode(pair.getKey(), "UTF-8"));
result.append("=");
result.append(URLEncoder.encode(pair.getValue(), "UTF-8"));
}
return result.toString();
}
private String getQuery2(HashMap<String, String> params) throws UnsupportedEncodingException {
StringBuilder result = new StringBuilder();
boolean first = true;
for (Map.Entry<String, String> pair : params.entrySet()) {
if (first)
first = false;
else
result.append("; ");
result.append(URLEncoder.encode(pair.getKey(), "UTF-8"));
result.append("=\"");
result.append(URLEncoder.encode(pair.getValue(), "UTF-8"));
result.append("\"");
}
return result.toString();
}
static String urlEncodeUTF8(String s) {
try {
return URLEncoder.encode(s, "UTF-8");
} catch (UnsupportedEncodingException e) {
throw new UnsupportedOperationException(e);
}
}
static String urlEncodeUTF8(Map<?, ?> map) {
StringBuilder sb = new StringBuilder();
for (Map.Entry<?, ?> entry : map.entrySet()) {
if (sb.length() > 0) {
sb.append("&");
}
sb.append(String.format("%s=%s",
urlEncodeUTF8(entry.getKey().toString()),
urlEncodeUTF8(entry.getValue().toString())
));
}
return sb.toString();
}
byte[] fullyReadFileToBytes(File f) throws IOException {
int size = (int) f.length();
byte bytes[] = new byte[size];
byte tmpBuff[] = new byte[size];
FileInputStream fis = new FileInputStream(f);
;
try {
int read = fis.read(bytes, 0, size);
if (read < size) {
int remain = size - read;
while (remain > 0) {
read = fis.read(tmpBuff, 0, remain);
System.arraycopy(tmpBuff, 0, bytes, size - remain, read);
remain -= read;
}
}
} catch (IOException e) {
throw e;
} finally {
fis.close();
}
return bytes;
}
private void applyHeaders(HttpURLConnection urlConnection) {
for (Map.Entry<String, String> param : headerParams.entrySet()) {
urlConnection.setRequestProperty(param.getKey(), param.getValue());
}
}
public Boolean isJsonParsing() {
return jsonParsing;
}
public void doJsonParsing(Boolean jsonParsing) {
this.jsonParsing = jsonParsing;
}
public Type getClassTypeForJson() {
return classTypeForJson;
}
public void setClassTypeForJson(Type classTypeForJson) {
this.classTypeForJson = classTypeForJson;
}
private boolean isNetworkConnected() {
ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = connectivityManager.getActiveNetworkInfo();
return activeNetwork != null && activeNetwork.isConnectedOrConnecting();
}
}
| 35.102345 | 174 | 0.52533 |
6f3e23ea632fc2895c5be6d37478aee2dbaa3b54 | 3,262 | package powercraft.transport;
import java.util.Random;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.nbt.NBTTagCompound;
import powercraft.api.network.PC_IPacketHandler;
import powercraft.api.tileentity.PC_TileEntity;
import powercraft.api.utils.PC_VecI;
import powercraft.api.utils.PC_WorldData;
public class PCtr_TileEntityEjectionBelt extends PC_TileEntity implements PC_IPacketHandler {
public static Random rand = new Random();
public int actionType = 0;
public int numStacksEjected = 1;
public int numItemsEjected = 1;
public int itemSelectMode = 0;
public boolean isActive = false;
public int getActionType() {
return actionType;
}
public void setActionType(int actionType) {
if (this.actionType != actionType) {
this.actionType = actionType;
}
}
public int getNumStacksEjected() {
return numStacksEjected;
}
public void setNumStacksEjected(int numStacksEjected) {
if (this.numStacksEjected != numStacksEjected) {
this.numStacksEjected = numStacksEjected;
}
}
public int getNumItemsEjected() {
return numItemsEjected;
}
public void setNumItemsEjected(int numItemsEjected) {
if (this.numItemsEjected != numItemsEjected) {
this.numItemsEjected = numItemsEjected;
}
}
public int getItemSelectMode() {
return itemSelectMode;
}
public void setItemSelectMode(int itemSelectMode) {
if (this.itemSelectMode != itemSelectMode) {
this.itemSelectMode = itemSelectMode;
notifyChanges("itemSelectMode");
}
}
@Override
public final boolean canUpdate() {
return true;
}
@Override
public final void updateEntity() {
if (!worldObj.isRemote) {
PC_VecI pos = new PC_VecI(xCoord, yCoord, zCoord);
PCtr_BlockBeltEjector block = (PCtr_BlockBeltEjector) worldObj.getBlock(xCoord, yCoord, zCoord);
if (block.isPowered) {
if (!isActive) {
if (!PCtr_BeltHelper.dispenseStackFromNearbyMinecart(worldObj, pos)) {
PCtr_BeltHelper.tryToDispenseItem(worldObj, pos);
}
isActive = true;
}
} else {
isActive = false;
}
worldObj.markBlockForUpdate(xCoord, yCoord, zCoord);
markDirty();
PC_WorldData data = PC_WorldData.forWorld(worldObj);
NBTTagCompound tag = data.getData();
}
}
@Override
public void writeToNBT(NBTTagCompound tag) {
super.writeToNBT(tag);
tag.setInteger("actionType", this.actionType);
tag.setInteger("itemSelectMode", this.itemSelectMode);
tag.setInteger("numItemsEjected", this.numItemsEjected);
tag.setInteger("numStacksEjected", this.numStacksEjected);
}
@Override
public void readFromNBT(NBTTagCompound tag) {
super.readFromNBT(tag);
this.actionType = tag.getInteger("actionType");
this.itemSelectMode = tag.getInteger("itemSelectMode");
this.numItemsEjected = tag.getInteger("numItemsEjected");
this.numStacksEjected = tag.getInteger("numStacksEjected");
}
@Override
public boolean handleIncomingPacket(EntityPlayer player, Object[] o) {
if ((Integer) o[0] == 1) {
setActionType((Integer) o[2]);
setItemSelectMode((Integer) o[3]);
setNumStacksEjected((Integer) o[4]);
setNumItemsEjected((Integer) o[5]);
}
return true;
}
}
| 27.183333 | 100 | 0.713979 |
016ffa4a2ea069961c24fb8b3f3ce50213726ca4 | 1,590 | /* AUTO-GENERATED FILE. DO NOT MODIFY.
*
* This class provides IDs to access resources declared in the URS file.
* It was automatically generated by NeoMAD and should not be modified by hand.
*/
package com.neomades.jsonexample;
public final class Res {
public static final class id {
public static final int DISCUSSION_USER_NAME = 13;
public static final int TL_WRITING_WITH_JSONWRITER_CONTENT = 14;
public static final int BUTTON_READ_JSONREADER = 15;
public static final int BUTTON_READ_JSONARRAY = 16;
public static final int DISCUSSION_LAYOUT = 17;
public static final int TL_JSON_STRING_TITLE = 18;
public static final int TL_WRITING_WITH_JSONARRAY_CONTENT = 19;
public static final int BUTTON_READ_JSON = 20;
public static final int DISCUSSION_TEXT = 21;
public static final int TEXT_LABEL_JSON_STRING = 22;
public static final int BUTTON_WRITE_JSON = 23;
}
public static final class layout {
public static final int MAIN_SCREEN = 8;
public static final int DISCUSSION_ITEM = 9;
public static final int READING_SCREEN = 10;
public static final int WRITING_SCREEN = 11;
public static final int DISCUSSION_SCREEN = 12;
}
public static final class string {
public static final int JSON_STRING_TITLE = 0;
public static final int JSON_STRING = 1;
public static final int READ_JSON = 2;
public static final int WRITE_JSON = 3;
public static final int READ_JSONARRAY = 4;
public static final int READ_JSONREADER = 5;
public static final int WRITING_WITH_JSONARRAY = 6;
public static final int WRITING_WITH_JSONWRITER = 7;
}
}
| 35.333333 | 79 | 0.769182 |
86e23f4dada390940cba17670aef7549fabb002f | 147 | package combining.observer;
public interface QuackObservable {
public void registerObserver(Observer observer);
public void notifyObservers();
} | 24.5 | 49 | 0.823129 |
b44867708f9cb31af01e35a0d0e61de8c8873a7a | 5,037 | package com.leichui.shortviedeo.utils;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
public class DateUtils {
// String->String
public static String getDate(String time, String format) {
try {
Long lt;
if (time.length() <= 10) {
lt = Long.valueOf(time + "000");
} else {
lt = Long.valueOf(time);
}
SimpleDateFormat dateFormat = new SimpleDateFormat(format);
Date date = new Date(lt);
return dateFormat.format(date);
} catch (Exception e) {
return "";
}
}
public static String secToTime(int time) {
String timeStr = null;
int hour = 0;
int minute = 0;
int second = 0;
if (time <= 0) {
{
return "00:00";
}
} else {
minute = time / 60;
if (minute < 60) {
second = time % 60;
timeStr = unitFormat(minute) + ":" + unitFormat(second);
} else {
hour = minute / 60;
if (hour > 99) {
{
return getDate(time + "", "yyyy-MM-dd");
}
}
// return "99:59:59";
// minute = minute % 60;
// second = time - hour * 3600 - minute * 60;
// timeStr = unitFormat(hour) + ":" + unitFormat(minute) + ":" + unitFormat(second);
}
}
if (hour == 0 && minute == 0) {
return "刚刚";
} else if (hour == 0 && minute != 0) {
return minute + "分钟";
} else {
return hour + "小时" + minute + "分钟";
}
}
private static String unitFormat(int i) {
String retStr = null;
if (i >= 0 && i < 10) {
{
retStr = "0" + Integer.toString(i);
}
} else {
{
retStr = "" + i;
}
}
return retStr;
}
public static String getToday(){
Calendar calendar = Calendar.getInstance();
int year = calendar.get(Calendar.YEAR);
int month = calendar.get(Calendar.MONTH)+1;
int day = calendar.get(Calendar.DAY_OF_MONTH);
return year + "-" + month + "-" + day;
}
public static Long date2TimeStamp(String date, String format) {
try {
SimpleDateFormat sdf = new SimpleDateFormat(format);
return (sdf.parse(date).getTime() / 1000);
} catch (Exception e) {
e.printStackTrace();
}
return 0l;
}
public static Long getTodayTime(){
return date2TimeStamp(getToday(),"yyyy-MM-dd");
}
public static String getTimeExpend(String startTime, String endTime){
//传入字串类型 2016/06/28 08:30
long longStart = getTimeMillis(startTime); //获取开始时间毫秒数
long longEnd = getTimeMillis(endTime); //获取结束时间毫秒数
long longExpend = longEnd - longStart; //获取时间差
long day = longExpend/ (24 *60 * 60 * 1000);
long longHours = longExpend / (60 * 60 * 1000); //根据时间差来计算小时数
long longMinutes = (longExpend - longHours * (60 * 60 * 1000)) / (60 * 1000); //根据时间差来计算分钟数
return String.valueOf(day);
}
private static long getTimeMillis(String strTime) {
long returnMillis = 0;
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date d = null;
try {
d = sdf.parse(strTime);
returnMillis = d.getTime();
} catch (ParseException e) {
}
return returnMillis;
}
/**
* 获得指定日期的前一天
* @param specifiedDay
* @return
* @throws Exception
*/
public static String getSpecifiedDayBefore(String specifiedDay){
//SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
Calendar c = Calendar.getInstance();
Date date=null;
try {
date = new SimpleDateFormat("yy-MM-dd").parse(specifiedDay);
} catch (ParseException e) {
e.printStackTrace();
}
c.setTime(date);
int day=c.get(Calendar.DATE);
c.set(Calendar.DATE,day-1);
String dayBefore=new SimpleDateFormat("yyyy-MM-dd").format(c.getTime());
return dayBefore;
}
/**
* 获得指定日期的后一天
* @param specifiedDay
* @return
*/
public static String getSpecifiedDayAfter(String specifiedDay){
Calendar c = Calendar.getInstance();
Date date=null;
try {
date = new SimpleDateFormat("yy-MM-dd").parse(specifiedDay);
} catch (ParseException e) {
e.printStackTrace();
}
c.setTime(date);
int day=c.get(Calendar.DATE);
c.set(Calendar.DATE,day+1);
String dayAfter=new SimpleDateFormat("yyyy-MM-dd").format(c.getTime());
return dayAfter;
}
}
| 28.948276 | 101 | 0.515188 |
f287add6ca04fe297889654373f0a98ea7d63462 | 356 | package ast.comment;
import token.Token;
public class NoteComment extends Comment {
private final Token note;
public NoteComment(Token note) {
this.note = note;
}
public Token getNote() {
return note;
}
@Override
public <R> R accept(CommentVisitor<R> visitor) {
return visitor.visit(this);
}
}
| 16.181818 | 52 | 0.623596 |
25b5a1dbdc2a907267df9d31b67fa9c3cda7040d | 855 | package fr.zom.testmod.init;
import fr.zom.testmod.TestMod;
import fr.zom.testmod.tileentity.TestTileEntity;
import fr.zom.zapi.utils.TileEntityUtils;
import net.minecraft.tileentity.TileEntityType;
import net.minecraftforge.event.RegistryEvent;
import net.minecraftforge.eventbus.api.SubscribeEvent;
import net.minecraftforge.fml.common.Mod;
import net.minecraftforge.registries.ObjectHolder;
@Mod.EventBusSubscriber(modid = TestMod.MODID, bus = Mod.EventBusSubscriber.Bus.MOD)
public class ModTileEntity
{
@ObjectHolder(TestMod.MODID + ":test_tile_entity")
public static final TileEntityType<?> test_tile_entity = TileEntityUtils.createType("test_tile_entity", TestTileEntity::new);
@SubscribeEvent
public static void registerTileEntities(final RegistryEvent.Register<TileEntityType<?>> e)
{
e.getRegistry().register(test_tile_entity);
}
}
| 32.884615 | 126 | 0.818713 |
be4a4f757a43a2b7d83521ac6f40db11b6cc96a5 | 3,257 | /*
* Copyright 2015 Allette Systems (Australia)
* http://www.allette.com.au
*
* 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.pageseeder.flint.content;
/**
* A basic immutable implementation of a content type with a name.
*
* <p>Two content types with the same name are considered equal.
*
* <p>The name string can be interned to enable strict equality comparison.
*
* @author Christophe Lauret
* @version 27 February 2013
*/
public final class NamedContentType implements ContentType {
/**
* A default content type instance for when no more than one type is needed by an application.
*/
public static final NamedContentType DEFAULT = new NamedContentType("default");
/**
* The name of this content type (immutable);
*/
private final String _name;
/**
* A hashcode value for faster retrieval.
*/
private final int _hashCode;
/**
* Creates a new content type with the given name interning the string automatically.
*
* <p>Warning: this is useful only
*
* @param name The name of this content type.
*/
public NamedContentType(String name) {
this._name = name.intern();
this._hashCode = this._name.hashCode();
}
/**
* Creates a new content type with the given name.
*
* <p>If the application uses many content types, it is best NOT to intern the string.
*
* @param name The name of the content type.
* @param intern <code>true</code> to intern the string; <code>false</code> otherwise.
*/
public NamedContentType(String name, boolean intern) {
this._name = intern? name.intern() : name;
this._hashCode = this._name.hashCode();
}
/**
* Returns a pre-computed hashcode value based on the name.
*
* {@inheritDoc}
*/
@Override
public int hashCode() {
return this._hashCode;
}
/**
* {@inheritDoc}
*/
@Override
public boolean equals(Object o) {
// filter out objects of the wrong type
if (!(o instanceof NamedContentType)) return false;
return this.equals((NamedContentType)o);
}
/**
* Compares two named content types for equality.
*
* @param type The type of equality.
* @return <code>true</code> if the two content types are equal;
* <code>false</code> otherwise.
*/
public boolean equals(NamedContentType type) {
if (type == this) return true;
if (this._name == type._name) return true;
return this._name.equals(type._name);
}
/**
* The name of this content type.
*
* @return the name of this content type.
*/
public String name() {
return this._name;
}
/**
* Returns the name of this content type.
*
* {@inheritDoc}
*/
@Override
public String toString() {
return this._name;
}
}
| 26.479675 | 96 | 0.671477 |
9e46aeaa8f06c9134140cc10c0ff990b0601513f | 1,207 | /*
Get All Entries From Zip File Example.
This Java example shows how to get enumeration of all entries
(i.e. files or directories) using entries method of
Java ZipFile class.
*/
import java.io.IOException;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
public class GetAllEntries {
public static void main(String args[])
{
try
{
/*
* Open zip file using,
*
* ZipFile(String fileName)
* constructor of the ZipFile class.
*
* This constructor throws IOException for any I/O error.
*/
ZipFile zipFile = new ZipFile("c:/FileIO/WebFiles.zip");
/*
* To get all entries from opened zip file, use
*
* Enumeration entries()
* method of ZipFile class.
*
* This method returns Enumeration of zip file entries.
*/
Enumeration e = zipFile.entries();
/*
* PLEASE VISIT ZipEntry Examples for more details on
* how to process entries.
*/
/*
* close the opened zip file using,
* void close()
* method.
*/
zipFile.close();
}
catch(IOException ioe)
{
System.out.println("Error opening zip file" + ioe);
}
}
} | 20.457627 | 63 | 0.628832 |
3603f2195d1d973f74b0d8bede4199ebf3085f94 | 872 | package net.ddns.zimportant.lovingpeople.service.persistence;
import android.graphics.Color;
import java.util.ArrayList;
public class HomePostsData extends FixturesData {
public static final int NUM_POST = 100;
private static ArrayList<String> colors = getColors();
public static ArrayList<String> getHomePosts() {
ArrayList<String> homePosts = new ArrayList<>();
for (int i = 0; i <= NUM_POST; ++i) {
homePosts.add(getRandomHomeContent());
}
return homePosts;
}
public static int getColor() {
return Color.parseColor(getRandomColor());
}
public static int getColor(int position) {
return Color.parseColor(colors.get(position % colors.size()));
}
public static ArrayList<String> getColors() {
ArrayList<String> colors = new ArrayList<>();
for (int i = 0; i <= NUM_POST; ++i) {
colors.add(getRandomColor());
}
return colors;
}
}
| 24.222222 | 64 | 0.713303 |
1c6e00a8497c4d832ab48f18d0ba1dba71fad4ed | 5,093 | package tech.jaya.currencytransaction.core.model;
import org.junit.jupiter.api.Test;
import tech.jaya.currencytransaction.core.exception.BaseBusinessException;
import tech.jaya.currencytransaction.core.exception.ErrorMessage;
import tech.jaya.currencytransaction.fixture.FixtureConversionTransaction;
import java.math.BigDecimal;
import java.util.UUID;
import static org.junit.jupiter.api.Assertions.*;
class ConversionTransactionTest {
@Test
void shouldConvertCurrencyWithSuccess() {
final var oneConversionTransaction = ConversionTransaction.builder()
.identifier(UUID.randomUUID().toString())
.userIdentifier("1")
.originCurrency("BRL")
.destinationCurrency("USD")
.originValue(new BigDecimal("10"))
.build();
assertNull(oneConversionTransaction.getDestinationValue());
assertNull(oneConversionTransaction.getConversionRate());
assertNull(oneConversionTransaction.getTransactionTime());
oneConversionTransaction.convertCurrencies(new BigDecimal("6.269056"), new BigDecimal("1.128929"));
assertEquals(new BigDecimal("1.80"), oneConversionTransaction.getDestinationValue());
assertEquals(new BigDecimal("0.180000"), oneConversionTransaction.getConversionRate());
assertNotNull(oneConversionTransaction.getTransactionTime());
}
@Test
void shouldThrowWhenDestinationValueFilledInExecuteConvert() {
final var oneConversionTransaction = ConversionTransaction.builder()
.identifier(UUID.randomUUID().toString())
.userIdentifier("1")
.originCurrency("BRL")
.destinationCurrency("USD")
.originValue(new BigDecimal("20"))
.destinationValue(new BigDecimal("111.37"))
.build();
assertNotNull(oneConversionTransaction.getDestinationValue());
assertNull(oneConversionTransaction.getConversionRate());
assertNull(oneConversionTransaction.getTransactionTime());
BaseBusinessException baseBusinessException = assertThrows(BaseBusinessException.class, () ->
oneConversionTransaction.convertCurrencies(new BigDecimal("6.333688"), new BigDecimal("1.137314")));
assertEquals(ErrorMessage.CONVERSION_ALREADY_TAKEN_PLACE, baseBusinessException.getErrorMessage());
}
@Test
void shouldReturnThatOriginAndDestinationCurrencySame() {
final var oneConversionTransaction = ConversionTransaction.builder()
.identifier(UUID.randomUUID().toString())
.userIdentifier("1")
.originCurrency("USD")
.destinationCurrency("usd")
.originValue(new BigDecimal("20"))
.build();
assertTrue(oneConversionTransaction.verifyIfOriginAndDestinationCurrencySame());
}
@Test
void shouldReturnThatOriginAndDestinationCurrencyNotSame() {
final var oneConversionTransaction = ConversionTransaction.builder()
.identifier(UUID.randomUUID().toString())
.userIdentifier("1")
.originCurrency("BRL")
.destinationCurrency("USD")
.originValue(new BigDecimal("20"))
.build();
assertFalse(oneConversionTransaction.verifyIfOriginAndDestinationCurrencySame());
}
@Test
void shouldBeEquals() {
final String generateIdentifier = UUID.randomUUID().toString();
final var first = ConversionTransaction.builder()
.identifier(generateIdentifier)
.build();
final var second = ConversionTransaction.builder()
.identifier(generateIdentifier)
.build();
assertEquals(first, second);
assertEquals(first.hashCode(), second.hashCode());
assertEquals(first.getIdentifier(), second.getIdentifier());
assertNotEquals(0, first.hashCode());
assertNotEquals(0, second.hashCode());
}
@Test
void shouldBeEqualsWhenSameObject() {
final var conversionTransactionData = FixtureConversionTransaction.one("1");
assertEquals(conversionTransactionData, conversionTransactionData);
assertEquals(conversionTransactionData.hashCode(), conversionTransactionData.hashCode());
assertEquals(conversionTransactionData.getIdentifier(), conversionTransactionData.getIdentifier());
}
@Test
void shouldReturnFalseWhenNull() {
final var account = new ConversionTransaction();
assertNotNull(account);
}
@Test
void shouldReturnFalseWhenOtherObject() {
final var conversion = ConversionTransaction.builder().build();
final var conversionCompared = ConversionTransaction.builder().identifier(UUID.randomUUID().toString()).build();
assertNotEquals(conversion, conversionCompared);
}
@Test
void shouldReturnFalseWhenOtherType() {
assertNotEquals(ConversionTransaction.builder().build(), new Object());
}
} | 40.102362 | 120 | 0.679757 |
2f998a12101f819210d8164f5dbae2485c97af18 | 1,855 | package org.parallaxsecond.parsec.protocol.operations_protobuf;
import com.google.protobuf.InvalidProtocolBufferException;
import org.parallaxsecond.parsec.protobuf.psa_generate_key.PsaGenerateKey;
import org.parallaxsecond.parsec.protocol.operations.NativeOperation;
import org.parallaxsecond.parsec.protocol.operations.NativeResult;
import org.parallaxsecond.parsec.protocol.requests.Opcode;
import org.parallaxsecond.parsec.protocol.requests.request.RequestBody;
import org.parallaxsecond.parsec.protocol.requests.response.ResponseBody;
public class PsaGenerateKeyProtobufOpConverter implements ProtobufOpConverter {
@Override
public NativeOperation bodyToOperation(RequestBody body, Opcode opcode)
throws InvalidProtocolBufferException {
PsaGenerateKey.Operation protoBufOp = PsaGenerateKey.Operation.parseFrom(body.getBuffer());
return NativeOperation.PsaGenerateKeyOperation.builder()
.keyName(protoBufOp.getKeyName())
.attributes(protoBufOp.getAttributes())
.build();
}
@Override
public RequestBody operationToBody(NativeOperation operation) {
NativeOperation.PsaGenerateKeyOperation psaGenerateKeyOperation =
(NativeOperation.PsaGenerateKeyOperation) operation;
return new RequestBody(
PsaGenerateKey.Operation.newBuilder()
.setKeyName(psaGenerateKeyOperation.getKeyName())
.setAttributes(psaGenerateKeyOperation.getAttributes())
.build()
.toByteArray());
}
@Override
public ResponseBody resultToBody(NativeResult result) {
return new ResponseBody(PsaGenerateKey.Result.newBuilder().build().toByteArray());
}
@Override
public NativeResult tryBodyToResult(ResponseBody body, Opcode opcode)
throws InvalidProtocolBufferException {
return NativeResult.PsaGenerateKeyResult.builder().build();
}
}
| 40.326087 | 95 | 0.78814 |
b838613bd740a63eda59ff7eb14e634b883b8c74 | 818 | package com.vimukti.accounter.web.client.ui;
import java.util.ArrayList;
import java.util.List;
public class Menu extends MenuItem {
List<MenuItem> menuItems;
public Menu(String title) {
super(title);
menuItems = new ArrayList<MenuItem>();
}
public List<MenuItem> getMenuItems() {
return menuItems;
}
public void addMenu(Menu menu) {
this.menuItems.add(menu);
}
public void addMenuItem(MenuItem menu) {
this.menuItems.add(menu);
}
public void addMenuItem(String title, String token) {
this.addMenuItem(new MenuItem(title, token, ""));
}
public void addMenuItem(String title, String token, String shortcut) {
this.addMenuItem(new MenuItem(title, token, shortcut));
}
public void addSeparatorItem() {
this.addMenuItem(new MenuItem());
}
}
| 20.45 | 72 | 0.689487 |
fdae7aac3385c5a2b61b6c6a1df7f474e2ae3e62 | 2,359 | package de.crysxd.ownfx;
import java.awt.AWTException;
import java.awt.Desktop;
import java.awt.Dimension;
import java.awt.Image;
import java.awt.Menu;
import java.awt.MenuItem;
import java.awt.PopupMenu;
import java.awt.SystemTray;
import java.awt.TrayIcon;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.net.URI;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
public class TrayControl implements ActionListener {
private final MenuItem MENU_EXIT = new MenuItem("Quit ownFX");
private final MenuItem MENU_OPEN_WEB = new MenuItem("Open Configurator");
private final Map<Integer, MenuItem> MENU_BRIGTHNESS = new HashMap<>();
public TrayControl() throws AWTException {
//Get Sysstem tray
SystemTray tray = SystemTray.getSystemTray();
//Determine optimized trayicon size
Dimension iconSize = tray.getTrayIconSize();
//Resize image
Image sizedImage = R.getImage("favicon.png", iconSize.width, iconSize.height);
//Create TrayIcon
TrayIcon ico = new TrayIcon(sizedImage);
//Create submenu for brightness
Menu submenu = new Menu("Brightness");
for(int i=0; i<=100; i+=10) {
MenuItem mi = new MenuItem(i + "%");
this.MENU_BRIGTHNESS.put(i, mi);
submenu.add(mi);
mi.addActionListener(this);
}
//Create Menu and
PopupMenu m = new PopupMenu();
m.add(this.MENU_OPEN_WEB);
this.MENU_OPEN_WEB.addActionListener(this);
m.add(submenu);
m.addSeparator();
m.add(this.MENU_EXIT);
this.MENU_EXIT.addActionListener(this);
//Add PopupMenu to ico
ico.setPopupMenu(m);
//Add Trayicon to SystemTray
tray.add(ico);
}
@Override
public void actionPerformed(ActionEvent e) {
if(e.getSource() == this.MENU_EXIT) {
System.exit(0);
} else if(e.getSource() == this.MENU_OPEN_WEB) {
try {
URI uri = new URI("http://localhost");
Desktop.getDesktop().browse(uri);
} catch(Exception e1) {
e1.printStackTrace();
}
} else if(this.MENU_BRIGTHNESS.containsValue(e.getSource())) {
int brightness = 100;
//Search brightness for the selected menu item
for(Entry<Integer, MenuItem> entry : this.MENU_BRIGTHNESS.entrySet()) {
if(entry.getValue() == e.getSource())
brightness = entry.getKey();
}
Main.getMain().setSystemBrightness(brightness);
}
}
}
| 25.095745 | 80 | 0.701992 |
71f8121b01f07b98b7e0a19c774bc581074c8135 | 352 | package br.com.zupacademy.henriquecesar.mercadolivre.repository;
import java.util.Optional;
import org.springframework.data.repository.CrudRepository;
import br.com.zupacademy.henriquecesar.mercadolivre.modelo.Usuario;
public interface UsuarioRepository extends CrudRepository<Usuario, Long> {
Optional<Usuario> findByLogin(String string);
}
| 25.142857 | 74 | 0.829545 |
a56c2ba3e366763ef71de06cfafbc58de37a8ae3 | 250 | package com.breadcrumbdata.anchor_service.repository;
import com.breadcrumbdata.anchor_service.dataobject.Level;
import org.springframework.data.jpa.repository.JpaRepository;
public interface LevelRepository extends JpaRepository<Level,Integer>{
}
| 31.25 | 70 | 0.864 |
200471954d8120accdc156c8c18ee3d326d09dcb | 778 | package de.geolykt.starloader.api.event.empire;
import org.jetbrains.annotations.NotNull;
import de.geolykt.starloader.api.empire.ActiveEmpire;
/**
* Event that is fired whenever the technology level of an empire decreases by
* one. This is the usual natural progression that decreases the technology
* level and usually is only fired if the empire is degenerating. However this
* event does not distinguish from naturally fired events and those fired by
* extensions.
*/
public class TechnologyLevelDecreaseEvent extends TechnologyLevelSetEvent {
/**
* Constructor.
*
* @param empire The affected empire
*/
public TechnologyLevelDecreaseEvent(@NotNull ActiveEmpire empire) {
super(empire, empire.getTechnologyLevel() - 1);
}
}
| 31.12 | 78 | 0.749357 |
9dc5f911024cf6ba9a611da76133bc9526f7b04f | 3,208 | /*
* Copyright (c) 2010-2013 the original author or authors
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
*/
package org.jmxtrans.embedded.util.net;
import java.io.BufferedWriter;
import java.io.FilterWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.nio.charset.Charset;
/**
* Convenience class for writing characters to a {@linkplain Socket}.
*
* @author <a href="mailto:[email protected]">Cyrille Le Clerc</a>
* @author <a href="mailto:[email protected]">Patrick Brühlmann</a>
*/
public class SocketWriter extends FilterWriter {
private final Socket socket;
private final DatagramSocket datagramSocket;
/**
* @param inetSocketAddress host and port of the underlying {@linkplain Socket}
* @param charset charset of the {@linkplain java.io.OutputStream} underlying {@linkplain Socket}
* @throws IOException
*/
public SocketWriter(InetSocketAddress inetSocketAddress, Charset charset) throws IOException {
this(new Socket(inetSocketAddress.getAddress(), inetSocketAddress.getPort()), charset);
}
public SocketWriter(Socket socket, Charset charset) throws IOException {
super(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(), charset)));
this.socket = socket;
this.datagramSocket = null;
}
public SocketWriter(DatagramSocket datagramSocket, Charset charset) throws IOException {
super(new UDPDatagramWriter(datagramSocket, charset));
this.datagramSocket = datagramSocket;
this.socket = null;
}
/**
* Return the underlying {@linkplain java.net.Socket}
*/
public Socket getSocket() {
return socket;
}
/**
* Return the underlying {@linkplain java.net.DatagramSocket}
*/
public DatagramSocket getDatagramSocket() {
return datagramSocket;
}
@Override
public String toString() {
return "SocketWriter{" +
"socket=" + ((socket != null) ? socket : datagramSocket) +
'}';
}
}
| 36.454545 | 112 | 0.712594 |
a7fec01100818dd8e93869e0ced023eb99388dce | 1,228 | /*
* Copyright (C) 2011 Google Inc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.appengine.datanucleus.annotations;
import org.datanucleus.ClassLoaderResolver;
import org.datanucleus.metadata.AbstractMemberMetaData;
import org.datanucleus.metadata.annotations.AnnotationObject;
import org.datanucleus.metadata.annotations.MemberAnnotationHandler;
/**
* Handler for the {@link Unindexed} annotation when applied to a field/property of a persistable class.
*/
public class UnindexedHandler implements MemberAnnotationHandler
{
public void processMemberAnnotation(AnnotationObject ann, AbstractMemberMetaData mmd, ClassLoaderResolver clr) {
mmd.addExtension("gae.unindexed", "true");
}
} | 39.612903 | 114 | 0.785016 |
652e9be3d80ba67dd9f837a07e41635cd8aa0479 | 417 | package ru.job4j.oop;
/**
* @author madrabit on 05.08.2019
* @version 1$
* @since 0.1
*/
public class BallStory {
public static void main(String[] args) {
Ball ball = new Ball();
Hare hare = new Hare();
Wolf wolf = new Wolf();
Fox fox = new Fox();
hare.tryEat(ball);
ball.run();
wolf.tryEat(ball);
ball.run();
fox.tryEat(ball);
}
}
| 19.857143 | 44 | 0.522782 |
3fd586c17393ab4754873fa26b0f7b02aaa90d51 | 336 | package com.lidong.consumer;
import org.springframework.stereotype.Component;
@Component
public class HelloServiceFallback implements HelloService {
@Override
public String callSayHello(String name) {
return "Error----"+name;
}
@Override
public String test(String name) {
return "没有资源";
}
}
| 17.684211 | 59 | 0.684524 |
b016a1c3b7322f1523763c26db171020359ff16d | 12,659 | /**
* SpectralType.java
*
* Copyright (c) 2017, Samuel Penn.
* See the file LICENSE at the root of the project.
*/
package uk.org.glendale.worldgen.astro.stars;
import uk.org.glendale.worldgen.web.Server;
/**
* Defines the spectral type of the star, using the Hertzsprung-Russell diagram.
* This is a measure of the surface temperature (and hence, colour) of the star,
* with 'Y' stars being coolest and 'O' stars the hottest. The digit provides
* further grading, with '0' being hottest and '9' being coolest.
*
* Spectral types L, T and Y are reserved for brown dwarfs (Y are theoretical).
* 'D' stars are White Dwarfs, and use a somewhat different categorisation. Type
* 'X' stars are X-ray sources, such as neutron stars and black holes. This
* latter type are completely unofficial, since I can't find the right way to
* classify these star types.
*
* @author Samuel Penn
*/
public enum SpectralType {
// < 700K (infrared), sub-brown dwarfs
Y9, Y8, Y7, Y6, Y5, Y4, Y3, Y2, Y1, Y0,
// 700 - 1,300 K (infrared), methane dwarfs
T9, T8, T7, T6, T5, T4, T3, T2, T1, T0,
// 1,300 - 2,000 K (dark red), dwarfs
L9, L8, L7, L6, L5, L4, L3, L2, L1, L0,
// 2,000 - 3,700 K (red)
M9, M8, M7, M6, M5, M4, M3, M2, M1, M0,
// 3,700 - 5,200 K (orange)
K9, K8, K7, K6, K5, K4, K3, K2, K1, K0,
// 5,200 - 6000 K (yellow)
G9, G8, G7, G6, G5, G4, G3, G2, G1, G0,
// 6,000 - 7,500 K (yellowish white)
F9, F8, F7, F6, F5, F4, F3, F2, F1, F0,
// 7,500 - 10,000 K (white)
A9, A8, A7, A6, A5, A4, A3, A2, A1, A0,
// 10,000 - 30,000 K (blue to blue white)
B9, B8, B7, B6, B5, B4, B3, B2, B1, B0,
// > 33,000 K (white)
O9, O8, O7, O6, O5, O4, O3, O2, O1, O0,
// White Dwarfs
D9, D8, D7, D6, D5, D4, D3, D2, D1, D0,
// Neutron Stars (X9 - X7) and Black Holes (X6 and hotter)
X9, X8, X7, X6, X5, X4, X3, X2, X1, X0;
/**
* Create a spectral type from a letter designation and digit.
* The lower the digit, the cooler the star.
*
* @param letter Letter, one of YTLMKGFABOD or X.
* @param digit Digit, from 0 to 9.
* @return
*/
public static SpectralType getSpectralType(char letter, int digit) {
String name = "" + letter + digit;
return valueOf(name);
}
public char getLetter() {
return toString().charAt(0);
}
public int getDigit() {
return Integer.parseInt("" + toString().charAt(1));
}
/**
* Gets the inverse of the digit part of this spectral type. Used because 0 is hotter than 9,
* but it makes some calculations easier if higher numbers are hotter.
*
* @return Gets value of 9 - digit.
*/
private int getInverseDigit() {
return 9 - Integer.parseInt("" + toString().charAt(1));
}
public String getRGBColour() {
String rgb = "0 0 0";
if (Server.getConfiguration().getUseRealStarColours()) {
// The colours for O - M are taken from http://www.vendian.org/mncharity/dir3/starcolor/
switch (getLetter()) {
case 'O':
rgb = "#9bb0ff";
break;
case 'B':
rgb = "#aabfff";
break;
case 'A':
rgb = "#cad7ff";
break;
case 'F':
rgb = "#f8f7ff";
break;
case 'G':
rgb = "#fff4ea";
break;
case 'K':
rgb = "#ffd2a1";
break;
case 'M':
rgb = "#ffcc6f";
break;
case 'L':
case 'T':
case 'Y':
rgb = "#ffbb50";
break;
case 'X':
// Drop neutron stars and black holes into the same category.
rgb = "#000000";
break;
case 'D':
rgb = "#ffffff";
break;
}
} else {
switch (getLetter()) {
case 'D':
rgb = "#ffffff";
break;
case 'X':
rgb = "#000000";
break;
case 'Y':
rgb = "#550000";
break;
case 'T':
rgb = "#550000";
break;
case 'L':
rgb = "#990000";
break;
case 'M':
rgb = "#ee0000";
break;
case 'K':
rgb = "#ee5500";
break;
case 'G':
rgb = "#eeee00";
break;
case 'F':
rgb = "#eeee00";
break;
case 'A':
rgb = "#7777ff";
break;
case 'B':
rgb = "#7777ff";
break;
case 'O':
rgb = "#7777ff";
break;
}
}
return rgb;
}
/**
* Get the surface temperature of the star.
*/
public int getSurfaceTemperature() {
int k = 0;
switch (getLetter()) {
case 'D':
// White Dwarfs. This does not use the proper way of calculating this.
k = (int) (40 + Math.pow(getInverseDigit(), 2.5) * 5) * 100;
break;
case 'X':
// X-Ray remnants, Neutron Stars and Black Holes.
k = 1000 + getInverseDigit() * getInverseDigit()
* getInverseDigit() * 2000;
break;
case 'Y':
// Ultra-cool brown dwarfs.
k = 300 + getInverseDigit() * 60;
break;
case 'T':
// Cool brown dwarfs (Methan Dwarfs)
k = 600 + getInverseDigit() * 70;
break;
case 'L':
// Cool dwarfs
k = 1300 + getInverseDigit() * 70;
break;
case 'M':
k = 2000 + getInverseDigit() * 170;
break;
case 'K':
k = 3700 + getInverseDigit() * 150;
break;
case 'G':
k = 5200 + getInverseDigit() * 80;
break;
case 'F':
k = 6000 + getInverseDigit() * 150;
break;
case 'A':
k = 7500 + getInverseDigit() * 250;
break;
case 'B':
k = 10000 + getInverseDigit() * 2000;
break;
case 'O':
k = 30000 + getInverseDigit() * 5000;
break;
}
return k;
}
/**
* Get the mass of a main sequence star with this spectral type, relative to Sol.
* This needs to be multiplied with the Luminosity mass modifier to find the actual
* mass of a specific star.
*
* @return Mass in Sols.
*/
public double getMass() {
double mass = 1.0;
int digit = getInverseDigit();
switch (getLetter()) {
case 'D':
mass = 0.1 * digit * 0.14;
break;
case 'Y':
mass = 0.020 + digit * 0.0005;
break;
case 'T':
mass = 0.025 + digit * 0.0005;
break;
case 'C':
mass = 0.030 + digit * 0.001;
break;
case 'L':
mass = 0.04 + digit * 0.005;
break;
case 'M':
mass = 0.08 + digit * 0.04;
break;
case 'K':
mass = 0.44 + digit * 0.04;
break;
case 'G':
mass = 0.8 + digit * 0.029;
break;
case 'F':
mass = 1.04 + digit * 0.04;
break;
case 'A':
mass = 1.4 + digit * 0.77;
break;
case 'B':
mass = 2.1 + digit * 1.5;
break;
case 'O':
mass = 16.0 + digit * 2.5;
break;
case 'X':
mass = 1.4 + digit * digit * 0.2;
break;
}
return mass;
}
/**
* Gets the radius modifier for this spectral type. Multiply this by the radius of
* the luminosity class to get an actual radius of a star in Sol radius.
*
* @return Radius relative to Sol.
*/
public double getRadius() {
double radius = 1.0;
int digit = getInverseDigit();
switch (getLetter()) {
case 'D':
radius = 0.75 * digit * 0.05;
break;
case 'Y': case 'T': case 'C':
radius = 0.1 + digit * 0.01;
break;
case 'L':
radius = 0.14 + digit * 0.01;
break;
case 'M':
radius = 0.24 + digit * 0.02;
break;
case 'K':
radius = 0.44 + digit * 0.04;
break;
case 'G':
radius = 0.86 + digit * 0.02;
break;
case 'F':
radius = 1.04 + digit * 0.04;
break;
case 'A':
radius = 1.4 + digit * 0.77;
break;
case 'B':
radius = 2.0 + digit * 0.2;
break;
case 'O':
radius = 7.0 + digit * 0.5;
break;
case 'X':
radius = 1.0;
break;
}
return radius;
}
/**
* Get the life time of the star, in billions of years.
*/
public double getLifeTime() {
double billions = 0.0;
if (toString().startsWith("M")) {
billions = 100;
} else if (toString().startsWith("K")) {
billions = 21;
} else if (toString().startsWith("G")) {
billions = 12;
} else if (toString().startsWith("F")) {
billions = 3.0;
} else if (toString().startsWith("A")) {
billions = 1.0;
} else if (toString().startsWith("B")) {
billions = 0.2;
} else if (toString().startsWith("O")) {
billions = 0.005;
} else if (toString().startsWith("Y")) {
billions = 800;
} else if (toString().startsWith("T")) {
billions = 400;
} else if (toString().startsWith("L")) {
billions = 200;
} else if (toString().startsWith("D")) {
billions = 100;
} else if (toString().startsWith("X")) {
billions = 1000;
}
return billions;
}
public SpectralType getColder() {
if (this.ordinal() == 0) {
return this;
} else {
return SpectralType.values()[this.ordinal() - 1];
}
}
public SpectralType getHotter() {
if (this.ordinal() == SpectralType.values().length - 1) {
return this;
} else {
return SpectralType.values()[this.ordinal() + 1];
}
}
/**
* Gets the spectral type that is shifted the given number of steps hotter or colder
* than the current one. A positive shift makes it that many steps hotter, a negative
* shift makes it colder. Can only be used on main-sequence stars, in the range Y
* to O. For stellar remnants it always returns the same spectral type.
*
* @param delta Amount to change this spectral type by.
* @return New modified spectral type.
*/
public SpectralType getSpectralType(int delta) {
if (ordinal() > O0.ordinal()) {
return this;
}
int st = this.ordinal() + delta;
if (st < Y9.ordinal()) {
st = Y9.ordinal();
} else if (st > O0.ordinal()) {
st = O9.ordinal();
}
return SpectralType.values()[st];
}
public static void main(String[] args) {
for (SpectralType t : new SpectralType[] { D9, D8, D7, D6, D5, D4, D3, D2, D1, D0 }) {
System.out.println(t.name() + ": " + t.getSurfaceTemperature());
}
}
} | 31.179803 | 100 | 0.432894 |
fdb783df0fc4327f7bffd37b4aeee6c1e8436bbc | 2,431 | package main.java.jce.compiling.utils;
import com.google.gson.Gson;
import com.google.gson.stream.JsonReader;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import java.io.*;
import java.util.List;
import java.util.Objects;
/**
* FileScriptCreator is a Tool which is use to
* Find proper FileScript in CompilerScript base on given information.
*
* Note: This program is Written with Lombok.
* @see <a href="https://projectlombok.org/">Lombok Site</a>
*/
@RequiredArgsConstructor
@AllArgsConstructor
public class FileScriptCreator {
@Getter private Pathify pathify;
@Getter private String fileLanguage;
@Getter private String parameters;
private String compilerScriptPath;
@Getter private List<String[]> customPairs;
public FileScript get() {
FileScript fileScript = findScript();
checkNullity(fileScript);
fileScript.setPathify(getPathify(), customPairs, parameters);
return fileScript;
}
private InputStream getCompilerScriptPath() {
if (compilerScriptPath != null) {
try { return new FileInputStream(compilerScriptPath); }
catch (FileNotFoundException e) { e.printStackTrace();}
}
return getDefaultCompilerScriptPath();
}
private InputStream getDefaultCompilerScriptPath() {
return getClass().getClassLoader().getResourceAsStream("main/resources/CompilerScript.json");
}
private void checkNullity(FileScript fileScript) {
if (fileScript == null) throw new IllegalArgumentException(
String.format("%s: Cannot find %s in %s",
getClass().getSimpleName(),
getFileLanguage(),
getCompilerScriptPath()));
}
/**
* @return All the FileScripts in CompilerScript
*/
private FileScript[] getFileScripts() {
return new Gson().fromJson(new JsonReader(new InputStreamReader(getCompilerScriptPath())),FileScript[].class);
}
/**
* @return proper FileScript for given information
*/
private FileScript findScript() {
FileScript fileScript = null;
for (FileScript script : Objects.requireNonNull(getFileScripts())) if (script.getLanguage().equals(getFileLanguage())) {
fileScript = script;
break;
}
return fileScript;
}
}
| 31.166667 | 128 | 0.66557 |
6482d3342e4acaf8a19bcef7228b1bd52a5cce18 | 99 | package com.panosen.collections;
public final class Should<TValue> extends Conditions<TValue> {
}
| 19.8 | 62 | 0.79798 |
428c628c6af7fe6b4ed022ea9ff16309bd538a7c | 980 | package com.jimmy.model;
/**
* 门户展示结果对象
*
* @author zhour
*/
public class AdminRevealResultModel extends BaseModel {
private BarChartPluginListEntity barChartResult;
private LineChartPluginListEntity lineChartResult;
private SmallChartPluginEntity smallChartResult;
public BarChartPluginListEntity getBarChartResult() {
return barChartResult;
}
public void setBarChartResult(BarChartPluginListEntity barChartResult) {
this.barChartResult = barChartResult;
}
public LineChartPluginListEntity getLineChartResult() {
return lineChartResult;
}
public void setLineChartResult(LineChartPluginListEntity lineChartResult) {
this.lineChartResult = lineChartResult;
}
public SmallChartPluginEntity getSmallChartResult() {
return smallChartResult;
}
public void setSmallChartResult(SmallChartPluginEntity smallChartResult) {
this.smallChartResult = smallChartResult;
}
}
| 25.789474 | 79 | 0.747959 |
67b6b131f2c34f53b3c467509f23788698677416 | 5,691 | package be.unamur.info.b314.compiler.pils.declarations;
import be.unamur.info.b314.compiler.GrammarParser;
import be.unamur.info.b314.compiler.listeners.Context;
import be.unamur.info.b314.compiler.mappers.SpaceRequirement;
import be.unamur.info.b314.compiler.nbc.symbols.Identifier;
import be.unamur.info.b314.compiler.pils.expressions.Expression;
import be.unamur.info.b314.compiler.pils.expressions.ExpressionLeaf;
import be.unamur.info.b314.compiler.pils.statements.Statement;
import be.unamur.info.b314.compiler.pils.values.Value;
import be.unamur.info.b314.compiler.visitors.FunctionVisitor;
import lombok.*;
import lombok.experimental.SuperBuilder;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
/**
* @author Hadrien BAILLY
*/
@Slf4j
@Data
@SuperBuilder(toBuilder = true)
@AllArgsConstructor
@EqualsAndHashCode(callSuper = true)
public class Function extends Symbol implements Declaration {
/**
* Type effectif de la fonction (doit être l'un des types énumérés).
*
* @see Type
*/
private final Type type;
/**
* liste des arguments de la fonction.
*/
@Singular
private final List<Variable> arguments;
/**
* Liste des déclarations locales de la fonction.
*/
@Singular
private final List<Variable> declarations;
/**
* Liste des instructions composant la fonction.
*/
@Builder.Default
private final List<Statement> statements = new ArrayList<>();
/**
* Le niveau d'identation
*/
@Getter(AccessLevel.NONE)
@Builder.Default
private final int indentation = 0;
/**
* Expression de retour.
*/
@Builder.Default
private Expression output = ExpressionLeaf.VOID;
/**
* Identifiant en nbc du registre de retour
*/
private Identifier outputIdentifier;
/**
* Fonction récuparant les données de la fonction courante
*
* @param ctx : l'instruction en cours de traitement.
* @param symbols : les tables des symboles courantes
* @return : un objet "Function" contenant le nom, le type, les paramètres, et le corps de la fonction.
*/
public static Function from(final GrammarParser.FctDeclContext ctx, final Context symbols) {
return new FunctionVisitor(symbols).visitFctDecl(ctx);
}
/**
* Reconstitue la fonction courante sous forme d'un string
*
* @return un String contenant les données de la fonction courante.
*/
public String getDeclaration() {
final String tab0 = StringUtils.repeat("\t", indentation) + "\t";
final String tab1 = tab0 + "\t";
return getName() + " as function (" + arguments.stream().map(Variable::getArgument).collect(Collectors.joining(", ")) + "): " + type
+ (declarations.size() != 0
? "\n" + tab0 + "declare local"
+ "\n" + tab1 + declarations.stream().map(Variable::getDeclaration).collect(Collectors.joining("\n" + tab1)) : "")
+ "\n" + tab0 + "do"
+ "\n" + (statements.size() != 0 ? tab1 + statements.stream().map(Object::toString).collect(Collectors.joining("\n" + tab1)) : "")
+ (isVoid() ? "" : "\n" + tab1 + "return " + output.toString())
+ "\n" + tab0 + "done";
}
/**
* Vérifie si la fonction courante est de type VOID.
*
* @return vrai si le type déclaré est VOID, faux sinon.
*/
public boolean isVoid() {
return type.equals(Type.VOID);
}
public SpaceRequirement getSpaceRequirement() {
final SpaceRequirement statementsRequirement = statements.stream()
.map(Statement::getSpaceRequirement)
.reduce(SpaceRequirement::merge)
.orElse(SpaceRequirement.NONE);
final SpaceRequirement outputRequirement = output.getSpaceRequirement();
return SpaceRequirement.merge(statementsRequirement, outputRequirement);
}
/**
* Ajoute un statement au corps de la fonction.
*
* @param statement le statement à rajouter.
*/
public void add(final Statement statement) {
this.statements.add(statement);
}
/**
* Indique si la fonction contient des déclarations.
*
* @return vrai s'il y a au moins une déclaration, faux sinon.
*/
public boolean hasDeclarations() {
return declarations.size() > 0;
}
/**
* Indique si la fonction contient des arguments formels.
*
* @return vrai si la fonction a au moins un argument, faux sinon.
*/
public boolean hasArguments() {
return arguments.size() > 0;
}
public Value run(final List<Expression> arguments) {
log.trace("Running function [{}] with arguments [{}]", getName(), arguments.stream().map(Expression::getValue).collect(Collectors.toList()));
IntStream.range(0, arguments.size())
.forEach(i -> this.arguments.get(i).set(arguments.get(i).getValue()));
statements.forEach(Statement::run);
return output.getValue();
}
@Override
public String toString() {
return super.toString();
}
@Override
public boolean isValid() {
return super.isValid()
&& type != null
&& ((isVoid() && (output == null || output.isVoid()))
^ (!isVoid() && output != null && output.isValid() && output.getType().equals(type)))
&& arguments.stream().allMatch(Variable::isValid)
&& statements.stream().allMatch(Statement::isValid);
}
}
| 32.895954 | 149 | 0.640309 |
a5982e2106f400970a316e2719891cd9df8b10e3 | 2,515 | /**
* Copyright 2005-2014 Red Hat, Inc.
*
* Red Hat 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.fabric8.agent.mvn;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;
/**
* Handler configuration.
*
* @since August 11, 2007
*/
public interface MavenConfiguration {
/**
* Returns true if the certificate should be checked on SSL connection, false otherwise.
*
* @return true if the certificate should be checked
*/
Boolean getCertificateCheck();
/**
* Returns the URL of maven settings file.
*
* @return the url to settings file
*/
URL getSettingsFileUrl();
/**
* Returns a list of default repositories to be searched before any other repositories.
*
* @return a list of default repositories. List can be null or empty if there are not default repositories to be searched.
*/
List<MavenRepositoryURL> getDefaultRepositories()
throws MalformedURLException;
/**
* Returns a list of repositories to be searched.
*
* @return a list of repositories. List can be null or empty if there are no repositories to be searched.
*/
List<MavenRepositoryURL> getRepositories()
throws MalformedURLException;
/**
* Returns the url of local repository.
*
* @return url of local repository. Can be null if there is no local repository.
*/
MavenRepositoryURL getLocalRepository();
/**
* Returns true if the fallback repositories should be used instead of default ones.
* Default value is false.
*
* @return true if the fallback repositories should
*/
Boolean useFallbackRepositories();
/**
* Enables the proxy server for a given URL.
*/
void enableProxy(URL url);
/**
* Returns if aether should be disabled or not.
*
* @return true if aether should be disabled
*/
Boolean isAetherDisabled();
}
| 29.244186 | 127 | 0.673161 |
0da77c9eecafebd07be52a5758d2e295ae16b25a | 2,831 | /*
* 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 macromedia.asc.parser;
import macromedia.asc.util.*;
import macromedia.asc.semantics.*;
/**
* Node
*
* @author Jeff Dyer
*/
public class PackageIdentifiersNode extends Node
{
private static final int IS_DEFINITION_FLAG = 1;
public ObjectList<IdentifierNode> list = new ObjectList<IdentifierNode>(5);
public String pkg_part;
public String def_part;
public PackageIdentifiersNode(IdentifierNode item, int pos, boolean isDefinition)
{
super(pos);
list.add(item);
if (isDefinition)
{
flags |= IS_DEFINITION_FLAG;
}
}
public Value evaluate(Context cx, Evaluator evaluator)
{
if (evaluator.checkFeature(cx, this))
{
return evaluator.evaluate(cx, this);
}
else
{
return null;
}
}
int size()
{
return this.list.size();
}
public int pos()
{
return list.size() != 0 ? list.last().pos() : 0;
}
// Used externally by SyntaxTreeDumper
public boolean isDefinition()
{
return (flags & IS_DEFINITION_FLAG) != 0;
}
public String toString()
{
return "PackageIdentifiers";
}
void clearIdentifierString()
{
if (pkg_part != null )
{
pkg_part = null;
}
if (def_part != null)
{
def_part = null;
}
}
private static final String ASTERISK = "*".intern();
public String toIdentifierString()
{
if( pkg_part == null )
{
StringBuilder buf = new StringBuilder();
//ListIterator<IdentifierNode> it = list.listIterator();
//while( it.hasNext() )
int len = list.size();
for(int x=0; x < len; x++)
{
IdentifierNode item = list.get(x);
if (x == len - 1 && isDefinition())
{
def_part = "";
if (ASTERISK != item.name)
def_part = item.name;
}
else
{
if( buf.length() > 0 )
{
buf.append(".");
}
buf.append(item.toIdentifierString());
}
}
pkg_part = buf.toString();
}
return pkg_part;
}
}
| 22.648 | 82 | 0.628753 |
f359d194257209856b1bd7d5689c5e8f24e770ea | 163 | package signature;
import java.io.File;
public class TestStandardTypes {
void signature() {
TestStandardTypes a= null;
String s= null;
File f= null;
}
}
| 13.583333 | 32 | 0.705521 |
4312f5611f5a22030f27db6452268bcafbd83482 | 4,845 | package fi.nls.oskari.control.layer;
import fi.nls.oskari.control.ActionConstants;
import fi.nls.oskari.control.ActionDeniedException;
import fi.nls.oskari.control.ActionException;
import fi.nls.oskari.control.ActionParameters;
import fi.nls.oskari.domain.map.OskariLayer;
import fi.nls.oskari.map.layer.OskariLayerService;
import fi.nls.oskari.map.layer.OskariLayerServiceMybatisImpl;
import fi.nls.oskari.service.OskariComponentManager;
import fi.nls.oskari.service.capabilities.CapabilitiesCacheService;
import fi.nls.oskari.util.PropertyUtil;
import fi.nls.test.control.JSONActionRouteTest;
import fi.nls.test.util.TestHelper;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.oskari.permissions.PermissionService;
import org.oskari.permissions.PermissionServiceMybatisImpl;
import org.oskari.permissions.model.*;
import org.powermock.modules.junit4.PowerMockRunner;
import java.util.HashMap;
import java.util.Map;
import static org.junit.Assert.fail;
import static org.junit.Assume.assumeTrue;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
/**
* Created by SMAKINEN on 28.8.2015.
*/
@RunWith(PowerMockRunner.class)
public class GetLayerCapabilitiesHandlerTest extends JSONActionRouteTest {
private static final String TEST_DATA = "test data";
private GetLayerCapabilitiesHandler handler = null;
@Before
public void setup() {
assumeTrue(TestHelper.dbAvailable());
OskariLayerService layerService = getOskariLayerService();
PermissionService permissionsService = getPermissionsService();
// replace the cache service with a test service
OskariComponentManager.removeComponentsOfType(CapabilitiesCacheService.class);
OskariComponentManager.addComponent(new CapabilitiesCacheServiceMock(TEST_DATA));
//CapabilitiesCacheService service = OskariComponentManager.getComponentOfType(CapabilitiesCacheService.class);
handler = new GetLayerCapabilitiesHandler();
PermissionHelper helper = new PermissionHelper(layerService, permissionsService);
handler.setPermissionHelper(helper);
handler.init();
}
@Test(expected = ActionDeniedException.class)
public void testHandleActionGuest()
throws Exception {
Map<String, String> httpParams = new HashMap<>();
httpParams.put(ActionConstants.KEY_ID, "1");
ActionParameters params = createActionParams(httpParams);
// only gave logged in user role permission so this should throw ActionDeniedException
handler.handleAction(params);
fail("Should have thrown exception");
}
@Test
public void testHandleActionUser()
throws Exception {
Map<String, String> httpParams = new HashMap<>();
httpParams.put(ActionConstants.KEY_ID, "1");
ActionParameters params = createActionParams(httpParams, getLoggedInUser());
handler.handleAction(params);
// logged in user has permission so this should TEST_DATA from mock service
verifyResponseContent(TEST_DATA);
}
@Test(expected = ActionException.class)
public void testHandleServiceException()
throws Exception {
Map<String, String> httpParams = new HashMap<>();
httpParams.put(ActionConstants.KEY_ID, "2");
ActionParameters params = createActionParams(httpParams, getLoggedInUser());
handler.handleAction(params);
fail("Should have thrown exception");
}
/* *********************************************
* Service mocks
* ********************************************
*/
private OskariLayerService getOskariLayerService() {
OskariLayerService layerService = mock(OskariLayerServiceMybatisImpl.class);
OskariLayer layer = new OskariLayer();
layer.setType("WMTS");
doReturn(layer).when(layerService).find(1);
OskariLayer errorLayer = new OskariLayer();
errorLayer.setType("ERROR");
doReturn(errorLayer).when(layerService).find(2);
return layerService;
}
private PermissionService getPermissionsService() {
PermissionService service = mock(PermissionServiceMybatisImpl.class);
Resource res = new Resource();
Permission p = new Permission();
p.setType(PermissionType.VIEW_LAYER);
p.setExternalType(PermissionExternalType.ROLE);
p.setExternalId("" + getLoggedInUser().getRoles().iterator().next().getId());
res.addPermission(p);
doReturn(res).when(service).findResource(ResourceType.maplayer, any(String.class));
return service;
}
@AfterClass
public static void delete() {
PropertyUtil.clearProperties();
}
} | 38.452381 | 119 | 0.715583 |
2bb8a935f632c19da7dd2acabf44ca482eab764b | 1,922 | package com.ymy.xxb.migrat.module.comyany.controller;
//import org.redisson.api.RLock;
//import org.redisson.api.RedissonClient;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.web.bind.annotation.PostMapping;
//import org.springframework.web.bind.annotation.RequestMapping;
//import org.springframework.web.bind.annotation.RequestParam;
//import org.springframework.web.bind.annotation.RestController;
//import com.ymy.xxb.migrat.common.constant.Constants;
//import com.ymy.xxb.migrat.common.result.SoulResult;
//import com.ymy.xxb.migrat.module.comyany.constant.ModuleConst;
//import io.swagger.annotations.Api;
//import io.swagger.annotations.ApiOperation;
//import lombok.extern.slf4j.Slf4j;
/**
*
* redisson client server
*
* @author: wangyi
*
*/
// @Slf4j
// @RestController
// @RequestMapping(Constants.API_AUTH_PREFIX + ModuleConst.API.API_MODULE_REDISSION)
// @Api(value = "RedissonController API", tags = "redisson", description = "redission客户端服务")
public class RedssionController {
// @Autowired
// private RedissonClient redissonClient;
/**
* 用户通过客户端自行处理分布式锁业务
*
* @param lockKey
* @return
*/
// @PostMapping(value = "/lockBiz")
// @ApiOperation(value = "分布式锁业务操作" , httpMethod = "POST" , notes = "支持重入锁,线程安全,分布式业务锁操作" , produces = "application/json;charset=UTF-8")
// public SoulResult lockBiz(
// @RequestParam(value = "lockKey", required = true) String lockKey
// ) {
// RLock lock = redissonClient.getLock(lockKey);
// try {
// // 加锁,类似JAVA中ReentrantLock机制
// lock.lock();
//
// // BIZ 处理, 例如秒杀场景
// if (log.isInfoEnabled()) {
// log.info("Handler Success...");
// }
// } catch (Exception e) {
// e.printStackTrace();
// return SoulResult.error(String.format("BIZ处理失败, ERROR Detail: %s", e.getMessage()));
// } finally {
// lock.unlock();
// }
//
// return SoulResult.success("BIZ处理成功!");
// }
}
| 30.03125 | 138 | 0.707076 |
221538417b76899fe30551da0da851153ab8063a | 900 | package com.pugz.bloomful.common.world.gen.feature;
import com.mojang.datafixers.Dynamic;
import com.pugz.bloomful.core.util.BiomeFeatures;
import net.minecraft.world.biome.Biome;
import net.minecraft.world.biome.Biomes;
import net.minecraft.world.gen.feature.DoublePlantConfig;
import net.minecraft.world.gen.feature.DoublePlantFeature;
import net.minecraftforge.registries.ForgeRegistries;
import java.util.function.Function;
public class DelphiniumFeature extends DoublePlantFeature {
public DelphiniumFeature(Function<Dynamic<?>, ? extends DoublePlantConfig> builder) {
super(builder);
}
public static void addFeature() {
ForgeRegistries.BIOMES.getValues().forEach(DelphiniumFeature::generate);
}
public static void generate(Biome biome) {
if (biome == Biomes.FLOWER_FOREST) {
BiomeFeatures.addDelphiniums(biome, 4);
}
}
} | 32.142857 | 89 | 0.753333 |
aff4868ab5dc72fabdc16997a32b81afee301bae | 6,717 | /*
* 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.myfaces.trinidadinternal.ui.data.bean;
import java.util.Collection;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import org.apache.myfaces.trinidad.logging.TrinidadLogger;
import org.apache.myfaces.trinidadinternal.ui.UIXRenderingContext;
import org.apache.myfaces.trinidadinternal.ui.data.DataObject;
import org.apache.myfaces.trinidadinternal.ui.data.DataObjectList;
import org.apache.myfaces.trinidadinternal.ui.data.MutableDataObject;
/**
* Utilities for working with bean DataObject adapters. Provides
* a location to register adapter classes, which allow for a
* higher-performance implementation than ordinary introspection.
* However, developers should generally delay creating and registering
* an adapter class until performance metrics justify the addition.
* <p>
* By default, the Bean adapter classes will use the actual class
* of an object instance - that is, object.getClass() - to find
* an adapter, or use introspection to create an adapter. However,
* this is not always desirable for two reasons:
* <ol>
* <li>For efficiency reasons, it's faster to reuse the same
* adapter class for all implementations of a single interface.
*
* <li>Introspection cannot succeed on package-private classes. However,
* it works fine if that package-private class has a public superclass
* or implements a public interface - and that public class or interface
* supports those properties.
* </ol>
* <p>
* Adapters can be built using the BuildBeanDOAdapter tool,
* and all of this rigamarole can be entirely bypassed by
* handing to Cabo instances of these adapter classes instead
* of the bean classes themselves.
* <p>
* @see org.apache.myfaces.trinidadinternal.ui.tools.BuildBeanDOAdapter
* @version $Name: $ ($Revision: adfrt/faces/adf-faces-impl/src/main/java/oracle/adfinternal/view/faces/ui/data/bean/BeanAdapterUtils.java#0 $) $Date: 10-nov-2005.18:56:48 $
* @deprecated This class comes from the old Java 1.2 UIX codebase and should not be used anymore.
*/
@Deprecated
public class BeanAdapterUtils
{
/**
* Creates a DataObject adapter class around an object instance.
* Instead of using the actual class of the instance, use a superclass.
* See above for reasons why this may be useful.
*/
@SuppressWarnings("unchecked")
static public DataObject getAdapter(Object instance, Class<?> objClass)
throws IllegalAccessException, InstantiationException
{
if (instance == null)
return null;
if (instance instanceof DataObject)
return (DataObject) instance;
if (instance instanceof Map)
return new MapDataObject((Map<Object, Object>) instance);
if (objClass == null)
objClass = instance.getClass();
Class<?> adapterClass = _sAdapters.get(objClass);
if (adapterClass != null)
{
BeanDOAdapter adapter = (BeanDOAdapter) adapterClass.newInstance();
adapter.setInstance(instance);
return adapter;
}
else
{
return IntrospectionAdapter.getAdapter(instance);
}
}
/**
* Creates a DataObject adapter class around an object instance.
*/
static public DataObject getAdapter(Object instance)
throws IllegalAccessException, InstantiationException
{
return getAdapter(instance, null);
}
/**
* Creates a DataObject adapter class around an object instance.
* Instead of throwing exceptions, log exceptions with the
* RenderingContext's error log.
*/
static public DataObject getAdapter(
UIXRenderingContext context,
Object instance)
{
try
{
return getAdapter(instance);
}
catch (InstantiationException ie)
{
_LOG.severe(ie);
}
catch (IllegalAccessException iae)
{
_LOG.severe(iae);
}
return null;
}
/**
* Creates a DataObjectList adapter class around an object.
*/
static public DataObjectList getAdapterList(
UIXRenderingContext context, Object listInstance)
{
if (listInstance == null)
return null;
if (listInstance instanceof DataObjectList)
return (DataObjectList) listInstance;
if (listInstance instanceof Object[])
return new BeanArrayDataObjectList((Object[]) listInstance);
if (listInstance instanceof Collection)
return new BeanArrayDataObjectList(((Collection) listInstance).toArray());
if (_LOG.isInfo())
{
_LOG.info("CANNOT_CONVERT_INTO_DATAOBJECTLIST", new Object[]{listInstance, listInstance.getClass()});
}
return null;
}
/**
* Registers an adapter class to be used in place of introspection.
*/
static public void registerAdapterClass(
Class<?> beanClass,
Class<?> adapterClass)
{
// =-=AEW This forces classes to be loaded. Should we allow
// registration by string name?
if (!BeanDOAdapter.class.isAssignableFrom(adapterClass))
throw new IllegalArgumentException(_LOG.getMessage(
"ADAPTER_CLASS_NOT_IMPLEMENT_BEANDOADAPTER"));
_sAdapters.put(beanClass, adapterClass);
}
/**
* @deprecated This class comes from the old Java 1.2 UIX codebase and should not be used anymore.
*/
@Deprecated
static private final class MapDataObject implements MutableDataObject
{
public MapDataObject(Map<Object, Object> map)
{
_map = map;
}
public Object selectValue(UIXRenderingContext context, Object select)
{
return _map.get(select);
}
public void updateValue(
UIXRenderingContext context,
Object select,
Object value)
{
_map.put(select, value);
}
private final Map<Object, Object> _map;
}
static private final ConcurrentHashMap<Class<?>, Class<?>> _sAdapters =
new ConcurrentHashMap<Class<?>, Class<?>>(101);
private static final TrinidadLogger _LOG = TrinidadLogger.createTrinidadLogger(BeanAdapterUtils.class);
}
| 31.834123 | 174 | 0.71922 |
e861c7e1c6949ee3dfca6521cd2cea49fde840c0 | 6,357 | package com.griddelta.lyza.spark;
import static com.datastax.spark.connector.japi.CassandraJavaUtil.javaFunctions;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.lang.NotImplementedException;
import org.apache.spark.SparkConf;
import org.apache.spark.api.java.JavaSparkContext;
import org.apache.spark.api.java.function.Function;
import org.apache.spark.rdd.RDD;
import org.apache.spark.sql.DataFrame;
import org.apache.spark.sql.Row;
import org.apache.spark.sql.RowFactory;
import org.apache.spark.sql.SQLContext;
import org.apache.spark.sql.types.DataTypes;
import org.apache.spark.sql.types.StructField;
import org.apache.spark.sql.types.StructType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import scala.collection.JavaConversions;
import com.datastax.driver.core.Cluster;
import com.datastax.driver.core.ColumnMetadata;
import com.datastax.driver.core.KeyspaceMetadata;
import com.datastax.driver.core.Metadata;
import com.datastax.driver.core.TableMetadata;
import com.datastax.spark.connector.japi.CassandraRow;
public class SqlRunner implements Serializable {
private static final long serialVersionUID = 1L;
private static Logger LOGGER = LoggerFactory.getLogger(SqlRunner.class);
private transient JavaSparkContext context;
private transient SQLContext sqlContext;
private transient Metadata metadata;
@SuppressWarnings("serial")
public SqlRunner(String sparkMasterUrl, String cassandraHost, int cassandraPort, String keyspace, String table) {
SparkConf conf = new SparkConf();
conf.setAppName("Java API demo");
conf.setMaster(sparkMasterUrl);
conf.set("spark.cassandra.connection.host", cassandraHost);
context = new JavaSparkContext(conf);
sqlContext = new SQLContext(context);
Cluster cluster = Cluster.builder().addContactPoints(cassandraHost).withPort(cassandraPort).build();
metadata = cluster.getMetadata();
RDD<Row> cassandraRDD = javaFunctions(context).cassandraTable("test_keyspace", "products")
.map(new Function<CassandraRow, Row>() {
public Row call(CassandraRow cassandraRow) throws Exception {
List<Object> values = JavaConversions.asJavaList(cassandraRow.columnValues());
return RowFactory.create(values.toArray());
}
}).rdd();
cassandraRDD.cache();
LOGGER.info("Total Records Cached = [" + cassandraRDD.count() + "]");
StructType schema = getSchema(keyspace, table);
DataFrame dataFrame = sqlContext.createDataFrame(cassandraRDD, schema);
sqlContext.registerDataFrameAsTable(dataFrame, table);
}
private StructType getSchema(String keyspace, String table) {
KeyspaceMetadata keyspaceMetadata = metadata.getKeyspace(keyspace);
TableMetadata tableMetadata = keyspaceMetadata.getTable(table);
List<StructField> fields = new ArrayList<StructField>();
for (ColumnMetadata columnMetadata : tableMetadata.getColumns()) {
com.datastax.driver.core.DataType dataType = columnMetadata.getType();
if (dataType == com.datastax.driver.core.DataType.ascii()) {
fields.add(DataTypes.createStructField(columnMetadata.getName(), DataTypes.StringType, true));
} else if (dataType == com.datastax.driver.core.DataType.cint()) {
fields.add(DataTypes.createStructField(columnMetadata.getName(), DataTypes.IntegerType, true));
} else if (dataType == com.datastax.driver.core.DataType.cboolean()) {
fields.add(DataTypes.createStructField(columnMetadata.getName(), DataTypes.BooleanType, true));
} else if (dataType == com.datastax.driver.core.DataType.cfloat()) {
fields.add(DataTypes.createStructField(columnMetadata.getName(), DataTypes.FloatType, true));
} else if (dataType == com.datastax.driver.core.DataType.bigint()) {
fields.add(DataTypes.createStructField(columnMetadata.getName(), DataTypes.LongType, true));
} else if (dataType == com.datastax.driver.core.DataType.cdouble()) {
fields.add(DataTypes.createStructField(columnMetadata.getName(), DataTypes.DoubleType, true));
} else if (dataType == com.datastax.driver.core.DataType.timestamp()) {
fields.add(DataTypes.createStructField(columnMetadata.getName(), DataTypes.TimestampType, true));
} else if (dataType == com.datastax.driver.core.DataType.varchar()) {
fields.add(DataTypes.createStructField(columnMetadata.getName(), DataTypes.StringType, true));
} else if (dataType == com.datastax.driver.core.DataType.text()) {
fields.add(DataTypes.createStructField(columnMetadata.getName(), DataTypes.StringType, true));
} else {
throw new NotImplementedException("Sorry [" + dataType + "] type is not supported yet.");
}
// TODO: Map remaining types.
}
StructType schema = DataTypes.createStructType(fields);
LOGGER.debug("Schema = [{}]", schema);
return schema;
}
public DataFrame query(String sql) {
DataFrame result = null;
try {
long start = System.currentTimeMillis();
LOGGER.info("Running query: [" + sql + "]");
result = sqlContext.sql(sql);
long count = result.count();
long stop = System.currentTimeMillis();
LOGGER.info("DONE: [" + count + "] records returned in [" + (stop - start) + "] milliseconds.");
} catch (Exception e) {
LOGGER.error("ERROR", e);
}
return result;
}
public static void main(String[] args) {
LOGGER.debug("Executing sqlRunner with [" + args + "]");
if (args.length != 5) {
System.err
.println("Syntax: com.griddelta.lyza.SqlRunner <sparkMasterUrl> <cassandraHost> <cassandraPort> <keyspace> <table>");
System.exit(1);
}
SqlRunner sqlRunner = new SqlRunner(args[0], args[1], Integer.parseInt(args[2]), args[3], args[4]);
sqlRunner.query("SELECT id, price from products WHERE price < 0.50");
}
}
| 49.27907 | 137 | 0.673588 |
6bd42bd3fcfa84b6b67cc9596ba69321a38f869c | 246 | package io.singularitynet.sdk.ethereum;
/**
* Entity which has an Ethereum address.
*/
public interface WithAddress {
/**
* Return Ethereum address of the entity.
* @return Ethereum address.
*/
Address getAddress();
}
| 16.4 | 45 | 0.654472 |
aa1ff6b35e2070bebd645e5816262a5fa9ac0743 | 573 | package com.sharkman.nodetree.aspect;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* <p> Description:节点树配置</p>
* <p> CreationTime: 2021/8/27 16:21
* <br>Email: <a href="mailto:[email protected]">[email protected]</a></p>
*
* @author yanpengyu
* @version 1.0
* @since 2.1
*/
@Configuration
public class NodeTreeConfig {
/**
* 注入Bean
*
* @return 切面bean
*/
@Bean
public NodeTreeAspect nodeTreeAspect() {
return new NodeTreeAspect();
}
}
| 20.464286 | 86 | 0.668412 |
367c0575e1d6321fd27eafa5bb03328a2749066f | 526 | package de.pxlab.pxl.display.editor;
/**
* The vision demonstrations version of the PXLab display editor.
*
* @version 0.2.0
*/
/*
*
* 2006/11/22
*/
public class VisionDemonstrations {
// ---------------------------------------------------------------
// Application entry point
// ---------------------------------------------------------------
public static void main(String[] args) {
new DisplayEditor(
new de.pxlab.pxl.gui.BigList(de.pxlab.pxl.Topics.DEMO), args,
false);
}
}
| 23.909091 | 68 | 0.477186 |
f72f7c7abe529bb4667edefd798fd0ee7e0eba56 | 1,718 | package me.andrew.silentbackground.mixin;
import me.andrew.silentbackground.SilentBackgroundMod;
import net.minecraft.client.option.GameOptions;
import net.minecraft.client.sound.SoundSystem;
import net.minecraft.sound.SoundCategory;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Redirect;
@Mixin(SoundSystem.class)
public abstract class SoundSystemMixin {
@Redirect(
method = "getSoundVolume",
at = @At(
value = "INVOKE",
target = "Lnet/minecraft/client/option/GameOptions;getSoundVolume(Lnet/minecraft/sound/SoundCategory;)F"
)
)
public float redirectGetSoundVolume1(GameOptions options, SoundCategory soundCategory) {
return SilentBackgroundMod.getModifiedVolume(soundCategory);
}
@Redirect(
method = "start",
at = @At(
value = "INVOKE",
target = "Lnet/minecraft/client/option/GameOptions;getSoundVolume(Lnet/minecraft/sound/SoundCategory;)F"
)
)
public float redirectGetSoundVolume2(GameOptions options, SoundCategory soundCategory) {
return SilentBackgroundMod.getModifiedVolume(soundCategory);
}
@Redirect(
method = "tick()V",
at = @At(
value = "INVOKE",
target = "Lnet/minecraft/client/option/GameOptions;getSoundVolume(Lnet/minecraft/sound/SoundCategory;)F"
)
)
public float redirectGetSoundVolume3(GameOptions options, SoundCategory soundCategory) {
return SilentBackgroundMod.getModifiedVolume(soundCategory);
}
}
| 37.347826 | 124 | 0.672293 |
da3883a871d6da3d6eace87a0187b8b52ed26722 | 972 | package com.patrykkosieradzki.quizletify.api.google;
import org.junit.Test;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.nullValue;
public class LanguageTest {
@Test
public void whenLanguagePolishThenAbbreviationIsGiven() {
assertThat(Language.POLISH.toString(), is("pl"));
}
@Test
public void whenLanguageEnglishThenAbbreviationIsGiven() {
assertThat(Language.ENGLISH.toString(), is("en"));
}
@Test
public void whenPolishAbbreviationIsPassedThenLanguageIsGiven() {
assertThat(Language.fromString("pl"), is(Language.POLISH));
}
@Test
public void whenEnglishAbbreviationIsPassedThenLanguageIsGiven() {
assertThat(Language.fromString("en"), is(Language.ENGLISH));
}
@Test
public void whenInvalidAbbreviationThenNull() {
assertThat(Language.fromString("asd"), is(nullValue()));
}
}
| 26.27027 | 70 | 0.717078 |
144f91e9eca8a91245ff188b87d81375c00ba7ac | 7,913 |
package jam.io;
import java.io.File;
import java.io.IOException;
import jam.app.JamLogger;
import jam.lang.JamException;
import jam.util.RegexUtil;
/**
* Provides utility methods for operating on files and file names.
*
* <p>All methods wrap checked exceptions ({@code IOException}s) in
* runtime exceptions.
*/
public final class FileUtil {
private FileUtil() {}
/**
* Creates a required directory (including all nonexistent parent
* directories) if it does not already exist.
*
* @param dir the required directory.
*
* @throws RuntimeException if the input directory does not exist
* and cannot be created, or if the {@code dir} path does exist
* but is not a directory.
*/
public static void ensureDir(File dir) {
if (!dir.exists()) {
boolean success = dir.mkdirs();
if (success)
JamLogger.info("Created directory [%s]...", dir.getAbsolutePath());
else
throw JamException.runtime("Failed to create directory [%s].", dir.getAbsolutePath());
}
else if (!dir.isDirectory()) {
throw JamException.runtime("Path [%s] exists but is not a directory.", dir.getAbsolutePath());
}
}
/**
* Creates a required directory (including all nonexistent parent
* directories) if it does not already exist.
*
* @param dirName the name of the required directory.
*
* @throws RuntimeException if the input directory does not exist
* and cannot be created, or if the {@code dir} path does exist
* but is not a directory.
*/
public static void ensureDir(String dirName) {
ensureDir(new File(dirName));
}
/**
* Creates the parent directories of a file if they do not already
* exist (e.g., before attempting to open a new file for writing).
*
* @param file the file of interest.
*
* @throws RuntimeException if the parent directories did not
* already exist and could not be created.
*/
public static void ensureParentDirs(File file) {
ensureDir(FileUtil.getParentFile(file));
}
/**
* Determines whether a file exists.
*
* @param fileName the name of the file to check.
*
* @return {@code true} iff a file with the specified name exists.
*/
public static boolean exists(String fileName) {
File file = new File(fileName);
return file.exists();
}
/**
* Returns the basename of a file: the last name in the path
* sequence.
*
* @param file the file of interest.
*
* @return the basename of the specified file.
*/
public static String getBaseName(File file) {
return file.getName();
}
/**
* Returns the prefix of the basename of a file: the substring of
* the basename before the first dot.
*
* @param file the file of interest.
*
* @return the basename prefix of the specified file.
*/
public static String getBaseNamePrefix(File file) {
return getPrefix(getBaseName(file));
}
private static String getPrefix(String fileName) {
return RegexUtil.DOT.split(fileName)[0];
}
/**
* Returns the canonical form of the specified file but never
* throws checked exceptions.
*
* @param file a file to examine.
*
* @return the canonical form of the specified file.
*
* @throws RuntimeException if {@code file.getCanonicalPath}
* throws an {@code IOException}.
*/
public static File getCanonicalFile(File file) {
return new File(getCanonicalPath(file));
}
/**
* Returns the canonical path of the specified file but never
* throws checked exceptions.
*
* @param file a file to examine.
*
* @return the canonical path of the specified file.
*
* @throws RuntimeException if {@code file.getCanonicalPath}
* throws an {@code IOException}.
*/
public static String getCanonicalPath(File file) {
String result = null;
try {
result = file.getCanonicalPath();
}
catch (IOException ioex) {
throw JamException.runtime(ioex);
}
return result;
}
/**
* Returns the canonical <em>prefix</em> of the specified file
* (everything before the first dot in the canonical path) but
* never throws checked exceptions.
*
* @param file a file to examine.
*
* @return the canonical prefix of the specified file.
*
* @throws RuntimeException if {@code file.getCanonicalPath}
* throws an {@code IOException}.
*/
public static String getCanonicalPrefix(File file) {
return getPrefix(getCanonicalPath(file));
}
/**
* Returns the name of the parent directory of a file, or
* {@code .} (dot) if the file does not specify a parent.
*
* <p>Unlike the method {@code java.io.File.getParent}, this
* method never returns {@code null}.
*
* @param file a file to examine.
*
* @return the name of the parent directory of the specified file,
* or {@code .} (dot) if the file does not specify a parent.
*/
public static String getDirName(File file) {
String result = file.getParent();
if (result == null)
result = ".";
return result;
}
/**
* Returns the parent directory of a file, or the "dot" directory
* if the file does not specify a parent.
*
* <p>Unlike the method {@code java.io.File.getParentFile}, this
* method never returns {@code null}.
*
* @param file a file to examine.
*
* @return the parent directory of the specified file, or the
* "dot" directory if the file does not specify a parent.
*/
public static File getParentFile(File file) {
return new File(getDirName(file));
}
/**
* Identifies canonical files.
*
* @param file a file to examine.
*
* @return {@code true} iff the specified file has a canonical
* path name.
*/
public static boolean isCanonicalFile(File file) {
return file.equals(getCanonicalFile(file));
}
/**
* Builds a composite file name by joining components with the
* system-dependent name separator.
*
* @param dirName the first directory in the composite path.
*
* @param pathNames the subdirectories and final base name in
* the composite path.
*
* @return the composite file name.
*/
public static String join(String dirName, String... pathNames) {
StringBuilder builder = new StringBuilder(dirName);
for (String pathName : pathNames) {
builder.append(File.separator);
builder.append(pathName);
}
return builder.toString();
}
/**
* Creates a new file by building a composite file name.
*
* @param dirName the first directory in the composite path.
*
* @param pathNames the subdirectories and final base name in
* the composite path.
*
* @return a new file with the composite file name.
*/
public static File newFile(String dirName, String... pathNames) {
return new File(join(dirName, pathNames));
}
/**
* Asserts that a file exists.
*
* @param fileName the name of the required file.
*
* @throws RuntimeException if the file does not exist.
*/
public static void requireFile(String fileName) {
requireFile(new File(fileName));
}
/**
* Asserts that a file exists.
*
* @param file the required file.
*
* @throws RuntimeException if the file does not exist.
*/
public static void requireFile(File file) {
if (!file.exists())
throw JamException.runtime("File [%s] does not exist.", getCanonicalPath(file));
}
}
| 28.879562 | 106 | 0.620119 |
066ffa6e5a21eff6d987f2e3788a112d38f8a8e0 | 680 | /********************************************************************************
* Copyright (c) 2011-2017 Red Hat Inc. and/or its affiliates and others
*
* This program and the accompanying materials are made available under the
* terms of the Apache License, Version 2.0 which is available at
* http://www.apache.org/licenses/LICENSE-2.0
*
* SPDX-License-Identifier: Apache-2.0
********************************************************************************/
package org.eclipse.ceylon.ide.common.model;
import org.eclipse.ceylon.model.loader.AbstractModelLoader;
public interface LazyModuleManagerEx {
void initModelLoader(AbstractModelLoader modelLoader);
}
| 40 | 82 | 0.588235 |
9e74f7345c28646145752045164485c15f3d9f4b | 21,274 | /*
* Copyright 2006-2011 The Virtual Laboratory for e-Science (VL-e)
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* For details, see the LICENCE.txt file location in the root directory of this
* distribution or obtain the Apache Licence at the following location:
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* See: http://www.vl-e.nl/
* See: LICENCE.txt (located in the root folder of this distribution).
* ---
* $Id: VNode.java,v 1.12 2011-06-07 15:13:51 ptdeboer Exp $
* $Date: 2011-06-07 15:13:51 $
*/
// source:
package nl.uva.vlet.vrs;
import static nl.uva.vlet.data.VAttributeConstants.ATTR_ATTRIBUTE_NAMES;
import static nl.uva.vlet.data.VAttributeConstants.ATTR_CHARSET;
import static nl.uva.vlet.data.VAttributeConstants.ATTR_HOSTNAME;
import static nl.uva.vlet.data.VAttributeConstants.ATTR_ICONURL;
import static nl.uva.vlet.data.VAttributeConstants.ATTR_ISCOMPOSITE;
import static nl.uva.vlet.data.VAttributeConstants.ATTR_ISEDITABLE;
import static nl.uva.vlet.data.VAttributeConstants.ATTR_ISVLINK;
import static nl.uva.vlet.data.VAttributeConstants.ATTR_LOCATION;
import static nl.uva.vlet.data.VAttributeConstants.ATTR_MIMETYPE;
import static nl.uva.vlet.data.VAttributeConstants.ATTR_NAME;
import static nl.uva.vlet.data.VAttributeConstants.ATTR_PATH;
import static nl.uva.vlet.data.VAttributeConstants.ATTR_PORT;
import static nl.uva.vlet.data.VAttributeConstants.ATTR_RESOURCE_CLASS;
import static nl.uva.vlet.data.VAttributeConstants.ATTR_RESOURCE_TYPES;
import static nl.uva.vlet.data.VAttributeConstants.ATTR_SCHEME;
import static nl.uva.vlet.data.VAttributeConstants.ATTR_TYPE;
import static nl.uva.vlet.data.VAttributeConstants.ATTR_URI_FRAGMENT;
import static nl.uva.vlet.data.VAttributeConstants.ATTR_URI_QUERY;
import java.net.URI;
import java.net.URL;
import nl.uva.vlet.Global;
import nl.uva.vlet.data.StringList;
import nl.uva.vlet.data.VAttribute;
import nl.uva.vlet.data.VAttributeSet;
import nl.uva.vlet.exception.VRLSyntaxException;
import nl.uva.vlet.exception.VlException;
import nl.uva.vlet.util.MimeTypes;
import nl.uva.vlet.util.ResourceLoader;
import nl.uva.vlet.vfs.VDir;
import nl.uva.vlet.vfs.VFSNode;
import nl.uva.vlet.vfs.VFile;
import nl.uva.vlet.vrl.VRL;
/**
* The VNode class, the super class of all resource nodes in the VRS package.
* It can be seen as a handler object, for example a reference to
* a (remote) file or directory or other generic resource.
* Every VNode is associated with a VRL.
*
* @author P.T. de Boer
* @see VFSNode
* @see VFile
* @see VDir
*/
public abstract class VNode //implements IVNode
{
/**
* Class object counter.
* Currently used for debugging (see vnodeid)
*/
private static long vnodecounter=0;
static private String[] attributeNames=
{
ATTR_TYPE,
ATTR_NAME,
ATTR_SCHEME,
ATTR_HOSTNAME,
ATTR_PORT,
ATTR_ICONURL,
ATTR_PATH,
ATTR_MIMETYPE,
ATTR_LOCATION
};
// ========================================================================
// ========================================================================
/** The URI Compatable VRL or which specified the resource location */
private VRL _nodeVRL=null;
/**
* Object ID.
* Currently used for debugging, but can be used
* to uniquely identify VNode objects in memory
*/
private long vnodeid=vnodecounter++;
/**
* The *NEW* VRSContext to ensure shared environments !
* Is FINAL, once set it may never be changed.
*/
protected final VRSContext vrsContext;
// protected ResourceManager resourceManager;
// ========================================================================
// Constuctors/Initializers
// ========================================================================
/** Block empty constructor */
@SuppressWarnings("unused")
private VNode()
{
vrsContext=null;
}
// ========================================================================
// Field Methods
// ========================================================================
/**
*
*/
public VNode(VRSContext context,VRL vrl)
{
this.vrsContext=context;
setLocation(vrl);
}
/**
* See getVRL()
* @see getVRL()
*/
final public VRL getLocation()
{
return _nodeVRL;
}
/** Returns extension part of VRL */
final public String getExtension()
{
return this.getLocation().getExtension();
}
/** Returns VRSContext which whas used to create this node */
final public VRSContext getVRSContext()
{
return this.vrsContext;
}
/**
* Returns Virtual Resource Locator (VRL) of this object.
* This is an URI compatible class but with more (URL like) features.
*
* @see VRL
* @see java.net.URI
*/
final public VRL getVRL()
{
return _nodeVRL;
}
/**
* Returns URI (java.net.URI) of this object.
* This method is the same as getVRL().toURI();
* <p>
* @see VRL
* @see java.net.URI
*/
final public URI getURI() throws VlException
{
if (_nodeVRL==null)
return null;
return _nodeVRL.toURI();
}
/**
* Returns URL (java.net.URL) of this object.
* This method is the same as getVRL().toURL();
* <p>
* @see VRL
* @see java.net.URI
*/
final public URL getURL() throws VlException
{
if (_nodeVRL==null)
return null;
return _nodeVRL.toURL();
}
/** Get unique VNode id. Currently used for debugging */
public long getNodeID()
{
return vnodeid;
}
/**
* Returns the short name of the resource.<br>
* The default is the basename of the resource or the last part
* of the path part in the URI.
* To use another name, subclassses must
* overide this method.
*/
public String getName()
{
if (_nodeVRL==null)
return null;
return _nodeVRL.getBasename(); // default= last part of path
}
/** Returns logical path of this resource */
public String getPath()
{
if (_nodeVRL==null)
return null;
return _nodeVRL.getPath();
}
/** Returns Hostname */
public String getHostname()
{
if (_nodeVRL==null)
return null;
return _nodeVRL.getHostname();
}
/** Returns Port. If the value <=0 then the default port must be used. */
public int getPort()
{
return _nodeVRL.getPort();
}
/** Returns basename part of the path of a node. */
public String getBasename()
{
// Default implementation: getBasename of path
return _nodeVRL.getBasename();
}
/**
* Returns Mime Type based upon file filename/extension.
* For a more robust method, use MimeTypes.getMagicMimeType().
*
* @throws VlException
*
* @see MimeTypes.getMagicMimeType(byte[])
* @see MimeTypes.getMimeType(String)
*/
public String getMimeType() throws VlException
{
return MimeTypes.getDefault().getMimeType(this.getPath());
}
/**
* Default charset for text resources
* @throws VlException
*/
public String getCharSet() throws VlException
{
return ResourceLoader.CHARSET_UTF8;
}
/**
* Check whether this VNode implements the VComposite interface.
*/
public boolean isComposite()
{
return (this instanceof VComposite);
}
/**
*Get the names of the all attributes this resource has.
*To get the subset of resource specific
*/
public String[] getAttributeNames()
{
return attributeNames;
}
/**
* Get the names of the resource specific attributes leaving out default attributes and
* optional super class attributes this resource has.
* This typically is the subset of getAttributeNames() minus super.getAttributeNames();
*/
public String[] getResourceAttributeNames()
{
return null;
}
/**
* Get all attributes defined by attributeNames
* @throws VlException
*/
public VAttribute[] getAttributes() throws VlException
{
return getAttributes(getAttributeNames());
}
/**
* Get all attributes defined by <code>names</code>.<br>
* Elements in the <code>names</code> array may be null!
* It means do not fetch the attribute.
* This is to speed up fetching of indexed attributes.
* <br>
* <b>Developpers note</b>:<br>
* Subclasses are encouraged to overide this method to
* speed up fetching multiple attributes as this method
* does a getAttribute call per attribute.
* @throws VlException
*/
public VAttribute[] getAttributes(String names[]) throws VlException
{
VAttribute[] attrs = new VAttribute[names.length];
for (int i = 0; i < names.length; i++)
{
if (names[i]!=null)
attrs[i] = getAttribute(names[i]);
else
attrs[i]=null;
}
return attrs;
}
/**
* Same as getAttributes(), but return the attributes in an
* (Ordened) Attribute set.
*
* @param names
* @return
* @throws VlException
*/
public VAttributeSet getAttributeSet(String names[]) throws VlException
{
return new VAttributeSet(getAttributes(names));
}
/**
* Get Non-mutable attribute. This is an attribute which can be derived from the
* location or doesn't change during the lifetime of the Object because it
* is implicit bound to the object class.
* Even if the object doesn't exist the attribute can be determined, for
* example the Resource Type of a VFile which doesn't change during
* the lifetime of the (VFile) Object as this always must be "File" !
*/
public VAttribute getNonmutableAttribute(String name) throws VlException
{
// by prefix values with "", a NULL value will be convert to "NULL".
if (name.compareTo(ATTR_TYPE) == 0)
return new VAttribute(name, ""+getType());
else if (name.compareTo(ATTR_LOCATION) == 0)
return new VAttribute(name, getVRL());
else if (name.compareTo(ATTR_NAME) == 0)
return new VAttribute(name, ""+getName());
else if (name.compareTo(ATTR_HOSTNAME) == 0)
return new VAttribute(name, getHostname());
// only return port attribute if it has a meaningful value
else if (name.compareTo(ATTR_PORT) == 0)
return new VAttribute(name,getPort());
else if (name.compareTo(ATTR_ICONURL) == 0)
return new VAttribute(name, getIconURL());
else if (name.compareTo(ATTR_SCHEME) == 0)
return new VAttribute(name, getScheme());
else if (name.compareTo(ATTR_PATH) == 0)
return new VAttribute(name, getPath());
else if ( (name.compareTo(ATTR_URI_QUERY) == 0) && getLocation().hasQuery() )
return new VAttribute(name, getQuery());
else if ( (name.compareTo(ATTR_URI_FRAGMENT) == 0) && getLocation().hasFragment() )
return new VAttribute(name, getLocation().getFragment());
else if (name.compareTo(ATTR_NAME) == 0)
return new VAttribute(name, getName());
else if (name.compareTo(ATTR_LOCATION) == 0)
return new VAttribute(name, getLocation().toString());
else if (name.compareTo(ATTR_MIMETYPE) == 0)
return new VAttribute(name, getMimeType());
else if (name.compareTo(ATTR_ISVLINK) == 0)
return new VAttribute(name, getLocation().isVLink());
else if (name.compareTo(ATTR_CHARSET) == 0)
return new VAttribute(name, getCharSet());
return null;
}
/**
* This is the single method a Node has to implement so that attributes can be fetched.
* subclasses can override this method and do a super.getAttribute first to
* check whether the superclass provides an attribute name.
*
* @throws VlException */
public VAttribute getAttribute(String name) throws VlException
{
if (name==null)
return null;
// Check Non-mutable attributes first!
VAttribute attr=this.getNonmutableAttribute(name);
if (attr!=null)
return attr;
// ===
// VAttribute Interface for remote invokation
// ===
else if (name.compareTo(ATTR_ISCOMPOSITE) == 0)
return new VAttribute(name, (this instanceof VComposite));
else if (name.compareTo(ATTR_RESOURCE_CLASS) == 0)
return new VAttribute(name, this.getClass().getCanonicalName());
else if (name.compareTo(ATTR_RESOURCE_TYPES) == 0)
{
if (this instanceof VComposite)
{
String types[]=((VComposite)this).getResourceTypes();
StringList list=new StringList(types);
return new VAttribute(name,list.toString(","));
}
else
return null;
}
else if (name.compareTo(ATTR_ISEDITABLE) == 0)
{
if (this instanceof VEditable)
return new VAttribute(name,((VEditable)this).isEditable());
else
return new VAttribute(name,false);
}
else if (name.compareTo(ATTR_ATTRIBUTE_NAMES) == 0)
{
StringList attrL=new StringList(this.getAttributeNames());
return new VAttribute(name,attrL.toString(","));
}
return null;
}
/** Return Query part of VRL */
public String getQuery()
{
VRL loc=getLocation();
if (loc==null)
return null;
return loc.getQuery();
}
/**
* Return this node's location as String representation.<br>
* Note that special characters are not encoded.
*/
public String toString()
{
return "("+getType()+")"+getLocation();
}
/** @see setVRL(VRL loc) */
protected void setLocation(VRL loc)
{
this._nodeVRL=loc;
}
/**
* Only subclasses may change the location.
* Note that the location should be immutable:
* It may not change during the lifetime of the object!
*
*/
protected void setVRL(VRL loc)
{
this._nodeVRL=loc;
}
/** Compares whether the nodes represent the same location */
public int compareTo(VNode other)
{
if (other==null)
return 1; // this > null
return _nodeVRL.compareTo(other.getLocation());
}
/**
* Returns optional icon URL given the preferred size.
* Default implementation is to call getIconURL().
* This method allows resources to return different icons
* for different sizes.
* The actual displayed size in the vbrowser may differ
* from the given size and the preferredSize should be regarded as an indication.
* It is recommended to provide optimized icons for sizes less
* than or equal to 16.
*/
public String getIconURL(int preferredSize)
{
return getIconURL();
}
/** Returns optional icon url */
public String getIconURL()
{
return null;
}
/**
* Returns simple text file or complete HTML page. Method should point to
* installed documentation.
* Default is to return help about this type.
*/
public VRL getHelp()
{
return Global.getHelpUrl(this.getType());
}
//public abstract String getType(); // type (File) or class
/**
* Get Parent Node (if any).<br>
* Default implementation is to open the location provided
* by getParentLocation(). Override that method to provide
* the parent location of this node.
* Overide this method to provide a more eficient way
* to return a VNode that is the (logical) parent of this.
*
* @see #getParents()
* @see #getParentLocation()
* @return Parent VNode or null.
* @throws VlException
*/
public VNode getParent() throws VlException
{
VRL pvrl=getParentLocation();
if (pvrl==null)
return null;
return vrsContext.openLocation(getParentLocation());
}
/**
* Returns logical parent location of this node.
* By default this method returns getVRL().getParent();
* If an implementation has another 'logical' parent then just
* the dirname of the current location, override this method.
*/
public VRL getParentLocation()
{
if (this.getVRL()==null)
return null;
return this._nodeVRL.getParent();
}
/**
* Get Parents if the Node is part of a Graph.
* <br>
* Returns one parent if Node is part of a Tree or null if
* Node has no parents.
* @throws VlException
*/
public VNode[] getParents() throws VlException // for Graph
{
VNode parent=getParent();
if (parent==null)
return null;
VNode nodes[]=new VNode[1];
nodes[0]=parent;
return nodes;
}
public String getScheme()
{
return this.getLocation().getScheme();
}
/**
* Like cloneable, to use this method, implement the VDuplicatable interface
* and override this method to return a copy.
* By default the object should create a deep copy of it's contents
* and it's children.
* This default behaviour is different then clone().
*/
public VNode duplicate() throws VlException
{
throw new nl.uva.vlet.exception.NotImplementedException("Duplicate method not implemented");
}
/**
* New Action Method version I. (Under Construction).
* The ActionMappings are taken from the VRS.getActionMappings();
* @see ActionMenuMapping class.
*/
//public void performAction(String name, ActionContext actionContext,VRL selections[]) throws VlException
//{
// throw new NotImplementedException("Node doesn't support actions:"+getName());
// }
/**
* Resolve relative or absolute path against this resource.
* Uses VRL.resolvePaths(this.getPath(),subPath) as default
* implementation.
*/
public String resolvePath(String subPath)
{
String result=VRL.resolvePaths(this.getPath(),subPath);
return result;
}
/** Resolve path against this VRL and return resolved VRL */
public VRL resolvePathVRL(String path) throws VRLSyntaxException
{
return getLocation().resolvePath(path);
}
/**
* Status String for nodes which implemented Status.
* Returns NULL if not supported.
* This method is exposed in the toplevel VNode interface even if not supported.
* @return
* @throws VlException
*/
public String getStatus() throws VlException
{
return null;
}
/**
* Synchronized cached attributes and/or refresh (optional) cached attributes
* from remote resource.
* This is an import method in the case that an resource caches resource attributes, like
* file attributes.
* @since VLET 1.2
* @return - false : not applicable/not implemented for this resource.<br>
* - true : synchronize/refresh is implemented and was successful.
* @throws VlException when resource synchronisation wasn't successful
*/
public boolean sync() throws VlException
{
return false;
}
/** Fire attribute(s) changed event with this resource as even source.*/
protected void fireAttributesChanged(VAttribute attrs[])
{
ResourceEvent event=ResourceEvent.createAttributesChangedEvent(getVRL(),attrs);
this.vrsContext.getResourceEventNotifier().fire(event);
}
/** Fire attribute changed event with this resource as even source.*/
protected void fireAttributeChanged(VAttribute attr)
{
ResourceEvent event=ResourceEvent.createAttributesChangedEvent(getVRL(),
new VAttribute[]{attr});
this.vrsContext.getResourceEventNotifier().fire(event);
}
// ========================================================================
// Abstract Interface
// ========================================================================
/** Returns resource type, if it has one */
public abstract String getType();
/** Whether this node (still) exists
* @throws VlException */
public abstract boolean exists() throws VlException;
}
| 30.787265 | 109 | 0.611827 |
232bf7ff60650168c76bd261cf93fe9e9a7e663d | 735 | package com.company.model;
public class HexadecimalNumber extends Number {
private String number;
/**
* Constructor for HexadecimalNumber
* @param number String
*/
public HexadecimalNumber(String number) {
this.number = number;
}
/**
* Returns number associated with this class
* @return Hexadecimal
*/
public String getNumber() {
return number;
}
/**
* Sets a number to this class
* @param number Hexadecimal
*/
public void setNumber(String number) {
this.number = number;
}
/**
* String value of number
* @return String
*/
@Override
public String toString() {
return number;
}
}
| 18.375 | 48 | 0.583673 |
77a8c82127747daced1ef223047189566d248384 | 413 | package net.jahhan.jedis;
import lombok.Data;
import lombok.EqualsAndHashCode;
import redis.clients.jedis.Jedis;
@Data
@EqualsAndHashCode(callSuper=false)
public class WriteJedis extends BaseJedis {
public WriteJedis(Jedis jedis) {
this.jedis = jedis;
this.client = jedis.getClient();
}
@Override
public void close() {
this.jedis.close();
}
}
| 18.772727 | 44 | 0.646489 |
84b31787f92513363307d3f0906225aa064fd460 | 4,031 | package com.taig.dna;
import static com.taig.dna.Nucleotide.Purine.Adenine;
import static com.taig.dna.Nucleotide.Purine.Guanine;
import static com.taig.dna.Nucleotide.Pyrimidine.Cytosine;
import static com.taig.dna.Nucleotide.Pyrimidine.Thymine;
/**
* Representation of <a href="https://en.wikipedia.org/wiki/Nucleotide">nucleotides</a> (the basic module of DNA
* sequences).
* <p/>
* Currently limited to {@link Guanine}, {@link Adenine}, {@link Thymine} and {@link Cytosine}.
*/
public abstract class Nucleotide
{
protected final char group;
protected final char molecule;
protected Nucleotide( char group, char molecule )
{
this.group = group;
this.molecule = molecule;
}
/**
* Create a nucleotide with its abbreviation (e.g. 'G' to instantiate {@link Guanine}).
*
* @param abbreviation The nucleotide's abbreviation.
* @return The nucleotide object that matches the given abbreviation.
* @throws IllegalArgumentException If the given abbreviation is not a valid nucleotide.
*/
public static Nucleotide newInstance( char abbreviation )
{
switch( Character.toUpperCase( abbreviation ) )
{
case Adenine.ABBREVIATION:
return new Adenine();
case Cytosine.ABBREVIATION:
return new Cytosine();
case Guanine.ABBREVIATION:
return new Guanine();
case Thymine.ABBREVIATION:
return new Thymine();
default:
throw new IllegalArgumentException( "Cannot create nucleotide from '" + abbreviation + "'." );
}
}
/**
* Get the nucleotide's subgroup's abbreviation (e.g. 'R' for Purine).
*
* @return The nucleotide's subgroup's abbreviation.
*/
public char getGroup()
{
return group;
}
/**
* Get the nucleotide's abbreviation (e.g. 'A' for Adenine).
*
* @return The nucleotide's abbreviation.
*/
public char getMolecule()
{
return molecule;
}
/**
* Get the nucleotide's complementary nucleotide.
*
* @return The complementary nucleotide.
*/
public abstract Nucleotide getComplement();
/**
* @param object The object that should be checked for equality with this nucleotide.
* @return <code>true</code> if the given object and this nucleotide have the same abbreviation letter, otherwise
* <code>false</code>.
*/
@Override
public boolean equals( Object object )
{
if( object instanceof Nucleotide )
{
return molecule == ( (Nucleotide) object ).getMolecule();
}
return false;
}
/**
* Represents the nucleotide with it's abbreviation letter (uppercase).
*
* @return The nucleotide's abbreviation letter (uppercase).
*/
@Override
public String toString()
{
return String.valueOf( molecule );
}
public static abstract class Purine extends Nucleotide
{
public static final char ABBREVIATION = 'R';
protected Purine( char molecule )
{
super( ABBREVIATION, molecule );
}
public static class Adenine extends Purine
{
public static final char ABBREVIATION = 'A';
public Adenine()
{
super( ABBREVIATION );
}
@Override
public Nucleotide getComplement()
{
return new Thymine();
}
}
public static class Guanine extends Purine
{
public static final char ABBREVIATION = 'G';
public Guanine()
{
super( ABBREVIATION );
}
@Override
public Nucleotide getComplement()
{
return new Cytosine();
}
}
}
public static abstract class Pyrimidine extends Nucleotide
{
public static final char ABBREVIATION = 'Y';
protected Pyrimidine( char molecule )
{
super( ABBREVIATION, molecule );
}
public static class Cytosine extends Pyrimidine
{
public static final char ABBREVIATION = 'C';
public Cytosine()
{
super( ABBREVIATION );
}
@Override
public Nucleotide getComplement()
{
return new Guanine();
}
}
public static class Thymine extends Pyrimidine
{
public static final char ABBREVIATION = 'T';
public Thymine()
{
super( ABBREVIATION );
}
@Override
public Nucleotide getComplement()
{
return new Adenine();
}
}
}
} | 21.55615 | 114 | 0.685934 |
adea4e232f6a8afda10fa6a98bee273c56352d34 | 3,810 | package com.morpho.demo.customs;
import android.content.Context;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import com.morpho.demo.R;
import java.util.Random;
/**
* Created by Alex on 23/01/2015.
*/
public class CloudView extends FrameLayout{
private ImageView center;
private int type;
private int size;
private RelativeLayout centerC;
private static final int TYPE_1 = 1;
private static final int TYPE_2 = 2;
private static final int TYPE_3 = 3;
public static final int SIZE_1 = 10;
public static final int SIZE_2 = 20;
public static final int SIZE_3 = 30;
public CloudView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
initView();
}
public CloudView(Context context, AttributeSet attrs) {
super(context, attrs);
initView();
}
public CloudView(Context context) {
super(context);
initView();
}
public CloudView(Context context,int size) {
super(context);
this.size = size;
initView();
}
private void setType(int type,int size){
this.type = type;
this.size = size;
if(center != null) {
switch (type) {
case TYPE_1:
//center.setImageResource(R.drawable.logo_morpho);
center.setImageResource(R.drawable.logo_teknei);
break;
case TYPE_2:
//center.setImageResource(R.drawable.logo_morpho);
center.setImageResource(R.drawable.logo_teknei);
break;
case TYPE_3:
//center.setImageResource(R.drawable.logo_morpho);
center.setImageResource(R.drawable.logo_teknei);
break;
}
/*
RelativeLayout.LayoutParams params = null;
switch (size){
case SIZE_1:
params = new RelativeLayout.LayoutParams(40* TypedValue.COMPLEX_UNIT_DIP,40* TypedValue.COMPLEX_UNIT_DIP);
break;
case SIZE_2:
params = new RelativeLayout.LayoutParams(75* TypedValue.COMPLEX_UNIT_DIP,75* TypedValue.COMPLEX_UNIT_DIP);
break;
case SIZE_3:
params = new RelativeLayout.LayoutParams(100* TypedValue.COMPLEX_UNIT_DIP,100* TypedValue.COMPLEX_UNIT_DIP);
break;
}
params.addRule(RelativeLayout.CENTER_IN_PARENT);
center.setScaleType(ImageView.ScaleType.FIT_CENTER);
center.setLayoutParams(params);
*/
}
}
private void initView(){
View view = LayoutInflater.from(getContext())
.inflate(R.layout.cloud_layout, null);
center = (ImageView) view.findViewById(R.id.center);
centerC = (RelativeLayout) view.findViewById(R.id.centerC);
type = getRandumNumber(1,3);
addView(view);
}
@Override
protected void onAnimationStart() {
super.onAnimationStart();
switch (type) {
case TYPE_1:
type = TYPE_2;
break;
case TYPE_2:
type = TYPE_3;
break;
case TYPE_3:
type = TYPE_1;
break;
}
setType(type,size);
}
private static int getRandumNumber(int low, int high){
Random r = new Random();
int Low = low;
int High = high;
int R = r.nextInt(High-Low) + Low;
return R;
}
}
| 28.432836 | 128 | 0.571916 |
899959ca64c3530050dfa284c22ac582dd762f21 | 1,219 | package org.nrocn.user.utils;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.crypto.digest.DigestUtil;
import org.nrocn.user.entity.AccountEntity;
import org.nrocn.user.model.AccountDomain;
import java.util.Date;
import java.util.UUID;
public abstract class AccountUtils {
//加盐
private static String fixedSalt(String basesalt,String salt){
return DigestUtil.md5Hex(salt + UUID.randomUUID().toString() + DateUtil.now().toString() + basesalt);
}
private static String password(String salt,String basepwd){
return DigestUtil.md5Hex(basepwd + salt + basepwd);
}
public static AccountEntity newPassword(String pwd, String basesalt){
//加盐
int i = RandomUtil.randomInt(8);
String salt = AccountUtils.fixedSalt(basesalt, String.valueOf(i));
AccountEntity accountEntity = new AccountEntity();
accountEntity.setPasswordSalt(salt);
String password = AccountUtils.password(salt, pwd);
accountEntity.setPassword(password);
return accountEntity;
}
public static String checkPassword(String pwd, String salt){
return AccountUtils.password(salt, pwd);
}
}
| 32.078947 | 109 | 0.712059 |
8de9d3fe1bb466d122f09d6abbbcc96bb1c9eca9 | 443 | package com.aias.polar.im.server.DTO;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import java.io.Serializable;
/**
* @author liuhy
*/
@Data
@AllArgsConstructor
@Builder
public class UserDTO implements Serializable {
private static final long serialVersionUID = 1677859057767295585L;
private Integer id;
private String username;
private String avatar;
private String firstLetter;
}
| 17.038462 | 70 | 0.760722 |
dfa5ad991bd2f17c09dfa9148265093764672853 | 7,250 | package acw.setm.perplexity;
import java.io.BufferedReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import acw.common.utils.collection.StringIdDualDict;
import acw.common.utils.file.FileIOUtils;
import acw.setm.files.SETMFile_Params;
import acw.setm.files.SETMFile_Perplexity;
import acw.setm.files.SETMFile_Psi;
import acw.setm.files.SETMFile_Rho;
import acw.setm.files.SETMFile_Tassign;
import acw.setm.files.SETMFile_Theta;
import acw.setm.files.SETMFile_Varphi;
public class SETMPerplexityWrapper {
private SETMPerplexity setmPerplexity;
private StringIdDualDict dictW;
private StringIdDualDict dictOE;
public SETMPerplexityWrapper(String fpParams, String fpRho, String fpVarphiW, String fpPsiE){
// read params
SETMFile_Params params = new SETMFile_Params();
params.readParams(fpParams);
// read phi, varphiW, psiE
double[][] rho = SETMFile_Rho.readRho(fpRho, params.K, params.VSE);
double[][] varphiW = SETMFile_Varphi.readVarphi(fpVarphiW, params.K, params.VW);
double[][] psiE = SETMFile_Psi.readPsi(fpPsiE, params.K, params.VAE);
setmPerplexity = new SETMPerplexity(params.K, params.lambda, rho, varphiW, psiE);
}
public SETMPerplexityWrapper(String fpParams, String fpRho, String fpVarphiW, String fpPsiE, String fpWMap, String fpOEMap){
this(fpParams, fpRho, fpVarphiW, fpPsiE);
dictW = new StringIdDualDict();
dictW.readStr2IdMap(fpWMap);
dictOE = new StringIdDualDict();
dictOE.readStr2IdMap(fpOEMap);
}
public double calcPerplexity(String fpTestTheta, String fpTassignSE, String fpTassignW, String fpTassignOE, String fpOutPerplexity) throws IOException{
BufferedReader brTheta = FileIOUtils.getBufferedReader(fpTestTheta);
BufferedReader brTassignSE = FileIOUtils.getBufferedReader(fpTassignSE);
BufferedReader brTassignW = FileIOUtils.getBufferedReader(fpTassignW);
BufferedReader brTassignOE = FileIOUtils.getBufferedReader(fpTassignOE);
FileWriter fileWriter = FileIOUtils.getFileWriter(fpOutPerplexity);
String lineTheta, lineTassignSE, lineTassignW, lineTassignOE;
while(true){
lineTheta = brTheta.readLine();
lineTassignSE = brTassignSE.readLine();
lineTassignW = brTassignW.readLine();
lineTassignOE = brTassignOE.readLine();
if(lineTheta == null || lineTassignSE == null || lineTassignW == null || lineTassignOE == null){
break;
}
// read document topic distribution
String[] thetaValArr = lineTheta.split(SETMFile_Theta.elementSeperator);
double[] docTopicDist = new double[thetaValArr.length];
for (int i = 0; i < docTopicDist.length; i++) {
docTopicDist[i] = Double.parseDouble(thetaValArr[i]);
}
// read salient entities
int[] salEntities = null;
if(!lineTassignSE.equals("NULL")){
String[] tassignValArrSE = lineTassignSE.split(SETMFile_Tassign.elementSeperator);
salEntities = new int[tassignValArrSE.length];
for (int i = 0; i < salEntities.length; i++) {
String[] seTopicArr = tassignValArrSE[i].split(SETMFile_Tassign.pairSeperator);
if(!seTopicArr[0].equals("")){
salEntities[i] = Integer.parseInt(seTopicArr[0]);
}
}
}
// read words
String[] tassignValArrW = lineTassignW.split(SETMFile_Tassign.elementSeperator);
int[] words = new int[tassignValArrW.length];
for (int i = 0; i < words.length; i++) {
String[] wordTopicArr = tassignValArrW[i].split(SETMFile_Tassign.pairSeperator);
if(!wordTopicArr[0].equals("")){
words[i] = Integer.parseInt(wordTopicArr[0]);
}
}
// read observed entities
int[] obsEntities = null;
if(!lineTassignOE.equals("NULL")){
String[] tassignValArrOE = lineTassignOE.split(SETMFile_Tassign.elementSeperator);
obsEntities = new int[tassignValArrOE.length];
for (int i = 0; i < obsEntities.length; i++) {
String[] oeTopicArr = tassignValArrOE[i].split(SETMFile_Tassign.pairSeperator);
if(!oeTopicArr[0].equals("")){
obsEntities[i] = Integer.parseInt(oeTopicArr[0]);
}
}
}
// calculate perplexity
double[] docPerplexityWELength = setmPerplexity.computeSETMPerplexity4Doc(docTopicDist, salEntities, words, obsEntities);
fileWriter.write(docPerplexityWELength[0] + " " + (int)docPerplexityWELength[1] + " " + docPerplexityWELength[2] + " " + (int)docPerplexityWELength[3]);
fileWriter.write(System.lineSeparator());
}
brTheta.close();
brTassignSE.close();
brTassignW.close();
brTassignOE.close();
fileWriter.close();
double perplexity = SETMFile_Perplexity.calcPerplexity(fpOutPerplexity);
return perplexity;
}
public double calcPerplexityForWE(String fpTestTheta, String fpDocW, String fpDocOE, String fpOutPerplexity) throws IOException{
BufferedReader brTheta = FileIOUtils.getBufferedReader(fpTestTheta);
BufferedReader brDocW = null, brDocOE = null;
if(fpDocW != null){
brDocW = FileIOUtils.getBufferedReader(fpDocW);
}
if(fpDocOE != null){
brDocOE = FileIOUtils.getBufferedReader(fpDocOE);
}
FileWriter fileWriter = FileIOUtils.getFileWriter(fpOutPerplexity);
String lineTheta, lineDocW = "", lineDocOE = "";
while(true){
lineTheta = brTheta.readLine();
if(brDocW != null){
lineDocW = brDocW.readLine();
}
if(brDocOE != null){
lineDocOE = brDocOE.readLine();
}
if(lineTheta == null){
break;
}
// read document topic distribution
String[] thetaValArr = lineTheta.split(SETMFile_Theta.elementSeperator);
double[] docTopicDist = new double[thetaValArr.length];
for (int i = 0; i < docTopicDist.length; i++) {
docTopicDist[i] = Double.parseDouble(thetaValArr[i]);
}
// read observed entities
int[] words = null;
if(brDocW != null){
if(!lineDocW.equals("NULL")){
List<Integer> wordList = new ArrayList<Integer>();
String[] wordStrArr = lineDocW.split(" ");
for (int i = 0; i < wordStrArr.length; i++) {
int oeId = dictW.getID(wordStrArr[i]);
if(oeId >= 0){
wordList.add(oeId);
}
}
words = new int[wordList.size()];
for (int i = 0; i < words.length; i++) {
words[i] = wordList.get(i);
}
}
}
// read observed entities
int[] obsEntities = null;
if(brDocOE != null){
if(!lineDocOE.equals("NULL")){
List<Integer> oeList = new ArrayList<Integer>();
String[] oeStrArr = lineDocOE.split(" ");
for (int i = 0; i < oeStrArr.length; i++) {
int oeId = dictOE.getID(oeStrArr[i]);
if(oeId >= 0){
oeList.add(oeId);
}
}
obsEntities = new int[oeList.size()];
for (int i = 0; i < obsEntities.length; i++) {
obsEntities[i] = oeList.get(i);
}
}
}
// calculate perplexity
double[] docPerplexityWELength = setmPerplexity.computeSETMPerplexity4Doc(docTopicDist, null, words, obsEntities);
fileWriter.write(docPerplexityWELength[0] + " " + (int)docPerplexityWELength[1] + " " + docPerplexityWELength[2] + " " + (int)docPerplexityWELength[3]);
fileWriter.write(System.lineSeparator());
}
brTheta.close();
if(brDocW != null){
brDocW.close();
}
if(brDocOE != null){
brDocOE.close();
}
fileWriter.close();
double perplexity = SETMFile_Perplexity.calcPerplexity(fpOutPerplexity);
return perplexity;
}
}
| 35.365854 | 155 | 0.705241 |
430b1d182807100c38b7d0d887bcb481123ae27b | 334 | package com.fillmore_labs.kafka.sensors.serde.ion.serialization;
import org.immutables.value.Value;
@Value.Immutable
public interface StateDurationIon {
static ImmutableStateDurationIon.Builder builder() {
return ImmutableStateDurationIon.builder();
}
String getId();
ReadingIon getReading();
long getDuration();
}
| 19.647059 | 64 | 0.775449 |
d4f4a242427e3bfc223bc148cf74e16d896dd51a | 544 | package de.paulomart.ioc.examples;
import de.paulomart.ioc.Container;
public class TestClass {
public static void main(String[] args) throws Exception {
Container container = new Container();
container.autoRegister(ClassLoader.getSystemClassLoader(), "de.paulomart.ioc.examples");
// or register all class manuelly
// container.registerTransient(A.class);
// container.registerSingeltion(B.class);
// container.registerSingeltion(C.class);
InterfaceC r = container.resolve(InterfaceC.class);
System.out.println(r);
}
}
| 27.2 | 90 | 0.753676 |
1c64223673fe350240d6dff30e1b824dc2acdd6a | 5,919 | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.
package com.azure.resourcemanager.labservices.implementation;
import com.azure.core.management.SystemData;
import com.azure.core.util.Context;
import com.azure.resourcemanager.labservices.fluent.models.UserInner;
import com.azure.resourcemanager.labservices.models.InvitationState;
import com.azure.resourcemanager.labservices.models.InviteBody;
import com.azure.resourcemanager.labservices.models.ProvisioningState;
import com.azure.resourcemanager.labservices.models.RegistrationState;
import com.azure.resourcemanager.labservices.models.User;
import com.azure.resourcemanager.labservices.models.UserUpdate;
import java.time.Duration;
import java.time.OffsetDateTime;
public final class UserImpl implements User, User.Definition, User.Update {
private UserInner innerObject;
private final com.azure.resourcemanager.labservices.LabServicesManager serviceManager;
public String id() {
return this.innerModel().id();
}
public String name() {
return this.innerModel().name();
}
public String type() {
return this.innerModel().type();
}
public SystemData systemData() {
return this.innerModel().systemData();
}
public ProvisioningState provisioningState() {
return this.innerModel().provisioningState();
}
public String displayName() {
return this.innerModel().displayName();
}
public String email() {
return this.innerModel().email();
}
public RegistrationState registrationState() {
return this.innerModel().registrationState();
}
public InvitationState invitationState() {
return this.innerModel().invitationState();
}
public OffsetDateTime invitationSent() {
return this.innerModel().invitationSent();
}
public Duration totalUsage() {
return this.innerModel().totalUsage();
}
public Duration additionalUsageQuota() {
return this.innerModel().additionalUsageQuota();
}
public UserInner innerModel() {
return this.innerObject;
}
private com.azure.resourcemanager.labservices.LabServicesManager manager() {
return this.serviceManager;
}
private String resourceGroupName;
private String labName;
private String username;
private UserUpdate updateBody;
public UserImpl withExistingLab(String resourceGroupName, String labName) {
this.resourceGroupName = resourceGroupName;
this.labName = labName;
return this;
}
public User create() {
this.innerObject =
serviceManager
.serviceClient()
.getUsers()
.createOrUpdate(resourceGroupName, labName, username, this.innerModel(), Context.NONE);
return this;
}
public User create(Context context) {
this.innerObject =
serviceManager
.serviceClient()
.getUsers()
.createOrUpdate(resourceGroupName, labName, username, this.innerModel(), context);
return this;
}
UserImpl(String name, com.azure.resourcemanager.labservices.LabServicesManager serviceManager) {
this.innerObject = new UserInner();
this.serviceManager = serviceManager;
this.username = name;
}
public UserImpl update() {
this.updateBody = new UserUpdate();
return this;
}
public User apply() {
this.innerObject =
serviceManager
.serviceClient()
.getUsers()
.update(resourceGroupName, labName, username, updateBody, Context.NONE);
return this;
}
public User apply(Context context) {
this.innerObject =
serviceManager.serviceClient().getUsers().update(resourceGroupName, labName, username, updateBody, context);
return this;
}
UserImpl(UserInner innerObject, com.azure.resourcemanager.labservices.LabServicesManager serviceManager) {
this.innerObject = innerObject;
this.serviceManager = serviceManager;
this.resourceGroupName = Utils.getValueFromIdByName(innerObject.id(), "resourceGroups");
this.labName = Utils.getValueFromIdByName(innerObject.id(), "labs");
this.username = Utils.getValueFromIdByName(innerObject.id(), "users");
}
public User refresh() {
this.innerObject =
serviceManager
.serviceClient()
.getUsers()
.getWithResponse(resourceGroupName, labName, username, Context.NONE)
.getValue();
return this;
}
public User refresh(Context context) {
this.innerObject =
serviceManager
.serviceClient()
.getUsers()
.getWithResponse(resourceGroupName, labName, username, context)
.getValue();
return this;
}
public void invite(InviteBody body) {
serviceManager.users().invite(resourceGroupName, labName, username, body);
}
public void invite(InviteBody body, Context context) {
serviceManager.users().invite(resourceGroupName, labName, username, body, context);
}
public UserImpl withEmail(String email) {
this.innerModel().withEmail(email);
return this;
}
public UserImpl withAdditionalUsageQuota(Duration additionalUsageQuota) {
if (isInCreateMode()) {
this.innerModel().withAdditionalUsageQuota(additionalUsageQuota);
return this;
} else {
this.updateBody.withAdditionalUsageQuota(additionalUsageQuota);
return this;
}
}
private boolean isInCreateMode() {
return this.innerModel().id() == null;
}
}
| 30.668394 | 120 | 0.658895 |
046cda2a7162f2cd062bcbdd33ab433f5dba9b17 | 1,560 | import java.util.Arrays;
public class JumpSearch {
private static final int NOT_FOUND = -1;
/**
* Performs the Jump Search (also called Block Search)
*
* @param array
* The input array of ints
* @param key
* The int to look for
* @return The index of the key ({@link #NOT_FOUND} if the key was not found).
*/
static int search(int[] array, int key) {
// Determine the block size
int blockSize = (int) Math.sqrt(array.length);
// Left and Right indexes for the current block
int left = 0;
int right = blockSize;
// Iterate over the array until we find the right block
while (array[right] < blockSize && right < array.length) {
left = right;
right += blockSize;
if (right > array.length - 1) {
right = array.length;
}
}
// Search the block for the key
for (int i = left; i < right; i++) {
if (array[i] == key) {
return i;
}
}
// Return NOT_FOUND if the key was not found
return NOT_FOUND;
}
public static void main(String[] args) {
int[] test = { 1, 2, 3, 20, 60, 66, 77, 78, 100, 120, 123 };
int key = 77;
int indexOfKey = search(test, key);
System.out.println("The Sample Array: " + Arrays.toString(test));
System.out.println("The Test Key: " + key);
System.out.println("The Index Of The Key: " + indexOfKey);
}
} | 29.433962 | 82 | 0.530128 |
1871e91548a0dabf5484d16c9364aadd1da6f35c | 2,242 | package net.daergoth.coreapi.rule;
import java.io.Serializable;
import java.util.List;
/**
* Represents {@code Rule} entities in the Core API.
* If all of the {@code Condition}s for a {@code Rule} are met
* the rule's {@code Action}s will be executed.
*
* @see net.daergoth.coreapi.rule.ConditionDTO
* @see net.daergoth.coreapi.rule.ActionDTO
*/
public class RuleDTO implements Serializable {
private static final long serialVersionUID = -1320473883280317106L;
private Long id;
private String name;
private boolean enabled;
private List<ConditionDTO> conditions;
private List<ActionDTO> actions;
/**
* Getter for the {@code Rule}'s ID.
* @return the ID of the rule
*/
public Long getId() {
return id;
}
/**
* Setter for the {@code Rule}'s ID.
* @param id the new ID for the rule
*/
public void setId(Long id) {
this.id = id;
}
/**
* Getter for the {@code Rule}'s name.
* @return the name of the rule
*/
public String getName() {
return name;
}
/**
* Setter for the {@code Rule}'s name.
* @param name the new name for the rule
*/
public void setName(String name) {
this.name = name;
}
/**
* Getter for the {@code Rule}'s status.
* @return the status of the rule
*/
public boolean isEnabled() {
return enabled;
}
/**
* Setter for the {@code Rule}'s status.
* @param enabled the new status for the rule
*/
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
/**
* Getter for the {@code Rule}'s {@code Condition}s.
* @return the list of conditions of the rule
*/
public List<ConditionDTO> getConditions() {
return conditions;
}
/**
* Setter for the {@code Rule}'s {@code Condition}s.
* @param conditions list of the new conditions for the rule
*/
public void setConditions(List<ConditionDTO> conditions) {
this.conditions = conditions;
}
/**
* Getter for the {@code Rule}'s {@code Action}s.
* @return the list of actions of the rule
*/
public List<ActionDTO> getActions() {
return actions;
}
/**
* Setter for the {@code Rule}'s {@code Action}s.
* @param actions list of the new actions for the rule
*/
public void setActions(List<ActionDTO> actions) {
this.actions = actions;
}
}
| 20.568807 | 68 | 0.662801 |
e4c556cf8faa39c1a391084e68a24bafcd205673 | 6,270 | /*
* Copyright 2018-2021 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dev.miku.r2dbc.mysql;
import dev.miku.r2dbc.mysql.cache.Caches;
import dev.miku.r2dbc.mysql.client.Client;
import dev.miku.r2dbc.mysql.codec.Codecs;
import io.r2dbc.spi.IsolationLevel;
import org.assertj.core.api.ThrowableTypeAssert;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.mockito.Mockito.mock;
/**
* Unit tests for {@link MySqlConnection}.
*/
class MySqlConnectionTest {
private final Client client = mock(Client.class);
private final Codecs codecs = mock(Codecs.class);
private final IsolationLevel level = IsolationLevel.REPEATABLE_READ;
private final String product = "MockConnection";
private final MySqlConnection noPrepare = new MySqlConnection(client, ConnectionContextTest.mock(),
codecs, level, Caches.createQueryCache(0),
Caches.createPrepareCache(0), product, null);
@Test
void createStatement() {
String condition = "SELECT * FROM test";
MySqlConnection allPrepare = new MySqlConnection(client, ConnectionContextTest.mock(),
codecs, level, Caches.createQueryCache(0),
Caches.createPrepareCache(0), product, sql -> true);
MySqlConnection halfPrepare = new MySqlConnection(client, ConnectionContextTest.mock(),
codecs, level, Caches.createQueryCache(0),
Caches.createPrepareCache(0), product, sql -> false);
MySqlConnection conditionPrepare = new MySqlConnection(client, ConnectionContextTest.mock(),
codecs, level, Caches.createQueryCache(0),
Caches.createPrepareCache(0), product, sql -> sql.equals(condition));
assertThat(noPrepare.createStatement("SELECT * FROM test WHERE id=1"))
.isExactlyInstanceOf(TextSimpleStatement.class);
assertThat(noPrepare.createStatement(condition))
.isExactlyInstanceOf(TextSimpleStatement.class);
assertThat(noPrepare.createStatement("SELECT * FROM test WHERE id=?"))
.isExactlyInstanceOf(TextParametrizedStatement.class);
assertThat(allPrepare.createStatement("SELECT * FROM test WHERE id=1"))
.isExactlyInstanceOf(PrepareSimpleStatement.class);
assertThat(allPrepare.createStatement(condition))
.isExactlyInstanceOf(PrepareSimpleStatement.class);
assertThat(allPrepare.createStatement("SELECT * FROM test WHERE id=?"))
.isExactlyInstanceOf(PrepareParametrizedStatement.class);
assertThat(halfPrepare.createStatement("SELECT * FROM test WHERE id=1"))
.isExactlyInstanceOf(TextSimpleStatement.class);
assertThat(halfPrepare.createStatement(condition))
.isExactlyInstanceOf(TextSimpleStatement.class);
assertThat(halfPrepare.createStatement("SELECT * FROM test WHERE id=?"))
.isExactlyInstanceOf(PrepareParametrizedStatement.class);
assertThat(conditionPrepare.createStatement("SELECT * FROM test WHERE id=1"))
.isExactlyInstanceOf(TextSimpleStatement.class);
assertThat(conditionPrepare.createStatement(condition))
.isExactlyInstanceOf(PrepareSimpleStatement.class);
assertThat(conditionPrepare.createStatement("SELECT * FROM test WHERE id=?"))
.isExactlyInstanceOf(PrepareParametrizedStatement.class);
}
@SuppressWarnings("ConstantConditions")
@Test
void badCreateStatement() {
assertThatIllegalArgumentException().isThrownBy(() -> noPrepare.createStatement(null));
}
@SuppressWarnings("ConstantConditions")
@Test
void badCreateSavepoint() {
ThrowableTypeAssert<?> asserted = assertThatIllegalArgumentException();
asserted.isThrownBy(() -> noPrepare.createSavepoint(""));
asserted.isThrownBy(() -> noPrepare.createSavepoint("`"));
asserted.isThrownBy(() -> noPrepare.createSavepoint("name`"));
asserted.isThrownBy(() -> noPrepare.createSavepoint("nam`e"));
asserted.isThrownBy(() -> noPrepare.createSavepoint(null));
}
@SuppressWarnings("ConstantConditions")
@Test
void badReleaseSavepoint() {
ThrowableTypeAssert<?> asserted = assertThatIllegalArgumentException();
asserted.isThrownBy(() -> noPrepare.releaseSavepoint(""));
asserted.isThrownBy(() -> noPrepare.releaseSavepoint("`"));
asserted.isThrownBy(() -> noPrepare.releaseSavepoint("name`"));
asserted.isThrownBy(() -> noPrepare.releaseSavepoint("nam`e"));
asserted.isThrownBy(() -> noPrepare.releaseSavepoint(null));
}
@SuppressWarnings("ConstantConditions")
@Test
void badRollbackTransactionToSavepoint() {
ThrowableTypeAssert<?> asserted = assertThatIllegalArgumentException();
asserted.isThrownBy(() -> noPrepare.rollbackTransactionToSavepoint(""));
asserted.isThrownBy(() -> noPrepare.rollbackTransactionToSavepoint("`"));
asserted.isThrownBy(() -> noPrepare.rollbackTransactionToSavepoint("name`"));
asserted.isThrownBy(() -> noPrepare.rollbackTransactionToSavepoint("nam`e"));
asserted.isThrownBy(() -> noPrepare.rollbackTransactionToSavepoint(null));
}
@SuppressWarnings("ConstantConditions")
@Test
void badSetTransactionIsolationLevel() {
assertThatIllegalArgumentException().isThrownBy(() -> noPrepare.setTransactionIsolationLevel(null));
}
@SuppressWarnings("ConstantConditions")
@Test
void badValidate() {
assertThatIllegalArgumentException().isThrownBy(() -> noPrepare.validate(null));
}
}
| 43.846154 | 108 | 0.714514 |
0905eb901707070d56412919dac3b46df78ad296 | 787 | package qunar.tc.qconfig.admin.support;
/**
* @author zhenyu.nie created on 2015 2015/10/21 20:11
*/
public class AdminConstants {
public static final String PROPERTY_FILE_SUFFIX = ".properties";
public static final int MAX_FILE_SIZE_IN_K = 512;
public static final int MAX_DESC_LENGTH = 150;
public static final int PARSE_JSON_ERROR_CODE = 100;
public static final String DEFAULT_TEMPLATE_GROUP = "b_qconfig_template";
public static final String CLIENT_UPLOAD_USERNAME = "upload.api";
public static final String PROPERTIES_TEMPLATE_SUFFIX = ".pro";
public static final int TEMPLATE_MAPPING_VERSION_NOT_EXIST = -1;
public static final int TEMPLATE_VERSION_NOT_EXIST = -1;
public static final String NOAH3_BUILGGROUP_PREFIX = "n3_";
}
| 28.107143 | 77 | 0.754765 |
fcdef17139e446b9b5195a0623c32d7ad98ec455 | 3,235 | /*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.buck.cli;
import com.facebook.buck.command.config.ConfigDifference;
import com.facebook.buck.command.config.ConfigDifference.ConfigChange;
import com.facebook.buck.core.config.BuckConfig;
import com.facebook.buck.support.cli.args.GlobalCliOptions;
import com.facebook.buck.util.config.Configs;
import com.google.common.base.Predicates;
import com.google.common.collect.ImmutableSet;
import java.io.IOException;
import java.nio.file.Path;
import java.util.Comparator;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;
/** Formats messages that will be displayed in console */
class UIMessagesFormatter {
static final String COMPARISON_MESSAGE_PREFIX =
"Running with reused config, some configuration changes would not be applied: ";
static final String USING_ADDITIONAL_CONFIGURATION_OPTIONS_PREFIX =
"Using additional configuration options from ";
/** Formats comparison of {@link BuckConfig}s into UI message */
static Optional<String> reusedConfigWarning(Map<String, ConfigChange> diff) {
if (diff.isEmpty()) {
return Optional.empty();
}
StringBuilder diffBuilder = new StringBuilder(COMPARISON_MESSAGE_PREFIX);
diffBuilder
.append(System.lineSeparator())
.append(ConfigDifference.formatConfigDiffShort(diff, 4));
return Optional.of(diffBuilder.toString());
}
static String reuseConfigPropertyProvidedMessage() {
return String.format(
"`%s` parameter provided. Reusing previously defined config.",
GlobalCliOptions.REUSE_CURRENT_CONFIG_ARG);
}
static Optional<String> useSpecificOverridesMessage(
Path root, ImmutableSet<Path> overridesToIgnore) throws IOException {
Path mainConfigPath = Configs.getMainConfigurationFile(root);
String userSpecifiedOverrides =
Configs.getDefaultConfigurationFiles(root).stream()
.filter(path -> isValidPath(path, overridesToIgnore, mainConfigPath))
.map(path -> path.startsWith(root) ? root.relativize(path) : path)
.map(Objects::toString)
.distinct()
.sorted(Comparator.naturalOrder())
.collect(Collectors.joining(", "));
return Optional.of(userSpecifiedOverrides)
.filter(Predicates.not(String::isEmpty))
.map(USING_ADDITIONAL_CONFIGURATION_OPTIONS_PREFIX::concat);
}
private static boolean isValidPath(
Path path, ImmutableSet<Path> overridesToIgnore, Path mainConfigPath) {
return !overridesToIgnore.contains(path.getFileName()) && !mainConfigPath.equals(path);
}
}
| 38.975904 | 91 | 0.742504 |
6a0c40eba55fc8b6bf04857a25f684c0e51d604f | 1,328 | package Java_Array_String;
/**
Palindrome
Astrologist believes that having a palindromic name is very auspicious .
As we all know, a palindrome is a word that can be read the same way in either direction.
condition1 - There should not be a space or any special character in the word entered.
condition2 - If yes, display "Invalid Input". Write a Java program to determine whether a given word is a palindrome or not.
Sample Input 1:
Enter the word :
Malayalam
Sample Output 1:
Malayalam is a Palindrome
Sample Input 2:
Enter the word :
Apple
Sample Output 2:
Apple is not a Palindrome
Sample Input 3:
Enter the word :
no on
Sample Output 3:
Invalid Input
Sample Input 4:
Enter the word :
@nnn
Sample Output 4:
Invalid Input
*/
import java.util.*;
public class Palindrome
{
public static void main(String[] args)
{
Scanner SC = new Scanner(System.in);
System.out.println("Enter the word:");
String str = SC.nextLine();
if(str.matches("^[a-zA-Z]*$"))
{
StringBuffer sb = new StringBuffer(str);
sb.reverse();
String r =sb.toString();
if(r.equalsIgnoreCase(str))
System.out.println(str+" is a Palindrome");
else
System.out.println(str+" is not a Palindrome");
}
else
System.out.println("Invalid Input");
}
}
| 22.508475 | 125 | 0.680723 |
585f83532490f8de471227bd6b320afa0965534e | 722 | // Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
package com.microsoft.azure.sdk.iot.service.transport;
public class TransportUtils
{
/** Version identifier key */
public static final String versionIdentifierKey = "com.microsoft:client-version";
public static String javaServiceClientIdentifier = "com.microsoft.azure.sdk.iot.iot-service-client/";
public static String serviceVersion = "1.8.24";
public static String getJavaServiceClientIdentifier()
{
return javaServiceClientIdentifier;
}
public static String getServiceVersion()
{
return serviceVersion;
}
} | 31.391304 | 105 | 0.736842 |
abaee2d0affba765a859695ad175d91a982392c4 | 744 | package com.tenhawks.auth.bean;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Data;
import javax.validation.constraints.Email;
import javax.validation.constraints.NotBlank;
/**
* This class has utilities related to user's object
* @author Mukhtiar Ahmed
*
*/
@Data
public class UserDTO {
private String userId;
@NotBlank(message = "Username is mandatory")
private String userName;
@Email(message = "Eamil address is mandatory")
private String emailAddress;
@NotBlank(message = "password is mandatory")
@JsonProperty(access = JsonProperty.Access.WRITE_ONLY)
private String password;
private String fullName;
private boolean enabled;
private String phoneNumber;
private String profileImage;
}
| 18.146341 | 55 | 0.771505 |
3b734bf57ba17d760562398eb09937f420039bd5 | 663 | package com.moonpi.swiftnotes.ColorPicker;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;
import com.moonpi.swiftnotes.R;
public class DecryptedList extends AppCompatActivity {
TextView tv;
int i;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_decrypted_list);
tv=(TextView)findViewById(R.id.textView14);
String arr[]=getIntent().getStringArrayExtra("body");
for(i=0;i<arr.length;i++) {
tv.setText(arr[i].toString() + "\n");
}
}
}
| 24.555556 | 61 | 0.689291 |
c1386a00b9decdd3c7e301e5856c71ed2ad4f39e | 520 | /**
*
*/
package jframe.pay.domain;
/**
* @author dzh
* @date Aug 1, 2014 7:10:47 PM
* @since 1.0
*/
public enum PayType {
/**
* 银联支付
*/
Y(1, "UPMP"),
/**
* 微信支付 APP
*/
W(2, "WEPAY"),
/**
* 支付宝
*/
A(3, "ALIPAY"),
;
public final int type;
public final String name;
private PayType(int type, String name) {
this.type = type;
this.name = name;
}
public String toStrVal() {
return String.valueOf(type);
}
}
| 13.684211 | 44 | 0.473077 |
cb95dfa3c86a0d3b70cbd55687aa50b923b1fc81 | 4,432 | /*
* Copyright 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.
*/
package leap.db.model;
import leap.lang.Buildable;
import leap.lang.Collections2;
import leap.lang.Strings;
import leap.lang.json.JsonArray;
import leap.lang.json.JsonObject;
import leap.lang.json.JsonParsable;
import leap.lang.json.JsonValue;
import java.util.ArrayList;
import java.util.List;
public class DbForeignKeyBuilder implements Buildable<DbForeignKey>,JsonParsable {
protected String name;
protected DbSchemaObjectName foreignTable;
protected List<DbForeignKeyColumn> columns = new ArrayList<>();
protected DbCascadeAction onUpdate;
protected DbCascadeAction onDelete;
public DbForeignKeyBuilder() {
}
public DbForeignKeyBuilder(DbForeignKey fk) {
this.name = fk.getName();
this.foreignTable = fk.getForeignTable();
this.onUpdate = fk.getOnUpdate();
this.onDelete = fk.getOnDelete();
Collections2.addAll(columns, fk.getColumns());
}
public String getName() {
return name;
}
public DbForeignKeyBuilder setName(String name) {
this.name = name;
return this;
}
public DbSchemaObjectName getForeignTable() {
return foreignTable;
}
public DbForeignKeyBuilder setForeignTable(DbSchemaObjectName foreignTable) {
this.foreignTable = foreignTable;
return this;
}
public List<DbForeignKeyColumn> getColumns() {
return columns;
}
public DbForeignKeyBuilder addColumn(DbForeignKeyColumn column){
return addColumn(column,-1);
}
public DbForeignKeyBuilder addColumn(DbForeignKeyColumn column,int index){
if(index < 0){
columns.add(column);
}else{
columns.add(index,column);
}
return this;
}
public DbCascadeAction getOnUpdate() {
return onUpdate;
}
public DbForeignKeyBuilder setOnUpdate(DbCascadeAction onUpdate) {
this.onUpdate = onUpdate;
return this;
}
public DbCascadeAction getOnDelete() {
return onDelete;
}
public DbForeignKeyBuilder setOnDelete(DbCascadeAction onDelete) {
this.onDelete = onDelete;
return this;
}
public boolean matchColumns(DbForeignKeyBuilder fk) {
if(columns.size() != fk.columns.size()) {
return false;
}
if(!getForeignTable().equalsIgnoreCase(fk.getForeignTable())) {
return false;
}
for(int i=0;i<columns.size();i++) {
DbForeignKeyColumn c1 = columns.get(i);
DbForeignKeyColumn c2 = fk.columns.get(i);
if(!c1.getLocalColumnName().equalsIgnoreCase(c2.getLocalColumnName())) {
return false;
}
if(!c1.getForeignColumnName().equalsIgnoreCase(c2.getForeignColumnName())) {
return false;
}
}
return true;
}
@Override
public DbForeignKey build() {
return new DbForeignKey(name, foreignTable, columns.toArray(new DbForeignKeyColumn[columns.size()]), onUpdate, onDelete);
}
@Override
public void parseJson(JsonValue value) {
JsonObject o = value.asJsonObject();
this.name = o.getString("name");
JsonObject foreignTable = o.getObject("foreignTable");
if(null != foreignTable){
DbSchemaObjectNameBuilder nb = new DbSchemaObjectNameBuilder();
nb.parseJson(foreignTable);
this.foreignTable = nb.build();
}
JsonArray columns = o.getArray("columns");
if(null != columns){
for(JsonValue v : columns){
JsonObject column = v.asJsonObject();
addColumn(new DbForeignKeyColumn(column.getString("localColumnName"), column.getString("foreignColumnName")));
}
}
String onUpdate = o.getString("onUpdate");
if(!Strings.isEmpty(onUpdate)){
this.onUpdate = DbCascadeAction.valueOf(onUpdate);
}
String onDelete = o.getString("onDelete");
if(!Strings.isEmpty(onDelete)){
this.onDelete = DbCascadeAction.valueOf(onDelete);
}
}
}
| 27.190184 | 126 | 0.693366 |
d74fb994ba080a2684301cac48af90387eb040c3 | 572 | package com.purbon.kafka.topology.model;
import java.util.Map;
public class User {
private String principal;
private Map<String, String> metadata;
public User() {
this("");
}
public User(String principal) {
this.principal = principal;
}
public String getPrincipal() {
return principal;
}
public void setPrincipal(String principal) {
this.principal = principal;
}
public Map<String, String> getMetadata() {
return metadata;
}
public void setMetadata(Map<String, String> metadata) {
this.metadata = metadata;
}
}
| 16.823529 | 57 | 0.676573 |
dacadc650dc00bef98d9846d07ef9c2090e1da04 | 3,149 | /*
* Copyright 2019 OST.com Inc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*/
package com.ost.ostwallet.entity;
import android.util.Log;
import com.ost.walletsdk.OstSdk;
import com.ost.walletsdk.models.entities.OstUser;
import org.json.JSONException;
import org.json.JSONObject;
public class User {
private static final String TAG = "OstLogInUser";
private static final String APP_USER_ID = "app_user_id";
private static final String TOKEN_ID = "token_id";
private static final String USER_NAME = "username";
private static final String USER_ID = "user_id";
private static final String TOKEN_HOLDER_ADDRESS = "token_holder_address";
private static final String STATUS = "status";
private static final String AVAILABLE_BALANCE = "available_balance";
private final String tokenHolderAddress;
private final String balance;
private final String status;
private String id;
private String ostUserId;
private String tokenId;
private String userName;
public static User newInstance(JSONObject usersJSONObject, JSONObject balancesJSONObject) {
try {
String id = usersJSONObject.getString(APP_USER_ID);
String userName = usersJSONObject.getString(USER_NAME);
String tokenId = usersJSONObject.getString(TOKEN_ID);
String ostUserId = usersJSONObject.getString(USER_ID);
String tokenHolderAddress = usersJSONObject.getString(TOKEN_HOLDER_ADDRESS);
String status = usersJSONObject.getString(STATUS);
String balance = "0";
JSONObject balanceJsonObject = balancesJSONObject.optJSONObject(id);
if (null != balanceJsonObject) {
balance = balanceJsonObject.getString(AVAILABLE_BALANCE);
}
return new User(id, userName, tokenId, ostUserId, tokenHolderAddress, balance, status);
} catch (JSONException e) {
Log.e(TAG, "JSON exception", e.getCause());
}
return null;
}
public User(String id, String userName, String tokenId, String ostUserId, String tokenHolderAddress, String balance, String status) {
this.id = id;
this.userName = userName;
this.tokenId = tokenId;
this.ostUserId = ostUserId;
this.tokenHolderAddress = tokenHolderAddress;
this.balance = balance;
this.status = status;
}
public String getId() {
return id;
}
public String getOstUserId() {
return ostUserId;
}
public OstUser getOstUser() {
return OstSdk.getUser(ostUserId);
}
public String getTokenId() {
return tokenId;
}
public String getUserName() {
return userName;
}
public String getTokenHolderAddress() {
return tokenHolderAddress;
}
public String getBalance() {
return balance;
}
public String getStatus() {
return status;
}
} | 31.178218 | 137 | 0.668149 |
dcfa398aa3f78070e4eb6ee8015ec6bc8484fc41 | 1,703 |
package com.example.android.quakereport;
import java.text.SimpleDateFormat;
import java.util.Date;
public class earthquake {
/** Magnitude of the earthquake */
private double mMagnitude;
/* Location of the earthquake */
private String mLocation;
/* date of the earthquake occured */
private String mDate;
/* time of the earthquake */
private Long mTimeInMilliseconds;
/* Construct a new object.
*
*/
public earthquake(double magnitude, String location, long timeInMilliseconds) {
mMagnitude = magnitude;
mLocation = location;
mTimeInMilliseconds = timeInMilliseconds;
}
/* returns the magnitude of the earthquake */
public double getMagnitude() {
return mMagnitude;
}
/* returns the location of the earthquake */
public String getmLocation() {
return mLocation;
}
/* returns the date of the earthquake */
public String getmDate() {
return mDate;
}
/**
* Returns the time of the earthquake.
*/
public long getTimeInMilliseconds() {
return mTimeInMilliseconds;
}
/**
* Return the formatted date string (i.e. "Mar 3, 1984") from a Date object.
*/
private String formatDate(Date dateObject) {
SimpleDateFormat dateFormat = new SimpleDateFormat("LLL dd, yyyy");
return dateFormat.format(dateObject);
}
/**
* Return the formatted date string (i.e. "4:30 PM") from a Date object.
*/
private String formatTime(Date dateObject) {
SimpleDateFormat timeFormat = new SimpleDateFormat("h:mm a");
return timeFormat.format(dateObject);
}
}
| 19.574713 | 83 | 0.635937 |
1fba3128e3648302c65dce8f3f9aea5ab942ac73 | 4,823 | package change;
import java.util.Date;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
/**
* Created by wm on 16/12/3.
*/
public class MyThreadFactoryMain {
public static void main(String[] args) throws InterruptedException {
MyThreadFactory threadFactory = new MyThreadFactory("wm");
ExecutorService executor = Executors.newCachedThreadPool(threadFactory);
MyTask task = new MyTask();
/*
* Submit the task
*/
executor.submit(task);
/*
* Shutdown the executor
*/
executor.shutdown();
/*
* Wait for the finalization of the executor
*/
executor.awaitTermination(1, TimeUnit.DAYS);
/*
* Write a message indicating the end of the program
*/
System.out.printf("Main: End of the program.\n");
}
public static class MyTask implements Runnable {
/**
* Main method of the task. It sleeps the thread for two seconds
*/
@Override
public void run() {
try {
TimeUnit.SECONDS.sleep(2);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public static class MyThread extends Thread {
/**
* Creation date of the thread
*/
private Date creationDate;
/**
* Start date of the thread
*/
private Date startDate;
/**
* Finish date of the thread
*/
private Date finishDate;
/**
* Constructor of the class. It establishes the value of the creation date attribute
*
* @param target Runnable object that this thread is going to execute
* @param name Name of the thread
*/
public MyThread(Runnable target, String name) {
super(target, name);
setCreationDate();
}
/**
* Main method of the thread. Stores the start and finish date of the thread and calls
* the run() method of its parent class
*/
@Override
public void run() {
setStartDate();
super.run();
setFinishDate();
System.out.printf("Thread: %s\n", toString());
}
/**
* Method that establish the creation date of the thread
*/
public void setCreationDate() {
creationDate = new Date();
}
/**
* Method that establish the start date of the thread
*/
public void setStartDate() {
startDate = new Date();
}
/**
* Method that establish the finish date of the thread
*/
public void setFinishDate() {
finishDate = new Date();
}
/**
* Method that calculates the execution time of the thread as the difference
* between the finish date and the start date.
*
* @return
*/
public long getExecutionTime() {
long ret;
ret = finishDate.getTime() - startDate.getTime();
return ret;
}
/**
* Method that generates a String with information about the creation date and the
* execution time of the thread
*/
public String toString() {
StringBuffer buffer = new StringBuffer();
buffer.append(getName());
buffer.append(": ");
buffer.append(" Creation Date: ");
buffer.append(creationDate);
buffer.append(" : Running time: ");
buffer.append(getExecutionTime());
buffer.append(" Milliseconds.");
return buffer.toString();
}
}
public static class MyThreadFactory implements ThreadFactory {
/**
* Attribute to store the number of threads created by the Factory
*/
private int counter;
/**
* Prefix to use in the name of the threads created by the Factory
*/
private String prefix;
/**
* Constructor of the class. Initializes its attributes
*
* @param prefix Prefix to use in the name of the threads
*/
public MyThreadFactory(String prefix) {
this.prefix = prefix;
counter = 1;
}
/**
* Method that create a new MyThread object to execute the Runnable
* object that receives as parameter
*/
@Override
public Thread newThread(Runnable r) {
MyThread myThread = new MyThread(r, prefix + "-" + counter);
counter++;
return myThread;
}
}
}
| 26.211957 | 94 | 0.545926 |
2ec1e986e2c2b1c4ab50dbf4d53dadb67323de5c | 10,990 | /**
* Dianping.com Inc.
* Copyright (c) 2003-2013 All Rights Reserved.
*/
package com.dianping.pigeon.remoting.common.config;
import com.dianping.pigeon.config.ConfigManagerLoader;
import com.dianping.pigeon.log.Logger;
import com.dianping.pigeon.log.LoggerLoader;
import com.dianping.pigeon.remoting.ServiceFactory;
import com.dianping.pigeon.remoting.common.util.Constants;
import com.dianping.pigeon.remoting.common.util.ServiceConfigUtils;
import com.dianping.pigeon.remoting.invoker.concurrent.InvocationCallback;
import com.dianping.pigeon.remoting.invoker.config.InvokerConfig;
import com.dianping.pigeon.remoting.invoker.config.annotation.Reference;
import com.dianping.pigeon.remoting.provider.config.ProviderConfig;
import com.dianping.pigeon.remoting.provider.config.ServerConfig;
import com.dianping.pigeon.remoting.provider.config.annotation.Service;
import com.dianping.pigeon.remoting.provider.config.spring.ServiceInitializeListener;
import com.dianping.pigeon.util.ClassUtils;
import com.dianping.pigeon.util.LangUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.aop.support.AopUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
public class AnnotationBean extends ServiceInitializeListener implements DisposableBean,
BeanFactoryPostProcessor, BeanPostProcessor, ApplicationContextAware {
private static final Logger logger = LoggerLoader.getLogger(AnnotationBean.class);
private String annotationPackage = ConfigManagerLoader.getConfigManager().getStringValue(
"pigeon.provider.interface.packages", "com.dianping");
private String[] annotationPackages = new String[] { "com.dianping" };
private final ConcurrentMap<String, InvokerConfig<?>> invokerConfigs = new ConcurrentHashMap<String, InvokerConfig<?>>();
public String getPackage() {
return annotationPackage;
}
public void setPackage(String annotationPackage) {
this.annotationPackage = annotationPackage;
this.annotationPackages = (annotationPackage == null || annotationPackage.length() == 0) ? null
: Constants.COMMA_SPLIT_PATTERN.split(annotationPackage);
}
private ApplicationContext applicationContext;
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
if (annotationPackage == null || annotationPackage.length() == 0) {
return;
}
if (beanFactory instanceof BeanDefinitionRegistry) {
try {
// init scanner
Class<?> scannerClass = ClassUtils
.loadClass("org.springframework.context.annotation.ClassPathBeanDefinitionScanner");
Object scanner = scannerClass.getConstructor(
new Class<?>[] { BeanDefinitionRegistry.class, boolean.class }).newInstance(
new Object[] { (BeanDefinitionRegistry) beanFactory, true });
// add filter
Class<?> filterClass = ClassUtils
.loadClass("org.springframework.core.type.filter.AnnotationTypeFilter");
Object filter = filterClass.getConstructor(Class.class).newInstance(Service.class);
Method addIncludeFilter = scannerClass.getMethod("addIncludeFilter",
ClassUtils.loadClass("org.springframework.core.type.filter.TypeFilter"));
addIncludeFilter.invoke(scanner, filter);
// scan packages
String[] packages = Constants.COMMA_SPLIT_PATTERN.split(annotationPackage);
Method scan = scannerClass.getMethod("scan", new Class<?>[] { String[].class });
scan.invoke(scanner, new Object[] { packages });
} catch (Throwable e) {
// spring 2.0
}
}
}
public int getDefaultPort(int port) {
if (port == 4040) {
try {
String app = ConfigManagerLoader.getConfigManager().getAppName();
if (StringUtils.isNotBlank(app)) {
return LangUtils.hash(app, 6000, 2000);
}
} catch (Throwable t) {
}
}
return port;
}
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
Class<?> beanClass = AopUtils.getTargetClass(bean);
if (beanClass == null || !isMatchPackage(beanClass.getName())) {
return bean;
}
Service service = beanClass.getAnnotation(Service.class);
if (service != null) {
Class serviceInterface = service.interfaceClass();
if (void.class.equals(service.interfaceClass())) {
serviceInterface = ServiceConfigUtils.getServiceInterface(beanClass);
}
if (serviceInterface == null) {
serviceInterface = beanClass;
}
ProviderConfig<Object> providerConfig = new ProviderConfig<Object>(serviceInterface, bean);
providerConfig.setService(bean);
providerConfig.setUrl(service.url());
providerConfig.setVersion(service.version());
providerConfig.setSharedPool(service.useSharedPool());
providerConfig.setActives(service.actives());
ServerConfig serverConfig = new ServerConfig();
serverConfig.setPort(getDefaultPort(service.port()));
serverConfig.setSuffix(service.group());
serverConfig.setAutoSelectPort(service.autoSelectPort());
providerConfig.setServerConfig(serverConfig);
ServiceFactory.addService(providerConfig);
}
postProcessBeforeInitialization(bean, beanName);
return bean;
}
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
if (!isMatchPackage(bean.getClass().getName())) {
return bean;
}
Method[] methods = bean.getClass().getMethods();
for (Method method : methods) {
String name = method.getName();
if (name.length() > 3 && name.startsWith("set") && method.getParameterTypes().length == 1
&& Modifier.isPublic(method.getModifiers()) && !Modifier.isStatic(method.getModifiers())) {
try {
Reference reference = method.getAnnotation(Reference.class);
if (reference != null) {
Object value = refer(reference, method.getParameterTypes()[0]);
if (value != null) {
method.invoke(bean, new Object[] {});
}
}
} catch (Throwable e) {
logger.error("Failed to init remote service reference at method " + name + " in class "
+ bean.getClass().getName() + ", cause: " + e.getMessage(), e);
}
}
}
Class<?> superClass = bean.getClass().getSuperclass();
while (superClass != null && isMatchPackage(superClass)) {
referFields(bean, superClass.getDeclaredFields());
superClass = superClass.getSuperclass();
}
referFields(bean, bean.getClass().getDeclaredFields());
return bean;
}
private void referFields(Object bean, Field[] fields) {
for (Field field : fields) {
try {
if (!field.isAccessible()) {
field.setAccessible(true);
}
Reference reference = field.getAnnotation(Reference.class);
if (reference != null) {
Object value = refer(reference, field.getType());
if (value != null) {
field.set(bean, value);
}
}
} catch (Throwable e) {
logger.error("Failed to init remote service reference at field " + field.getName() + " in class "
+ bean.getClass().getName() + ", cause: " + e.getMessage(), e);
}
}
}
private Object refer(Reference reference, Class<?> referenceClass) { // method.getParameterTypes()[0]
String interfaceName;
if (!void.class.equals(reference.interfaceClass())) {
interfaceName = reference.interfaceClass().getName();
} else if (referenceClass.isInterface()) {
interfaceName = referenceClass.getName();
} else {
throw new IllegalStateException(
"The @Reference undefined interfaceClass or interfaceName, and the property type "
+ referenceClass.getName() + " is not a interface.");
}
String callbackClassName = reference.callback();
InvocationCallback callback = null;
if (StringUtils.isNotBlank(callbackClassName)) {
Class<?> clazz;
try {
clazz = ClassUtils.loadClass(callbackClassName);
} catch (ClassNotFoundException e) {
throw new IllegalStateException("The @Reference undefined callback " + callbackClassName
+ ", is not a ServiceCallback interface.");
}
if (!InvocationCallback.class.isAssignableFrom(clazz)) {
throw new IllegalStateException("The @Reference undefined callback " + callbackClassName
+ ", is not a ServiceCallback interface.");
}
try {
callback = (InvocationCallback) clazz.newInstance();
} catch (InstantiationException e) {
throw new IllegalStateException("The @Reference undefined callback " + callbackClassName
+ ", is not a ServiceCallback interface.");
} catch (IllegalAccessException e) {
throw new IllegalStateException("The @Reference undefined callback " + callbackClassName
+ ", is not a ServiceCallback interface.");
}
}
String key = reference.group() + "/" + reference.url() + "@" + interfaceName + ":" + reference.version() + ":"
+ reference.serialize() + ":" + reference.protocol() + ":" + reference.timeout() + ":"
+ reference.callType();
InvokerConfig<?> invokerConfig = invokerConfigs.get(key);
if (invokerConfig == null) {
invokerConfig = new InvokerConfig(referenceClass, reference.url(), reference.timeout(),
reference.callType(), reference.serialize(), callback, reference.group(), false,
reference.loadbalance(), reference.cluster(), reference.retries(), reference.timeoutRetry(),
reference.vip(), reference.version(), reference.protocol());
invokerConfig.setSecret(reference.secret());
invokerConfigs.putIfAbsent(key, invokerConfig);
invokerConfig = invokerConfigs.get(key);
}
return ServiceFactory.getService(invokerConfig);
}
private boolean isMatchPackage(String beanClassName) {
if (annotationPackages == null || annotationPackages.length == 0) {
return true;
}
for (String pkg : annotationPackages) {
if (beanClassName.startsWith(pkg)) {
return true;
}
}
return false;
}
private boolean isMatchPackage(Class type) {
String beanClassName = type.getName();
for (String pkg : annotationPackages) {
if (beanClassName.startsWith(pkg)) {
return true;
}
}
return false;
}
@Override
public void destroy() throws Exception {
}
}
| 40.25641 | 123 | 0.718289 |
945e7d66782b198fa95a33f286686edd92b2bb64 | 1,940 | /*
*
*/
package org.inventivetalent.advancedslabs;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.block.data.BlockData;
import org.inventivetalent.advancedslabs.entity.IEntitySpawner;
import org.inventivetalent.advancedslabs.entity.ISlabFallingBlock;
import org.inventivetalent.reflection.minecraft.Minecraft;
import org.inventivetalent.reflection.resolver.ClassResolver;
public class EntityManager {
static ClassResolver classResolver = new ClassResolver();
private AdvancedSlabs plugin;
public final Class<?> EntitySpawnerClass;
public final Class<?> FallingBlockClass;
public IEntitySpawner spawner;
public EntityManager(AdvancedSlabs plugin) {
this.plugin = plugin;
EntitySpawnerClass = classResolver.resolveSilent("org.inventivetalent.advancedslabs.entity.EntitySpawner_" + Minecraft.VERSION.name());
FallingBlockClass = classResolver.resolveSilent("org.inventivetalent.advancedslabs.entity.SlabEntityFallingSand_" + Minecraft.VERSION.name());
if (EntitySpawnerClass == null) {
plugin.getLogger().severe("This plugin is currently not compatible with this server version (" + Minecraft.VERSION.name() + ")");
throw new RuntimeException("Incompatible Server Version");
}
try {
this.spawner = (IEntitySpawner) EntitySpawnerClass.newInstance();
} catch (ReflectiveOperationException e) {
throw new RuntimeException(e);
}
}
public ISlabFallingBlock spawnFallingBlock(Location location, BlockData blockData) {
return this.spawner.spawnFallingBlock(location, blockData.getMaterial(), blockData.getAsString());
}
public ISlabFallingBlock spawnFallingBlock(Location location, Material material, String data) {
return this.spawner.spawnFallingBlock(location, material, data);
}
@Deprecated
public ISlabFallingBlock spawnFallingBlock(Location location, Material material, byte data) {
return this.spawner.spawnFallingBlock(location, material, data);
}
}
| 33.448276 | 144 | 0.796392 |
2f95473696021e0d87c7008f868a015e715180f0 | 3,850 | /*
* Process Services Enterprise API
* Provides access to the complete features provided by Alfresco Process Services powered by Activiti. You can use this API to integrate Alfresco Process Services with external applications.
*
* OpenAPI spec version: 1.0
*
*
* NOTE: This class is auto generated by the swagger code generator program.
* https://github.com/swagger-api/swagger-codegen.git
* Do not edit the class manually.
*/
package org.activiti.engine.remote.client.api;
import org.activiti.engine.remote.client.ApiException;
import org.activiti.engine.remote.client.model.ResultListDataRepresentationAlfrescoContentRepresentation;
import org.activiti.engine.remote.client.model.ResultListDataRepresentationAlfrescoNetworkRepresenation;
import org.activiti.engine.remote.client.model.ResultListDataRepresentationAlfrescoSiteRepresenation;
import org.junit.Test;
import org.junit.Ignore;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* API tests for IntegrationAlfrescoCloudApi
*/
@Ignore
public class IntegrationAlfrescoCloudApiTest {
private final IntegrationAlfrescoCloudApi api = new IntegrationAlfrescoCloudApi();
/**
* Alfresco Cloud Authorization
*
* Returns Alfresco OAuth HTML Page
*
* @throws ApiException
* if the Api call fails
*/
@Test
public void confirmAuthorisationUsingGETTest() throws ApiException {
String code = null;
api.confirmAuthorisationUsingGET(code);
// TODO: test validations
}
/**
* List Alfresco networks
*
*
*
* @throws ApiException
* if the Api call fails
*/
@Test
public void getAllNetworksUsingGETTest() throws ApiException {
ResultListDataRepresentationAlfrescoNetworkRepresenation response = api.getAllNetworksUsingGET();
// TODO: test validations
}
/**
* List Alfresco sites
*
* Returns ALL Sites
*
* @throws ApiException
* if the Api call fails
*/
@Test
public void getAllSitesUsingGETTest() throws ApiException {
String networkId = null;
ResultListDataRepresentationAlfrescoSiteRepresenation response = api.getAllSitesUsingGET(networkId);
// TODO: test validations
}
/**
* List files and folders inside a specific folder identified by path
*
*
*
* @throws ApiException
* if the Api call fails
*/
@Test
public void getContentInFolderPathUsingGETTest() throws ApiException {
String networkId = null;
String siteId = null;
String path = null;
ResultListDataRepresentationAlfrescoContentRepresentation response = api.getContentInFolderPathUsingGET(networkId, siteId, path);
// TODO: test validations
}
/**
* List files and folders inside a specific folder
*
*
*
* @throws ApiException
* if the Api call fails
*/
@Test
public void getContentInFolderUsingGETTest() throws ApiException {
String networkId = null;
String folderId = null;
ResultListDataRepresentationAlfrescoContentRepresentation response = api.getContentInFolderUsingGET(networkId, folderId);
// TODO: test validations
}
/**
* List files and folders inside a specific site
*
*
*
* @throws ApiException
* if the Api call fails
*/
@Test
public void getContentInSiteUsingGETTest() throws ApiException {
String networkId = null;
String siteId = null;
ResultListDataRepresentationAlfrescoContentRepresentation response = api.getContentInSiteUsingGET(networkId, siteId);
// TODO: test validations
}
}
| 28.10219 | 191 | 0.678961 |
c6c91bce5afaa8b604e9848da06008c11238789e | 3,463 | package mekanism.generators.client.render;
import javax.annotation.ParametersAreNonnullByDefault;
import mekanism.api.text.EnumColor;
import mekanism.client.MekanismClient;
import mekanism.client.model.ModelEnergyCube.ModelEnergyCore;
import mekanism.client.render.MekanismRenderer;
import mekanism.client.render.tileentity.MekanismTileEntityRenderer;
import mekanism.client.render.tileentity.RenderEnergyCube;
import mekanism.generators.common.GeneratorsProfilerConstants;
import mekanism.generators.common.tile.fusion.TileEntityFusionReactorController;
import net.minecraft.client.render.VertexConsumer;
import net.minecraft.client.render.VertexConsumerProvider;
import net.minecraft.client.render.block.entity.BlockEntityRenderDispatcher;
import net.minecraft.client.util.math.MatrixStack;
import net.minecraft.client.util.math.Vector3f;
import net.minecraft.util.profiler.Profiler;
@ParametersAreNonnullByDefault
public class RenderFusionReactor extends MekanismTileEntityRenderer<TileEntityFusionReactorController> {
private static final double SCALE = 100_000_000;
private final ModelEnergyCore core = new ModelEnergyCore();
public RenderFusionReactor(BlockEntityRenderDispatcher renderer) {
super(renderer);
}
@Override
protected void render(TileEntityFusionReactorController tile, float partialTick, MatrixStack matrix, VertexConsumerProvider renderer, int light, int overlayLight,
Profiler profiler) {
if (tile.getMultiblock().isFormed() && tile.getMultiblock().isBurning()) {
matrix.push();
matrix.translate(0.5, -1.5, 0.5);
long scaledTemp = Math.round(tile.getMultiblock().getLastPlasmaTemp() / SCALE);
float ticks = MekanismClient.ticksPassed + partialTick;
double scale = 1 + 0.7 * Math.sin(Math.toRadians(ticks * 3.14 * scaledTemp + 135F));
VertexConsumer buffer = core.getBuffer(renderer);
renderPart(matrix, buffer, overlayLight, EnumColor.AQUA, scale, ticks, scaledTemp, -6, -7, 0, 36);
scale = 1 + 0.8 * Math.sin(Math.toRadians(ticks * 3 * scaledTemp));
renderPart(matrix, buffer, overlayLight, EnumColor.RED, scale, ticks, scaledTemp, 4, 4, 0, 36);
scale = 1 - 0.9 * Math.sin(Math.toRadians(ticks * 4 * scaledTemp + 90F));
renderPart(matrix, buffer, overlayLight, EnumColor.ORANGE, scale, ticks, scaledTemp, 5, -3, -35, 106);
matrix.pop();
}
}
@Override
protected String getProfilerSection() {
return GeneratorsProfilerConstants.FUSION_REACTOR;
}
private void renderPart(MatrixStack matrix, VertexConsumer buffer, int overlayLight, EnumColor color, double scale, float ticks, long scaledTemp, int mult1,
int mult2, int shift1, int shift2) {
float ticksScaledTemp = ticks * scaledTemp;
matrix.push();
matrix.scale((float) scale, (float) scale, (float) scale);
matrix.multiply(Vector3f.POSITIVE_Y.getDegreesQuaternion(ticksScaledTemp * mult1 + shift1));
matrix.multiply(RenderEnergyCube.coreVec.getDegreesQuaternion(ticksScaledTemp * mult2 + shift2));
core.render(matrix, buffer, MekanismRenderer.FULL_LIGHT, overlayLight, color, 1);
matrix.pop();
}
@Override
public boolean isGlobalRenderer(TileEntityFusionReactorController tile) {
return tile.getMultiblock().isFormed() && tile.getMultiblock().isBurning();
}
} | 48.097222 | 166 | 0.732024 |
bef5b3957c4bf3a5814ddbb6be5cc491500e4910 | 25,177 | package io.ably.lib.test.realtime;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import io.ably.lib.realtime.AblyRealtime;
import io.ably.lib.realtime.Channel;
import io.ably.lib.realtime.ChannelState;
import io.ably.lib.test.common.Helpers.ChannelWaiter;
import io.ably.lib.test.common.Helpers.CompletionSet;
import io.ably.lib.test.common.Helpers.CompletionWaiter;
import io.ably.lib.test.common.Helpers.MessageWaiter;
import io.ably.lib.test.common.ParameterizedTest;
import io.ably.lib.types.AblyException;
import io.ably.lib.types.ChannelOptions;
import io.ably.lib.types.ClientOptions;
import io.ably.lib.types.ErrorInfo;
import io.ably.lib.util.Crypto;
import io.ably.lib.util.Crypto.CipherParams;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import javax.crypto.KeyGenerator;
import javax.crypto.spec.IvParameterSpec;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.Timeout;
public class RealtimeCryptoTest extends ParameterizedTest {
@Rule
public Timeout testTimeout = Timeout.seconds(30);
/**
* Connect to the service
* and publish an encrypted message on that channel using
* the default cipher params
*/
@Test
public void single_send() {
String channelName = "single_send_" + testParams.name;
AblyRealtime ably = null;
try {
ClientOptions opts = createOptions(testVars.keys[0].keyStr);
ably = new AblyRealtime(opts);
/* create a channel */
ChannelOptions channelOpts = new ChannelOptions() {{ encrypted = true; }};
final Channel channel = ably.channels.get(channelName, channelOpts);
/* attach */
channel.attach();
(new ChannelWaiter(channel)).waitFor(ChannelState.attached);
assertEquals("Verify attached state reached", channel.state, ChannelState.attached);
/* subscribe */
MessageWaiter messageWaiter = new MessageWaiter(channel);
/* publish to the channel */
String messageText = "Test message (subscribe_send_binary)";
CompletionWaiter msgComplete = new CompletionWaiter();
channel.publish("test_event", messageText, msgComplete);
/* wait for the publish callback to be called */
msgComplete.waitFor();
assertTrue("Verify success callback was called", msgComplete.success);
/* wait for the subscription callback to be called */
messageWaiter.waitFor(1);
assertEquals("Verify message subscription was called", messageWaiter.receivedMessages.size(), 1);
/* check the correct plaintext recovered from the message */
assertTrue("Verify correct plaintext received", messageText.equals(messageWaiter.receivedMessages.get(0).data));
} catch (AblyException e) {
e.printStackTrace();
fail("init0: Unexpected exception instantiating library");
} finally {
if(ably != null)
ably.close();
}
}
/**
* Connect to the service
* and publish an encrypted message on that channel using
* a 256-bit key
*/
@Test
public void single_send_256() {
String channelName = "single_send_256_" + testParams.name;
AblyRealtime ably = null;
try {
ClientOptions opts = createOptions(testVars.keys[0].keyStr);
ably = new AblyRealtime(opts);
/* create a key */
KeyGenerator keygen = KeyGenerator.getInstance("AES");
keygen.init(256);
byte[] key = keygen.generateKey().getEncoded();
final CipherParams params = Crypto.getDefaultParams(key);
/* create a channel */
ChannelOptions channelOpts = new ChannelOptions() {{ encrypted = true; this.cipherParams = params; }};
final Channel channel = ably.channels.get(channelName, channelOpts);
/* attach */
channel.attach();
(new ChannelWaiter(channel)).waitFor(ChannelState.attached);
assertEquals("Verify attached state reached", channel.state, ChannelState.attached);
/* subscribe */
MessageWaiter messageWaiter = new MessageWaiter(channel);
/* publish to the channel */
String messageText = "Test message (subscribe_send_binary)";
CompletionWaiter msgComplete = new CompletionWaiter();
channel.publish("test_event", messageText, msgComplete);
/* wait for the publish callback to be called */
msgComplete.waitFor();
assertTrue("Verify success callback was called", msgComplete.success);
/* wait for the subscription callback to be called */
messageWaiter.waitFor(1);
assertEquals("Verify message subscription was called", messageWaiter.receivedMessages.size(), 1);
/* check the correct plaintext recovered from the message */
assertTrue("Verify correct plaintext received", messageText.equals(messageWaiter.receivedMessages.get(0).data));
} catch (AblyException e) {
e.printStackTrace();
fail("init0: Unexpected exception instantiating library");
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
fail("init0: Unexpected exception generating key");
} finally {
if(ably != null)
ably.close();
}
}
/**
* Connect to the service using the default (binary) protocol
* and attach, subscribe to an event, and publish multiple
* messages on that channel
*/
private void _multiple_send(String channelName, int messageCount, long delay) {
AblyRealtime ably = null;
try {
ClientOptions opts = createOptions(testVars.keys[0].keyStr);
ably = new AblyRealtime(opts);
/* generate and remember message texts */
String[] messageTexts = new String[messageCount];
for(int i = 0; i < messageCount; i++)
messageTexts[i] = "Test message (_multiple_send) " + i;
/* create a channel */
ChannelOptions channelOpts = new ChannelOptions() {{ encrypted = true; }};
final Channel channel = ably.channels.get(channelName, channelOpts);
/* attach */
channel.attach();
(new ChannelWaiter(channel)).waitFor(ChannelState.attached);
assertEquals("Verify attached state reached", channel.state, ChannelState.attached);
/* subscribe */
MessageWaiter messageWaiter = new MessageWaiter(channel);
/* publish to the channel */
CompletionSet msgComplete = new CompletionSet();
for(int i = 0; i < messageCount; i++) {
channel.publish("test_event", messageTexts[i], msgComplete.add());
try { Thread.sleep(delay); } catch(InterruptedException e){}
}
/* wait for the publish callback to be called */
ErrorInfo[] errors = msgComplete.waitFor();
assertTrue("Verify success from all message callbacks", errors.length == 0);
/* wait for the subscription callback to be called */
messageWaiter.waitFor(messageCount);
assertEquals("Verify message subscriptions all called", messageWaiter.receivedMessages.size(), messageCount);
/* check the correct plaintext recovered from the message */
for(int i = 0; i < messageCount; i++)
assertTrue("Verify correct plaintext received", messageTexts[i].equals(messageWaiter.receivedMessages.get(i).data));
} catch (AblyException e) {
e.printStackTrace();
fail("init0: Unexpected exception instantiating library");
} finally {
if(ably != null)
ably.close();
}
}
@Test
public void multiple_send_2_200() {
int messageCount = 2;
long delay = 200L;
_multiple_send("multiple_send_binary_2_200_" + testParams.name, messageCount, delay);
}
@Test
public void multiple_send_20_100() {
int messageCount = 20;
long delay = 100L;
_multiple_send("multiple_send_binary_20_100_" + testParams.name, messageCount, delay);
}
/**
* Connect twice to the service, using the default (binary) protocol
* and the text protocol. Publish an encrypted message on that channel using
* the default cipher params and verify correct receipt.
*/
@Test
public void single_send_binary_text() {
String channelName = "single_send_binary_text_" + testParams.name;
AblyRealtime txAbly = null, rxAbly = null;
try {
ClientOptions txOpts = createOptions(testVars.keys[0].keyStr);
txAbly = new AblyRealtime(txOpts);
ClientOptions rxOpts = createOptions(testVars.keys[0].keyStr);
rxOpts.useBinaryProtocol = !testParams.useBinaryProtocol;
rxAbly = new AblyRealtime(rxOpts);
/* create a key */
final CipherParams params = Crypto.getDefaultParams();
/* create a channel */
final ChannelOptions txChannelOpts = new ChannelOptions() {{ encrypted = true; cipherParams = params; }};
final Channel txChannel = txAbly.channels.get(channelName, txChannelOpts);
ChannelOptions rxChannelOpts = new ChannelOptions() {{ encrypted = true; cipherParams = params; }};
final Channel rxChannel = rxAbly.channels.get(channelName, rxChannelOpts);
/* attach */
txChannel.attach();
rxChannel.attach();
(new ChannelWaiter(txChannel)).waitFor(ChannelState.attached);
(new ChannelWaiter(rxChannel)).waitFor(ChannelState.attached);
assertEquals("Verify attached state reached", txChannel.state, ChannelState.attached);
assertEquals("Verify attached state reached", rxChannel.state, ChannelState.attached);
/* subscribe */
MessageWaiter messageWaiter = new MessageWaiter(rxChannel);
/* publish to the channel */
String messageText = "Test message (single_send_binary_text)";
CompletionWaiter msgComplete = new CompletionWaiter();
txChannel.publish("test_event", messageText, msgComplete);
/* wait for the publish callback to be called */
msgComplete.waitFor();
assertTrue("Verify success callback was called", msgComplete.success);
/* wait for the subscription callback to be called */
messageWaiter.waitFor(1);
assertEquals("Verify message subscription was called", messageWaiter.receivedMessages.size(), 1);
/* check the correct plaintext recovered from the message */
assertTrue("Verify correct plaintext received", messageText.equals(messageWaiter.receivedMessages.get(0).data));
} catch (AblyException e) {
e.printStackTrace();
fail("init0: Unexpected exception instantiating library");
} finally {
if(txAbly != null)
txAbly.close();
}
}
/**
* Connect twice to the service, using different cipher keys.
* Publish an encrypted message on that channel using
* the default cipher params and verify that the decrypt failure
* is noticed as bad recovered plaintext.
*/
@Test
public void single_send_key_mismatch() {
AblyRealtime txAbly = null, rxAbly = null;
try {
ClientOptions txOpts = createOptions(testVars.keys[0].keyStr);
txAbly = new AblyRealtime(txOpts);
ClientOptions rxOpts = createOptions(testVars.keys[0].keyStr);
rxAbly = new AblyRealtime(rxOpts);
/* create a channel */
final ChannelOptions txChannelOpts = new ChannelOptions() {{ encrypted = true; }};
final Channel txChannel = txAbly.channels.get("single_send_binary_text", txChannelOpts);
ChannelOptions rxChannelOpts = new ChannelOptions() {{ encrypted = true; }};
final Channel rxChannel = rxAbly.channels.get("single_send_binary_text", rxChannelOpts);
/* attach */
txChannel.attach();
rxChannel.attach();
(new ChannelWaiter(txChannel)).waitFor(ChannelState.attached);
(new ChannelWaiter(rxChannel)).waitFor(ChannelState.attached);
assertEquals("Verify attached state reached", txChannel.state, ChannelState.attached);
assertEquals("Verify attached state reached", rxChannel.state, ChannelState.attached);
/* subscribe */
MessageWaiter messageWaiter = new MessageWaiter(rxChannel);
/* publish to the channel */
String messageText = "Test message (single_send_key_mismatch)";
CompletionWaiter msgComplete = new CompletionWaiter();
txChannel.publish("test_event", messageText, msgComplete);
/* wait for the publish callback to be called */
msgComplete.waitFor();
assertTrue("Verify success callback was called", msgComplete.success);
/* wait for the subscription callback to be called */
messageWaiter.waitFor(1);
assertEquals("Verify message subscription was called", messageWaiter.receivedMessages.size(), 1);
/* check the correct plaintext recovered from the message */
assertFalse("Verify correct plaintext not received", messageText.equals(messageWaiter.receivedMessages.get(0).data));
} catch (AblyException e) {
e.printStackTrace();
fail("init0: Unexpected exception instantiating library");
} finally {
if(txAbly != null)
txAbly.close();
}
}
/**
* Connect twice to the service, one with and one without encryption.
* Publish an unencrypted message and verify that the receiving connection
* does not attempt to decrypt it.
*/
@Test
public void single_send_unencrypted() {
AblyRealtime txAbly = null, rxAbly = null;
try {
ClientOptions txOpts = createOptions(testVars.keys[0].keyStr);
txAbly = new AblyRealtime(txOpts);
ClientOptions rxOpts = createOptions(testVars.keys[0].keyStr);
rxAbly = new AblyRealtime(rxOpts);
/* create a channel */
final Channel txChannel = txAbly.channels.get("single_send_unencrypted");
ChannelOptions rxChannelOpts = new ChannelOptions() {{ encrypted = true; }};
final Channel rxChannel = rxAbly.channels.get("single_send_unencrypted", rxChannelOpts);
/* attach */
txChannel.attach();
rxChannel.attach();
(new ChannelWaiter(txChannel)).waitFor(ChannelState.attached);
(new ChannelWaiter(rxChannel)).waitFor(ChannelState.attached);
assertEquals("Verify attached state reached", txChannel.state, ChannelState.attached);
assertEquals("Verify attached state reached", rxChannel.state, ChannelState.attached);
/* subscribe */
MessageWaiter messageWaiter = new MessageWaiter(rxChannel);
/* publish to the channel */
String messageText = "Test message (single_send_unencrypted)";
CompletionWaiter msgComplete = new CompletionWaiter();
txChannel.publish("test_event", messageText, msgComplete);
/* wait for the publish callback to be called */
msgComplete.waitFor();
assertTrue("Verify success callback was called", msgComplete.success);
/* wait for the subscription callback to be called */
messageWaiter.waitFor(1);
assertEquals("Verify message subscription was called", messageWaiter.receivedMessages.size(), 1);
/* check the correct text recovered from the message */
assertTrue("Verify correct message text received", messageText.equals(messageWaiter.receivedMessages.get(0).data));
} catch (AblyException e) {
e.printStackTrace();
fail("init0: Unexpected exception instantiating library");
} finally {
if(txAbly != null)
txAbly.close();
}
}
/**
* Connect twice to the service, one with and one without encryption.
* Publish an unencrypted message and verify that the receiving connection
* does not attempt to decrypt it.
*/
@Test
public void single_send_encrypted_unhandled() {
AblyRealtime txAbly = null, rxAbly = null;
try {
ClientOptions txOpts = createOptions(testVars.keys[0].keyStr);
txAbly = new AblyRealtime(txOpts);
ClientOptions rxOpts = createOptions(testVars.keys[0].keyStr);
rxAbly = new AblyRealtime(rxOpts);
/* create a channel */
ChannelOptions txChannelOpts = new ChannelOptions() {{ encrypted = true; }};
final Channel txChannel = txAbly.channels.get("single_send_encrypted_unhandled", txChannelOpts);
final Channel rxChannel = rxAbly.channels.get("single_send_encrypted_unhandled");
/* attach */
txChannel.attach();
rxChannel.attach();
(new ChannelWaiter(txChannel)).waitFor(ChannelState.attached);
(new ChannelWaiter(rxChannel)).waitFor(ChannelState.attached);
assertEquals("Verify attached state reached", txChannel.state, ChannelState.attached);
assertEquals("Verify attached state reached", rxChannel.state, ChannelState.attached);
/* subscribe */
MessageWaiter messageWaiter = new MessageWaiter(rxChannel);
/* publish to the channel */
String messageText = "Test message (single_send_encrypted_unhandled)";
CompletionWaiter msgComplete = new CompletionWaiter();
txChannel.publish("test_event", messageText, msgComplete);
/* wait for the publish callback to be called */
msgComplete.waitFor();
assertTrue("Verify success callback was called", msgComplete.success);
/* wait for the subscription callback to be called */
messageWaiter.waitFor(1);
assertEquals("Verify message subscription was called", messageWaiter.receivedMessages.size(), 1);
/* check the the message payload is indicated as encrypted */
// assertTrue("Verify correct message text received", messageWaiter.receivedMessages.get(0).data instanceof CipherData);
} catch (AblyException e) {
e.printStackTrace();
fail("init0: Unexpected exception instantiating library");
} finally {
if(txAbly != null)
txAbly.close();
}
}
/**
* Check Channel.setOptions updates CipherParams correctly:
* - publish a message using a key, verifying correct receipt;
* - publish with an updated key on the tx connection and verify that it is not decrypted by the rx connection;
* - publish with an updated key on the rx connection and verify connect receipt
*/
@Test
public void set_cipher_params() {
AblyRealtime txAbly = null, rxAbly = null;
try {
ClientOptions txOpts = createOptions(testVars.keys[0].keyStr);
txAbly = new AblyRealtime(txOpts);
ClientOptions rxOpts = createOptions(testVars.keys[0].keyStr);
rxOpts.useBinaryProtocol = !testParams.useBinaryProtocol;
rxAbly = new AblyRealtime(rxOpts);
/* create a key */
final CipherParams params1 = Crypto.getDefaultParams();
/* create a channel */
ChannelOptions txChannelOpts = new ChannelOptions() {{ encrypted = true; cipherParams = params1; }};
final Channel txChannel = txAbly.channels.get("set_cipher_params", txChannelOpts);
ChannelOptions rxChannelOpts = new ChannelOptions() {{ encrypted = true; cipherParams = params1; }};
final Channel rxChannel = rxAbly.channels.get("set_cipher_params", rxChannelOpts);
/* attach */
txChannel.attach();
rxChannel.attach();
(new ChannelWaiter(txChannel)).waitFor(ChannelState.attached);
(new ChannelWaiter(rxChannel)).waitFor(ChannelState.attached);
assertEquals("Verify attached state reached", txChannel.state, ChannelState.attached);
assertEquals("Verify attached state reached", rxChannel.state, ChannelState.attached);
/* subscribe */
MessageWaiter messageWaiter = new MessageWaiter(rxChannel);
/* publish to the channel */
String messageText = "Test message (set_cipher_params)";
CompletionWaiter msgComplete = new CompletionWaiter();
txChannel.publish("test_event", messageText, msgComplete);
/* wait for the publish callback to be called */
msgComplete.waitFor();
assertTrue("Verify success callback was called", msgComplete.success);
/* wait for the subscription callback to be called */
messageWaiter.waitFor(1);
assertEquals("Verify message subscription was called", messageWaiter.receivedMessages.size(), 1);
/* check the correct plaintext recovered from the message */
assertTrue("Verify correct plaintext received", messageText.equals(messageWaiter.receivedMessages.get(0).data));
/* create a second key and set tx channel opts */
final CipherParams params2 = Crypto.getDefaultParams();
txChannelOpts = new ChannelOptions() {{ encrypted = true; cipherParams = params2; }};
txChannel.setOptions(txChannelOpts);
/* publish to the channel, wait, check message bad */
messageWaiter.reset();
txChannel.publish("test_event", messageText, msgComplete);
messageWaiter.waitFor(1);
assertFalse("Verify correct plaintext not received", messageText.equals(messageWaiter.receivedMessages.get(0).data));
/* See issue https://github.com/ably/ably-java/issues/202
* This final part of the test fails intermittently. For now just try
* it multiple times. */
for (int count = 4;; --count) {
assertTrue("Verify correct plaintext received", count != 0);
/* set rx channel opts */
rxChannel.setOptions(txChannelOpts);
/* publish to the channel, wait, check message bad */
messageWaiter.reset();
txChannel.publish("test_event", messageText, msgComplete);
messageWaiter.waitFor(1);
if (messageText.equals(messageWaiter.receivedMessages.get(0).data))
break;
}
} catch (AblyException e) {
e.printStackTrace();
fail("init0: Unexpected exception instantiating library");
} finally {
if(txAbly != null)
txAbly.close();
}
}
/**
* Test channel options creation from the cipher key
* Tests TB3
*/
@Test
public void channel_options_from_cipher_key() {
String channelName = "cipher_params_test_" + testParams.name;
AblyRealtime ably1 = null, ably2 = null;
try {
ClientOptions opts = createOptions(testVars.keys[0].keyStr);
ably1 = new AblyRealtime(opts);
ably2 = new AblyRealtime(opts);
/* 128-bit key */
byte[] key = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16};
/* Same key but encoded with Base64 */
String base64key = "AQIDBAUGBwgJCgsMDQ4PEA==";
/* create a sending channel using byte[] array */
final Channel channelSend = ably1.channels.get(channelName, ChannelOptions.fromCipherKey(key));
/* create a receiving channel using (the same) key encoded with base64 */
final Channel channelReceive = ably2.channels.get(channelName, ChannelOptions.fromCipherKey(base64key));
/* attach */
channelSend.attach();
channelReceive.attach();
/* subscribe */
MessageWaiter messageWaiter = new MessageWaiter(channelReceive);
/* publish to the channel */
String messageText = "Test message";
CompletionWaiter msgComplete = new CompletionWaiter();
channelSend.publish("test_event", messageText, msgComplete);
/* wait for the publish callback to be called */
msgComplete.waitFor();
assertTrue("Verify success callback was called", msgComplete.success);
/* wait for the subscription callback to be called */
messageWaiter.waitFor(1);
assertEquals("Verify message subscription was called", messageWaiter.receivedMessages.size(), 1);
/* check the correct plaintext recovered from the message */
assertTrue("Verify correct plaintext received", messageText.equals(messageWaiter.receivedMessages.get(0).data));
} catch (AblyException e) {
e.printStackTrace();
fail("init0: Unexpected exception instantiating library");
} finally {
if(ably1 != null)
ably1.close();
if(ably2 != null)
ably2.close();
}
}
/**
* Test Crypto.getDefaultParams
* @throws AblyException
*
* Tests RSE1
*/
@Test
public void cipher_params() throws AblyException {
/* 128-bit key */
/* {0xFF, 0xFE, 0xFD, 0xFC, 0xFB, 0xFA, 0xF9, 0xF8, 0xF7, 0xF6, 0xF5, 0xF4, 0xF3, 0xF2, 0xF1, 0xF0}; */
byte[] key = {-1, -2, -3, -4, -5, -6, -7, -8, -9, -10, -11, -12, -13, -14, -15, -16};
/* Same key but encoded with Base64 */
String base64key = "//79/Pv6+fj39vX08/Lx8A==";
/* Same key but encoded in URL style (RFC 4648 s.5) */
String base64key2 = "__79_Pv6-fj39vX08_Lx8A==";
/* IV */
byte[] iv = {16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1};
final CipherParams params1 = Crypto.getDefaultParams(key); params1.ivSpec = new IvParameterSpec(iv);
final CipherParams params2 = Crypto.getDefaultParams(base64key); params2.ivSpec = new IvParameterSpec(iv);
final CipherParams params3 = Crypto.getDefaultParams(params1); params3.ivSpec = new IvParameterSpec(iv);
final CipherParams params4 = Crypto.getDefaultParams(base64key2); params4.ivSpec = new IvParameterSpec(iv);
assertTrue("Verify keyLength is calculated properly",
params1.keyLength == key.length*8 && params2.keyLength == key.length*8 && params3.keyLength == key.length*8 && params4.keyLength == key.length*8);
byte[] plaintext = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16};
Crypto.ChannelCipher channelCipher1 = Crypto.getCipher(new ChannelOptions() {{ encrypted=true; cipherParams=params1; }});
Crypto.ChannelCipher channelCipher2 = Crypto.getCipher(new ChannelOptions() {{ encrypted=true; cipherParams=params2; }});
Crypto.ChannelCipher channelCipher3 = Crypto.getCipher(new ChannelOptions() {{ encrypted=true; cipherParams=params3; }});
Crypto.ChannelCipher channelCipher4 = Crypto.getCipher(new ChannelOptions() {{ encrypted=true; cipherParams=params4; }});
byte[] ciphertext1 = channelCipher1.encrypt(plaintext);
byte[] ciphertext2 = channelCipher2.encrypt(plaintext);
byte[] ciphertext3 = channelCipher3.encrypt(plaintext);
byte[] ciphertext4 = channelCipher4.encrypt(plaintext);
assertTrue("Verify all the cipertexts are equal",
Arrays.equals(ciphertext1, ciphertext2) &&
Arrays.equals(ciphertext1, ciphertext3) &&
Arrays.equals(ciphertext1, ciphertext4));
}
/**
* Test Crypto.generateRandomKey
* Tests RSE2
*/
@Test public void generate_random_key() {
final int numberOfRandomKeys = 50;
final int randomKeyBits = 256;
byte[][] randomKeys = new byte[numberOfRandomKeys][];
for (int i=0; i<numberOfRandomKeys; i++) {
randomKeys[i] = Crypto.generateRandomKey(randomKeyBits);
assertEquals("Verify random data has correct length", randomKeys[i].length, (randomKeyBits + 7) / 8);
for (int j=0; j<i; j++)
assertFalse("Verify random data is unique", Arrays.equals(randomKeys[i], randomKeys[j]));
}
}
}
| 38.496942 | 150 | 0.727052 |
9d0bdb99ce885025e369b3bda59bf2a4205ba159 | 522 | module frogger {
exports frogger;
exports frogger.constant;
exports frogger.controller;
exports frogger.model.actor.staticActor;
exports frogger.model;
exports frogger.view;
exports frogger.service;
exports frogger.model.actor.movableActor;
exports frogger.model.actor;
opens frogger.controller to javafx.fxml;
requires transitive javafx.base;
requires transitive javafx.controls;
requires transitive javafx.fxml;
requires transitive javafx.graphics;
requires transitive javafx.media;
requires junit;
}
| 24.857143 | 42 | 0.808429 |
c9d9739b4cf54c706acbb02b627623f0f77efc6e | 7,026 | package com.github.nagyesta.abortmission.strongback.h2.repository;
import com.github.nagyesta.abortmission.core.healthcheck.StageStatisticsSnapshot;
import com.github.nagyesta.abortmission.core.healthcheck.impl.DefaultStageStatisticsSnapshot;
import com.github.nagyesta.abortmission.core.telemetry.StageTimeMeasurement;
import org.jdbi.v3.core.mapper.RowMapper;
import org.jdbi.v3.core.statement.StatementContext;
import org.jdbi.v3.core.transaction.TransactionIsolationLevel;
import org.jdbi.v3.sqlobject.config.RegisterConstructorMapper;
import org.jdbi.v3.sqlobject.config.RegisterRowMapper;
import org.jdbi.v3.sqlobject.customizer.Bind;
import org.jdbi.v3.sqlobject.customizer.BindBean;
import org.jdbi.v3.sqlobject.statement.SqlQuery;
import org.jdbi.v3.sqlobject.statement.SqlUpdate;
import org.jdbi.v3.sqlobject.transaction.Transaction;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
/**
* The repository we will use for data access.
*/
public interface LaunchStatisticsRepository {
/**
* Inserts a single time measurement to the database.
*
* @param contextName The name of the Abort-Mission context.
* @param matcherName The name of the matcher we need to filter for.
* @param countdown True if we need the countdown values false otherwise.
* @param measurement The measurement we observed.
*/
@SqlUpdate("INSERT INTO LAUNCH_STATISTICS("
+ " CONTEXT_NAME,"
+ " MATCHER_NAME,"
+ " LAUNCH_ID,"
+ " COUNTDOWN,"
+ " TEST_CLASS,"
+ " TEST_METHOD,"
+ " TEST_RESULT,"
+ " START_MILLIS,"
+ " END_MILLIS) "
+ "VALUES ("
+ " :contextName,"
+ " :matcherName,"
+ " :launchId,"
+ " :countdown,"
+ " :testClassId,"
+ " :testCaseId,"
+ " :result,"
+ " :start,"
+ " :end)")
@Transaction(value = TransactionIsolationLevel.READ_COMMITTED)
void insertStageTimeMeasurement(@Bind("contextName") String contextName,
@Bind("matcherName") String matcherName,
@Bind("countdown") boolean countdown,
@BindBean StageTimeMeasurement measurement);
/**
* Fetches all previously recorded measurements for the given matcher name.
* The order of entries will be by start, end, class, method, launchId, result.
*
* @param matcherName The name of the matcher we need to filter for.
* @return The matching measurements.
*/
@SqlQuery("SELECT"
+ " LAUNCH_ID as launchId,"
+ " TEST_CLASS as testClassId,"
+ " TEST_METHOD as testCaseId,"
+ " TEST_RESULT as result,"
+ " START_MILLIS as start,"
+ " END_MILLIS as end "
+ "FROM LAUNCH_STATISTICS "
+ "WHERE MATCHER_NAME = :matcherName "
+ "ORDER BY START_MILLIS, END_MILLIS, TEST_CLASS, TEST_METHOD, LAUNCH_ID, TEST_RESULT")
@RegisterConstructorMapper(StageTimeMeasurement.class)
@Transaction(value = TransactionIsolationLevel.READ_COMMITTED, readOnly = true)
List<StageTimeMeasurement> fetchAllMeasurementsForMatcher(@Bind("matcherName") String matcherName);
/**
* Fetches all previously recorded measurements for the given matcher name.
* The order of entries will be by start, end, class, method, launchId, result.
*
* @param contextName The name of the Abort-Mission context.
* @param matcherName The name of the matcher we need to filter for.
* @param countdown True if we need the countdown values false otherwise.
* @return The matching measurements.
*/
@SqlQuery("SELECT"
+ " LAUNCH_ID as launchId,"
+ " TEST_CLASS as testClassId,"
+ " TEST_METHOD as testCaseId,"
+ " TEST_RESULT as result,"
+ " START_MILLIS as start,"
+ " END_MILLIS as end "
+ "FROM LAUNCH_STATISTICS "
+ "WHERE CONTEXT_NAME = :contextName"
+ " AND MATCHER_NAME = :matcherName"
+ " AND COUNTDOWN = :countdown "
+ "ORDER BY START_MILLIS, END_MILLIS, TEST_CLASS, TEST_METHOD, LAUNCH_ID, TEST_RESULT")
@RegisterConstructorMapper(StageTimeMeasurement.class)
@Transaction(value = TransactionIsolationLevel.READ_COMMITTED, readOnly = true)
List<StageTimeMeasurement> fetchMeasurementsFor(@Bind("contextName") String contextName,
@Bind("matcherName") String matcherName,
@Bind("countdown") boolean countdown);
/**
* Fetches all matcher names we used so far.
*
* @return The matcher names.
*/
@SqlQuery("SELECT DISTINCT MATCHER_NAME "
+ "FROM LAUNCH_STATISTICS "
+ "ORDER BY MATCHER_NAME")
@Transaction(value = TransactionIsolationLevel.READ_COMMITTED, readOnly = true)
List<String> fetchAllMatcherNames();
/**
* Gets a snapshot of the previously recorded measurements for abort evaluation.
*
* @param contextName The name of the Abort-Mission context.
* @param matcherName The name of the matcher we need to filter for.
* @param countdown True if we need the countdown values false otherwise.
* @return The snapshot.
*/
@SqlQuery("SELECT"
+ " SUM(CASE WHEN TEST_RESULT = 0 THEN 1 ELSE 0 END) as failed,"
+ " SUM(CASE WHEN TEST_RESULT = 1 THEN 1 ELSE 0 END) as aborted,"
+ " SUM(CASE WHEN TEST_RESULT = 2 THEN 1 ELSE 0 END) as suppressed,"
+ " SUM(CASE WHEN TEST_RESULT = 3 THEN 1 ELSE 0 END) as succeeded "
+ "FROM LAUNCH_STATISTICS "
+ "WHERE CONTEXT_NAME = :contextName"
+ " AND MATCHER_NAME = :matcherName"
+ " AND COUNTDOWN = :countdown")
@RegisterRowMapper(H2BackedStageStatisticsSnapshotMapper.class)
@Transaction(value = TransactionIsolationLevel.READ_COMMITTED, readOnly = true)
StageStatisticsSnapshot getSnapshot(@Bind("contextName") String contextName,
@Bind("matcherName") String matcherName,
@Bind("countdown") boolean countdown);
/**
* Mapper class for calling the {@link StageStatisticsSnapshot} constructor properly.
*/
class H2BackedStageStatisticsSnapshotMapper implements RowMapper<StageStatisticsSnapshot> {
@Override
public StageStatisticsSnapshot map(final ResultSet rs, final StatementContext ctx) throws SQLException {
return new DefaultStageStatisticsSnapshot(
rs.getInt("failed"),
rs.getInt("succeeded"),
rs.getInt("aborted"),
rs.getInt("suppressed"));
}
}
}
| 44.751592 | 112 | 0.628523 |
904a3adf85464ee069ded3ff0ba680668dfa4a58 | 150 | package com.xiaohuzhou.server.handler;
/**
* @Auther: ZhouXiaoHu
* @Date: 2019/5/26
* @Description:
*/
public class MichiProtocServerHandler {
}
| 15 | 39 | 0.706667 |
330b8287fdccc538556297ec4b2375f0edf8fd42 | 2,474 | package com.sakila.entities;
// Generated Nov 10, 2017 10:25:35 AM by Hibernate Tools 4.3.5.Final
import java.util.Date;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import static javax.persistence.GenerationType.IDENTITY;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
/**
* Inventory generated by hbm2java
*/
@Entity
@Table(name = "inventory", catalog = "sakila")
public class Inventory implements java.io.Serializable {
private Integer inventoryId;
private Film film;
private Store store;
private Date lastUpdate;
private Set<Rental> rentals = new HashSet<Rental>(0);
public Inventory() {
}
public Inventory(Film film, Store store, Date lastUpdate) {
this.film = film;
this.store = store;
this.lastUpdate = lastUpdate;
}
public Inventory(Film film, Store store, Date lastUpdate, Set<Rental> rentals) {
this.film = film;
this.store = store;
this.lastUpdate = lastUpdate;
this.rentals = rentals;
}
@Id
@GeneratedValue(strategy = IDENTITY)
@Column(name = "inventory_id", unique = true, nullable = false)
public Integer getInventoryId() {
return this.inventoryId;
}
public void setInventoryId(Integer inventoryId) {
this.inventoryId = inventoryId;
}
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "film_id", nullable = false)
public Film getFilm() {
return this.film;
}
public void setFilm(Film film) {
this.film = film;
}
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "store_id", nullable = false)
public Store getStore() {
return this.store;
}
public void setStore(Store store) {
this.store = store;
}
@Temporal(TemporalType.TIMESTAMP)
@Column(name = "last_update", nullable = false, length = 19)
public Date getLastUpdate() {
return this.lastUpdate;
}
public void setLastUpdate(Date lastUpdate) {
this.lastUpdate = lastUpdate;
}
@OneToMany(fetch = FetchType.LAZY, mappedBy = "inventory")
public Set<Rental> getRentals() {
return this.rentals;
}
public void setRentals(Set<Rental> rentals) {
this.rentals = rentals;
}
}
| 24.49505 | 82 | 0.711803 |
d198e7ac298d645816bcede40843fb37638f0625 | 1,966 | package org.txazo.java.concurrency.thread;
import org.junit.Test;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class ThreadLocalTest {
/**
* VM Args: -server -verbose:gc -Xms100M -Xmx100M
*/
@Test
public void test() {
for (int i = 0; i < 100; i++) {
newThreadLocal();
}
}
private void newThreadLocal() {
ThreadLocal threadLocal = new ThreadLocal<byte[]>() {
@Override
protected byte[] initialValue() {
return new byte[1024 * 1024];
}
};
threadLocal.get();
}
/**
* VM Args: -server -verbose:gc -Xms100M -Xmx100M -Xmn50M
*/
@Test
public void test1() throws Exception {
ThreadLocal threadLocal = new ThreadLocal();
ExecutorService executor = Executors.newFixedThreadPool(1);
executor.submit(() ->
threadLocal.set(new byte[1024 * 1024 * 10])
);
Thread.sleep(1000);
System.gc();
executor.submit(() ->
threadLocal.remove()
);
Thread.sleep(1000);
System.gc();
}
/**
* VM Args: -server -verbose:gc -Xms100M -Xmx100M -Xmn50M
*/
@Test
public void testThreadLocal() {
ThreadLocal threadLocal = new DataThreadLocal();
threadLocal.set(new byte[1024 * 1024 * 10]);
System.gc();
threadLocal = null;
// key被回收, value未被回收
System.gc();
}
private class DataThreadLocal extends ThreadLocal {
private byte[] data = new byte[1024 * 1024 * 10];
}
@Test
public void test3() throws Exception {
int length = 100;
ThreadLocal[] threadLocals = new ThreadLocal[length];
for (int i = 0; i < length; i++) {
threadLocals[i] = new ThreadLocal();
threadLocals[i].set(1);
}
System.in.read();
}
}
| 23.129412 | 67 | 0.546287 |
c489a66d15465483a53336cefdb4b0083ab035b3 | 697 | import javax.swing.JOptionPane;
public class LoteDeTerra {
public static void main (String [] args) {
String recebe = "";
float largura,comprimento,area;
try{
recebe = JOptionPane.showInputDialog("Informe o valor da largura :");
largura = Float.parseFloat(recebe);
recebe = JOptionPane.showInputDialog("Informe o valor do comprimento :");
comprimento = Float.parseFloat(recebe);
area = largura * comprimento;
JOptionPane.showMessageDialog(null,"A área total do do lote é de: "+area);
}
catch (NumberFormatException erro) {
JOptionPane.showMessageDialog(null,"Houve erro na conversao, digite apenas caracteres numericos"+erro.toString());
}
System.exit(0);
}
} | 31.681818 | 116 | 0.728838 |
b421165252dfa089f0b7241602c8b4f2348c8b28 | 1,180 | package amu.zhcet.firebase.messaging.token;
import amu.zhcet.data.user.fcm.UserFcmTokenRepository;
import amu.zhcet.firebase.messaging.FirebaseErrorParsingUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.lang.NonNull;
import org.springframework.stereotype.Service;
@Slf4j
@Service
public class MessagingTokenDetachService {
private final UserFcmTokenRepository userFcmTokenRepository;
public MessagingTokenDetachService(UserFcmTokenRepository userFcmTokenRepository) {
this.userFcmTokenRepository = userFcmTokenRepository;
}
public void detachToken(@NonNull String token, @NonNull FirebaseErrorParsingUtils.Reason reason) {
final String reasonString = reason.getJson();
userFcmTokenRepository
.findByFcmToken(token)
.map(userFcmToken -> {
log.warn("Deleting FCM token {} for user {} because {}", token, userFcmToken.getUserId(), reasonString);
userFcmToken.setDisabled(true);
userFcmToken.setReason(reasonString);
return userFcmToken;
}).ifPresent(userFcmTokenRepository::save);
}
}
| 36.875 | 124 | 0.710169 |
1436b5f8c8672c08445fefcc9c2c793d3be3437f | 4,193 | package org.hadatac.hasneto.loader;
import java.util.HashMap;
import java.util.Map;
public class Loader {
private static boolean clean = false;
private static boolean showHelp = false;
private static boolean loadOntology = false;
private static boolean loadXls = false;
private static boolean verbose = false;
private static Map<String, String> argsMap = new HashMap<String, String>();
private static MetadataContext metadata = null;
public static MetadataContext getMetadataContext() {
return metadata;
}
private static void printHelp() {
System.out.println("Usage: hasnetoloader [options] -u username -p password -k knowldgeBaseURL[-i inputXLS]");
System.out.println(" -i inputXLS: generate ttl and load it into knowledge base;");
System.out.println(" inputXLS parsing warnings and errors are printed as they");
System.out.println(" are identified, if any");
System.out.println(" -c : clears knowldge base");
System.out.println(" -o : loads associated ontologies");
System.out.println(" -v : verbose mode on, including curl's outputs");
System.out.println(" -h : this help");
System.out.println("");
System.out.println("Example: hasnetoloader -c -o -u user -p abcde1234 -k http://localhost/slor4 -i myspreadsheet.xlsx ");
System.out.println(" this command will clear the knowledgbase, load associated ontologies, convert myspreadsheet.xlsx");
System.out.println(" into turtle (ttl), and load the turtle into the knowledgebase.");
}
private static boolean parseArguments(String[] args) {
if (args.length == 0) {
printHelp();
return false;
}
for (int i=0; i < args.length; i++) {
args[i] = args[i].toLowerCase().trim();
if ( (!args[i].equals("-i")) &&
(!args[i].equals("-c")) &&
(!args[i].equals("-o")) &&
(!args[i].equals("-v")) &&
(!args[i].equals("-h")) &&
(!args[i].equals("-u")) &&
(!args[i].equals("-p")) &&
(!args[i].equals("-k")) ) {
System.out.println("Argument " + args[i] + " is invalid.\n");
return false;
}
if (args[i].equals("-c")) {
clean = true;
}
if (args[i].equals("-o")) {
loadOntology = true;
}
if (args[i].equals("-i")) {
loadXls = true;
}
if (args[i].equals("-v")) {
verbose = true;
}
if (args[i].equals("-h")) {
showHelp = true;
}
if ( (args[i].equals("-i")) ||
(args[i].equals("-u")) ||
(args[i].equals("-p")) ||
(args[i].equals("-k")) ) {
if (i == (args.length - 1)) {
System.out.println("Argument " + args[i] + " misses associated value.\n");
return false;
}
if (args[i + 1].startsWith("-")) {
System.out.println("Argument " + args[i] + " misses associated value.\n");
return false;
}
argsMap.put(args[i], args[i + 1]);
i++;
}
}
return true;
}
private static boolean validArguments (String[] args) {
if (!parseArguments(args)) {
return false;
}
if (argsMap.get("-u") == null) {
System.out.println("Argument -u is missing.\n");
return false;
}
if (argsMap.get("-p") == null) {
System.out.println("Argument -p is missing.\n");
return false;
}
if (argsMap.get("-k") == null) {
System.out.println("Argument -k is missing.\n");
return false;
}
return true;
}
public static void main(String[] args) {
if (validArguments(args)) {
if (showHelp) {
printHelp();
} else {
NameSpaces.getInstance();
if (verbose) {
System.out.println("Verbose mode is on");
}
metadata = new MetadataContext(argsMap.get("-u"), argsMap.get("-p"), argsMap.get("-k"), verbose);
if (clean) {
System.out.println("Executing CLEAN");
metadata.clean();
System.out.println("");
}
if (loadOntology) {
System.out.println("Executing LOADONTOLOGY");
metadata.loadOntologies();
System.out.println("");
}
if (loadXls) {
System.out.println("Executing LOADXLS");
String ttl = "";
ttl = SpreadsheetProcessing.generateTTL(argsMap.get("-i"));
//System.out.println(ttl);
}
}
}
}
}
| 29.118056 | 130 | 0.591223 |
3b0f304ec98ea85dadea3c5ef92389faf3f587bc | 301 | package warmup;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
class SimpleArraySumTest {
@Test
void simpleArraySum() {
// 1 2 3 4 10 11
int[] testArray = {1, 2, 3, 4, 10, 11};
Assertions.assertEquals(SimpleArraySum.simpleArraySum(testArray), 31);
}
} | 21.5 | 74 | 0.694352 |
08cc752c5b9419ad5be47f4fd955677374bd3187 | 6,887 | package com.android.deskclock;
import android.content.Context;
import android.util.AttributeSet;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
/**
* This class adjusts the locations of children buttons and text of this view group by adjusting the
* margins of each item. The left and right buttons are aligned with the bottom of the circle. The
* stop button and label text are located within the circle with the stop button near the bottom and
* the label text near the top. The maximum text size for the label text view is also calculated.
*/
public class CircleButtonsLayout extends FrameLayout {
private Context mContext;
private int mCircleTimerViewId;
private int mResetAddButtonId;
private int mLabelId;
private int mLabelTextId;
private float mStrokeSize;
private float mDiamOffset;
private CircleTimerView mCtv;
private ImageButton mResetAddButton;
private FrameLayout mLabel;
private TextView mLabelText;
@SuppressWarnings("unused")
public CircleButtonsLayout(Context context) {
this(context, null);
mContext = context;
}
public CircleButtonsLayout(Context context, AttributeSet attrs) {
super(context, attrs);
mContext = context;
}
public void setCircleTimerViewIds(int circleTimerViewId, int stopButtonId, int labelId, int labelTextId) {
mCircleTimerViewId = circleTimerViewId;
mResetAddButtonId = stopButtonId;
mLabelId = labelId;
mLabelTextId = labelTextId;
float dotStrokeSize = mContext.getResources().getDimension(R.dimen.circletimer_dot_size);
float markerStrokeSize =
mContext.getResources().getDimension(R.dimen.circletimer_marker_size);
mStrokeSize = mContext.getResources().getDimension(R.dimen.circletimer_circle_size);
mDiamOffset = Utils.calculateRadiusOffset(mStrokeSize, dotStrokeSize, markerStrokeSize) * 2;
}
@Override
public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
// We must call onMeasure both before and after re-measuring our views because the circle
// may not always be drawn here yet. The first onMeasure will force the circle to be drawn,
// and the second will force our re-measurements to take effect.
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
remeasureViews();
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
protected void remeasureViews() {
if (mCtv == null) {
mCtv = (CircleTimerView) findViewById(mCircleTimerViewId);
if (mCtv == null) {
return;
}
mResetAddButton = (ImageButton) findViewById(mResetAddButtonId);
mLabel = (FrameLayout) findViewById(mLabelId);
mLabelText = (TextView) findViewById(mLabelTextId);
}
int frameWidth = mCtv.getMeasuredWidth();
int frameHeight = mCtv.getMeasuredHeight();
int minBound = Math.min(frameWidth, frameHeight);
int circleDiam = (int) (minBound - mDiamOffset);
if (mResetAddButton != null) {
final MarginLayoutParams resetAddParams = (MarginLayoutParams) mResetAddButton
.getLayoutParams();
resetAddParams.bottomMargin = circleDiam / 6;
if (minBound == frameWidth) {
resetAddParams.bottomMargin += (frameHeight - frameWidth) / 2;
}
}
if (mLabel != null) {
// label will be null if this is a stopwatch, which does not have a label.
MarginLayoutParams labelParams = (MarginLayoutParams) mLabel.getLayoutParams();
labelParams.topMargin = circleDiam/6;
if (minBound == frameWidth) {
labelParams.topMargin += (frameHeight-frameWidth)/2;
}
/* The following formula has been simplified based on the following:
* Our goal is to calculate the maximum width for the label frame.
* We may do this with the following diagram to represent the top half of the circle:
* ___
* . | .
* ._________| .
* . ^ | .
* / x | \
* |_______________|_______________|
*
* where x represents the value we would like to calculate, and the final width of the
* label will be w = 2 * x.
*
* We may find x by drawing a right triangle from the center of the circle:
* ___
* . | .
* ._________| .
* . . | .
* / . | }y \
* |_____________.t|_______________|
*
* where t represents the angle of that triangle, and y is the height of that triangle.
*
* If r = radius of the circle, we know the following trigonometric identities:
* cos(t) = y / r
* and sin(t) = x / r
* => r * sin(t) = x
* and sin^2(t) = 1 - cos^2(t)
* => sin(t) = +/- sqrt(1 - cos^2(t))
* (note: because we need the positive value, we may drop the +/-).
*
* To calculate the final width, we may combine our formulas:
* w = 2 * x
* => w = 2 * r * sin(t)
* => w = 2 * r * sqrt(1 - cos^2(t))
* => w = 2 * r * sqrt(1 - (y / r)^2)
*
* Simplifying even further, to mitigate the complexity of the final formula:
* sqrt(1 - (y / r)^2)
* => sqrt(1 - (y^2 / r^2))
* => sqrt((r^2 / r^2) - (y^2 / r^2))
* => sqrt((r^2 - y^2) / (r^2))
* => sqrt(r^2 - y^2) / sqrt(r^2)
* => sqrt(r^2 - y^2) / r
* => sqrt((r + y)*(r - y)) / r
*
* Placing this back in our formula, we end up with, as our final, reduced equation:
* w = 2 * r * sqrt(1 - (y / r)^2)
* => w = 2 * r * sqrt((r + y)*(r - y)) / r
* => w = 2 * sqrt((r + y)*(r - y))
*/
// Radius of the circle.
int r = circleDiam / 2;
// Y value of the top of the label, calculated from the center of the circle.
int y = frameHeight / 2 - labelParams.topMargin;
// New maximum width of the label.
double w = 2 * Math.sqrt((r + y) * (r - y));
mLabelText.setMaxWidth((int) w);
}
}
}
| 43.866242 | 111 | 0.553652 |
6d04ced2f2dc4e16d5f1e72997c0cd0bb4107d7f | 1,356 | package org.constantgatherer;
import org.constantgatherer.model.Gatherer;
import org.constantgatherer.model.GathererFragment;
import org.constantgatherer.model.GathererType;
import org.constantgatherer.model.webdriver.Command;
import org.constantgatherer.model.webdriver.CommandType;
/**
* User: ggomes
* Date: 12-01-2014
* Time: 23:07
* Copyright Tango Telecom 2014
*/
public class Test {
public static Gatherer createMockSpotConfig(){
String rnd = String.valueOf(Math.random() * 1000);
Gatherer gatherer = new Gatherer();
gatherer.setName("world_clock"+rnd);
gatherer.setType(GathererType.SCRAPER);
GathererFragment gathererFragment = new GathererFragment();
gathererFragment.setVisibility("static");
gathererFragment.setName("time");
gatherer.getFragments().add(gathererFragment);
Command command1 = new Command();
command1.setCommandType(CommandType.OPEN);
command1.setTarget("http://www.timeanddate.com/worldclock/city.html?n=4");
Command command2 = new Command();
command2.setCommandType(CommandType.GET_TEXT);
command2.setTarget("strong.big");
gathererFragment.getCommands().add(command1);
gathererFragment.getCommands().add(command2);
return gatherer;
}
}
| 34.769231 | 83 | 0.69174 |
5bb789ef4e02be368ab358580d18b464c537ec2e | 9,091 | /****************************************************************************************************************
* Developer: Minhas Kamal(BSSE-0509, IIT, DU) *
* Date: 04-Jan-2014 *
* Modified: 01-Jan-2015 *
****************************************************************************************************************/
package com.minhasKamal.ultimateCalculator.calculators.unitConverter;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.io.IOException;
import java.util.Arrays;
import javax.swing.AbstractAction;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JComponent;
import javax.swing.JTextField;
import javax.swing.KeyStroke;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import com.minhasKamal.ultimateCalculator.mainFrame.UltimateCalculatorFrame;
import com.minhasKamal.ultimateCalculator.notifications.message.Message;
import com.minhasKamal.ultimateCalculator.utils.fileIO.FileIO;
/**
* A Unit Converter
*
* @author Minhas Kamal
*/
public class UnitConverter extends UltimateCalculatorFrame{
//**
// Variable Declaration #*******D*******#
//**
@SuppressWarnings("rawtypes")
private JComboBox jCBoxTypeSelection;
@SuppressWarnings("rawtypes")
private JComboBox[] jComboBoxType;
private JTextField[] jTFieldIO;
//other variables
private int SelectedIndex;
private UnitConverterOperation.UnitConverter[] valuesEnum;
private int from, to;
private boolean buttonPressed;
// End of Variable Declaration #_______D_______#
/***##Constructor##***/
public UnitConverter() {
SelectedIndex=1;
valuesEnum = UnitConverterOperation.Length.values();
from=1;
to=1;
buttonPressed=false;
initialComponent();
super.jCBItemMode[4].setSelected(true);
}
/**
* Method for Initializing all the GUI variables and placing them all to specific space on
* the frame. It also specifies criteria of the main frame.
*/
@SuppressWarnings({ "serial" })
private void initialComponent() {
// GUI Initialization
// GUI Declaration
UnitConverterGui unitConvgui = new UnitConverterGui();
//instruction
try {
super.instruction = FileIO.readWholeFile(getClass().getResourceAsStream("/res/txts/" +
"UnitConverterInstruction.txt"));
} catch (IOException e) {
super.instruction = "EMPTY";
}
//**
// Assignation #*******A*******#
//**
jCBoxTypeSelection = unitConvgui.jCBoxTypeSelection;
jComboBoxType = unitConvgui.jComboBoxType;
jTFieldIO = unitConvgui.jTFieldIO;
JButton jButtonConvert = unitConvgui.jButtonConvert;
// End of Assignation #_______A_______#
//**
// Adding Action Events & Other Attributes #*******AA*******#
//**
jCBoxTypeSelection.addActionListener(this::jCBoxTypeSelectionActionPerformed);
jComboBoxType[0].addActionListener(this::jComboBoxTypeFromActionPerformed);
jComboBoxType[1].addActionListener(this::jComboBoxTypeToActionPerformed);
jButtonConvert.addActionListener(evt -> {
buttonPressed=true;
jButtonConvertActionPerformed();
buttonPressed=false;
});
jButtonConvert.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).
put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER,0), "ENTER_pressed");
jButtonConvert.getActionMap().put("ENTER_pressed", new AbstractAction() {
public void actionPerformed(ActionEvent evt) {
buttonPressed=true;
jButtonConvertActionPerformed();
buttonPressed=false;
}
});
// End of Adding Action Events & Other Attributes #_______AA_______#
//setting criterion of the frame
super.gui.setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
super.gui.setTitle("Unit Converter");
super.gui.setBounds(230, 115, 350, 400);
super.gui.add(unitConvgui);
super.gui.setResizable(false);
super.gui.setLayout(null);
super.gui.setFocusable(true);
}
//**
// Action Events #*******AE*******#
//**
//Mode
@SuppressWarnings({ "unchecked", "rawtypes" })
private void jCBoxTypeSelectionActionPerformed(ActionEvent evt){
SelectedIndex=jCBoxTypeSelection.getSelectedIndex()+1;
if(SelectedIndex==1){
valuesEnum = UnitConverterOperation.Length.values();
//Setting types
jComboBoxType[0].setModel(new DefaultComboBoxModel(new String[] {"Angstrom", "Nanometer", "Micron",
"Millimeter", "Centimeter", "Meter", "KiloMeter", "Inch", "Feet", "Yard", "Nautical Mile", "Mile",
"Rod"}));
jComboBoxType[1].setModel(new DefaultComboBoxModel(new String[] {"Angstrom", "Nanometer", "Micron",
"Millimeter", "Centimeter", "Meter", "KiloMeter", "Inch", "Feet", "Yard", "Nautical Mile", "Mile",
"Rod"}));
}else if(SelectedIndex==2){
valuesEnum = UnitConverterOperation.Weight.values();
//Setting types
jComboBoxType[0].setModel(new DefaultComboBoxModel(new String[] {"Milligram", "Gram", "Kilogram",
"Tonne", "Ounce", "Pound", "Carat"}));
jComboBoxType[1].setModel(new DefaultComboBoxModel(new String[] {"Milligram", "Gram", "Kilogram",
"Tonne", "Ounce", "Pound", "Carat"}));
}else if(SelectedIndex==3){
valuesEnum = UnitConverterOperation.Temperature.values();
//Setting types
jComboBoxType[0].setModel(new DefaultComboBoxModel(new String[] {"Celsius", "Fahrenheit", "Kelvin"}));
jComboBoxType[1].setModel(new DefaultComboBoxModel(new String[] {"Celsius", "Fahrenheit", "Kelvin"}));
}else if(SelectedIndex==4){
//Setting types
jComboBoxType[0].setModel(new DefaultComboBoxModel(new String[] {"Square Centimeter", "Square Meter",
"Hectare", "Square Kilometer", "Square Inch", "Square Feet", "Square Yard", "Square Mile", "Katha",
"Bigha", "Satak", "Acre"}));
jComboBoxType[1].setModel(new DefaultComboBoxModel(new String[] {"Square Centimeter", "Square Meter",
"Hectare", "Square Kilometer", "Square Inch", "Square Feet", "Square Yard", "Square Mile", "Katha",
"Bigha", "Satak", "Acre"}));
}else if(SelectedIndex==5){
valuesEnum = UnitConverterOperation.Volume.values();
//Setting types
jComboBoxType[0].setModel(new DefaultComboBoxModel(new String[] {"Cubic Centimeter", "Cubic Meter",
"Cubic Inch", "Cubic Feet", "Cubic Yard", "Liter", "Gallon(UK)", "Gallon(US)"}));
jComboBoxType[1].setModel(new DefaultComboBoxModel(new String[] {"Cubic Centimeter", "Cubic Meter",
"Cubic Inch", "Cubic Feet", "Cubic Yard", "Liter", "Gallon(UK)", "Gallon(US)"}));
}else if(SelectedIndex==6){
valuesEnum = UnitConverterOperation.Time.values();
//Setting types
jComboBoxType[0].setModel(new DefaultComboBoxModel(new String[] {"Nanosecond", "Millisecond",
"Second", "Minute", "Hour", "Day" , "Week"}));
jComboBoxType[1].setModel(new DefaultComboBoxModel(new String[] {"Nanosecond", "Millisecond",
"Second", "Minute", "Hour", "Day" , "Week"}));
}else if(SelectedIndex==7){
valuesEnum = UnitConverterOperation.Energy.values();
//Setting types
jComboBoxType[0].setModel(new DefaultComboBoxModel(new String[] {"Joule", "Kilojoule",
"Calorie", "Kilocalorie", "Electron-Volts", "Foot-Pound"}));
jComboBoxType[1].setModel(new DefaultComboBoxModel(new String[]{"Joule", "Kilojoule",
"Calorie", "Kilocalorie", "Electron-Volts", "Foot-Pound"}));
}else if(SelectedIndex==8){
valuesEnum = UnitConverterOperation.Power.values();
//Setting types
jComboBoxType[0].setModel(new DefaultComboBoxModel(new String[] {"Watt", "Kilowatt",
"Horsepower" }));
jComboBoxType[1].setModel(new DefaultComboBoxModel(new String[] {"Watt", "Kilowatt",
"Horsepower" }));
}
//initializing
from=1;
to=1;
jTFieldIO[1].setText("");
}
//Combo Box Item//
private void jComboBoxTypeFromActionPerformed(ActionEvent evt){
from=jComboBoxType[0].getSelectedIndex()+1;
jButtonConvertActionPerformed();
}
private void jComboBoxTypeToActionPerformed(ActionEvent evt){
to=jComboBoxType[1].getSelectedIndex()+1;
jButtonConvertActionPerformed();
}
//Convert Button//
private void jButtonConvertActionPerformed(){
try{
double input=Double.parseDouble(jTFieldIO[0].getText());
double output=UnitConverterOperation.Convert(valuesEnum[from-1], valuesEnum[to-1], input);
jTFieldIO[1].setText(output+"");
}catch(NumberFormatException e){
if(buttonPressed) new Message("Math Error!\n Please input correctly.", 420);
else jTFieldIO[1].setText("");
}
}
/********* Main Method *********/
public static void main(String[] args) {
/*// Set the NIMBUS look and feel //*/
try {
UIManager.setLookAndFeel("javax.swing.plaf.nimbus.NimbusLookAndFeel");
} catch (ClassNotFoundException| InstantiationException| IllegalAccessException| UnsupportedLookAndFeelException ex) {
// do nothing if operation is unsuccessful
}
/* Create */
new UnitConverter();
}
}
| 36.219124 | 120 | 0.676933 |
3051a3c285b90ad63b17ac968ab6a673f48e3c4f | 3,533 | package ui.client.controllers;
import javafx.application.Platform;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.geometry.Insets;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Priority;
import javafx.scene.layout.VBox;
import play.Playlist;
import play.Song;
import rmi.ClientContainer;
import ui.Message;
import ui.ResourceHandler;
import ui.SongButton;
import ui.UITools;
public class EditPlaylistController implements IController {
@FXML private VBox songContainer;
@FXML private TextField tbDescription;
@FXML private TextField tbName;
@FXML private TextField tbSearch;
@FXML private TextField tbSong;
private Playlist playlist;
private ClientContainer container;
private UITools.UIManager uiManager;
public void initialize() {
uiManager = new UITools.UIManager();
container = ResourceHandler.getContainer();
if(container.getSelectedPlaylist() == null) {
playlist = new Playlist("", container.getUser());
container.uploadPlaylist(playlist);
container.setSelectedPlaylist(playlist);
} else {
playlist = container.getSelectedPlaylist();
tbName.setText(playlist.getName());
tbDescription.setText(playlist.getDescription());
for (Song s : playlist.getSongs()) {
addSongUI(s);
}
}
container.setController(this);
}
public void addSong(ActionEvent actionEvent) {
uiManager.openInNewWindow("newsong.fxml", "Add Song");
}
public void savePlaylist(ActionEvent actionEvent) {
String name = tbName.getText();
String description = tbDescription.getText();
if(container.updatePlaylist(name, description)) {
uiManager.loadFXML("menu.fxml", "Menu");
}
else {
Message.show("Error", "Please enter a name");
}
}
public void backToMenu(ActionEvent actionEvent) {
uiManager.loadFXML("menu.fxml", "Menu");
}
public void removeSong(ActionEvent actionEvent) {
SongButton btn = (SongButton) actionEvent.getSource();
Song song = btn.getSong();
container.removeSong(playlist, song);
}
private void addSongUI(Song s) {
HBox root = new HBox();
root.getStyleClass().add("playlist");
AnchorPane pane = new AnchorPane();
Label songInfo = new Label(String.format("%s %s", s.getName(), s.getArtist()));
SongButton btn = new SongButton(s);
btn.getStyleClass().addAll("deletebutton");
btn.setText("x");
btn.setOnAction(this::removeSong);
AnchorPane.setBottomAnchor(songInfo, 5.0);
AnchorPane.setTopAnchor(songInfo, 5.0);
AnchorPane.setLeftAnchor(songInfo, 5.0);
AnchorPane.setRightAnchor(btn, 0.0);
pane.getChildren().addAll(songInfo, btn);
root.getChildren().add(pane);
HBox.setHgrow(pane, Priority.ALWAYS);
VBox.setMargin(root, new Insets(10, 0, 10, 0));
songContainer.getChildren().add(root);
}
private void displaySongs() {
songContainer.getChildren().clear();
for (Song s : playlist.getSongs()) {
addSongUI(s);
}
}
@Override
public void update() {
playlist = container.getSelectedPlaylist();
Platform.runLater(this::displaySongs);
}
}
| 32.412844 | 87 | 0.652703 |
daaa80334ef870e070f062cc25e2480f0cb3b06d | 7,402 | package org.aion.harness.tests.integ.multikernel;
import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.concurrent.TimeUnit;
import org.aion.harness.main.*;
import org.aion.harness.main.NodeConfigurations.DatabaseOption;
import org.aion.harness.main.NodeFactory.NodeType;
import org.aion.harness.result.Result;
import org.aion.harness.tests.integ.multikernel.BeaconHashSidechainTest;
import org.aion.harness.tests.integ.runner.exception.TestRunnerInitializationException;
import org.aion.harness.tests.integ.runner.internal.TestNodeManager;
import org.apache.commons.io.FileUtils;
/**
* Like {@link TestNodeManager} but with some modified functionality that
* {@link BeaconHashSidechainTest} specifically needs.
*/
public final class BeaconHashSidechainNodeManager {
private NodeType nodeType;
private LocalNode localNode;
private final String expectedKernelLocation;
private final String handedwrittenConfigs;
private static final String WORKING_DIR = System.getProperty("user.dir");
private static final long EXIT_LOCK_TIMEOUT = 3;
private static final TimeUnit EXIT_LOCK_TIMEOUT_UNIT = TimeUnit.MINUTES;
public BeaconHashSidechainNodeManager(NodeType nodeType) {
this.nodeType = nodeType;
if(nodeType == NodeType.JAVA_NODE) {
this.expectedKernelLocation = WORKING_DIR + "/aion";
this.handedwrittenConfigs = WORKING_DIR + "/test_resources/custom";
} else {
throw new UnsupportedOperationException("Unsupported kernel type. This manager only works for JAVA_NODE.");
}
}
public BeaconHashSidechainNodeManager(NodeType nodeType,
String expectedKernelLocation,
String handwrittenConfigs) {
this.nodeType = nodeType;
this.expectedKernelLocation = expectedKernelLocation;
this.handedwrittenConfigs = handwrittenConfigs;
}
/**
* Starts up a local node of the specified type if no node has currently been started.
*
* If anything goes wrong this method will throw an exception to halt the runner.
*/
public void startLocalNode(boolean mining, boolean clearDb) throws Exception {
if (this.localNode == null) {
// Verify the kernel is in the expected location and overwrite its config & genesis files.
checkKernelExistsAndOverwriteConfigs();
if (this.nodeType != NodeType.RUST_NODE) {
if (clearDb) {
clearDb();
}
Path path = Paths.get(expectedKernelLocation + "/custom/config/config.xml");
Charset charset = StandardCharsets.UTF_8;
// hackily set the mining
String content = new String(Files.readAllBytes(path), charset);
if (mining) {
content = content.replaceAll("<mining>false</mining>", "<mining>true</mining>");
} else {
content = content.replaceAll("<mining>true</mining>", "<mining>false</mining>");
}
Files.write(path, content.getBytes(charset));
} else {
if(clearDb){
clearRustDb();
}
}
// Acquire the system-wide lock.
ProhibitConcurrentHarness.acquireTestLock();
// Initialize the node.
NodeConfigurations configurations = NodeConfigurations.alwaysUseBuiltKernel(
Network.CUSTOM, expectedKernelLocation, DatabaseOption.PRESERVE_DATABASE);
LocalNode node;
if (this.nodeType != NodeType.RUST_NODE || mining) {
node = NodeFactory.getNewLocalNodeInstance(nodeType);
} else{
node = NodeFactory.getNewLocalNodeInstanceWithoutMiner(nodeType);
}
node.configure(configurations);
Result result = node.initialize();
if (!result.isSuccess()) {
throw new TestRunnerInitializationException("Failed to initialize the node: " + result.getError());
}
// Start the node.
result = node.start();
if (!result.isSuccess()) {
throw new TestRunnerInitializationException("Failed to start the node: " + result.getError());
}
this.localNode = node;
} else {
throw new IllegalStateException("Attempted to start running a local node but one is already running!");
}
}
/**
* Stops a local node if one is currently running.
*/
public void shutdownLocalNode() throws Exception {
if (isKernelRunning()) {
try {
this.localNode.blockingStop(EXIT_LOCK_TIMEOUT, EXIT_LOCK_TIMEOUT_UNIT);
} catch (Throwable e) {
e.printStackTrace();
} finally {
ProhibitConcurrentHarness.releaseTestLock();
this.localNode = null;
}
} else {
throw new IllegalStateException("Attempted to stop running a local node but no node is currently running!");
}
}
/**
* Returns a newly created node listener that is listening to the current running local node.
*/
public NodeListener newNodeListener() {
if (this.localNode != null) {
return NodeListener.listenTo(this.localNode);
} else {
throw new IllegalStateException("Attempted to get a new listener but no local node is currently running!");
}
}
private void checkKernelExistsAndOverwriteConfigs() throws IOException {
if (!kernelExists()) {
throw new TestRunnerInitializationException("Expected to find a kernel at: " + expectedKernelLocation);
}
overwriteConfigAndGenesis();
}
private boolean kernelExists() {
File kernel = new File(expectedKernelLocation);
return kernel.exists() && kernel.isDirectory();
}
private void overwriteConfigAndGenesis() throws IOException {
if(nodeType == NodeType.RUST_NODE) {
overwriteIfTargetDirExists(new File(handedwrittenConfigs),
new File(expectedKernelLocation + "/custom"));
} else if(nodeType == NodeType.JAVA_NODE
|| nodeType == NodeType.PROXY_JAVA_NODE ) {
FileUtils.copyDirectory(new File(handedwrittenConfigs),
new File(expectedKernelLocation + "/custom"));
} else {
throw new IllegalStateException("Unsupported kernel");
}
}
private static void overwriteIfTargetDirExists(File source, File target) throws IOException {
if (target.exists()) {
FileUtils.copyDirectory(source, target);
}
}
public void clearDb() throws IOException {
File db = new File(expectedKernelLocation + "/custom/database");
FileUtils.deleteDirectory(db);
}
public void clearRustDb() throws IOException {
File db = new File(expectedKernelLocation + "/data");
FileUtils.deleteDirectory(db);
}
public boolean isKernelRunning() {
return this.localNode != null;
}
}
| 38.957895 | 120 | 0.633613 |
613fe339c1b15c6e6f15025465c86145e442f592 | 8,006 | package TicTacToe.build1;
import processing.core.PApplet;
public class TicTacToeApp extends PApplet
{
Grid[][] grid = new Grid[3][3];
int size = 600; // Universal Size :) 600 is default.
int gridSize = size / 3 - 1;
boolean xTurn; // X always starts first.
int gameScreen = 0; // 0 = game; 1 = winScreen /*This is done so that the mouse inputs can reset the game.
/*|--> see mouseReleased() line:49.*/
@Override
public void settings()
{
size(size, size);
}
public void init()
{
for (int i = 0; i < 3; ++i)
{
for (int j = 0; j < 3; ++j)
{
grid[i][j].setXON('N');
}
}
gameScreen = 0;
xTurn = true;
}
@Override
public void setup()
{
background(0);
for (int i = 0; i < 3; ++i)
{
for (int j = 0; j < 3; ++j)
{
grid[i][j] = new Grid(i * gridSize, j * gridSize, gridSize, gridSize);
}
}
init();
}
@Override
public void mouseReleased()
{
if (gameScreen == 0)
{
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
if (grid[i][j].getXON() == 'N' &&
(mouseX > grid[i][j].getX() && mouseX < grid[i][j].getX() + grid[i][j].getSizeX()) &&
(mouseY > grid[i][j].getY() && mouseY < grid[i][j].getY() + grid[i][j].getSizeY()))
{
grid[i][j].mousePressed(xTurn);
grid[i][j].gridColor = color(90,90,90);
xTurn = !xTurn;
}
}
}
}
if (gameScreen == 1) // When winScreen(char Player) /*line: 131*/ is activated a noLoop() is called
{ // and gameScreen is set to 1. By changing gameScreen to 1, it tells
init(); // mouseReleased() to reset and start looping draw() again when mouse input is
loop(); // activated.
}
}
@Override
public void draw()
{
if (gameScreen == 0) //gameScreens are handy for menus too ;) but here it is not implemented.
{
for (int i = 0; i < 3; ++i)
{
for (int j = 0; j < 3; j++)
{
grid[i][j].draw();
grid[i][j].drawPlayerInput();
flashyButtons(i, j);
}
}
checkWinner();
}
}
private void flashyButtons(int x, int y) // this is just for fun, does exactly what it says, don't pay too much attention.
{
if((mouseX > grid[x][y].getX() && mouseX < grid[x][y].getX() + grid[x][y].getSizeX()) &&
(mouseY > grid[x][y].getY() && mouseY < grid[x][y].getY() + grid[x][y].getSizeY()))
grid[x][y].gridColor = color(60,60,60);
else
grid[x][y].gridColor = 0;
}
public void checkWinner()
{
boolean win = false;
char checkPlayer = 'X';
for(int i = 0; i < 2; ++i)
{
if ((grid[0][0].getXON() == checkPlayer && grid[0][1].getXON() == checkPlayer && grid[0][2].getXON() == checkPlayer) || //top to bottom from left to right.
(grid[1][0].getXON() == checkPlayer && grid[1][1].getXON() == checkPlayer && grid[1][2].getXON() == checkPlayer) ||
(grid[2][0].getXON() == checkPlayer && grid[2][1].getXON() == checkPlayer && grid[2][2].getXON() == checkPlayer) ||
(grid[0][0].getXON() == checkPlayer && grid[1][0].getXON() == checkPlayer && grid[2][0].getXON() == checkPlayer) || //left to right from top to bottom.
(grid[0][1].getXON() == checkPlayer && grid[1][1].getXON() == checkPlayer && grid[2][1].getXON() == checkPlayer) ||
(grid[0][2].getXON() == checkPlayer && grid[1][2].getXON() == checkPlayer && grid[2][2].getXON() == checkPlayer) ||
(grid[0][0].getXON() == checkPlayer && grid[1][1].getXON() == checkPlayer && grid[2][2].getXON() == checkPlayer) || // diagonals left to right from top to bottom
(grid[0][2].getXON() == checkPlayer && grid[1][1].getXON() == checkPlayer && grid[2][0].getXON() == checkPlayer))
{
winScreen(checkPlayer);
win = true;
}
checkPlayer = 'O';
}
checkPlayer = 'N';
if ((grid[0][0].getXON() != checkPlayer && grid[0][1].getXON() != checkPlayer && grid[0][2].getXON() != checkPlayer) && //top to bottom from left to right.
(grid[1][0].getXON() != checkPlayer && grid[1][1].getXON() != checkPlayer && grid[1][2].getXON() != checkPlayer) &&
(grid[2][0].getXON() != checkPlayer && grid[2][1].getXON() != checkPlayer && grid[2][2].getXON() != checkPlayer) && !win)
{
winScreen(checkPlayer);
}
}
void winScreen(char Player)
{
noLoop(); // The noLoop() here is important for the opacity of rect and to stop draw from well...
textAlign(CENTER, CENTER); // drawing grids all over our lovely winScreen() :)
textSize(gridSize / 2F);
fill(0, 180); //fill() has a second parameter for opacity --> see Processing Reference for more info.
rect(grid[0][1].getX(), grid[0][1].getY(), gridSize * 3 + 4, gridSize);
fill(255);
if (Player == 'N')
text("Draw!", width / 2F, height / 2F);
else
text(Player + " Wins!", width / 2F, height / 2F);
gameScreen = 1; // gameScreen now equals 1, mouseReleased has got the go ahead to reset the game
}
public static void main(String[] args)
{
PApplet.runSketch(new String[]{""}, new TicTacToeApp());
}
/*///////////////////////
//////////Grid//////////
/////////////////////*/
class Grid
{
float x;
float y;
float sizeX;
float sizeY;
char XON;
int gridColor = 0;
public Grid(float x, float y, float sizeX, float sizeY)
{
this.x = x;
this.y = y;
this.sizeX = sizeX;
this.sizeY = sizeY;
}
public float getX()
{
return x;
}
public float getY()
{
return y;
}
public float getSizeX()
{
return sizeX;
}
public float getSizeY()
{
return sizeY;
}
public char getXON()
{
return XON;
}
public void setXON(char nXON)
{
XON = nXON;
}
public void draw()
{
stroke(255);
fill(gridColor);
rect(x, y, sizeX, sizeY); // Can be simplified with square(x,y,size) to get rid of variable sizeY.
} // but decided to use rect(x,y,sizeX,sizeY) for more universal use. Menu
// buttons for example.
public void drawPlayerInput()
{
fill(255);
if(XON != 'N')
text(XON, x + sizeX / 2, y + sizeY / 2.5F);
}
public void mousePressed(boolean turn)
{
textAlign(CENTER, CENTER);
textSize(sizeY);
fill(255);
if (turn)
XON = 'X';
if (!turn)
XON = 'O';
}
}
}
| 35.114035 | 182 | 0.434424 |
a259d34cc0eafacaa90d7d63437a10fe79f96562 | 9,647 | /*
* Copyright 2002-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.webauthn4j.springframework.security.webauthn.sample.app.web;
import com.webauthn4j.data.client.challenge.Challenge;
import com.webauthn4j.springframework.security.WebAuthnRegistrationRequestValidationResponse;
import com.webauthn4j.springframework.security.WebAuthnRegistrationRequestValidator;
import com.webauthn4j.springframework.security.authenticator.WebAuthnAuthenticator;
import com.webauthn4j.springframework.security.authenticator.WebAuthnAuthenticatorImpl;
import com.webauthn4j.springframework.security.authenticator.WebAuthnAuthenticatorManager;
import com.webauthn4j.springframework.security.challenge.ChallengeRepository;
import com.webauthn4j.springframework.security.exception.PrincipalNotFoundException;
import com.webauthn4j.springframework.security.exception.WebAuthnAuthenticationException;
import com.webauthn4j.util.Base64UrlUtil;
import com.webauthn4j.util.UUIDUtil;
import com.webauthn4j.util.exception.WebAuthnException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationTrustResolver;
import org.springframework.security.authentication.AuthenticationTrustResolverImpl;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.provisioning.UserDetailsManager;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.Collections;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;
/**
* Login controller
*/
@SuppressWarnings("SameReturnValue")
@Controller
public class WebAuthnSampleController {
private final Log logger = LogFactory.getLog(getClass());
private static final String REDIRECT_LOGIN = "redirect:login";
private static final String FORWARD_SIGNUP = "redirect:signup";
private static final String VIEW_SIGNUP_SIGNUP = "signup/signup";
private static final String VIEW_DASHBOARD_DASHBOARD = "dashboard/dashboard";
private static final String VIEW_LOGIN_LOGIN = "login/login";
private static final String VIEW_LOGIN_AUTHENTICATOR_LOGIN = "login/authenticator-login";
private static final String VIEW_AUTHORIZED_CALLBACK = "authorized/callback";
@Autowired
private UserDetailsManager userDetailsManager;
@Autowired
private WebAuthnAuthenticatorManager webAuthnAuthenticatorManager;
@Autowired
private WebAuthnRegistrationRequestValidator registrationRequestValidator;
@Autowired
private ChallengeRepository challengeRepository;
@Autowired
private PasswordEncoder passwordEncoder;
private AuthenticationTrustResolver authenticationTrustResolver = new AuthenticationTrustResolverImpl();
@ModelAttribute
public void addAttributes(Model model, HttpServletRequest request) {
Challenge challenge = challengeRepository.loadOrGenerateChallenge(request);
model.addAttribute("webAuthnChallenge", Base64UrlUtil.encodeToString(challenge.getValue()));
model.addAttribute("webAuthnCredentialIds", getCredentialIds());
}
@GetMapping(value = "/")
public String root(RedirectAttributes redirectAttributes) {
return FORWARD_SIGNUP;
}
@GetMapping(value = "/dashboard")
public String index(RedirectAttributes redirectAttributes) {
return VIEW_DASHBOARD_DASHBOARD;
}
@GetMapping(value = "/signup")
public String signup(Model model) {
UserCreateForm userCreateForm = new UserCreateForm();
UUID userHandle = UUID.randomUUID();
String userHandleStr = Base64UrlUtil.encodeToString(UUIDUtil.convertUUIDToBytes(userHandle));
userCreateForm.setUserHandle(userHandleStr);
model.addAttribute("userForm", userCreateForm);
return VIEW_SIGNUP_SIGNUP;
}
@PostMapping(value = "/signup")
public String create(HttpServletRequest request, @Valid @ModelAttribute("userForm") UserCreateForm userCreateForm, BindingResult result, Model model, RedirectAttributes redirectAttributes) {
try {
if (result.hasErrors()) {
model.addAttribute("errorMessage", "Your input needs correction.");
logger.debug("User input validation failed.");
return VIEW_SIGNUP_SIGNUP;
}
WebAuthnRegistrationRequestValidationResponse registrationRequestValidationResponse;
try {
registrationRequestValidationResponse = registrationRequestValidator.validate(
request,
userCreateForm.getAuthenticator().getClientDataJSON(),
userCreateForm.getAuthenticator().getAttestationObject(),
userCreateForm.getAuthenticator().getTransports(),
userCreateForm.getAuthenticator().getClientExtensions()
);
}
catch (WebAuthnException | WebAuthnAuthenticationException e){
model.addAttribute("errorMessage", "Authenticator registration request validation failed. Please try again.");
logger.debug("WebAuthn registration request validation failed.", e);
return VIEW_SIGNUP_SIGNUP;
}
String username = userCreateForm.getUsername();
String password = passwordEncoder.encode(userCreateForm.getPassword());
boolean singleFactorAuthenticationAllowed = userCreateForm.isSingleFactorAuthenticationAllowed();
List<GrantedAuthority> authorities;
if(singleFactorAuthenticationAllowed){
authorities = Collections.singletonList(new SimpleGrantedAuthority("SINGLE_FACTOR_AUTHN_ALLOWED"));
}
else {
authorities = Collections.emptyList();
}
User user = new User(username, password, authorities);
WebAuthnAuthenticator authenticator = new WebAuthnAuthenticatorImpl(
"authenticator",
user.getUsername(),
registrationRequestValidationResponse.getAttestationObject().getAuthenticatorData().getAttestedCredentialData(),
registrationRequestValidationResponse.getAttestationObject().getAttestationStatement(),
registrationRequestValidationResponse.getAttestationObject().getAuthenticatorData().getSignCount(),
registrationRequestValidationResponse.getTransports(),
registrationRequestValidationResponse.getRegistrationExtensionsClientOutputs(),
registrationRequestValidationResponse.getAttestationObject().getAuthenticatorData().getExtensions()
);
try {
userDetailsManager.createUser(user);
webAuthnAuthenticatorManager.createAuthenticator(authenticator);
} catch (IllegalArgumentException ex) {
model.addAttribute("errorMessage", "Registration failed. The user may already be registered.");
logger.debug("Registration failed.", ex);
return VIEW_SIGNUP_SIGNUP;
}
}
catch (RuntimeException ex){
model.addAttribute("errorMessage", "Registration failed by unexpected error.");
logger.debug("Registration failed.", ex);
return VIEW_SIGNUP_SIGNUP;
}
redirectAttributes.addFlashAttribute("successMessage", "User registration finished.");
return REDIRECT_LOGIN;
}
@GetMapping(value = "/login")
public String login() {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (authenticationTrustResolver.isAnonymous(authentication)) {
return VIEW_LOGIN_LOGIN;
} else {
return VIEW_LOGIN_AUTHENTICATOR_LOGIN;
}
}
@GetMapping(value = "/authorized/callback", params = {"code", "state"})
public String authorizedCallback(@RequestParam("state") String state,
@RequestParam("code") String code,
Model model) {
// TODO: should validate the state parameter and need implementation of `Proof Key for Code Exchange`
model.addAttribute("authorizationCode", code);
return VIEW_AUTHORIZED_CALLBACK;
}
private List<String> getCredentialIds() {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
Object principal = authentication.getPrincipal();
if (principal == null || authenticationTrustResolver.isAnonymous(authentication)) {
return Collections.emptyList();
} else {
try {
List<WebAuthnAuthenticator> webAuthnAuthenticators = webAuthnAuthenticatorManager.loadAuthenticatorsByUserPrincipal(principal);
return webAuthnAuthenticators.stream()
.map(webAuthnAuthenticator -> Base64UrlUtil.encodeToString(webAuthnAuthenticator.getAttestedCredentialData().getCredentialId()))
.collect(Collectors.toList());
} catch (PrincipalNotFoundException e) {
return Collections.emptyList();
}
}
}
}
| 41.581897 | 191 | 0.805743 |
50ba7852886d66040967ebfea091ea8fedd7417e | 11,323 | package ch.dvbern.util.doctemplate.validator;
import java.awt.Desktop;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Stack;
import java.util.regex.Pattern;
import ch.dvbern.lib.doctemplate.common.DocTemplateException;
import ch.dvbern.util.doctemplate.validator.structure.RTFStructureParser;
import ch.dvbern.util.doctemplate.validator.structure.StructureNode;
import javafx.application.Application;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.control.Menu;
import javafx.scene.control.MenuBar;
import javafx.scene.control.MenuItem;
import javafx.scene.control.TextArea;
import javafx.scene.control.TreeItem;
import javafx.scene.control.TreeView;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.input.KeyCombination;
import javafx.scene.layout.BorderPane;
import javafx.stage.FileChooser;
import javafx.stage.FileChooser.ExtensionFilter;
import javafx.stage.Stage;
import net.sourceforge.rtf.UnsupportedRTFTemplate;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.xml.sax.SAXException;
import static java.nio.charset.StandardCharsets.UTF_8;
/**
* Main class for the doctemplate validator cli/gui
*
* @author Raphael Gosteli
*/
public class Validator extends Application {
/* Logger */
private static final Log LOG = LogFactory.getLog(Validator.class);
/* cli arguments */
private static final String NO_GUI_ARG = "--no-gui";
private static final Collection<String> SUPPORTED_FILE_EXTENSIONS = Collections.singletonList(".rtf");
private static final Pattern WHITESPACE_PATTERN = Pattern.compile(" ");
private static final Pattern BACKSLASH_PATTERN = Pattern.compile(
"\\\\");
/* fields */
private static boolean guiEnabled = true;
private static File file = null;
/* javafx objects */
private static Stage stage = null;
private static BorderPane root = null;
private static Stack<StructureNode> structureNodeStack = null;
private static TreeItem<String> rootTreeItem = null;
private static TextArea outputTextArea = null;
/**
* Entry point for the validator
*
* @param args the commandline arguments
*/
public static void main(String[] args) {
parseArguments(args);
/* launch the application in gui or cli mode */
if (guiEnabled) {
launch(args);
} else {
/* file "validation" */
if (file.exists() && file.isFile()) {
validateDoctemplate(file);
} else {
LOG.error("Specified file '" + file.getPath() + "' does not exist!");
System.exit(-1);
}
}
}
private static void parseArguments(String[] args) {
for (String arg : args) {
if (arg.equalsIgnoreCase(NO_GUI_ARG)) {
guiEnabled = false;
} else {
/* check if its a supported file extension */
for (String supportedFileExtension : SUPPORTED_FILE_EXTENSIONS) {
if (arg.endsWith(supportedFileExtension)) {
file = new File(arg);
break;
}
}
}
}
}
private static void validateDoctemplate(File f) {
resetOutputTextArea();
try {
FileInputStream fileInputStream = new FileInputStream(f);
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(fileInputStream, UTF_8));
RTFStructureParser structureParser = new RTFStructureParser();
/* parse the doctemplate */
structureNodeStack =
structureParser.parse(bufferedReader);
if (structureNodeStack.size() == 1) {
StructureNode rootStructureNode = structureNodeStack.get(0);
if (guiEnabled) {
/* update the tree view */
rootTreeItem.setValue(rootStructureNode.getKey());
rootTreeItem.getChildren().clear();
listNodes(rootStructureNode.getNodes(), rootTreeItem);
}
}
log("Structure valid!", false);
} catch (SAXException | IOException | UnsupportedRTFTemplate | DocTemplateException e) {
LOG.error(e);
log(e.getMessage(), true);
}
}
private static void listNodes(List<StructureNode> nodes, TreeItem<String> parentTreeItem) {
for (StructureNode node : nodes) {
/* tree item value string builder */
StringBuilder valueBuilder = new StringBuilder();
if (node.getType() != null) {
TreeItem<String> treeItem = new TreeItem<>();
switch (node.getType()) {
case DOCUMENT:
valueBuilder.append("Document");
break;
case IF:
valueBuilder.append("If");
treeItem.setGraphic(new ImageView(new Image("if.png")));
break;
case FIELD:
valueBuilder.append("Field");
treeItem.setGraphic(new ImageView(new Image("field.png")));
break;
case WHILE:
valueBuilder.append("Iteration");
treeItem.setGraphic(new ImageView(new Image("iteration.png")));
break;
}
valueBuilder.append(' ').append(node.getKey());
treeItem.setValue(valueBuilder.toString());
parentTreeItem.getChildren().add(treeItem);
/* start recursion if the node has child nodes */
if (node.getNodes() != null && !node.getNodes().isEmpty()) {
listNodes(node.getNodes(), treeItem);
}
}
}
}
private static void resetOutputTextArea() {
outputTextArea.setText("");
outputTextArea.setStyle("-fx-text-fill: #008000;");
}
private static void log(String s, boolean exception) {
if (exception) {
outputTextArea.setStyle("-fx-text-fill: #ff0000;");
}
outputTextArea.setText(s);
}
/**
* This method gets called if the application runs in gui mode
*
* @param primaryStage the entry point stage
*/
@Override
public void start(Stage primaryStage) {
stage = primaryStage;
constructUI();
/* stage initialization */
primaryStage.setTitle("doctemplate - Validator");
primaryStage.setScene(new Scene(root, 800, 600));
primaryStage.show();
}
private void constructUI() {
root = new BorderPane();
/* tree view */
rootTreeItem = new TreeItem<>("Root");
TreeView<String> treeView = new TreeView<>(rootTreeItem);
/* output */
outputTextArea = new TextArea();
outputTextArea.setEditable(false);
outputTextArea.setStyle("-fx-text-fill: #008000;");
outputTextArea.setStyle("-fx-font-family: Consolas, monospace;");
root.setTop(getMenuBar());
root.setLeft(treeView);
root.setCenter(outputTextArea);
}
private Node getMenuBar() {
Menu fileMenu = new Menu("File");
/* open file menu item */
MenuItem openFileItem = new MenuItem("Open");
openFileItem.setAccelerator(KeyCombination.valueOf("Ctrl+N"));
openFileItem.setOnAction(event -> {
FileChooser fileChooser = new FileChooser();
fileChooser.setTitle("Choose doctemplate document");
for (String supportedFileExtension : SUPPORTED_FILE_EXTENSIONS) {
fileChooser.getExtensionFilters().add(new ExtensionFilter(supportedFileExtension.substring(1) + ' '
+ "doctemplate",
'*' + supportedFileExtension));
}
file = fileChooser.showOpenDialog(stage);
if (file != null && file.canRead()) {
validateDoctemplate(file);
}
});
/* exit menu item */
MenuItem exitItem = new MenuItem("Exit");
exitItem.setOnAction(event -> {
System.exit(0);
});
fileMenu.getItems().add(openFileItem);
fileMenu.getItems().add(exitItem);
/* generate menu */
Menu generateMenu = new Menu("Generate");
MenuItem navigationDocumentItem = new MenuItem("Navigation document");
navigationDocumentItem.setAccelerator(KeyCombination.valueOf("Ctrl+G"));
navigationDocumentItem.setOnAction(event -> {
handleNavigationDocumentGeneration();
});
generateMenu.getItems().add(navigationDocumentItem);
MenuBar menuBar = new MenuBar();
menuBar.getMenus().add(fileMenu);
menuBar.getMenus().add(generateMenu);
return menuBar;
}
private void handleNavigationDocumentGeneration() {
/* check if the required fields are provided */
if (file != null && structureNodeStack != null) {
if (structureNodeStack.size() == 1) {
StructureNode rootStructureNode = structureNodeStack.get(0);
try {
/* create temp file */
File navigationFile = File.createTempFile(String.format("%s_navigation", file.getName()),
".rtf");
navigationFile.deleteOnExit();
FileOutputStream fileOutputStream = new FileOutputStream(navigationFile);
String doctemplateUrl = getFileProtocolUrl(file);
/* basic rtf template */
String rtfTemplate = "{\\rtf1\\ansi\\deff0 {\\fonttbl {\\f0 Arial;}}\n"
+ "\\f0\\fs32 %s }";
/* get the hyperlink list */
rtfTemplate = String.format(rtfTemplate, getRtfLinkList(rootStructureNode.getNodes(), 0,
doctemplateUrl));
fileOutputStream.write(rtfTemplate.getBytes(UTF_8));
fileOutputStream.close();
/* open the document using the default file handler if provided */
if (Desktop.isDesktopSupported()) {
Desktop.getDesktop().browse(new URL(getFileProtocolUrl(navigationFile)).toURI());
}
} catch (IOException | URISyntaxException e) {
LOG.error(e);
}
}
}
}
private String getRtfLinkList(List<StructureNode> structureNodes, int indent, String url) {
/* rtf hyperlink template */
String hyperlinkTemplate = "{\\field{\\*\\fldinst HYPERLINK \"%s\" \\\\l \"%s\"}{\\fldrslt %s}}";
StringBuilder rtfLinkListBuilder = new StringBuilder();
for (StructureNode structureNode : structureNodes) {
if (structureNode.getType() != null) {
StringBuilder indentString = new StringBuilder();
for (int i = 0; i < indent; i++) {
indentString.append(" ");
}
switch (structureNode.getType()) {
case DOCUMENT:
case FIELD:
break;
case IF:
/* hyperlink for the IF_{condition} */
String ifHyperlink = String.format(hyperlinkTemplate, url, "IF_" + structureNode.getKey(),
"IF_" + structureNode.getKey());
/* hyperlink for the ENDIF_{condition} */
String endifHyperlink = String.format(hyperlinkTemplate, url, "ENDIF_" + structureNode.getKey(),
"ENDIF_" + structureNode.getKey());
/* format the hyperlink template */
rtfLinkListBuilder.append(String.format("\\line %s %s %s \\line %s %s", indentString, ifHyperlink,
getRtfLinkList(structureNode.getNodes(), indent + 1, url), indentString, endifHyperlink));
break;
case WHILE:
/* hyperlink for the WHILE_{condition} */
String whileHyperlink = String.format(hyperlinkTemplate, url, "WHILE_" + structureNode.getKey(),
"IF_" + structureNode.getKey());
/* hyperlink for the ENDWHILE_{condition} */
String endWhileHyperlink = String.format(hyperlinkTemplate, url,
"ENDWHILE_" + structureNode.getKey(),
"ENDIF_" + structureNode.getKey());
/* format the hyperlink template */
rtfLinkListBuilder.append(String.format("\\line %s %s %s \\line %s %s", indentString,
whileHyperlink,
getRtfLinkList(structureNode.getNodes(), indent + 1, url),
indentString, endWhileHyperlink));
break;
}
}
}
return rtfLinkListBuilder.toString();
}
private String getFileProtocolUrl(File f) {
/* formats the file:///{file_path} url */
return String.format("file:///%s", f.getPath()).replaceAll("\\\\", "/").replaceAll(" ", "%20");
}
}
| 29.875989 | 103 | 0.700344 |
c128ec7fd2ddff4d4fbed7cc6fd3ea1a7ba63af9 | 5,359 | /*
* Copyright (C) 2005-2020 Gregory Hedlund & Yvan Rose
*
* 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 ca.phon.ui.layout;
import java.lang.ref.*;
import java.util.*;
import javax.swing.*;
import com.jgoodies.forms.layout.*;
import ca.phon.util.*;
/**
* Utility class for building dialog button bars. The layout
* defines three sections: right, left, and center. Buttons
* are added to one of these three regions and displayed in
* the order added.
*
*
*/
public class ButtonBarBuilder {
// list of right-aligned components in order added
private final List<WeakReference<JComponent>> rightAlignedComponents
= Collections.synchronizedList(new ArrayList<WeakReference<JComponent>>());
private final List<WeakReference<JComponent>> leftAlignedComponents
= Collections.synchronizedList(new ArrayList<WeakReference<JComponent>>());
private final List<WeakReference<JComponent>> centerAlignedComponents
= Collections.synchronizedList(new ArrayList<WeakReference<JComponent>>());
private WeakReference<JComponent> leftFillComponent;
private WeakReference<JComponent> rightFillComponent;
public ButtonBarBuilder addComponentRight(JComponent btn) {
final WeakReference<JComponent> compRef = new WeakReference<JComponent>(btn);
rightAlignedComponents.add(compRef);
return this;
}
public ButtonBarBuilder addComponentLeft(JComponent btn) {
final WeakReference<JComponent> compRef = new WeakReference<JComponent>(btn);
leftAlignedComponents.add(compRef);
return this;
}
public ButtonBarBuilder addComponentCenter(JComponent btn) {
final WeakReference<JComponent> compRef = new WeakReference<JComponent>(btn);
centerAlignedComponents.add(compRef);
return this;
}
public ButtonBarBuilder setLeftFillComponent(JComponent comp) {
final WeakReference<JComponent> compRef = new WeakReference<JComponent>(comp);
leftFillComponent = compRef;
return this;
}
public ButtonBarBuilder setRightFillComponent(JComponent comp) {
final WeakReference<JComponent> compRef = new WeakReference<JComponent>(comp);
rightFillComponent = compRef;
return this;
}
private String createColumnSchema() {
final StringBuilder sb = new StringBuilder();
sb.append("left:pref");
for(int i = 1; i < leftAlignedComponents.size(); i++) {
sb.append(",left:pref");
}
sb.append(",fill:pref:grow");
sb.append(",center:pref");
for(int i = 1; i < centerAlignedComponents.size(); i++) {
sb.append(",center:pref");
}
sb.append(",fill:pref:grow");
sb.append(",right:pref");
for(int i = 1; i < rightAlignedComponents.size(); i++) {
sb.append(",right:pref");
}
return sb.toString();
}
public JComponent build() {
final CellConstraints cc = new CellConstraints();
final FormLayout layout = new FormLayout(createColumnSchema(), "pref");
final JPanel retVal = new JPanel(layout);
int colIdx = 1;
for(int i = 0; i < leftAlignedComponents.size(); i++) {
final WeakReference<JComponent> buttonRef = leftAlignedComponents.get(i);
final JComponent button = buttonRef.get();
retVal.add(button, cc.xy(colIdx, 1));
++colIdx;
}
if(colIdx == 1) ++colIdx;
if(leftFillComponent != null) {
retVal.add(leftFillComponent.get(), cc.xy(colIdx, 1));
}
++colIdx;
int oldIdx = colIdx;
for(int i = 0; i < centerAlignedComponents.size(); i++) {
final WeakReference<JComponent> buttonRef = centerAlignedComponents.get(i);
final JComponent button = buttonRef.get();
retVal.add(button, cc.xy(colIdx, 1));
++colIdx;
}
if(colIdx == oldIdx) ++colIdx;
if(rightFillComponent != null) {
retVal.add(rightFillComponent.get(), cc.xy(colIdx, 1));
}
++colIdx;
for(int i = 0; i < rightAlignedComponents.size(); i++) {
final WeakReference<JComponent> buttonRef = rightAlignedComponents.get(i);
final JComponent button = buttonRef.get();
retVal.add(button, cc.xy(colIdx, 1));
++colIdx;
}
return retVal;
}
/* Helper methods */
public static JComponent buildOkBar(JComponent okButton) {
final ButtonBarBuilder builder = new ButtonBarBuilder();
builder.addComponentRight(okButton);
return builder.build();
}
public static JComponent buildOkCancelBar(JComponent okButton, JComponent cancelButton) {
return buildOkCancelBar(okButton, cancelButton, new JComponent[0]);
}
public static JComponent buildOkCancelBar(JComponent okButton, JComponent cancelButton, JComponent ... otherBtns) {
final ButtonBarBuilder builder = new ButtonBarBuilder();
if(OSInfo.isMacOs()) {
builder.addComponentRight(cancelButton);
builder.addComponentRight(okButton);
} else {
builder.addComponentRight(okButton);
builder.addComponentRight(cancelButton);
}
for(JComponent btn:otherBtns) {
builder.addComponentLeft(btn);
}
return builder.build();
}
}
| 29.607735 | 116 | 0.724949 |
7076d03729c4edf34861a741a0ecb21788017c71 | 4,377 | // snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.]
// snippet-sourcedescription:[PutFile.java demonstrates how to upload a file to a branch.]
//snippet-keyword:[AWS SDK for Java v2]
//snippet-keyword:[Code Sample]
// snippet-service:[AWS CodeCommit]
// snippet-sourcetype:[full-example]
//snippet-sourcedate:[11/03/2020]
// snippet-sourceauthor:[AWS - scmacdon]
/*
Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
SPDX-License-Identifier: Apache-2.0
*/
package com.example.commit;
// snippet-start:[codecommit.java2.put_file.import]
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.codecommit.CodeCommitClient;
import software.amazon.awssdk.services.codecommit.model.CodeCommitException;
import software.amazon.awssdk.services.codecommit.model.PutFileRequest;
import software.amazon.awssdk.core.SdkBytes;
import software.amazon.awssdk.services.codecommit.model.PutFileResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
// snippet-end:[codecommit.java2.put_file.import]
public class PutFile {
public static void main(String[] args) {
final String USAGE = "\n" +
"Usage:\n" +
" PutFile <repoName> <branchName> <filePath> <email> <name> <repoPath> <commitId>\n\n" +
"Where:\n" +
" repoName - the name of the repository.\n" +
" branchName - the name of the branch.\n" +
" filePath - the location of the file on the local drive (i.e., C:/AWS/uploadGlacier.txt).\n" +
" email - the email of the user whom uploads the file.\n" +
" name - the name of the user.\n" +
" repoPath - the location in the repo to store the file.\n" +
" commitId - the full commit ID of the head commit in the branch (you can retrieve this value from the AWS CodeCommit Console).\n" ;
if (args.length != 7) {
System.out.println(USAGE);
System.exit(1);
}
String repoName = args[0];
String branchName = args[1];
String filePath = args[2];
String email = args[3];
String name = args[4];
String repoPath = args[5];
String commitId = args[6];
Region region = Region.US_EAST_1;
CodeCommitClient codeCommitClient = CodeCommitClient.builder()
.region(region)
.build();
uploadFile(codeCommitClient, filePath, repoName, branchName, email, name, repoPath, commitId);
codeCommitClient.close();
}
// snippet-start:[codecommit.java2.put_file.main]
public static void uploadFile(CodeCommitClient codeCommitClient,
String filePath,
String repoName,
String branchName,
String email,
String name,
String repoPath,
String commitId ){
try {
// Create an SdkBytes object that represents the file to upload
File myFile = new File(filePath);
InputStream is = new FileInputStream(myFile);
SdkBytes fileToUpload = SdkBytes.fromInputStream(is);
PutFileRequest fileRequest = PutFileRequest.builder()
.fileContent(fileToUpload)
.repositoryName(repoName)
.commitMessage("Uploaded via the Java API")
.branchName(branchName)
.filePath(repoPath)
.parentCommitId(commitId)
.email(email)
.name(name)
.build();
// Upload file to the branch
PutFileResponse fileResponse = codeCommitClient.putFile(fileRequest);
System.out.println("The commit ID is "+fileResponse.commitId());
} catch (CodeCommitException | FileNotFoundException e) {
System.err.println(e.getMessage());
System.exit(1);
}
}
// snippet-end:[codecommit.java2.put_file.main]
}
| 41.292453 | 153 | 0.586018 |
c98cdb051a1235e8be2ef43887969cef51072efb | 2,574 | /* (c) https://github.com/MontiCore/monticore */
package de.monticore.symbols.oosymbols._symboltable;
import com.google.common.collect.Lists;
import de.monticore.symbols.basicsymbols._symboltable.FunctionSymbol;
import de.monticore.symbols.basicsymbols._symboltable.TypeVarSymbol;
import de.monticore.symbols.basicsymbols._symboltable.VariableSymbol;
import de.monticore.types.check.SymTypeExpression;
import de.se_rwth.commons.logging.Log;
import java.util.List;
public class OOTypeSymbol extends OOTypeSymbolTOP {
public OOTypeSymbol(String name) {
super(name);
}
public void setMethodList(List<MethodSymbol> methodList){
for(MethodSymbol method: methodList){
getSpannedScope().add(method);
getSpannedScope().add((FunctionSymbol) method);
}
}
/**
* get a list of all the methods the type definition can access
*/
public List<MethodSymbol> getMethodList() {
if (spannedScope == null) {
return Lists.newArrayList();
}
return getSpannedScope().getLocalMethodSymbols();
}
/**
* search in the scope for methods with a specific name
*/
public List<MethodSymbol> getMethodList(String methodname) {
return getSpannedScope().resolveMethodMany(methodname);
}
/**
* get a list of all the fields the type definition can access
*/
public List<FieldSymbol> getFieldList() {
if (spannedScope == null) {
return Lists.newArrayList();
}
return getSpannedScope().getLocalFieldSymbols();
}
/**
* search in the scope for methods with a specific name
*/
public List<FieldSymbol> getFieldList(String fieldname) {
return getSpannedScope().resolveFieldMany(fieldname);
}
public List<TypeVarSymbol> getTypeParameterList() {
if(spannedScope==null){
return Lists.newArrayList();
}
return getSpannedScope().getLocalTypeVarSymbols();
}
public void addTypeVarSymbol(TypeVarSymbol t) {
getSpannedScope().add(t);
}
public void addFieldSymbol(FieldSymbol f) {
getSpannedScope().add(f);
getSpannedScope().add((VariableSymbol) f);
}
public void addMethodSymbol(MethodSymbol m) {
getSpannedScope().add(m);
getSpannedScope().add((FunctionSymbol) m);
}
public boolean isPresentSuperClass() {
return !getSuperClassesOnly().isEmpty();
}
public SymTypeExpression getSuperClass() {
if (isPresentSuperClass()) {
return getSuperClassesOnly().get(0);
}
Log.error("0xA1067 SuperClass does not exist");
// Normally this statement is not reachable
throw new IllegalStateException();
}
}
| 26.536082 | 69 | 0.714452 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.