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
|
---|---|---|---|---|---|
f31ee243dbdc81f1d0ef901a907cbb74bc50de08 | 309 | package ru.job4j.profession;
/**
* Класс описывающий профессию
*
* @author Viktor Shiayn
* @since 17.12.18
*/
public class Profession {
private String name;
private String profession;
/**
* @return возвращает имя
*/
public String getName() {
return this.name;
}
}
| 15.45 | 30 | 0.618123 |
b8de78d1895f0ec68f620e59086aacff3e73d6a5 | 3,688 | package com.refinery408;
import javax.swing.AbstractButton;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;
import javax.swing.plaf.basic.BasicButtonUI;
import java.awt.BasicStroke;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
public class ButtonTabComponent extends JPanel {
private final JTabbedPane pane;
public ButtonTabComponent(final JTabbedPane pane) {
super(new BorderLayout());
if (pane == null) {
throw new NullPointerException("TabbedPane is null");
}
this.pane = pane;
setOpaque(false);
JLabel label = new JLabel() {
public String getText() {
int i = pane.indexOfTabComponent(ButtonTabComponent.this);
if (i != -1) {
return pane.getTitleAt(i);
}
return null;
}
};
label.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 8));
add(label, BorderLayout.LINE_START);
add(new TabCloseButton(), BorderLayout.LINE_END);
setBorder(BorderFactory.createEmptyBorder(3, 4, 1, 0));
}
private class TabCloseButton extends JButton implements ActionListener {
public TabCloseButton() {
int size = 17;
setPreferredSize(new Dimension(size, size));
setToolTipText("Close tab");
setUI(new BasicButtonUI());
setContentAreaFilled(false);
setFocusable(false);
setBorder(BorderFactory.createEtchedBorder());
setBorderPainted(false);
addMouseListener(buttonMouseListener);
setRolloverEnabled(true);
addActionListener(this);
}
public void actionPerformed(ActionEvent e) {
int i = pane.indexOfTabComponent(ButtonTabComponent.this);
if (i != -1) {
pane.remove(i);
}
}
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g.create();
//shift the image for pressed buttons
if (getModel().isPressed()) {
g2.translate(1, 1);
}
g2.setStroke(new BasicStroke(2));
g2.setColor(Color.BLACK);
if (getModel().isRollover()) {
g2.setColor(Color.RED);
}
int delta = 5;
g2.drawLine(delta, delta, getWidth() - delta - 1, getHeight() - delta - 1);
g2.drawLine(getWidth() - delta - 1, delta, delta, getHeight() - delta - 1);
g2.dispose();
}
}
private final static MouseListener buttonMouseListener = new MouseAdapter() {
public void mouseEntered(MouseEvent e) {
Component component = e.getComponent();
if (component instanceof AbstractButton) {
AbstractButton button = (AbstractButton) component;
button.setBorderPainted(true);
}
}
public void mouseExited(MouseEvent e) {
Component component = e.getComponent();
if (component instanceof AbstractButton) {
AbstractButton button = (AbstractButton) component;
button.setBorderPainted(false);
}
}
};
}
| 34.148148 | 87 | 0.600868 |
4a184ff2401b8a9b1d9c8da29000a55a484fe3a7 | 6,107 | package com.springboot.core.controller;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.ExcessiveAttemptsException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import com.springboot.core.common.base.BaseController;
import com.springboot.core.common.domain.AjaxResult;
import com.springboot.core.model.auto.SysNotice;
import com.springboot.core.model.auto.TsysUser;
import com.springboot.core.model.custom.SysMenu;
import com.springboot.core.shiro.util.ShiroUtils;
import com.springboot.core.util.StringUtils;
import io.swagger.annotations.ApiOperation;
@Controller
@RequestMapping("/admin")
public class AdminController extends BaseController {
private static Logger logger = LoggerFactory.getLogger(AdminController.class);
private String prefix = "admin";
@ApiOperation(value = "首页", notes = "首页")
@GetMapping("/index")
public String index(HttpServletRequest request) {
request.getSession().setAttribute("sessionUserName", ShiroUtils.getUser().getNickname());
// 获取公告信息
List<SysNotice> notices = sysNoticeService.getuserNoticeNotRead(ShiroUtils.getUser(), 0);
request.getSession().setAttribute("notices", notices);
return prefix + "/index";
}
@ApiOperation(value = "获取登录用户菜单栏", notes = "获取登录用户菜单栏")
@GetMapping("/getUserMenu")
@ResponseBody
public List<SysMenu> getUserMenu(){
List<SysMenu> sysMenus=sysPermissionService.getSysMenus(ShiroUtils.getUserId());
return sysMenus;
}
/**
* 请求到登陆界面
*
* @param request
* @return
*/
@ApiOperation(value = "请求到登陆界面", notes = "请求到登陆界面")
@GetMapping("/login")
public String login(ModelMap modelMap) {
try {
if ((null != SecurityUtils.getSubject() && SecurityUtils.getSubject().isAuthenticated()) || SecurityUtils.getSubject().isRemembered()) {
return "redirect:/" + prefix + "/index";
} else {
System.out.println("--进行登录验证..验证开始");
return "login";
}
} catch (Exception e) {
e.printStackTrace();
}
return "login";
}
/**
* 用户登陆验证
*
* @param user
* @param rcode
* @param redirectAttributes
* @param rememberMe
* @param model
* @param request
* @return
*/
@ApiOperation(value = "用户登陆验证", notes = "用户登陆验证")
@PostMapping("/login")
@ResponseBody
public AjaxResult login(TsysUser user, RedirectAttributes redirectAttributes, boolean rememberMe,
HttpServletRequest request) {
String userName = user.getUsername();
Subject currentUser = SecurityUtils.getSubject();
// 是否验证通过
if (!currentUser.isAuthenticated()) {
UsernamePasswordToken token = new UsernamePasswordToken(userName, user.getPassword());
try {
if (rememberMe) {
token.setRememberMe(true);
}
// 存入用户
currentUser.login(token);
if (StringUtils.isNotNull(ShiroUtils.getUser())) {
return AjaxResult.success();
} else {
return AjaxResult.error(500, "未知账户");
}
} catch (UnknownAccountException uae) {
logger.info("对用户[" + userName + "]进行登录验证..验证未通过,未知账户");
return AjaxResult.error(500, "未知账户");
} catch (IncorrectCredentialsException ice) {
logger.info("对用户[" + userName + "]进行登录验证..验证未通过,错误的凭证");
return AjaxResult.error(500, "用户名或密码不正确");
} catch (LockedAccountException lae) {
logger.info("对用户[" + userName + "]进行登录验证..验证未通过,账户已锁定");
return AjaxResult.error(500, "账户已锁定");
} catch (ExcessiveAttemptsException eae) {
logger.info("对用户[" + userName + "]进行登录验证..验证未通过,错误次数过多");
return AjaxResult.error(500, "用户名或密码错误次数过多");
} catch (AuthenticationException ae) {
// 通过处理Shiro的运行时AuthenticationException就可以控制用户登录失败或密码错误时的情景
logger.info("对用户[" + userName + "]进行登录验证..验证未通过,堆栈轨迹如下");
ae.printStackTrace();
return AjaxResult.error(500, "用户名或密码不正确");
}
} else {
if (StringUtils.isNotNull(ShiroUtils.getUser())) {
// 跳转到 get请求的登陆方法
// view.setViewName("redirect:/"+prefix+"/index");
return AjaxResult.success();
} else {
return AjaxResult.error(500, "未知账户");
}
}
}
/**
* 退出登陆
*
* @return
*/
@ApiOperation(value = "退出登陆", notes = "退出登陆")
@GetMapping("/Loginout")
@ResponseBody
public AjaxResult LoginOut(HttpServletRequest request, HttpServletResponse response) {
// 在这里执行退出系统前需要清空的数据
Subject subject = SecurityUtils.getSubject();
// 注销
subject.logout();
return success();
}
/**** 页面测试 ****/
@ApiOperation(value = "404页面", notes = "404页面")
@GetMapping("Out404")
public String Out404(HttpServletRequest request, HttpServletResponse response) {
return "redirect:/error/404";
}
@GetMapping("Out403")
@ApiOperation(value = "403页面", notes = "403页面")
public String Out403(HttpServletRequest request, HttpServletResponse response) {
return "redirect:/error/403";
}
@ApiOperation(value = "500页面", notes = "500页面")
@GetMapping("Out500")
public String Out500(HttpServletRequest request, HttpServletResponse response) {
return "redirect:/error/500";
}
/**
* 权限测试跳转页面
*
* @param request
* @param response
* @return
*/
@ApiOperation(value = "权限测试跳转页面", notes = "权限测试跳转页面")
@GetMapping("Outqx")
@RequiresPermissions("system:user:asd")
public String Outqx(HttpServletRequest request, HttpServletResponse response) {
return "redirect:/error/500";
}
/**** 页面测试EDN ****/
}
| 30.688442 | 139 | 0.727362 |
5e0da73ad784f192014d58de63bfcdc4a1c483fb | 1,196 | package com.rbkmoney.threeds.server.converter.commonplatform;
import com.rbkmoney.threeds.server.domain.root.Message;
import com.rbkmoney.threeds.server.domain.root.emvco.PReq;
import com.rbkmoney.threeds.server.dto.ValidationResult;
import lombok.RequiredArgsConstructor;
import org.springframework.core.convert.converter.Converter;
@RequiredArgsConstructor
public class PReqToFixedPReqConverter implements Converter<ValidationResult, Message> {
@Override
public Message convert(ValidationResult validationResult) {
PReq pReq = (PReq) validationResult.getMessage();
PReq pReqFixed = PReq.builder()
.threeDSServerRefNumber(pReq.getThreeDSServerRefNumber())
.threeDSServerOperatorID(pReq.getThreeDSServerOperatorID())
.threeDSServerTransID(pReq.getThreeDSServerTransID())
.messageExtension(pReq.getMessageExtension())
.serialNum(null)
.threeDSRequestorURL(pReq.getThreeDSRequestorURL())
.build();
pReqFixed.setMessageVersion(pReq.getMessageVersion());
pReqFixed.setRequestMessage(pReq.getRequestMessage());
return pReqFixed;
}
}
| 41.241379 | 87 | 0.728261 |
bd7d2a9ea55d9f359db32ea321982539a076586d | 224 | package org.rabbitmq.demo;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class RabbitMqDemoApplicationTests {
@Test
void contextLoads() {
}
}
| 16 | 60 | 0.758929 |
f7d7d3db63b9d3b2e3444a11b86bde9bdfffbcad | 7,531 | /**
* BNField6.java
*
* Arithmetic in the finite extension field GF(p^6) with p = 3 (mod 4).
*
* Copyright (C) Paulo S. L. M. Barreto and Geovandro C. C. F. Pereira.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package com.ibm.pross.common.util.crypto.pairing;
import java.math.BigInteger;
import java.security.SecureRandom;
public class BNField6 {
public static final String differentFields = "Operands are in different finite fields";
/**
* BN parameters (singleton)
*/
BNParams bn;
/**
* Components
*/
BNField2[] v;
BNField6(BNParams bn) {
this.bn = bn;
v = new BNField2[3];
this.v[0] = this.v[1] = this.v[2] = bn.Fp2_0;
}
BNField6(BNParams bn, BigInteger k) {
this.bn = bn;
v = new BNField2[3];
this.v[0] = new BNField2(bn, k);
this.v[1] = this.v[2] = bn.Fp2_0;
}
BNField6(BNParams bn, BNField2 v0) {
this.bn = bn;
v = new BNField2[3];
this.v[0] = v0;
this.v[1] = this.v[2] = bn.Fp2_0;
}
BNField6(BNParams bn, BNField2 v0, BNField2 v1, BNField2 v2) {
this.bn = bn;
v = new BNField2[3];
this.v[0] = v0;
this.v[1] = v1;
this.v[2] = v2;
}
/**
* Compute a random field element.
*
* @param rand a cryptographically strong pseudo-random number generator.
*
* @return a random field element.
*/
BNField6(BNParams bn, SecureRandom rand) {
this.bn = bn;
v = new BNField2[3];
this.v[0] = new BNField2(bn, rand);
this.v[1] = new BNField2(bn, rand);
this.v[2] = new BNField2(bn, rand);
}
public BNField6 randomize(SecureRandom rand) {
return new BNField6(bn, rand);
}
public boolean isZero() {
return v[0].isZero() && v[1].isZero() && v[2].isZero();
}
public boolean isOne() {
return v[0].isOne() && v[1].isZero() && v[2].isZero();
}
public boolean equals(Object o) {
if (!(o instanceof BNField6)) {
return false;
}
BNField6 w = (BNField6) o;
return bn == w.bn && // singleton comparison
v[0].equals(w.v[0]) && v[1].equals(w.v[1]) && v[2].equals(w.v[2]);
}
public BNField6 negate() {
return new BNField6(bn, v[0].negate(), v[1].negate(), v[2].negate());
}
/**
* Compute this^((p^2)^m), the m-th conjugate of this over GF(p^2).
*/
public BNField6 conjugate(int m) {
switch (m) {
default: // only to make the compiler happy
case 0:
return this;
case 1:
return new BNField6(bn, v[0], v[1].multiply(bn.zeta1).negate(), v[2].multiply(bn.zeta0));
case 2:
return new BNField6(bn, v[0], v[1].multiply(bn.zeta0), v[2].multiply(bn.zeta1).negate());
}
}
public BNField6 add(BNField6 w) {
if (bn != w.bn) { // singleton comparison
throw new IllegalArgumentException(differentFields);
}
return new BNField6(bn, v[0].add(w.v[0]), v[1].add(w.v[1]), v[2].add(w.v[2]));
}
public BNField6 subtract(BNField6 w) {
if (bn != w.bn) { // singleton comparison
throw new IllegalArgumentException(differentFields);
}
return new BNField6(bn, v[0].subtract(w.v[0]), v[1].subtract(w.v[1]), v[2].subtract(w.v[2]));
}
public BNField6 twice(int k) {
return new BNField6(bn, v[0].twice(k), v[1].twice(k), v[2].twice(k));
}
public BNField6 halve() {
return new BNField6(bn, v[0].halve(), v[1].halve(), v[2].halve());
}
public BNField6 multiply(BNField6 w) {
if (w == this) {
return square();
}
if (bn != w.bn) { // singleton comparison
throw new IllegalArgumentException(differentFields);
}
if (isOne() || w.isZero()) {
return w;
}
if (isZero() || w.isOne()) {
return this;
}
BNField2 d00 = v[0].multiply(w.v[0]), d11 = v[1].multiply(w.v[1]), d22 = v[2].multiply(w.v[2]),
d01 = v[0].add(v[1]).multiply(w.v[0].add(w.v[1])).subtract(d00.add(d11)),
d02 = v[0].add(v[2]).multiply(w.v[0].add(w.v[2])).subtract(d00.add(d22)),
d12 = v[1].add(v[2]).multiply(w.v[1].add(w.v[2])).subtract(d11.add(d22));
if (bn.b == 3) {
return new BNField6(bn, d12.divideV().add(d00), d22.divideV().add(d01), d02.add(d11));
} else {
return new BNField6(bn, d12.multiplyV().add(d00), d22.multiplyV().add(d01), d02.add(d11));
}
}
public BNField6 multiplyConj() {
if (isOne() || isZero()) {
return this;
}
if (bn.b == 3) {
return new BNField6(bn, v[0].square().subtract(v[1].multiply(v[2]).divideV()),
v[2].square().divideV().subtract(v[0].multiply(v[1])).multiply(bn.zeta0),
v[0].multiply(v[2]).subtract(v[1].square()).multiply(bn.zeta1));
} else {
// (v0^2 - v1*v2*xi) + (v2^2*xi - v0*v1)*zeta*w + (v0*v2 - v1^2)*(zeta+1)*w^2 =
return new BNField6(bn, v[0].square().subtract(v[1].multiply(v[2]).multiplyV()),
v[2].square().multiplyV().subtract(v[0].multiply(v[1])).multiply(bn.zeta0),
v[0].multiply(v[2]).subtract(v[1].square()).multiply(bn.zeta1));
}
}
/**
* Complete the norm evaluation.
*/
public BNField2 normCompletion(BNField6 k) {
BNField2 d00 = v[0].multiply(k.v[0]), d12 = v[1].multiply(k.v[2]).add(v[2].multiply(k.v[1]));
if (bn.b == 3) {
return d12.divideV().add(d00);
} else {
return d12.multiplyV().add(d00);
}
}
public BNField6 multiply(BNField2 w) {
if (bn != w.bn) { // singleton comparison
throw new IllegalArgumentException(differentFields);
}
if (w.isOne()) {
return this;
}
return new BNField6(bn, v[0].multiply(w), v[1].multiply(w), v[2].multiply(w));
}
public BNField6 square() {
if (isZero() || isOne()) {
return this;
}
BNField2 a0 = v[0];
BNField2 a1 = v[1];
BNField2 a2 = v[2];
// Chung-Hasan SQR3 for F_{p^6} over F_{p^2}
/*
* c0 = S0 = a0^2, S1 = (a2 + a1 + a0)^2, S2 = (a2 - a1 + a0)^2, c3 = S3 =
* 2*a1*a2, c4 = S4 = a2^2, T1 = (S1 + S2)/2, c1 = S1 - T1 - S3, c2 = T1 - S4 -
* S0.
*/
BNField2 c0 = a0.square();
BNField2 S1 = a2.add(a1).add(a0).square();
BNField2 S2 = a2.subtract(a1).add(a0).square();
BNField2 c3 = a1.multiply(a2).twice(1);
BNField2 c4 = a2.square();
BNField2 T1 = S1.add(S2).halve();
BNField2 c1 = S1.subtract(T1).subtract(c3);
BNField2 c2 = T1.subtract(c4).subtract(c0);
// z^3 = xi
// z^4 = xi*z
// c4^*xi*z + c3*xi + c2*z^2 + c1*z + c0
// c2^*z^2 + (c4^*xi + c1)*z + (c3*xi + c0)
if (bn.b == 3) {
c0 = c0.add(c3.divideV());
c1 = c1.add(c4.divideV());
} else {
c0 = c0.add(c3.multiplyV());
c1 = c1.add(c4.multiplyV());
}
return new BNField6(bn, c0, c1, c2);
}
public BNField6 multiplyV() {
// (a0, a1, a2) -> (a2*xi, a0, a1)
return new BNField6(bn, v[2].multiplyV(), v[0], v[1]);
}
public BNField6 divideV() {
// (a0, a1, a2) -> (a2/xi, a0, a1)
return new BNField6(bn, v[2].divideV(), v[0], v[1]);
}
public String toString() {
return "(" + v[0] + ", " + v[1] + ", " + v[2] + ")";
}
}
| 29.189922 | 98 | 0.586509 |
360566fb1b2ca27148503fef0d3429d2ebd74053 | 1,130 | package wtvindonesia.application.com.model;
import java.io.Serializable;
public class tagihan_telkom_detail implements Serializable {
private static final long serialVersionUID = 1L;
String periode;
double nilaiTagihan, denda, admin, transaksi, fee, total;
public tagihan_telkom_detail(String periode, double nilaiTagihan, double denda, double admin, double transaksi, double total, double fee) {
this.periode = periode;
this.nilaiTagihan = nilaiTagihan;
this.denda = denda;
this.admin = admin;
this.transaksi = transaksi;
this.fee = fee;
this.total = total;
}
public String getPeriode() {
return this.periode;
}
public double getNilaiTagihan() {
return this.nilaiTagihan;
}
public double getDenda() {
return this.denda;
}
public double getAdmin() {
return this.admin;
}
public double getTransaksi() {
return this.transaksi;
}
public double getTotal() {
return this.total;
}
public double getFee() {
return this.fee;
}
}
| 22.156863 | 143 | 0.633628 |
4a40fadd14b4e0694792b0e430b47266cf487e90 | 1,176 | /*
* Copyright (C) 2012 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package android.mediastress.cts;
import android.os.Environment;
import java.io.File;
import junit.framework.Assert;
public class WorkDir {
static final File getTopDir() {
Assert.assertEquals(Environment.getExternalStorageState(), Environment.MEDIA_MOUNTED);
return Environment.getExternalStorageDirectory();
}
static final String getTopDirString() {
return (getTopDir().getAbsolutePath() + File.separator);
}
static final String getMediaDirString() {
return (getTopDirString() + "test/");
}
}
| 30.153846 | 94 | 0.721939 |
692913af3dd825358535ab1fb81f2b207faa4651 | 1,988 | import java.util.Scanner;
public class TicTacToe{
public static int row, col;
public static Scanner scan = new Scanner(System.in);
public static char [][]board = new char [3][3];
public static char turn = 'X';
public static void main(String[] args){
for (int i = 0; i < 3; i++){
for (int j = 0; j < 3; j++){
board[i][j] = '_';
}
}
Play();
}
public static void Play() {
boolean playing = true;
//prints the board first. then user can enter row & column.
PrintBoard();
while(playing){
System.out.println(" Please enter a row and column. Example: 1(row), 2(column) like so. ");
System.out.println("Enter only numbers 1-3 b/c there are only 3 rows and 3 columns.");
System.out.println("Dont act foolish and enter 5(row) & 9(column)");
row = scan.nextInt() -1;
col = scan.nextInt() -1;
board[row][col] = turn;
if (GameOver(row, col)) {
playing = false;
System.out.println("Game over Player " + turn + " wins :)");
}
PrintBoard();
if (turn == 'X')
turn = 'O';
else
turn = 'X';
}
}
public static void PrintBoard(){
for (int i = 0; i < 3; i++){
System.out.println();
for (int j = 0; j < 3; j++){
if (j == 0)
System.out.print("| ");
System.out.print(board[i][j] + " | ");
}
}
System.out.println();
}
public static boolean GameOver(int rowMove, int colMove){
//check horizontal and vertical wins.
if (board[0][colMove] == board[1][colMove]
&& board[0][colMove] == board[2][colMove])
return true;
if (board [rowMove][0] == board[rowMove][1]
&& board[rowMove][0] == board[rowMove][2])
return true;
//check diagonal wins.
if (board[0][0] == board[1][1] && board[0][0] == board[2][2]
&& board[1][1] != '_')
return true;
if (board[0][2] == board[1][1] && board[0][2] == board[2][0]
&& board[1][1] != '_')
return true;
return false;
}
}
| 25.487179 | 95 | 0.547787 |
c5ccf14e2eb9346174a2020e80b9364769302434 | 2,304 | package gBacktracking;
/**
*
Start in the leftmost columm
If all queens are placed, return true
for (every possible choice among the rows in this column)
if the queen can be placed safely there,
make that choice and then recursively try to place the rest of the queens if recursion successful, return true
if !successful, remove queen and try another row in this column
if all rows have been tried and nothing worked, return false to trigger backtracking
* @author arpana
*
*/
public class NQueens {
static int NQ = 8;
static Boolean[][] board = new Boolean[NQ][NQ];
public static void main(String[] args){
NQueens nQueens = new NQueens();
nQueens.solveNQueens();
}
public void solveNQueens(){
clearBoard(); // Set all board positions to false
solve(0); // Attempt to solve the puzzle
}
private Boolean solve(int col) {
if(col > board[0].length)
return true;
for(int rowToTry = 0; rowToTry < board.length; rowToTry++){
if(isSafe(rowToTry, col)){
placeQueen(rowToTry, col);
if(solve(col+1)) return true;
removeQueen(rowToTry, col);
}
}
return false;
}
private void removeQueen(int Qrow, int Qcol){
board[Qrow][Qcol] = false;
}
private void placeQueen(int Qrow, int Qcol){
board[Qrow][Qcol] = true;
}
boolean isSafe(int row, int col){
return(lowerDiagClear(row,col) && rowIsClear(row, col) && upperDiagClear(row, col));
}
private boolean upperDiagClear(int Qrow, int Qcol) {
int row, col;
for (row = Qrow, col = Qcol; col >= 0 && row < board.length; row++, col--) {
if(board[Qrow][col])
return false;
}
return true;
}
private boolean rowIsClear(int Qrow, int Qcol) {
for(int col=0; col< Qcol; col++){
if(board[Qrow][col])
return false;
}
return true;
}
private boolean lowerDiagClear(int Qrow, int Qcol) {
int row, col;
for (row = Qrow, col = Qcol; row >= 0 && row < board.length; row--, col--) {
if(board[Qrow][col])
return false;
}
return true;
}
private static void clearBoard() {
for(int row =0; row< board.length; row++){
for(int col = 0; col < board[0].length; col++){
board[row][col] = false;
}
}
}
}
| 24.252632 | 113 | 0.61849 |
e977284f381f92f162ad9072f7002e687fd20396 | 989 | package hiennguyen.me.architecture.example.features.login.views;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import hiennguyen.me.architecture.R;
import hiennguyen.me.architecture.databinding.ActivitySplashBinding;
import hiennguyen.me.architecture.example.features.base.views.BaseActivity;
import hiennguyen.me.architecture.example.features.home.views.HomeActivity;
import hiennguyen.me.architecture.example.features.login.viewmodels.SplashViewModel;
public class SplashScreenActivity extends BaseActivity<ActivitySplashBinding, SplashViewModel> {
@Override
protected int layoutId() {
return R.layout.activity_splash;
}
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
new Handler().postDelayed(() -> {
navigator.startActivity(HomeActivity.class);
navigator.finishActivity();
}, 400);
}
}
| 32.966667 | 96 | 0.76542 |
c777529bc3d85c93163328bad924eab8c7dd24c8 | 1,307 | package systems.coyote;
public class TestResponse {
String location = null;
int status = 0;
String data = null;
private Exception exception = null;
private volatile boolean complete = false;
public TestResponse( final String url ) {
location = url;
}
public String getData() {
return data;
}
/**
* @return the exception thrown by the client
*/
public Exception getException() {
return exception;
}
public String getLocation() {
return location;
}
public int getStatus() {
return status;
}
/**
* @return true if the exchange was completed successfully, false if there was an error.
*/
public boolean isComplete() {
return complete;
}
/**
* @param flag The state of the completion, true means the exchange completed successfully.
*/
public void setComplete( final boolean flag ) {
complete = flag;
}
public void setData( final String data ) {
this.data = data;
}
/**
* @param ex The exception thrown by the client performing its request.
*/
public void setException( final Exception ex ) {
exception = ex;
}
public void setLocation( final String url ) {
location = url;
}
public void setStatus( final int code ) {
status = code;
}
}
| 13.07 | 93 | 0.634277 |
b21536934e5562b49a20ef8de9f5449327cf743b | 793 | package com.ciskow.salesapp.repositories;
import com.ciskow.salesapp.dto.SaleSuccessDTO;
import com.ciskow.salesapp.dto.SaleSumDTO;
import com.ciskow.salesapp.entities.Sale;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import java.util.List;
public interface SaleRepository extends JpaRepository<Sale, Long> {
@Query("SELECT new com.ciskow.salesapp.dto.SaleSumDTO(obj.seller, SUM(obj.amount)) " +
" FROM Sale AS obj GROUP BY obj.seller")
List<SaleSumDTO> amountGroupedBySeller();
@Query("SELECT new com.ciskow.salesapp.dto.SaleSuccessDTO(obj.seller, SUM(obj.visited), SUM(obj.deals)) " +
" FROM Sale AS obj GROUP BY obj.seller")
List<SaleSuccessDTO> successGroupedBySeller();
} | 39.65 | 111 | 0.757881 |
cd44a7d4ab49ee2b07538dcf7af4a240f950e941 | 4,515 | package com.tubitv.media.controller;
import android.support.annotation.Nullable;
import android.view.View;
import android.webkit.WebView;
import com.google.android.exoplayer2.C;
import com.google.android.exoplayer2.SimpleExoPlayer;
import com.tubitv.media.utilities.PlayerDeviceUtils;
/**
* Created by allensun on 8/3/17.
* on Tubitv.com, [email protected]
*/
public class PlayerUIController {
public boolean isPlayingAds = false;
private SimpleExoPlayer contentPlayer;
private SimpleExoPlayer adPlayer;
private WebView vpaidWebView;
private View exoPlayerView;
private int adResumeWindow = C.INDEX_UNSET;
private long adResumePosition = C.TIME_UNSET;
private int movieResumeWindow = C.INDEX_UNSET;
private long movieResumePosition = C.TIME_UNSET;
private boolean hasHistory = false;
private long historyPosition = C.TIME_UNSET;
public PlayerUIController() {
}
public PlayerUIController(@Nullable SimpleExoPlayer contentPlayer, @Nullable SimpleExoPlayer adPlayer,
@Nullable WebView vpaidWebView, @Nullable View exoPlayerView) {
this.contentPlayer = contentPlayer;
this.adPlayer = adPlayer;
this.vpaidWebView = vpaidWebView;
this.exoPlayerView = exoPlayerView;
}
public SimpleExoPlayer getContentPlayer() {
return contentPlayer;
}
public void setContentPlayer(SimpleExoPlayer contentPlayer) {
this.contentPlayer = contentPlayer;
}
public SimpleExoPlayer getAdPlayer() {
// We'll reuse content player to play ads for single player instance case
if (PlayerDeviceUtils.useSinglePlayer()) {
return contentPlayer;
}
return adPlayer;
}
public void setAdPlayer(SimpleExoPlayer adPlayer) {
this.adPlayer = adPlayer;
}
public WebView getVpaidWebView() {
return vpaidWebView;
}
public void setVpaidWebView(WebView vpaidWebView) {
this.vpaidWebView = vpaidWebView;
}
public View getExoPlayerView() {
return exoPlayerView;
}
public void setExoPlayerView(View exoPlayerView) {
this.exoPlayerView = exoPlayerView;
}
/**
* This is set when user want to begin the movie from current position
*
* @param pos
*/
public void setPlayFromHistory(long pos) {
hasHistory = true;
historyPosition = pos;
}
public boolean hasHistory() {
return hasHistory;
}
public long getHistoryPosition() {
return historyPosition;
}
public void clearHistoryRecord() {
hasHistory = false;
historyPosition = C.TIME_UNSET;
}
public void setAdResumeInfo(int window, long position) {
adResumeWindow = window;
adResumePosition = position;
}
public void clearAdResumeInfo() {
setAdResumeInfo(C.INDEX_UNSET, C.TIME_UNSET);
}
public void setMovieResumeInfo(int window, long position) {
movieResumeWindow = window;
movieResumePosition = position;
}
public void clearMovieResumeInfo() {
setMovieResumeInfo(C.INDEX_UNSET, C.TIME_UNSET);
}
public int getAdResumeWindow() {
return adResumeWindow;
}
public long getAdResumePosition() {
return adResumePosition;
}
public int getMovieResumeWindow() {
return movieResumeWindow;
}
public long getMovieResumePosition() {
return movieResumePosition;
}
public static class Builder {
private SimpleExoPlayer contentPlayer = null;
private SimpleExoPlayer adPlayer = null;
private WebView vpaidWebView = null;
private View exoPlayerView = null;
public Builder() {
}
public Builder setContentPlayer(SimpleExoPlayer contentPlayer) {
this.contentPlayer = contentPlayer;
return this;
}
public Builder setAdPlayer(SimpleExoPlayer adPlayer) {
this.adPlayer = adPlayer;
return this;
}
public Builder setVpaidWebView(WebView vpaidWebView) {
this.vpaidWebView = vpaidWebView;
return this;
}
public Builder setExoPlayerView(View exoPlayerView) {
this.exoPlayerView = exoPlayerView;
return this;
}
public PlayerUIController build() {
return new PlayerUIController(contentPlayer, adPlayer, vpaidWebView, exoPlayerView);
}
}
}
| 24.807692 | 106 | 0.663566 |
c4c86ae2926e047081f49aa5ac3315f0d0e04bc9 | 303 | package com.at.hal9000.domain.service.push.model;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.ToString;
@Data
@ToString(callSuper = true)
@EqualsAndHashCode(callSuper = true)
public class AlarmPinValueEvent extends Event {
private String pinId;
private String value;
}
| 20.2 | 49 | 0.785479 |
aaafebd418d6716191a936b7f2236a15a8778eed | 27,748 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.activemq.artemis.core.config;
import javax.json.JsonArrayBuilder;
import javax.json.JsonObject;
import javax.json.JsonObjectBuilder;
import javax.json.JsonString;
import javax.json.JsonValue;
import java.io.Serializable;
import java.io.StringReader;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import org.apache.activemq.artemis.api.config.ActiveMQDefaultConfiguration;
import org.apache.activemq.artemis.api.core.client.ActiveMQClient;
import org.apache.activemq.artemis.core.server.ComponentConfigurationRoutingType;
import org.apache.activemq.artemis.utils.JsonLoader;
public final class BridgeConfiguration implements Serializable {
private static final long serialVersionUID = -1057244274380572226L;
public static String NAME = "name";
public static String QUEUE_NAME = "queue-name";
public static String FORWARDING_ADDRESS = "forwarding-address";
public static String FILTER_STRING = "filter-string";
public static String STATIC_CONNECTORS = "static-connectors";
public static String DISCOVERY_GROUP_NAME = "discovery-group-name";
public static String HA = "ha";
public static String TRANSFORMER_CONFIGURATION = "transformer-configuration";
public static String RETRY_INTERVAL = "retry-interval";
public static String RETRY_INTERVAL_MULTIPLIER = "retry-interval-multiplier";
public static String INITIAL_CONNECT_ATTEMPTS = "initial-connect-attempts";
public static String RECONNECT_ATTEMPTS = "reconnect-attempts";
public static String RECONNECT_ATTEMPTS_ON_SAME_NODE = "reconnect-attempts-on-same-node";
public static String USE_DUPLICATE_DETECTION = "use-duplicate-detection";
public static String CONFIRMATION_WINDOW_SIZE = "confirmation-window-size";
public static String PRODUCER_WINDOW_SIZE = "producer-window-size";
public static String CLIENT_FAILURE_CHECK_PERIOD = "client-failure-check-period";
public static String USER = "user";
public static String PASSWORD = "password";
public static String CONNECTION_TTL = "connection-ttl";
public static String MAX_RETRY_INTERVAL = "max-retry-interval";
public static String MIN_LARGE_MESSAGE_SIZE = "min-large-message-size";
public static String CALL_TIMEOUT = "call-timeout";
public static String ROUTING_TYPE = "routing-type";
public static String CONCURRENCY = "concurrency";
private String name = null;
private String queueName = null;
private String forwardingAddress = null;
private String filterString = null;
private List<String> staticConnectors = null;
private String discoveryGroupName = null;
private boolean ha = false;
private TransformerConfiguration transformerConfiguration = null;
private long retryInterval = ActiveMQClient.DEFAULT_RETRY_INTERVAL;
private double retryIntervalMultiplier = ActiveMQClient.DEFAULT_RETRY_INTERVAL_MULTIPLIER;
private int initialConnectAttempts = ActiveMQDefaultConfiguration.getDefaultBridgeInitialConnectAttempts();
private int reconnectAttempts = ActiveMQDefaultConfiguration.getDefaultBridgeReconnectAttempts();
private int reconnectAttemptsOnSameNode = ActiveMQDefaultConfiguration.getDefaultBridgeConnectSameNode();
private boolean useDuplicateDetection = ActiveMQDefaultConfiguration.isDefaultBridgeDuplicateDetection();
private int confirmationWindowSize = ActiveMQDefaultConfiguration.getDefaultBridgeConfirmationWindowSize();
// disable flow control
private int producerWindowSize = ActiveMQDefaultConfiguration.getDefaultBridgeProducerWindowSize();
private long clientFailureCheckPeriod = ActiveMQClient.DEFAULT_CLIENT_FAILURE_CHECK_PERIOD;
private String user = ActiveMQDefaultConfiguration.getDefaultClusterUser();
private String password = ActiveMQDefaultConfiguration.getDefaultClusterPassword();
private long connectionTTL = ActiveMQClient.DEFAULT_CONNECTION_TTL;
private long maxRetryInterval = ActiveMQClient.DEFAULT_MAX_RETRY_INTERVAL;
private int minLargeMessageSize = ActiveMQClient.DEFAULT_MIN_LARGE_MESSAGE_SIZE;
// At this point this is only changed on testcases
// The bridge shouldn't be sending blocking anyways
private long callTimeout = ActiveMQClient.DEFAULT_CALL_TIMEOUT;
private ComponentConfigurationRoutingType routingType = ComponentConfigurationRoutingType.valueOf(ActiveMQDefaultConfiguration.getDefaultBridgeRoutingType());
private int concurrency = ActiveMQDefaultConfiguration.getDefaultBridgeConcurrency();
public BridgeConfiguration() {
}
public BridgeConfiguration(String name) {
setName(name);
}
/**
* Set the value of a parameter based on its "key" {@code String}. Valid key names and corresponding {@code static}
* {@code final} are:
* <p><ul>
* <li>name: {@link #NAME}
* <li>queue-name: {@link #QUEUE_NAME}
* <li>forwarding-address: {@link #FORWARDING_ADDRESS}
* <li>filter-string: {@link #FILTER_STRING}
* <li>static-connectors: {@link #STATIC_CONNECTORS}
* <li>discovery-group-name: {@link #DISCOVERY_GROUP_NAME}
* <li>ha: {@link #HA}
* <li>transformer-configuration: {@link #TRANSFORMER_CONFIGURATION}
* <li>retry-interval: {@link #RETRY_INTERVAL}
* <li>RETRY-interval-multiplier: {@link #RETRY_INTERVAL_MULTIPLIER}
* <li>initial-connect-attempts: {@link #INITIAL_CONNECT_ATTEMPTS}
* <li>reconnect-attempts: {@link #RECONNECT_ATTEMPTS}
* <li>reconnect-attempts-on-same-node: {@link #RECONNECT_ATTEMPTS_ON_SAME_NODE}
* <li>use-duplicate-detection: {@link #USE_DUPLICATE_DETECTION}
* <li>confirmation-window-size: {@link #CONFIRMATION_WINDOW_SIZE}
* <li>producer-window-size: {@link #PRODUCER_WINDOW_SIZE}
* <li>client-failure-check-period: {@link #CLIENT_FAILURE_CHECK_PERIOD}
* <li>user: {@link #USER}
* <li>password: {@link #PASSWORD}
* <li>connection-ttl: {@link #CONNECTION_TTL}
* <li>max-retry-interval: {@link #MAX_RETRY_INTERVAL}
* <li>min-large-message-size: {@link #MIN_LARGE_MESSAGE_SIZE}
* <li>call-timeout: {@link #CALL_TIMEOUT}
* <li>routing-type: {@link #ROUTING_TYPE}
* <li>concurrency: {@link #CONCURRENCY}
* </ul><p>
* The {@code String}-based values will be converted to the proper value types based on the underlying property. For
* example, if you pass the value "TRUE" for the key "auto-created" the {@code String} "TRUE" will be converted to
* the {@code Boolean} {@code true}.
*
* @param key the key to set to the value
* @param value the value to set for the key
* @return this {@code BridgeConfiguration}
*/
public BridgeConfiguration set(String key, String value) {
if (key != null) {
if (key.equals(NAME)) {
setName(value);
} else if (key.equals(QUEUE_NAME)) {
setQueueName(value);
} else if (key.equals(FORWARDING_ADDRESS)) {
setForwardingAddress(value);
} else if (key.equals(FILTER_STRING)) {
setFilterString(value);
} else if (key.equals(STATIC_CONNECTORS)) {
// convert JSON array to string list
List<String> stringList = JsonLoader.readArray(new StringReader(value)).stream()
.map(v -> ((JsonString) v).getString())
.collect(Collectors.toList());
setStaticConnectors(stringList);
} else if (key.equals(DISCOVERY_GROUP_NAME)) {
setDiscoveryGroupName(value);
} else if (key.equals(HA)) {
setHA(Boolean.parseBoolean(value));
} else if (key.equals(TRANSFORMER_CONFIGURATION)) {
// create a transformer instance from a JSON string
TransformerConfiguration transformerConfiguration = TransformerConfiguration.fromJSON(value);
if (transformerConfiguration != null) {
setTransformerConfiguration(transformerConfiguration);
}
} else if (key.equals(RETRY_INTERVAL)) {
setRetryInterval(Long.parseLong(value));
} else if (key.equals(RETRY_INTERVAL_MULTIPLIER)) {
setRetryIntervalMultiplier(Double.parseDouble(value));
} else if (key.equals(INITIAL_CONNECT_ATTEMPTS)) {
setInitialConnectAttempts(Integer.parseInt(value));
} else if (key.equals(RECONNECT_ATTEMPTS)) {
setReconnectAttempts(Integer.parseInt(value));
} else if (key.equals(RECONNECT_ATTEMPTS_ON_SAME_NODE)) {
setReconnectAttemptsOnSameNode(Integer.parseInt(value));
} else if (key.equals(USE_DUPLICATE_DETECTION)) {
setUseDuplicateDetection(Boolean.parseBoolean(value));
} else if (key.equals(CONFIRMATION_WINDOW_SIZE)) {
setConfirmationWindowSize(Integer.parseInt(value));
} else if (key.equals(PRODUCER_WINDOW_SIZE)) {
setProducerWindowSize(Integer.parseInt(value));
} else if (key.equals(CLIENT_FAILURE_CHECK_PERIOD)) {
setClientFailureCheckPeriod(Long.parseLong(value));
} else if (key.equals(USER)) {
setUser(value);
} else if (key.equals(PASSWORD)) {
setPassword(value);
} else if (key.equals(CONNECTION_TTL)) {
setConnectionTTL(Long.parseLong(value));
} else if (key.equals(MAX_RETRY_INTERVAL)) {
setMaxRetryInterval(Long.parseLong(value));
} else if (key.equals(MIN_LARGE_MESSAGE_SIZE)) {
setMinLargeMessageSize(Integer.parseInt(value));
} else if (key.equals(CALL_TIMEOUT)) {
setCallTimeout(Long.parseLong(value));
} else if (key.equals(ROUTING_TYPE)) {
setRoutingType(ComponentConfigurationRoutingType.valueOf(value));
} else if (key.equals(CONCURRENCY)) {
setConcurrency(Integer.parseInt(value));
}
}
return this;
}
public String getName() {
return name;
}
/**
* @param name the name to set
*/
public BridgeConfiguration setName(final String name) {
this.name = name;
return this;
}
public String getQueueName() {
return queueName;
}
/**
* @param queueName the queueName to set
*/
public BridgeConfiguration setQueueName(final String queueName) {
this.queueName = queueName;
return this;
}
/**
* @return the connectionTTL
*/
public long getConnectionTTL() {
return connectionTTL;
}
public BridgeConfiguration setConnectionTTL(long connectionTTL) {
this.connectionTTL = connectionTTL;
return this;
}
/**
* @return the maxRetryInterval
*/
public long getMaxRetryInterval() {
return maxRetryInterval;
}
public BridgeConfiguration setMaxRetryInterval(long maxRetryInterval) {
this.maxRetryInterval = maxRetryInterval;
return this;
}
public String getForwardingAddress() {
return forwardingAddress;
}
/**
* @param forwardingAddress the forwardingAddress to set
*/
public BridgeConfiguration setForwardingAddress(final String forwardingAddress) {
this.forwardingAddress = forwardingAddress;
return this;
}
public String getFilterString() {
return filterString;
}
/**
* @param filterString the filterString to set
*/
public BridgeConfiguration setFilterString(final String filterString) {
this.filterString = filterString;
return this;
}
public TransformerConfiguration getTransformerConfiguration() {
return transformerConfiguration;
}
/**
* @param transformerConfiguration the transformerConfiguration to set
*/
public BridgeConfiguration setTransformerConfiguration(final TransformerConfiguration transformerConfiguration) {
this.transformerConfiguration = transformerConfiguration;
return this;
}
public List<String> getStaticConnectors() {
return staticConnectors;
}
/**
* @param staticConnectors the staticConnectors to set
*/
public BridgeConfiguration setStaticConnectors(final List<String> staticConnectors) {
this.staticConnectors = staticConnectors;
return this;
}
public String getDiscoveryGroupName() {
return discoveryGroupName;
}
/**
* @param discoveryGroupName the discoveryGroupName to set
*/
public BridgeConfiguration setDiscoveryGroupName(final String discoveryGroupName) {
this.discoveryGroupName = discoveryGroupName;
return this;
}
public boolean isHA() {
return ha;
}
/**
* @param ha is the bridge supporting HA?
*/
public BridgeConfiguration setHA(final boolean ha) {
this.ha = ha;
return this;
}
public long getRetryInterval() {
return retryInterval;
}
/**
* @param retryInterval the retryInterval to set
*/
public BridgeConfiguration setRetryInterval(final long retryInterval) {
this.retryInterval = retryInterval;
return this;
}
public double getRetryIntervalMultiplier() {
return retryIntervalMultiplier;
}
/**
* @param retryIntervalMultiplier the retryIntervalMultiplier to set
*/
public BridgeConfiguration setRetryIntervalMultiplier(final double retryIntervalMultiplier) {
this.retryIntervalMultiplier = retryIntervalMultiplier;
return this;
}
public int getInitialConnectAttempts() {
return initialConnectAttempts;
}
/**
* @param initialConnectAttempts the initialConnectAttempts to set
*/
public BridgeConfiguration setInitialConnectAttempts(final int initialConnectAttempts) {
this.initialConnectAttempts = initialConnectAttempts;
return this;
}
public int getReconnectAttempts() {
return reconnectAttempts;
}
/**
* @param reconnectAttempts the reconnectAttempts to set
*/
public BridgeConfiguration setReconnectAttempts(final int reconnectAttempts) {
this.reconnectAttempts = reconnectAttempts;
return this;
}
public boolean isUseDuplicateDetection() {
return useDuplicateDetection;
}
/**
* @param useDuplicateDetection the useDuplicateDetection to set
*/
public BridgeConfiguration setUseDuplicateDetection(final boolean useDuplicateDetection) {
this.useDuplicateDetection = useDuplicateDetection;
return this;
}
public int getConfirmationWindowSize() {
return confirmationWindowSize;
}
/**
* @param confirmationWindowSize the confirmationWindowSize to set
*/
public BridgeConfiguration setConfirmationWindowSize(final int confirmationWindowSize) {
this.confirmationWindowSize = confirmationWindowSize;
return this;
}
public int getProducerWindowSize() {
return producerWindowSize;
}
/**
* @param producerWindowSize the producerWindowSize to set
*/
public BridgeConfiguration setProducerWindowSize(final int producerWindowSize) {
this.producerWindowSize = producerWindowSize;
return this;
}
public long getClientFailureCheckPeriod() {
return clientFailureCheckPeriod;
}
public BridgeConfiguration setClientFailureCheckPeriod(long clientFailureCheckPeriod) {
this.clientFailureCheckPeriod = clientFailureCheckPeriod;
return this;
}
/**
* @return the minLargeMessageSize
*/
public int getMinLargeMessageSize() {
return minLargeMessageSize;
}
public BridgeConfiguration setMinLargeMessageSize(int minLargeMessageSize) {
this.minLargeMessageSize = minLargeMessageSize;
return this;
}
public String getUser() {
return user;
}
public BridgeConfiguration setUser(String user) {
this.user = user;
return this;
}
public String getPassword() {
return password;
}
public BridgeConfiguration setPassword(String password) {
this.password = password;
return this;
}
/**
* @return the callTimeout
*/
public long getCallTimeout() {
return callTimeout;
}
public int getReconnectAttemptsOnSameNode() {
return reconnectAttemptsOnSameNode;
}
public BridgeConfiguration setReconnectAttemptsOnSameNode(int reconnectAttemptsOnSameNode) {
this.reconnectAttemptsOnSameNode = reconnectAttemptsOnSameNode;
return this;
}
public ComponentConfigurationRoutingType getRoutingType() {
return routingType;
}
public BridgeConfiguration setRoutingType(ComponentConfigurationRoutingType routingType) {
this.routingType = routingType;
return this;
}
/**
* @return the bridge concurrency
*/
public int getConcurrency() {
return concurrency;
}
/**
* @param concurrency the bridge concurrency to set
*/
public BridgeConfiguration setConcurrency(int concurrency) {
this.concurrency = concurrency;
return this;
}
/**
* At this point this is only changed on testcases
* The bridge shouldn't be sending blocking anyways
*
* @param callTimeout the callTimeout to set
*/
public BridgeConfiguration setCallTimeout(long callTimeout) {
this.callTimeout = callTimeout;
return this;
}
/**
* This method returns a JSON-formatted {@code String} representation of this {@code BridgeConfiguration}. It is a
* simple collection of key/value pairs. The keys used are referenced in {@link #set(String, String)}.
*
* @return a JSON-formatted {@code String} representation of this {@code BridgeConfiguration}
*/
public String toJSON() {
JsonObjectBuilder builder = JsonLoader.createObjectBuilder();
// string fields which default to null (only serialize if value is not null)
if (getName() != null) {
builder.add(NAME, getName());
}
if (getQueueName() != null) {
builder.add(QUEUE_NAME, getQueueName());
}
if (getForwardingAddress() != null) {
builder.add(FORWARDING_ADDRESS, getForwardingAddress());
}
if (getFilterString() != null) {
builder.add(FILTER_STRING, getFilterString());
}
if (getDiscoveryGroupName() != null) {
builder.add(DISCOVERY_GROUP_NAME, getDiscoveryGroupName());
}
// string fields which default to non-null values (always serialize)
addNullable(builder, USER, getUser());
addNullable(builder, PASSWORD, getPassword());
// primitive data type fields (always serialize)
builder.add(HA, isHA());
builder.add(RETRY_INTERVAL, getRetryInterval());
builder.add(RETRY_INTERVAL_MULTIPLIER, getRetryIntervalMultiplier());
builder.add(INITIAL_CONNECT_ATTEMPTS, getInitialConnectAttempts());
builder.add(RECONNECT_ATTEMPTS, getReconnectAttempts());
builder.add(RECONNECT_ATTEMPTS_ON_SAME_NODE, getReconnectAttemptsOnSameNode());
builder.add(USE_DUPLICATE_DETECTION, isUseDuplicateDetection());
builder.add(CONFIRMATION_WINDOW_SIZE, getConfirmationWindowSize());
builder.add(PRODUCER_WINDOW_SIZE, getProducerWindowSize());
builder.add(CLIENT_FAILURE_CHECK_PERIOD, getClientFailureCheckPeriod());
builder.add(CONNECTION_TTL, getConnectionTTL());
builder.add(MAX_RETRY_INTERVAL, getMaxRetryInterval());
builder.add(MIN_LARGE_MESSAGE_SIZE, getMinLargeMessageSize());
builder.add(CALL_TIMEOUT, getCallTimeout());
builder.add(CONCURRENCY, getConcurrency());
// complex fields (only serialize if value is not null)
if (getRoutingType() != null) {
builder.add(ROUTING_TYPE, getRoutingType().name());
}
final List<String> staticConnectors = getStaticConnectors();
if (staticConnectors != null) {
JsonArrayBuilder arrayBuilder = JsonLoader.createArrayBuilder();
staticConnectors.forEach(arrayBuilder::add);
builder.add(STATIC_CONNECTORS, arrayBuilder);
}
TransformerConfiguration tc = getTransformerConfiguration();
if (tc != null) {
JsonObjectBuilder tcBuilder = JsonLoader.createObjectBuilder().add(TransformerConfiguration.CLASS_NAME, tc.getClassName());
if (tc.getProperties() != null && tc.getProperties().size() > 0) {
JsonObjectBuilder propBuilder = JsonLoader.createObjectBuilder();
tc.getProperties().forEach(propBuilder::add);
tcBuilder.add(TransformerConfiguration.PROPERTIES, propBuilder);
}
builder.add(TRANSFORMER_CONFIGURATION, tcBuilder);
}
return builder.build().toString();
}
private static void addNullable(JsonObjectBuilder builder, String key, String value) {
if (value == null) {
builder.addNull(key);
} else {
builder.add(key, value);
}
}
/**
* This method returns a {@code BridgeConfiguration} created from the JSON-formatted input {@code String}. The input
* should be a simple object of key/value pairs. Valid keys are referenced in {@link #set(String, String)}.
*
* @param jsonString json string
* @return the {@code BridgeConfiguration} created from the JSON-formatted input {@code String}
*/
public static BridgeConfiguration fromJSON(String jsonString) {
JsonObject json = JsonLoader.readObject(new StringReader(jsonString));
// name is the only required value
if (!json.containsKey(NAME)) {
return null;
}
BridgeConfiguration result = new BridgeConfiguration(json.getString(NAME));
for (Map.Entry<String, JsonValue> entry : json.entrySet()) {
if (entry.getValue().getValueType() == JsonValue.ValueType.STRING) {
result.set(entry.getKey(), ((JsonString) entry.getValue()).getString());
} else if (entry.getValue().getValueType() == JsonValue.ValueType.NULL) {
result.set(entry.getKey(), null);
} else {
result.set(entry.getKey(), entry.getValue().toString());
}
}
return result;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + (int) (callTimeout ^ (callTimeout >>> 32));
result = prime * result + (int) (clientFailureCheckPeriod ^ (clientFailureCheckPeriod >>> 32));
result = prime * result + confirmationWindowSize;
result = prime * result + producerWindowSize;
result = prime * result + (int) (connectionTTL ^ (connectionTTL >>> 32));
result = prime * result + ((discoveryGroupName == null) ? 0 : discoveryGroupName.hashCode());
result = prime * result + ((filterString == null) ? 0 : filterString.hashCode());
result = prime * result + ((forwardingAddress == null) ? 0 : forwardingAddress.hashCode());
result = prime * result + (ha ? 1231 : 1237);
result = prime * result + (int) (maxRetryInterval ^ (maxRetryInterval >>> 32));
result = prime * result + minLargeMessageSize;
result = prime * result + ((name == null) ? 0 : name.hashCode());
result = prime * result + ((password == null) ? 0 : password.hashCode());
result = prime * result + ((queueName == null) ? 0 : queueName.hashCode());
result = prime * result + initialConnectAttempts;
result = prime * result + reconnectAttempts;
result = prime * result + (int) (retryInterval ^ (retryInterval >>> 32));
long temp;
temp = Double.doubleToLongBits(retryIntervalMultiplier);
result = prime * result + (int) (temp ^ (temp >>> 32));
result = prime * result + ((staticConnectors == null) ? 0 : staticConnectors.hashCode());
result = prime * result + ((transformerConfiguration == null) ? 0 : transformerConfiguration.hashCode());
result = prime * result + (useDuplicateDetection ? 1231 : 1237);
result = prime * result + ((user == null) ? 0 : user.hashCode());
result = prime * result + concurrency;
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
BridgeConfiguration other = (BridgeConfiguration) obj;
if (callTimeout != other.callTimeout)
return false;
if (clientFailureCheckPeriod != other.clientFailureCheckPeriod)
return false;
if (confirmationWindowSize != other.confirmationWindowSize)
return false;
if (producerWindowSize != other.producerWindowSize)
return false;
if (connectionTTL != other.connectionTTL)
return false;
if (discoveryGroupName == null) {
if (other.discoveryGroupName != null)
return false;
} else if (!discoveryGroupName.equals(other.discoveryGroupName))
return false;
if (filterString == null) {
if (other.filterString != null)
return false;
} else if (!filterString.equals(other.filterString))
return false;
if (forwardingAddress == null) {
if (other.forwardingAddress != null)
return false;
} else if (!forwardingAddress.equals(other.forwardingAddress))
return false;
if (ha != other.ha)
return false;
if (maxRetryInterval != other.maxRetryInterval)
return false;
if (minLargeMessageSize != other.minLargeMessageSize)
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
if (password == null) {
if (other.password != null)
return false;
} else if (!password.equals(other.password))
return false;
if (queueName == null) {
if (other.queueName != null)
return false;
} else if (!queueName.equals(other.queueName))
return false;
if (initialConnectAttempts != other.initialConnectAttempts)
return false;
if (reconnectAttempts != other.reconnectAttempts)
return false;
if (retryInterval != other.retryInterval)
return false;
if (Double.doubleToLongBits(retryIntervalMultiplier) != Double.doubleToLongBits(other.retryIntervalMultiplier))
return false;
if (staticConnectors == null) {
if (other.staticConnectors != null)
return false;
} else if (!staticConnectors.equals(other.staticConnectors))
return false;
if (transformerConfiguration == null) {
if (other.transformerConfiguration != null)
return false;
} else if (!transformerConfiguration.equals(other.transformerConfiguration))
return false;
if (useDuplicateDetection != other.useDuplicateDetection)
return false;
if (user == null) {
if (other.user != null)
return false;
} else if (!user.equals(other.user))
return false;
if (concurrency != other.concurrency)
return false;
return true;
}
}
| 36.801061 | 161 | 0.686968 |
577a5b7267d5dfc89a5bd4ceb6fb5e32ae82751e | 1,424 |
public class multiD {
public static void main(String[] args){
//normal int array - 1D array
int[] values = {3, 4, 5};
//int 2D array
int[][] grid_values = {
{1,2,3},
{4,5,6},
{7,8,9}
};
for(int row=0; row < grid_values.length; row++){
for(int col=0; col < grid_values[row].length; col++){
System.out.print(grid_values[row][col] + "\t");
/*Java knows that even tho we got an int
when it sees the '+' which means concatenation
it automatically converts it as a string
*/
}
System.out.println();
}
//-------------------------------------
/*1. new insight
--allocating memory of same sizes regarding the first and second dimension
*/
//normal string array - 1D array
String[] texts = new String[3];
//String 2D array
String[][] grid_texts = new String[2][3];
grid_texts[0][1] = "Hello there"; //accessing--assigning values
//-----------------------------------
/*2. new for me
--allocating memory of second dimension to different sizes
*/
String[][] new_grid = new String[2][];
//see that the second number in new String[2][] is not defined.
//that will cause an error if you don't do the things below
new_grid[0] = new String[1];
new_grid[1] = new String[3];
new_grid[0][0] = "lala";
new_grid[1][2] = "po";
System.out.println(new_grid[0][0]);
System.out.println(new_grid[1][2]);
}
}
| 24.551724 | 81 | 0.577949 |
62f22e56398c8fa8040497e1eecb554e2b2861e0 | 3,560 | package com.nightonke.boommenusample;
import android.graphics.Color;
import com.nightonke.boommenu.BoomButtons.HamButton;
import com.nightonke.boommenu.BoomButtons.SimpleCircleButton;
import com.nightonke.boommenu.BoomButtons.TextInsideCircleButton;
import com.nightonke.boommenu.BoomButtons.TextOutsideCircleButton;
/**
* Created by Weiping Huang at 23:44 on 16/11/21
* For Personal Open Source
* Contact me at [email protected] or [email protected]
* For more projects: https://github.com/Nightonke
*/
public class BuilderManager {
private static int[] imageResources = new int[]{
R.drawable.bat,
R.drawable.bear,
R.drawable.bee,
R.drawable.butterfly,
R.drawable.cat,
R.drawable.deer,
R.drawable.dolphin,
R.drawable.eagle,
R.drawable.horse,
R.drawable.jellyfish,
R.drawable.owl,
R.drawable.peacock,
R.drawable.pig,
R.drawable.rat,
R.drawable.snake,
R.drawable.squirrel
};
private static int imageResourceIndex = 0;
static int getImageResource() {
if (imageResourceIndex >= imageResources.length) imageResourceIndex = 0;
return imageResources[imageResourceIndex++];
}
static SimpleCircleButton.Builder getSimpleCircleButtonBuilder() {
return new SimpleCircleButton.Builder()
.normalImageRes(getImageResource());
}
static TextInsideCircleButton.Builder getTextInsideCircleButtonBuilder() {
return new TextInsideCircleButton.Builder()
.normalImageRes(getImageResource())
.normalTextRes(R.string.text_inside_circle_button_text_normal);
}
static TextInsideCircleButton.Builder getTextInsideCircleButtonBuilderWithDifferentPieceColor() {
return new TextInsideCircleButton.Builder()
.normalImageRes(getImageResource())
.normalTextRes(R.string.text_inside_circle_button_text_normal)
.pieceColor(Color.WHITE);
}
static TextOutsideCircleButton.Builder getTextOutsideCircleButtonBuilder() {
return new TextOutsideCircleButton.Builder()
.normalImageRes(getImageResource())
.normalTextRes(R.string.text_outside_circle_button_text_normal);
}
static TextOutsideCircleButton.Builder getTextOutsideCircleButtonBuilderWithDifferentPieceColor() {
return new TextOutsideCircleButton.Builder()
.normalImageRes(getImageResource())
.normalTextRes(R.string.text_outside_circle_button_text_normal)
.pieceColor(Color.WHITE);
}
static HamButton.Builder getHamButtonBuilder() {
return new HamButton.Builder()
.normalImageRes(getImageResource())
.normalTextRes(R.string.text_ham_button_text_normal)
.subNormalTextRes(R.string.text_ham_button_sub_text_normal);
}
static HamButton.Builder getHamButtonBuilderWithDifferentPieceColor() {
return new HamButton.Builder()
.normalImageRes(getImageResource())
.normalTextRes(R.string.text_ham_button_text_normal)
.subNormalTextRes(R.string.text_ham_button_sub_text_normal)
.pieceColor(Color.WHITE);
}
private static BuilderManager ourInstance = new BuilderManager();
public static BuilderManager getInstance() {
return ourInstance;
}
private BuilderManager() {
}
}
| 35.959596 | 103 | 0.678371 |
aca24cbc780dbb5d32c55899bee0771535ba779f | 1,256 | /*
* 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.wuwang.aavt.media.hard;
import android.util.SparseArray;
import java.util.concurrent.LinkedBlockingQueue;
/**
* Recycler
*
* @author wuwang
* @version v1.0 2017:11:08 16:16
*/
class Recycler<T> {
private SparseArray<LinkedBlockingQueue<T>> datas=new SparseArray<>();
public void put(int index,T t){
if(datas.indexOfKey(index)<0){
datas.append(index,new LinkedBlockingQueue<T>());
}
datas.get(index).add(t);
}
public T poll(int index){
if(datas.indexOfKey(index)>=0){
return datas.get(index).poll();
}
return null;
}
public void clear(){
datas.clear();
}
}
| 25.632653 | 75 | 0.661624 |
188c4763d914d2e631e49223fc22e48720e579f8 | 3,956 | /*
* $Id: ImageArgument.java 3271 2008-04-18 20:39:42Z xlv $
* Copyright (c) 2005-2007 Bruno Lowagie, Carsten Hammer
*
* 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.
*/
/*
* This class was originally published under the MPL by Bruno Lowagie
* and Carsten Hammer.
* It was a part of iText, a Java-PDF library. You can now use it under
* the MIT License; for backward compatibility you can also use it under
* the MPL version 1.1: http://www.mozilla.org/MPL/
* A copy of the MPL license is bundled with the source code FYI.
*/
package com.lowagie.toolbox.arguments;
import java.awt.event.ActionEvent;
import javax.swing.JFileChooser;
import javax.swing.filechooser.FileFilter;
import com.lowagie.text.Image;
import com.lowagie.toolbox.AbstractTool;
import com.lowagie.toolbox.arguments.filters.ImageFilter;
/**
* StringArgument class if the argument is a com.lowagie.text.Image.
* @since 2.1.1 (imported from itexttoolbox project)
*/
public class ImageArgument extends AbstractArgument {
/** a filter to put on the FileChooser. */
private FileFilter filter;
/**
* Constructs a FileArgument.
* @param tool the tool that needs this argument
* @param name the name of the argument
* @param description the description of the argument
* @param filter a custom filter
*/
public ImageArgument(AbstractTool tool, String name, String description,
FileFilter filter) {
super(tool, name, description, null);
this.filter = filter;
}
/**
* Constructs a FileArgument.
* @param tool the tool that needs this argument
* @param name the name of the argument
* @param description the description of the argument
*/
public ImageArgument(AbstractTool tool, String name, String description) {
this(tool, name, description, new ImageFilter());
}
/**
* Gets the argument as an object.
* @return an object
* @throws InstantiationException
*/
public Object getArgument() throws InstantiationException {
if (value == null) {
return null;
}
try {
return Image.getInstance(value.toString());
} catch (Exception e) {
throw new InstantiationException(e.getMessage());
}
}
/**
*
* @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent)
* @param e ActionEvent
*/
public void actionPerformed(ActionEvent e) {
JFileChooser fc = new JFileChooser();
if (filter != null) {
fc.setFileFilter(filter);
}
fc.showOpenDialog(tool.getInternalFrame());
try {
setValue(fc.getSelectedFile().getAbsolutePath());
} catch (NullPointerException npe) {
}
}
}
| 35.321429 | 86 | 0.665824 |
cedbf4e7b5315495dfd9268dfe182d3878582120 | 743 | package org.abcframework.common.configuration.cache;
import java.util.List;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.cache.CacheManagerCustomizer;
import org.springframework.cache.concurrent.ConcurrentMapCacheManager;
import org.springframework.stereotype.Component;
@Component
public class CacheNamesCustomizer implements CacheManagerCustomizer<ConcurrentMapCacheManager> {
@Value("${cache.name.list}")
private List<String> cacheNameList;
public List<String> getCacheNameList() {
return cacheNameList;
}
@Override
public void customize(ConcurrentMapCacheManager cacheManager) {
cacheManager.setCacheNames(this.cacheNameList);
}
}
| 32.304348 | 97 | 0.79677 |
8ae88b5db732e7f99e6807141587899bf6eae663 | 1,045 | package com.MyCode.array.ArrayRotation;
/*
**
* Reference :- https://www.geeksforgeeks.org/program-for-array-rotation-continued-reversal-algorithm/
*/
public class ReverseAlgoforArrayRotation {
public static void main(String[] args) {
int arr[] = {1, 2, 3, 4, 5, 6, 7};
int n = arr.length;
int d = 2;
d=d%n;
arr=leftRotate(arr,d,n);
printArr(arr);
}
private static void printArr(int[] arr) {
for (int i = 0; i < arr.length; i++)
System.out.print(arr[i] +" ");
}
private static int[] leftRotate(int[] arr, int d,int n) {
arr=reverseArray(arr,0,d-1);
arr=reverseArray(arr,d,n-1);
arr=reverseArray(arr,0,n-1);
return arr;
}
private static int[] reverseArray(int[] arr, int start, int end) {
int temp;
while (start<end){
temp = arr[start];
arr[start]=arr[end];
arr[end]=temp;
start++;end--;
}
return arr;
}
}
| 20.490196 | 103 | 0.524402 |
334e82bc6c7bb6648baaf9de0a5b6514fa09ba06 | 464 | package com.bianmaren.service;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bianmaren.model.BaseModel;
/**
* @ClassName : SysSettingServiceImpl
* @Description : BaseService
* @Author : bianmaren
* @Date: 2020-08-20 23:47
* @Blog: http://www.bianmaren.com
*/
public class BaseServiceImpl<M extends BaseMapper<T>, T extends BaseModel> extends ServiceImpl<M, T> {
}
| 24.421053 | 102 | 0.760776 |
b8f5bb2b3d6dd8c3f0b8eaf8dc911d1c89c76e06 | 302 | package pv168.hotelmasters.superhotel;
import java.util.List;
/**
* @author 445434
*/
public interface GuestManager {
void createGuest(Guest guest);
void updateGuest(Guest guest);
void deleteGuest(Guest guest);
Guest findGuestById(Long guestId);
List<Guest> findAllGuests();
}
| 18.875 | 38 | 0.718543 |
b5b08b1ede2e45ac8ec53a9098c3cf32a19daded | 1,590 | /*
* Copyright (c) 2019 Rica Radu-Leonard
*/
package game.resources.characters.angels;
import game.resources.characters.angels.abstracts.Angel;
import game.resources.characters.heroes.knight.Knight;
import game.resources.characters.heroes.pyromancer.Pyromancer;
import game.resources.characters.heroes.rogue.Rogue;
import game.resources.characters.heroes.wizard.Wizard;
import game.resources.common.Constants;
public final class TheDoomer extends Angel {
public TheDoomer(final int line, final int column) {
super(line, column);
}
@Override
public void applyBuff(final Knight knight) {
if (!knight.isDead()) {
sendHitNotification(knight);
sendKilledNotification(knight);
knight.setHealthPoints(0);
}
}
@Override
public void applyBuff(final Pyromancer pyromancer) {
if (!pyromancer.isDead()) {
sendHitNotification(pyromancer);
sendKilledNotification(pyromancer);
pyromancer.setHealthPoints(0);
}
}
@Override
public void applyBuff(final Rogue rogue) {
if (!rogue.isDead()) {
sendHitNotification(rogue);
sendKilledNotification(rogue);
rogue.setHealthPoints(0);
}
}
@Override
public void applyBuff(final Wizard wizard) {
if (!wizard.isDead()) {
sendHitNotification(wizard);
sendKilledNotification(wizard);
wizard.setHealthPoints(0);
}
}
public String getType() {
return Constants.THE_DOOMER;
}
}
| 26.949153 | 62 | 0.64717 |
6fa659ab753a366b2e5903f0253c4d4c156d9f6b | 687 | package com.bad_elf.badelfgps;
import java.util.List;
import com.bad_elf.badelfgps.BadElfRemoteControlServer;
public class BadElfRemoteController {
public static final String TAG = "BadElfRemoteController";
private List<BadElfDevice> badElfDevices;
private BadElfRemoteControlServer server;
private BadElfDevice selectedDevice;
public void start() {
server = new BadElfRemoteControlServer();
}
public void stop() {
}
public void setDeviceList(List<BadElfDevice> badElfDevices) {
this.badElfDevices = badElfDevices;
}
public void setSelectedDevice(BadElfDevice device) {
this.selectedDevice = device;
}
}
| 21.46875 | 65 | 0.72198 |
e5e561b458c477b2ba7102aa74a18bcc27236ec1 | 4,347 | package edu.ucam.ux;
import java.util.List;
import javax.swing.BoxLayout;
import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.ListSelectionModel;
import edu.ucam.beans.Asignatura;
import edu.ucam.dao.InterfaceAsignatura;
import edu.ucam.dao.InterfaceExpediente;
import edu.ucam.dao.implement.AsignaturaImplement;
import edu.ucam.dao.implement.ExpedienteImplement;
import edu.ucam.ux.actions.ActionLogin;
import edu.ucam.ux.actions.ActionPanelMatricula;
public class PanelMatricula extends JPanel{
/**
*
*/
private static final long serialVersionUID = 1L;
private JList<String> listAsignaturasDisponibles, listAsignaturasMatriculadas;
private DefaultListModel<String> listMDisponibles, listMMatriculadas;
private JScrollPane jscrollDisponibles, jscrollMatriculadas;
private JButton btnAddMatricula;
private JPanel panelMain, panelDisponibles, panelMatriculadas;
public PanelMatricula() {
setSize(600, 300);
add(getPanelDisponibles());
add(getBtnAddMatricula());
add(getPanelMatriculadas());
System.out.println("El usuario logeado es: " + ActionLogin.getAlumnoIdentify().getDni());
}
public JPanel getPanelMain() {
if (panelMain == null) {
panelMain = new JPanel();
panelMain.add(getPanelDisponibles());
panelMain.add(getBtnAddMatricula());
panelMain.add(getlistAsignaturasMatriculadas());
}
return panelMain;
}
public JList<String> getlistAsignaturasDisponibles() {
if (listAsignaturasDisponibles == null) {
listAsignaturasDisponibles = new JList<>(getListMDisponibles());
listAsignaturasDisponibles.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
listAsignaturasDisponibles.setVisibleRowCount(5);
}
return listAsignaturasDisponibles;
}
public JList<String> getlistAsignaturasMatriculadas() {
if (listAsignaturasMatriculadas == null) {
listAsignaturasMatriculadas = new JList<>(getListMMatriculadas());
listAsignaturasDisponibles.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
listAsignaturasDisponibles.setVisibleRowCount(8);
}
return listAsignaturasMatriculadas;
}
public JButton getBtnAddMatricula() {
if (btnAddMatricula == null) {
btnAddMatricula = new JButton(">>");
btnAddMatricula.setActionCommand("addMatricula");
btnAddMatricula.addActionListener(new ActionPanelMatricula(this));
}
return btnAddMatricula;
}
public JScrollPane getJscrollDisponibles() {
if (jscrollDisponibles == null) {
jscrollDisponibles = new JScrollPane(getlistAsignaturasDisponibles());
}
return jscrollDisponibles;
}
public JScrollPane getJscrollMatriculadas() {
if (jscrollMatriculadas == null) {
jscrollMatriculadas = new JScrollPane(getlistAsignaturasMatriculadas());
}
return jscrollMatriculadas;
}
public DefaultListModel<String> getListMDisponibles(){
if (listMDisponibles == null) {
listMDisponibles = new DefaultListModel<>();
InterfaceAsignatura as = new AsignaturaImplement();
for (Asignatura a: as.getOnlyAsignaturas()) {
listMDisponibles.addElement(a.getName());
}
}
return listMDisponibles;
}
public DefaultListModel<String> getListMMatriculadas() {
if (listMMatriculadas == null) {
listMMatriculadas = new DefaultListModel<>();
InterfaceExpediente expediente = new ExpedienteImplement();
List<Asignatura> list = expediente.getAsignaturasMatriculadas(ActionLogin.getAlumnoIdentify());
for (Asignatura a : list) {
listMMatriculadas.addElement(a.getName());
}
}
return listMMatriculadas;
}
public JPanel getPanelDisponibles() {
if (panelDisponibles == null) {
panelDisponibles = new JPanel();
panelDisponibles.setLayout(new BoxLayout(panelDisponibles, BoxLayout.Y_AXIS));
panelDisponibles.add(new JLabel("Asignaturas Disponibles"));
panelDisponibles.add(getJscrollDisponibles());
}
return panelDisponibles;
}
public JPanel getPanelMatriculadas() {
if (panelMatriculadas == null) {
panelMatriculadas = new JPanel();
panelMatriculadas.setLayout(new BoxLayout(panelMatriculadas, BoxLayout.Y_AXIS));
panelMatriculadas.add(new JLabel("Matriculadas"));
panelMatriculadas.add(getJscrollMatriculadas());
}
return panelMatriculadas;
}
}
| 28.788079 | 98 | 0.766736 |
6381c0eef6b46e9a1f8b62a7d418b1948ae017f6 | 2,142 | package org.usfirst.frc.team2506.robot;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import edu.wpi.first.wpilibj.*;
public class RoboLib {
private Joystick joystick;
private RobotDrive driveTrain;
private Map<Integer, Solenoid[]> solenoids = new HashMap<Integer, Solenoid[]>();
private boolean solenoidClear = true;
public RoboLib(Joystick joystick) {
this.joystick = joystick;
}
public RoboLib(int joystickPort) {
this.joystick = new Joystick(joystickPort);
}
public void setupDriveTrain(int left, int right) {
driveTrain = new RobotDrive(left, right);
}
public void setupDriveTrain(int frontLeft, int rearLeft, int frontRight, int rearRight) {
driveTrain = new RobotDrive(frontLeft, rearLeft, frontRight, rearRight);
}
public void setupDriveTrain(SpeedController left, SpeedController right) {
driveTrain = new RobotDrive(left, right);
}
public void setupDriveTrain(SpeedController frontLeft, SpeedController rearLeft, SpeedController frontRight, SpeedController rearRight) {
driveTrain = new RobotDrive(frontLeft, rearLeft, frontRight, rearRight);
}
public void mapPiston(int button, int solenoidOn, int solenoidOff) {
Solenoid[] sols = new Solenoid[2];
sols[0] = new Solenoid(solenoidOn);
sols[1] = new Solenoid(solenoidOff);
solenoids.put(button, sols);
}
public void mapPiston(int button, Solenoid solenoidOn, Solenoid solenoidOff) {
Solenoid[] sols = new Solenoid[2];
sols[0] = solenoidOn;
sols[1] = solenoidOff;
solenoids.put(button, sols);
}
public void swapPiston (Solenoid solenoidOn, Solenoid solenoidOff) {
if (!solenoidOn.get() && solenoidClear) {
solenoidOn.set(true);
solenoidOff.set(false);
solenoidClear = false;
}
if (solenoidOn.get() && solenoidClear) {
solenoidOn.set(false);
solenoidOff.set(true);
solenoidClear = false;
}
}
public void main () {
driveTrain.tankDrive(joystick.getRawAxis(0), joystick.getRawAxis(5));
for (Entry<Integer, Solenoid[]> entry : solenoids.entrySet())
if (joystick.getRawButton(entry.getKey()))
swapPiston(entry.getValue()[0], entry.getValue()[1]);
}
}
| 30.6 | 138 | 0.733427 |
00918ba07bbeb5913b6ab7535049ccfb0aa48bf9 | 234 | public static void mattran_j(double a[][], double at[][], int n, int p) {
int i, j;
for (i = 0; i < n; i++) {
for (j = 0; j < p; j++) {
at[j][i] = a[i][j];
}
}
}
| 26 | 77 | 0.324786 |
76a45a6f9235741161990d6812debab3504077b4 | 1,308 | package com.feng.springcloud.consumer.service.impl;
import com.feng.springcloud.consumer.service.CallService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import javax.annotation.Resource;
import java.util.List;
/**
* consumer
* 2019/12/27 16:00
* ribbon实现服务调用
*
* @author lanhaifeng
* @since
**/
@Service("restTemplateCallService")
@Slf4j
public class RestTemplateCallServiceImpl implements CallService {
@Resource(name = "simpleRestTemplate")
private RestTemplate restTemplate;
@Autowired
private DiscoveryClient discoveryClient;
@Override
public String helloWorld(String serviceName, String name) {
try{
List<ServiceInstance> serviceInstances = discoveryClient.getInstances(serviceName);
return restTemplate.getForObject(serviceInstances.get(0).getUri().toString() + "/hi?name=" + name, String.class);
}catch(Exception e){
log.error("" + ExceptionUtils.getFullStackTrace(e));
return "抱歉" + name + ",服务" + serviceName + "无法访问";
}
}
}
| 30.418605 | 116 | 0.782875 |
e94a16a62d6c22b30cc51cf00c2af3c88a395f7e | 3,384 | package org.lflang.generator;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.lflang.ErrorReporter;
/**
* An error reporting strategy that considers only one line
* of validator output at a time.
*/
public class PerLineReportingStrategy implements CommandErrorReportingStrategy {
private final Pattern p;
/**
* Instantiates a reporting strategy for lines of
* validator output that match {@code p}.
* @param p a pattern that matches lines that should be
* reported via this strategy. This pattern
* must contain named capturing groups called
* "path", "line", "column", "message", and
* "severity".
*/
public PerLineReportingStrategy(Pattern p) {
for (String groupName : new String[]{"path", "line", "column", "message", "severity"}) {
assert p.pattern().contains(groupName) : String.format(
"Error line patterns must have a named capturing group called %s", groupName
);
}
this.p = p;
}
@Override
public void report(String validationOutput, ErrorReporter errorReporter, Map<Path, CodeMap> map) {
validationOutput.lines().forEach(line -> reportErrorLine(line, errorReporter, map));
}
/**
* Reports the validation message contained in
* {@code line} if such a message exists.
* @param line a line of validator output
* @param errorReporter an arbitrary ErrorReporter
* @param maps a mapping from generated file paths to
* CodeMaps
*/
private void reportErrorLine(String line, ErrorReporter errorReporter, Map<Path, CodeMap> maps) {
Matcher matcher = p.matcher(line);
if (matcher.matches()) {
final Path path = Paths.get(matcher.group("path"));
final Position generatedFilePosition = Position.fromOneBased(
Integer.parseInt(matcher.group("line")), Integer.parseInt(matcher.group("column"))
);
final String message = String.format(
"%s [%s:%s:%s]",
matcher.group("message"), path.getFileName(),
matcher.group("line"), matcher.group("column")
);
final CodeMap map = maps.get(path);
final boolean isError = matcher.group("severity").toLowerCase().contains("error");
if (map == null) {
if (isError) {
errorReporter.reportError(message);
} else {
errorReporter.reportWarning(message);
}
return;
}
for (Path srcFile : map.lfSourcePaths()) {
// FIXME: Is it desirable for the error to be reported to every single LF file associated
// with the generated file containing the error? Or is it best to be more selective?
Position lfFilePosition = map.adjusted(srcFile, generatedFilePosition);
if (isError) {
errorReporter.reportError(srcFile, lfFilePosition.getOneBasedLine(), message);
} else {
errorReporter.reportWarning(srcFile, lfFilePosition.getOneBasedLine(), message);
}
}
}
}
}
| 39.811765 | 105 | 0.599291 |
8c4361703eed61cc953f6750d7f6100398152a8e | 1,457 | package infrastructure;
import entities.ProductionEntity;
import shortages.ShortagesFacade;
import shortages.monitoring.ShortageService;
import java.util.List;
import java.util.stream.Collectors;
public class ShortageServiceACL {
private ShortageService oldService;
private ShortagesFacade newService;
public void processShortagesFromPlannerService(List<ProductionEntity> products) {
oldService.processShortagesFromPlannerService(products);
if (false) {
products.stream()
.map(entity -> entity.getForm().getRefNo())
.collect(Collectors.toList())
.forEach(refNo -> newService.afterProductionPlanChanged(refNo));
}
}
public void processShortagesFromLogisticService(String productRefNo) {
oldService.processShortagesFromLogisticService(productRefNo);
if (false) {
newService.afterDemandChanged(productRefNo);
}
}
public void processShortagesFromQualityService(String productRefNo) {
oldService.processShortagesFromQualityService(productRefNo);
if (false) {
newService.afterQualityLocks(productRefNo);
}
}
public void processShortagesFromWarehouseService(String productRefNo) {
oldService.processShortagesFromWarehouseService(productRefNo);
if (false) {
newService.afterStockChanges(productRefNo);
}
}
}
| 28.568627 | 85 | 0.694578 |
5efe2241caff3ba712213aef8b6a0783edcd1247 | 5,900 | package de.espend.idea.php.phpunit.completion;
import com.intellij.codeInsight.completion.*;
import com.intellij.codeInsight.lookup.LookupElement;
import com.intellij.patterns.PsiElementPattern;
import com.intellij.psi.PsiElement;
import com.intellij.util.ProcessingContext;
import com.jetbrains.php.PhpIndex;
import com.jetbrains.php.completion.PhpLookupElement;
import com.jetbrains.php.lang.psi.elements.Method;
import com.jetbrains.php.lang.psi.elements.PhpClass;
import com.jetbrains.php.lang.psi.elements.StringLiteralExpression;
import de.espend.idea.php.phpunit.reference.MockeryReferenceContributor;
import de.espend.idea.php.phpunit.utils.MockeryReferencingUtil;
import de.espend.idea.php.phpunit.utils.PatternUtil;
import org.jetbrains.annotations.NotNull;
import java.util.function.Function;
import java.util.stream.Collectors;
public class MockeryCompletionContributor extends CompletionContributor {
private enum Scope {
PARAMETER(PatternUtil.getMethodReferenceWithParameterInsideTokenStringPattern(),
MockeryReferencingUtil::findMockeryMockParametersOnParameterScope,
MockeryCompletionContributor::processParametersAsClasses),
ARRAY_HASH(PatternUtil.getMethodReferenceWithArrayHashInsideTokenStringPattern(),
MockeryReferencingUtil::findMockeryMockParametersOnArrayHashScope,
MockeryCompletionContributor::processParametersAsClasses),
ARRAY_ELEMENT(PatternUtil.getMethodReferenceWithArrayElementInsideTokenStringPattern(),
MockeryReferencingUtil::findMockeryMockParametersOnArrayElementScope,
MockeryCompletionContributor::processParametersAsClasses),
PARTIAL_STRING(PatternUtil.getMethodReferenceWithParameterInsideTokenStringPattern(),
MockeryReferencingUtil::findMockeryMockParametersOnPartialMockStringDeclarationScope,
MockeryCompletionContributor::processParametersAsClassAndMethodNames),
PARTIAL_CONCATENATION(PatternUtil.getMethodReferenceWithConcatenationInsideTokenStringPattern(),
MockeryReferencingUtil::findMockeryMockParametersOnPartialMockConcatenationDeclarationScope,
MockeryCompletionContributor::processParametersAsClassAndMethodNames);
private final PsiElementPattern.Capture<PsiElement> pattern;
private final Function<StringLiteralExpression, String[]> getMockCreationParametersMethod;
private final Consumer3<CompletionResultSet, PsiElement, String[]> processMockCreationParametersMethod;
Scope(PsiElementPattern.Capture<PsiElement> pattern,
Function<StringLiteralExpression, String[]> getMockCreationParametersMethod,
Consumer3<CompletionResultSet, PsiElement, String[]> processMockCreationParametersMethod) {
this.pattern = pattern;
this.getMockCreationParametersMethod = getMockCreationParametersMethod;
this.processMockCreationParametersMethod = processMockCreationParametersMethod;
}
public PsiElementPattern.Capture<PsiElement> getPattern() {
return pattern;
}
public String[] getMockCreationParameters(StringLiteralExpression exp) {
return getMockCreationParametersMethod.apply(exp);
}
public void processMockCreationParameters(CompletionResultSet resultSet, PsiElement psiElement, String[] mockCreationParameters) {
processMockCreationParametersMethod.accept(resultSet, psiElement, mockCreationParameters);
}
}
public MockeryCompletionContributor() {
extendByScope(Scope.PARAMETER);
extendByScope(Scope.ARRAY_HASH);
extendByScope(Scope.ARRAY_ELEMENT);
extendByScope(Scope.PARTIAL_STRING);
extendByScope(Scope.PARTIAL_CONCATENATION);
}
private void extendByScope(@NotNull Scope scope) {
extend(CompletionType.BASIC, scope.getPattern(), new CompletionProvider<>() {
@Override
protected void addCompletions(@NotNull CompletionParameters completionParameters, @NotNull ProcessingContext processingContext, @NotNull CompletionResultSet resultSet) {
PsiElement psiElement = completionParameters.getPosition();
PsiElement parent = psiElement.getParent();
if (parent instanceof StringLiteralExpression) {
String[] mockCreationParameters = scope.getMockCreationParameters((StringLiteralExpression) parent);
if (mockCreationParameters != null) {
scope.processMockCreationParameters(resultSet, psiElement, mockCreationParameters);
}
}
}
});
}
private static void processParametersAsClasses(CompletionResultSet resultSet, PsiElement psiElement, String[] mockCreationParameters) {
for (String parameter : mockCreationParameters) {
for (PhpClass phpClass : PhpIndex.getInstance(psiElement.getProject()).getAnyByFQN(parameter)) {
resultSet.addAllElements(phpClass.getMethods().stream()
.filter(method -> !method.getAccess().isPublic() || !method.getName().startsWith("__"))
.map((Function<Method, LookupElement>) PhpLookupElement::new)
.collect(Collectors.toSet())
);
}
}
}
private static void processParametersAsClassAndMethodNames(CompletionResultSet resultSet, PsiElement psiElement, String[] mockCreationParameters) {
if (mockCreationParameters.length > 0) {
String className = mockCreationParameters[0];
processParametersAsClasses(resultSet, psiElement, new String[]{className});
}
}
@FunctionalInterface
private interface Consumer3<T, U, V> {
void accept(T t, U u, V v);
}
}
| 51.304348 | 181 | 0.730508 |
1dcbb5de2b85d4efa1714ace8daec1e20e627d98 | 7,799 | /*
* Copyright 2015-present Open Networking Foundation
*
* 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.onosproject.rest.resources;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import org.onosproject.net.Host;
import org.onosproject.net.HostId;
import org.onosproject.net.SparseAnnotations;
import org.onosproject.net.host.DefaultHostDescription;
import org.onosproject.net.host.HostAdminService;
import org.onosproject.net.host.HostProvider;
import org.onosproject.net.host.HostProviderRegistry;
import org.onosproject.net.host.HostProviderService;
import org.onosproject.net.host.HostService;
import org.onosproject.net.provider.ProviderId;
import org.onosproject.rest.AbstractWebResource;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriBuilder;
import javax.ws.rs.core.UriInfo;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import static org.onlab.util.Tools.nullIsNotFound;
import static org.onlab.util.Tools.readTreeFromStream;
import static org.onosproject.net.HostId.hostId;
/**
* Manage inventory of end-station hosts.
*/
@Path("hosts")
public class HostsWebResource extends AbstractWebResource {
@Context
private UriInfo uriInfo;
private static final String HOST_NOT_FOUND = "Host is not found";
/**
* Get all end-station hosts.
* Returns array of all known end-station hosts.
*
* @return 200 OK with array of all known end-station hosts.
* @onos.rsModel Hosts
*/
@GET
@Produces(MediaType.APPLICATION_JSON)
public Response getHosts() {
final Iterable<Host> hosts = get(HostService.class).getHosts();
final ObjectNode root = encodeArray(Host.class, "hosts", hosts);
return ok(root).build();
}
/**
* Get details of end-station host.
* Returns detailed properties of the specified end-station host.
*
* @param id host identifier
* @return 200 OK with detailed properties of the specified end-station host
* @onos.rsModel Host
*/
@GET
@Produces(MediaType.APPLICATION_JSON)
@Path("{id}")
public Response getHostById(@PathParam("id") String id) {
final Host host = nullIsNotFound(get(HostService.class).getHost(hostId(id)),
HOST_NOT_FOUND);
final ObjectNode root = codec(Host.class).encode(host, this);
return ok(root).build();
}
/**
* Get details of end-station host with MAC/VLAN.
* Returns detailed properties of the specified end-station host.
*
* @param mac host MAC address
* @param vlan host VLAN identifier
* @return 200 OK with detailed properties of the specified end-station host
* @onos.rsModel Host
*/
@GET
@Produces(MediaType.APPLICATION_JSON)
@Path("{mac}/{vlan}")
public Response getHostByMacAndVlan(@PathParam("mac") String mac,
@PathParam("vlan") String vlan) {
final Host host = nullIsNotFound(get(HostService.class).getHost(hostId(mac + "/" + vlan)),
HOST_NOT_FOUND);
final ObjectNode root = codec(Host.class).encode(host, this);
return ok(root).build();
}
/**
* Creates a new host based on JSON input and adds it to the current
* host inventory.
*
* @param stream input JSON
* @return status of the request - CREATED if the JSON is correct,
* BAD_REQUEST if the JSON is invalid
* @onos.rsModel HostPut
*/
@POST
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response createAndAddHost(InputStream stream) {
URI location;
HostProviderRegistry hostProviderRegistry = get(HostProviderRegistry.class);
InternalHostProvider hostProvider = new InternalHostProvider();
try {
// Parse the input stream
ObjectNode root = readTreeFromStream(mapper(), stream);
HostProviderService hostProviderService = hostProviderRegistry.register(hostProvider);
hostProvider.setHostProviderService(hostProviderService);
HostId hostId = hostProvider.parseHost(root);
UriBuilder locationBuilder = uriInfo.getBaseUriBuilder()
.path("hosts")
.path(hostId.mac().toString())
.path(hostId.vlanId().toString());
location = locationBuilder.build();
} catch (IOException ex) {
throw new IllegalArgumentException(ex);
} finally {
hostProviderRegistry.unregister(hostProvider);
}
return Response
.created(location)
.build();
}
/**
* Removes infrastructure device.
* Administratively deletes the specified device from the inventory of
* known devices.
*
* @param mac host MAC address
* @param vlan host VLAN identifier
* @return 204 OK
* @onos.rsModel Host
*/
@DELETE
@Path("{mac}/{vlan}")
@Produces(MediaType.APPLICATION_JSON)
public Response removeHost(@PathParam("mac") String mac,
@PathParam("vlan") String vlan) {
get(HostAdminService.class).removeHost(hostId(mac + "/" + vlan));
return Response.noContent().build();
}
/**
* Internal host provider that provides host events.
*/
private final class InternalHostProvider implements HostProvider {
private final ProviderId providerId =
new ProviderId("host", "org.onosproject.rest");
private HostProviderService hostProviderService;
/**
* Prevents from instantiation.
*/
private InternalHostProvider() {
}
public void triggerProbe(Host host) {
// Not implemented since there is no need to check for hosts on network
}
public void setHostProviderService(HostProviderService service) {
this.hostProviderService = service;
}
/*
* Return the ProviderId of "this"
*/
public ProviderId id() {
return providerId;
}
/**
* Creates and adds new host based on given data and returns its host ID.
*
* @param node JsonNode containing host information
* @return host ID of new host created
*/
private HostId parseHost(JsonNode node) {
Host host = codec(Host.class).decode((ObjectNode) node, HostsWebResource.this);
HostId hostId = host.id();
DefaultHostDescription desc = new DefaultHostDescription(
host.mac(), host.vlan(), host.locations(), host.ipAddresses(), host.innerVlan(),
host.tpid(), host.configured(), (SparseAnnotations) host.annotations());
hostProviderService.hostDetected(hostId, desc, false);
return hostId;
}
}
}
| 34.973094 | 100 | 0.654571 |
e5c87c8b8a1e1899bd812137eb65c66f79c21fbd | 1,226 | package com.ruoyi.common.utils.spring;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.stereotype.Component;
/**
* spring工具类 方便在非spring管理环境中获取bean
*/
@Component
public final class SpringUtils implements BeanFactoryPostProcessor {
/**
* Spring应用上下文环境
*/
private static ConfigurableListableBeanFactory beanFactory;
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
SpringUtils.beanFactory = beanFactory;
}
/**
* 获取对象
*
* @param name
* @return Object 一个以所给名字注册的bean的实例
* @throws org.springframework.beans.BeansException
*/
public static <T> T getBean(String name) throws BeansException {
return (T) beanFactory.getBean(name);
}
/**
* 获取类型为requiredType的对象
*
* @param clz
* @return
* @throws org.springframework.beans.BeansException
*/
public static <T> T getBean(Class<T> clz) throws BeansException {
return beanFactory.getBean(clz);
}
}
| 27.244444 | 107 | 0.716966 |
f4f24d671cc106a395b94791aba038724aba2cd8 | 1,142 | package com.qiwen.interview.thread;
import java.util.concurrent.*;
/**
* 线程池
* @author liqiwen
* @since 1.2
* @version 1.2
*/
public class MultiThreadDemo {
public static void main(String[] args){
ExecutorService executorService = Executors.newFixedThreadPool(1);
ExecutorService executorService1 = Executors.newSingleThreadExecutor();
ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(1);
ExecutorService executorService2 = Executors.newCachedThreadPool();
ExecutorService executorService3 = Executors.newWorkStealingPool();
ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(10, 20, 0, TimeUnit.MICROSECONDS, new LinkedBlockingDeque<>(20), new ThreadPoolExecutor.CallerRunsPolicy());
for(int i = 0; i < 200; i++){
int finalI = i;
threadPoolExecutor.submit(new Runnable() {
@Override
public void run() {
System.out.println("开始执行任务:" + finalI + " 执行任务的线程:" + Thread.currentThread().getName());
}
});
}
}
}
| 31.722222 | 179 | 0.651489 |
729cce71526392555bfd0213e71b81f42436bd86 | 10,584 |
package com.hybris.mati.pages.WebshopPages;
import org.openqa.selenium.By;
import com.hybris.utils.*;
public class ProfilePage extends Page{
public enum FieldName implements Storable {
YOUR_ACCOUNT,
CHANGE_EMAIL_FORM,
EDIT_EMAIL_BUTTON,
EMAIL_CHANGE_TEXTFIELD,
EMAIL_CHANGE_SHOW_PASSWORD_CHECKBOX,
CONFIRM_PASSWORD_TEXFIELD,
EMAIL_CHANGE_BUTTON,
EMAIL_CHANGE_CANCEL_BUTTON,
PASSWORD_CHANGE_CANCEL_BUTTON,
YOUR_LOGIN_DATA,
MESSAGE_BOX,
PLEASE_CONTACT_CUSTOMER_SERVICE_LINK,
SUCCESS_MESSAGE_BOX,
ALERT_MESSAGE_BOX,
EMAIL_ERROR_MESSAGE_BOX,
PASSWORD_ERROR_MESSAGE_BOX,
PASSWORD_SUCCESS_MESSAGE_BOX,
EDIT_PASSWORD_BUTTON,
PASSWORD_CHANGE_BUTTON,
NEW_PASSWORD_TEXTFIELD,
REPEAT_NEW_PASSWORD_TEXTFIELD,
CHANGE_PASSWORD_FORM,
CURRENT_PASSWORD_TEXTFIELD,
CONTACT_DATA_EDIT_BUTTON,
DUMMY_EMAIL_ADDRESS,
YOUR_CONTACT_DATA,
CONTACT_DATA_TITLE_FIELD,
CONTACT_DATA_FIRST_NAME_FIELD,
CONTACT_DATA_LAST_NAME_FIELD,
CONTACT_DATA_FUNCTION_FIELD,
CONTACT_DATA_PHONE_FIELD,
CONTACT_DATA_MOBILE_PHONE_FIELD,
CONTACT_DATA_FAX_FIELD,
CONTACT_DATA_NEWSLETTER_CONFIRMATION_CHECKBOX,
FAX_ERROR_MESSAGE_BOX,
PHONE_ERROR_MESSAGE_BOX,
MOBILE_PHONE_ERROR_MESSAGE_BOX,
FIRST_NAME_TEXTFIELD,
LAST_NAME_TEXTFIELD,
PHONE_TEXTFIELD,
MOBILE_PHONE_TEXTFIELD,
FAX_TEXTFIELD,
YOUR_CONTACT_DATA_SAVE_BUTTON,
CONTACT_DATA_CANCEL_BUTTON,
YOUR_COMPANY_DATA,
COMPANY_NAME_ROW,
SECOND_COMPANY_NAME_ROW,
STREET_ADDRESS_ROW,
SECOND_STREET_ADDRESS_ROW,
CITY_ROW,
STATE_ROW,
ZIP_CODE_ROW,
COUNTRY_ROW,
TRADE_ROW,
NO_OF_EMPLOYEES_ROW,
CONTACT_CUSTOMER_SERVICE_LINK,
AGREE_AND_ACCEPT_CHECKBOX,
TITLE_SELECTION_DROPDOWN,
FUNCTION_SELECTION_DROPDOWN,
OTHER_FUNCTION,
MS_TITLE,
COMPANY_TITLE,
FOREMAN_FUNCTION,
OPEN_DASHBOARD_BUTTON,
ACCOUNT_DASHBOARD,
GO_TO_YOUR_SUBMITTALS_LINK,
}
public ProfilePage(){
addField(FieldName.YOUR_ACCOUNT, new Field(FieldType.LINK, By.xpath("//div[contains(@class, 'm-account-introduction a-page')]")));
addField(FieldName.CHANGE_EMAIL_FORM, new Field(FieldType.DIV, By.xpath("//form[@id='update-email' and not(contains(@style, 'none'))]")));
addField(FieldName.EDIT_EMAIL_BUTTON, new Field(FieldType.BUTTON, By.xpath("//a[contains(@class, 'js-form-toggle-trigger-email')]")));
addField(FieldName.EMAIL_CHANGE_TEXTFIELD, new Field(FieldType.TEXT, By.id("change-email-address")));
addField(FieldName.EMAIL_CHANGE_SHOW_PASSWORD_CHECKBOX, new Field(FieldType.CHECKBOX, By.xpath("//label[contains(@for, 'show-passwords-change-email')]")));
addField(FieldName.CONFIRM_PASSWORD_TEXFIELD, new Field(FieldType.TEXT, By.id("confirm-password")));
addField(FieldName.EMAIL_CHANGE_BUTTON, new Field(FieldType.BUTTON, By.xpath("//button[@id='change-email']")));
addField(FieldName.EMAIL_CHANGE_CANCEL_BUTTON, new Field(FieldType.BUTTON, By.xpath("//button[@id='cancel']")));
addField(FieldName.PASSWORD_CHANGE_CANCEL_BUTTON, new Field(FieldType.BUTTON, By.xpath("//div[@class='m-account-form-password-actions-cancel']/button")));
addField(FieldName.YOUR_LOGIN_DATA, new Field(FieldType.DIV, By.xpath("//div[contains(@class, 'o-account-credentials')]")));
addField(FieldName.MESSAGE_BOX, new Field(FieldType.DIV, By.xpath("//div[@class='m-message-text']")));
addField(FieldName.PLEASE_CONTACT_CUSTOMER_SERVICE_LINK, new Field(FieldType.DIV, By.xpath("//a[@data-trigger='#contact_overlay']")));
addField(FieldName.SUCCESS_MESSAGE_BOX, new Field(FieldType.TEXT, By.xpath("//div[@id='globalMessages']//div[contains(@class, 'm-message--success')]")));
addField(FieldName.ALERT_MESSAGE_BOX, new Field(FieldType.TEXT, By.xpath("//div[@id='globalMessages']//div[contains(@class, 'm-message--alert')]")));
addField(FieldName.EMAIL_ERROR_MESSAGE_BOX, new Field(FieldType.TEXT, By.id("change_email_error")));
addField(FieldName.PASSWORD_ERROR_MESSAGE_BOX, new Field(FieldType.TEXT, By.id("change_password_error")));
addField(FieldName.PASSWORD_SUCCESS_MESSAGE_BOX, new Field(FieldType.TEXT, By.id("success-message")));
addField(FieldName.EDIT_PASSWORD_BUTTON, new Field(FieldType.BUTTON, By.xpath("//a[contains(@class, 'js-form-toggle-trigger-password')]")));
addField(FieldName.PASSWORD_CHANGE_BUTTON, new Field(FieldType.BUTTON, By.xpath("//button[@id='update-password']")));
addField(FieldName.NEW_PASSWORD_TEXTFIELD, new Field(FieldType.TEXT, By.id("register-password")));
addField(FieldName.REPEAT_NEW_PASSWORD_TEXTFIELD, new Field(FieldType.TEXT, By.id("register-password-2")));
addField(FieldName.CHANGE_PASSWORD_FORM, new Field(FieldType.DIV, By.xpath("//form[@id='update-password' and not(contains(@style, 'none'))]")));
addField(FieldName.CURRENT_PASSWORD_TEXTFIELD, new Field(FieldType.TEXT, By.id("current-password")));
addField(FieldName.DUMMY_EMAIL_ADDRESS, new Field(FieldType.TEXT, By.id("dummy-email-address")));
addField(FieldName.CONTACT_DATA_EDIT_BUTTON, new Field(FieldType.BUTTON, By.xpath(".//a[@href='#editContactData']")));
addField(FieldName.YOUR_CONTACT_DATA, new Field(FieldType.SECTION, By.xpath("//div[contains(@class, 'o-account-form')]")));
addField(FieldName.CONTACT_DATA_TITLE_FIELD, new Field(FieldType.DIV, By.xpath(".//label[@for='title']")));
addField(FieldName.CONTACT_DATA_FIRST_NAME_FIELD, new Field(FieldType.DIV, By.xpath(".//label[@for='firstName']")));
addField(FieldName.CONTACT_DATA_LAST_NAME_FIELD, new Field(FieldType.DIV, By.xpath(".//label[@for='lastName']")));
addField(FieldName.CONTACT_DATA_FUNCTION_FIELD, new Field(FieldType.DIV, By.xpath(".//label[@for='function']")));
addField(FieldName.CONTACT_DATA_PHONE_FIELD, new Field(FieldType.DIV, By.xpath(".//div[contains(@class, 'a-input')]/label[@for='phone']")));
addField(FieldName.CONTACT_DATA_MOBILE_PHONE_FIELD, new Field(FieldType.DIV, By.xpath(".//div[contains(@class, 'a-input')]/label[@for='mobilePhone']")));
addField(FieldName.CONTACT_DATA_FAX_FIELD, new Field(FieldType.DIV, By.xpath(".//div[contains(@class, 'a-input')]/label[@for='fax']")));
addField(FieldName.CONTACT_DATA_NEWSLETTER_CONFIRMATION_CHECKBOX, new Field(FieldType.DIV, By.id("emailNewsletter-field")));
addField(FieldName.FAX_ERROR_MESSAGE_BOX, new Field(FieldType.SECTION, By.xpath("//div[@id='contact_form_error_message' and contains(., 'fax')]")));
addField(FieldName.PHONE_ERROR_MESSAGE_BOX, new Field(FieldType.SECTION, By.xpath("//div[@id='contact_form_error_message' and contains(., 'phone') and not(contains(., 'mobile'))]")));
addField(FieldName.MOBILE_PHONE_ERROR_MESSAGE_BOX, new Field(FieldType.SECTION, By.xpath("//div[@id='contact_form_error_message' and contains(., 'mobile')]")));
addField(FieldName.FIRST_NAME_TEXTFIELD, new Field(FieldType.TEXT, By.id("firstName")));
addField(FieldName.LAST_NAME_TEXTFIELD, new Field(FieldType.TEXT, By.id("lastName")));
addField(FieldName.PHONE_TEXTFIELD, new Field(FieldType.TEXT, By.id("phone")));
addField(FieldName.MOBILE_PHONE_TEXTFIELD, new Field(FieldType.TEXT, By.id("mobilePhone")));
addField(FieldName.FAX_TEXTFIELD, new Field(FieldType.TEXT, By.id("fax")));
addField(FieldName.YOUR_CONTACT_DATA_SAVE_BUTTON, new Field(FieldType.BUTTON, By.xpath(".//button[contains(@class, 'js-form-update-watcher-submit')]")));
addField(FieldName.CONTACT_DATA_CANCEL_BUTTON, new Field(FieldType.BUTTON, By.xpath(".//button[contains(@class, 'js-form-update-watcher-reset')]")));
addField(FieldName.YOUR_COMPANY_DATA, new Field(FieldType.SECTION, By.xpath("//div[@class='m-account-companydata']")));
addField(FieldName.COMPANY_NAME_ROW, new Field(FieldType.DIV, By.xpath(".//div[@class='m-account-companydata-row' and contains(., 'Company name') and not(contains(., '2'))]")));
addField(FieldName.SECOND_COMPANY_NAME_ROW, new Field(FieldType.DIV, By.xpath(".//div[@class='m-account-companydata-row' and contains(., 'Company name 2')]")));
addField(FieldName.STREET_ADDRESS_ROW, new Field(FieldType.DIV, By.xpath(".//div[@class='m-account-companydata-row' and contains(., 'Street address') and not(contains(., '2'))]")));
addField(FieldName.SECOND_STREET_ADDRESS_ROW, new Field(FieldType.DIV, By.xpath(".//div[@class='m-account-companydata-row' and contains(., 'Street address 2')]")));
addField(FieldName.CITY_ROW, new Field(FieldType.DIV, By.xpath(".//div[@class='m-account-companydata-row' and contains(., 'City')]")));
addField(FieldName.STATE_ROW, new Field(FieldType.DIV, By.xpath(".//div[@class='m-account-companydata-row' and contains(., 'State')]")));
addField(FieldName.ZIP_CODE_ROW, new Field(FieldType.DIV, By.xpath(".//div[@class='m-account-companydata-row' and contains(., 'Zip')]")));
addField(FieldName.COUNTRY_ROW, new Field(FieldType.DIV, By.xpath(".//div[@class='m-account-companydata-row' and contains(., 'Country')]")));
addField(FieldName.TRADE_ROW, new Field(FieldType.DIV, By.xpath(".//div[@class='m-account-companydata-row' and contains(., 'Trade')]")));
addField(FieldName.NO_OF_EMPLOYEES_ROW, new Field(FieldType.DIV, By.xpath(".//div[@class='m-account-companydata-row' and contains(., 'employees')]")));
addField(FieldName.CONTACT_CUSTOMER_SERVICE_LINK, new Field(FieldType.LINK, By.xpath("//a[@data-trigger-hash='#contact_callus']")));
addField(FieldName.AGREE_AND_ACCEPT_CHECKBOX, new Field(FieldType.DIV, By.xpath(".//div[@id='myprofile-agreement-field']")));
addField(FieldName.TITLE_SELECTION_DROPDOWN, new Field(FieldType.SECTION, By.id("title-field")));
addField(FieldName.FUNCTION_SELECTION_DROPDOWN, new Field(FieldType.SECTION, By.xpath("//span[@id='function-field']")));
addField(FieldName.OTHER_FUNCTION, new Field(FieldType.LINK, By.xpath(".//li[contains(@class, 'active-result') and contains(., 'Other')]")));
addField(FieldName.MS_TITLE, new Field(FieldType.LINK, By.xpath(".//li[contains(@class, 'active-result') and contains(., 'Ms')]")));
addField(FieldName.COMPANY_TITLE, new Field(FieldType.LINK, By.xpath(".//li[contains(@class, 'active-result') and contains(., 'Company')]")));
addField(FieldName.FOREMAN_FUNCTION, new Field(FieldType.LINK, By.xpath(".//li[contains(@class, 'active-result') and contains(., 'Foreman')]")));
addField(FieldName.OPEN_DASHBOARD_BUTTON, new Field(FieldType.BUTTON, By.xpath(".//a[contains(@class, 'm-nav-meta-loginlink')]")));
addField(FieldName.ACCOUNT_DASHBOARD, new Field(FieldType.DIV, By.xpath("//div[contains(@class, 'm-account-dashboard visible')]")));
addField(FieldName.GO_TO_YOUR_SUBMITTALS_LINK, new Field(FieldType.LINK, By.xpath("//a[@href='/myaccount-submittals#account-navigation' and @id='FavoriteListsPanelLink3']")));
}
} | 69.631579 | 185 | 0.763511 |
1b6da556fc702bb040d5aa3357518e9dbb8575b3 | 540 | package org.malloc.leet.code;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
/**
* @author malloc
* @since 2020/6/11
*/
class DailyTemperaturesTest {
private final DailyTemperatures temperatures = new DailyTemperatures();
@Test
void dailyTemperatures() {
int[] result = temperatures.dailyTemperatures(new int[]{73, 74, 75, 71, 69, 72, 76, 73});
Assertions.assertArrayEquals(new int[]{1, 1, 4, 2, 1, 1, 0, 0}, result);
}
} | 25.714286 | 97 | 0.683333 |
3638523c4549af4ecf063ab58d51c5f43fbd2155 | 426 | /*
* Copyright © 2019 VMware, Inc. All Rights Reserved.
* SPDX-License-Identifier: BSD-2-Clause
*/
package com.vmware.connectors.salesforce;
import javax.validation.constraints.NotBlank;
public class UpdateNextStepForm {
@NotBlank
private String nextStep;
public String getNextStep() {
return nextStep;
}
public void setNextstep(String nextStep) {
this.nextStep = nextStep;
}
}
| 19.363636 | 53 | 0.694836 |
267fd8636901c8e1b17928e4ac051210be2e64f3 | 673 | //(c) A+ Computer Science
//www.apluscompsci.com
//Name -
import static java.lang.System.*;
public class RomanNumeral
{
private Integer number;
private String roman;
private final static int[] NUMBERS= {1000,900,500,400,100,90,
50,40,10,9,5,4,1};
private final static String[] LETTERS = {"M","CM","D","CD","C","XC",
"L","XL","X","IX","V","IV","I"};
public RomanNumeral(String str)
{
}
public RomanNumeral(Integer orig)
{
}
public void setNumber(Integer num)
{
}
public void setRoman(String rom)
{
}
public Integer getNumber()
{
return number;
}
public String toString()
{
return roman + "\n";
}
} | 11.807018 | 69 | 0.609212 |
4af650d7b734360db979b0e888885156f769271c | 2,060 | package com.postnow.backend.model;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import org.hibernate.annotations.LazyCollection;
import org.hibernate.annotations.LazyCollectionOption;
import org.hibernate.annotations.OnDelete;
import org.hibernate.annotations.OnDeleteAction;
import org.hibernate.validator.constraints.Length;
import javax.persistence.*;
import javax.validation.constraints.Email;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@Entity
public class User implements Serializable {
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Id
private Long id;
@Email
@Length(min = 6, max = 35)
@Column(unique = true, nullable = false)
private String email;
@Column(unique = false, nullable = false)
private String password;
@Column(nullable = false)
private Boolean active;
@ManyToMany(cascade = CascadeType.MERGE, fetch = FetchType.EAGER)
@JoinTable(name = "users_roles", joinColumns = @JoinColumn(name = "user_id"), inverseJoinColumns = @JoinColumn(name = "role_id"))
private Set<UserRole> roles;
@OneToOne(cascade=CascadeType.ALL, orphanRemoval = true)
@OnDelete(action = OnDeleteAction.CASCADE)
private UserAdditionalData userAdditionalData = new UserAdditionalData();
@OneToMany(mappedBy = "user", cascade = CascadeType.ALL, orphanRemoval = true)
@OnDelete(action = OnDeleteAction.CASCADE)
private List<Post> postList = new ArrayList<>();
@OneToMany(mappedBy = "user", cascade = CascadeType.ALL, orphanRemoval = true)
@OnDelete(action = OnDeleteAction.CASCADE)
private List<PostComment> postCommentList = new ArrayList<>();
@LazyCollection(LazyCollectionOption.FALSE)
@OneToMany(mappedBy = "user", cascade = CascadeType.ALL, orphanRemoval = true)
@OnDelete(action = OnDeleteAction.CASCADE)
private List<PostLike> postLikeList = new ArrayList<>();
}
| 32.698413 | 133 | 0.752427 |
12984dc352bd5c44104543dd48dc75a3c5eae7d4 | 1,648 | package net.ros.common.fluid;
import lombok.Getter;
import lombok.Setter;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraftforge.fluids.Fluid;
import net.minecraftforge.fluids.FluidStack;
import net.minecraftforge.fluids.FluidTank;
public class LimitedTank extends FilteredFluidTank
{
@Getter
@Setter
private int transferRate;
public LimitedTank(final int capacity, final int transferRate)
{
super(capacity);
this.transferRate = transferRate;
}
@Override
public int fill(final FluidStack resource, final boolean doFill)
{
if (resource != null)
{
FluidStack copy = resource.copy();
copy.amount = Math.min(copy.amount, this.transferRate);
return super.fill(copy, doFill);
}
return super.fill(null, doFill);
}
@Override
public FluidStack drain(final int maxDrain, final boolean doDrain)
{
return super.drain(Math.min(maxDrain, this.transferRate), doDrain);
}
public Fluid getFluidType()
{
if (this.getFluid() != null)
return this.getFluid().getFluid();
return null;
}
@Override
public NBTTagCompound writeToNBT(NBTTagCompound tag)
{
tag.setInteger("capacity", this.getCapacity());
tag.setInteger("transferRate", this.transferRate);
return super.writeToNBT(tag);
}
@Override
public FluidTank readFromNBT(NBTTagCompound tag)
{
this.setCapacity(tag.getInteger("capacity"));
this.setTransferRate(tag.getInteger("transferRate"));
return super.readFromNBT(tag);
}
}
| 24.969697 | 75 | 0.656553 |
14802a44987bb2f42cce6f098c2ff572c47299b6 | 2,637 | /**
* 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.hadoop.yarn.api.protocolrecords;
import org.apache.hadoop.classification.InterfaceAudience.Private;
import org.apache.hadoop.classification.InterfaceAudience.Public;
import org.apache.hadoop.classification.InterfaceStability.Stable;
import org.apache.hadoop.classification.InterfaceStability.Unstable;
import org.apache.hadoop.yarn.api.ApplicationClientProtocol;
import org.apache.hadoop.yarn.util.Records;
/**
* <p>
* The response sent by the <code>ResourceManager</code> to the client aborting
* a submitted application.
* </p>
* <p>
* The response, includes:
* <ul>
* <li>A flag which indicates that the process of killing the application is
* completed or not.</li>
* </ul>
* Note: user is recommended to wait until this flag becomes true, otherwise if
* the <code>ResourceManager</code> crashes before the process of killing the
* application is completed, the <code>ResourceManager</code> may retry this
* application on recovery.
* </p>
*
* @see ApplicationClientProtocol#forceKillApplication(KillApplicationRequest)
*/
@Public
@Stable
public abstract class KillApplicationResponse {
@Private
@Unstable
public static KillApplicationResponse newInstance(boolean isKillCompleted) {
KillApplicationResponse response =
Records.newRecord(KillApplicationResponse.class);
response.setIsKillCompleted(isKillCompleted);
return response;
}
/**
* Get the flag which indicates that the process of killing application is completed or not.
*/
@Public
@Stable
public abstract boolean getIsKillCompleted();
/**
* Set the flag which indicates that the process of killing application is completed or not.
*/
@Private
@Unstable
public abstract void setIsKillCompleted(boolean isKillCompleted);
}
| 36.123288 | 96 | 0.749336 |
12322fe978cd69f5ffcfce12e5f135cb5cf3dfbb | 35,745 | /** ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
* File name : BrobIntTester.java
* Purpose : Test Harness for the GinormousInt java class, used as baseline for assessment
* @author : B.J. Johnson
* Date : 2017-04-05
* Description: @see <a href='http://bjohnson.lmu.build/cmsi186web/homework06.html'>Assignment Page</a>
* Notes : None
* Warnings : None
*
* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
* Revision History
* ================
* Ver Date Modified by: Reason for change or modification
* ----- ---------- ------------ ---------------------------------------------------------------------
* 1.0.0 2017-04-05 B.J. Johnson Initial writing and release
* 1.1.0 2017-04-13 B.J. Johnson Added new GinormousInt instances to check addition; refactored to
* check the new versions of compareTo and equals; verified that all
* additions work for both small and large numbers, as well as for
* values of different lengths and including same-sign negative value
* additions; ready to start subtractByte and subtractInt methods
*
* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
public class BrobIntTester {
private static String g01String = "144127909719710664015092431502440849849506284148982076191826176553";
private static String g02String = "144127909719710664015092431502440849849506284148982076191826176553";
private static String g03String = "144127909719710664015092431502440849849506284108982076191826176553";
private static String g04String = "14412790971971066401509243150244084984950628410898207";
private static String g05String = "0";
private static String g06String = "1";
private static String g07String = "10";
private static String g11String = "10";
private static String g12String = "20";
private static String g13String = "234567";
private static String g14String = "-234567";
private static String g15String = "-10";
private static String g16String = "-999999";
private static String g17String = "765";
private static String g18String = "23";
private static String g19String = "56789";
private static String g20String = "37";
private static String g21String = "14412790971971066401509243150";
private static String g22String = "412790971971";
private static BrobInt g1 = null;
private static BrobInt g2 = null;
private static BrobInt g3 = null;
private static BrobInt g4 = null;
private static BrobInt g5 = null;
private static BrobInt g6 = null;
private static BrobInt g7 = null;
private static BrobInt g8 = null;
private static BrobInt g9 = null;
private static BrobInt g10 = null;
private static BrobInt g11 = null;
private static BrobInt g12 = null;
private static BrobInt g13 = null;
private static BrobInt g14 = null;
private static BrobInt g15 = null;
private static BrobInt g16 = null;
private static BrobInt g17 = null;
private static BrobInt g18 = null;
private static BrobInt g19 = null;
private static BrobInt g20 = null;
private static BrobInt g21 = null;
private static BrobInt g22 = null;
private static int attempts = 0;
private static int successes = 0;
private static int testCount = 0;
public BrobIntTester() {
super();
}
/**
* silly little method to add zeros to the front of a number string
* to ensure it fills two places for test output alignment
* @return two-character string that is a two-place number from 00 to 99
* note: this method also increments the testCount private field
*/
private static String makeTwoDigits() {
testCount++;
if( testCount < 10 ) {
return new String( "0" + testCount );
} else {
return new Integer( testCount ).toString();
}
}
public static void main( String[] args ) {
BrobIntTester BIT = new BrobIntTester();
System.out.println( "\n Hello, world, from the BrobInt program!!\n" );
System.out.println( " TESTING CONSTRUCTOR AND CONSTANTS:\n" +
" ==================================" );
try {
System.out.println( " Test " + makeTwoDigits() + ": Making a new BrobInt: " );
g1 = new BrobInt( g01String );
}
catch( Exception e ) { System.out.println( " Exception thrown: " ); }
try {
System.out.println( " expecting: " + g01String + "\n" +
" and got: " + g1.toString() );
}
catch( Exception e ) { System.out.println( " Exception thrown: " ); }
System.out.println( "\n Test " + makeTwoDigits() + ": Making a second new BrobInt [same as first]: " );
try {
g2 = new BrobInt( g02String );
System.out.println( " expecting: " + g02String + "\n" +
" and got: " + g2.toString() );
}
catch( Exception e ) { System.out.println( " Exception thrown: " ); }
try {
System.out.println( " Test " + makeTwoDigits() + ": Comparing equality of g1 and g2 with 'equals()': " );
System.out.println( " expecting: true\n" + " and got: " + g1.equals( g2 ) );
}
catch( Exception e ) { System.out.println( " Exception thrown: " ); }
try {
System.out.println( "\n Test " + makeTwoDigits() + ": Making a third new BrobInt [differs at position 47 |]: " +
"\n [position indicated by down arrow] v " );
g3 = new BrobInt( g03String );
}
catch( Exception e ) { System.out.println( " Exception thrown: " ); }
try {
System.out.println( " expecting: " + g03String + "\n" +
" and got: " + g3.toString() );
System.out.println( " g1 is: " + g1.toString() );
}
catch( Exception e ) { System.out.println( " Exception thrown: " ); }
try {
System.out.println( " Test " + makeTwoDigits() + ": Comparing equality of g1 and g3 [detect different digit]: " );
System.out.println( " expecting: false\n" + " and got: " + g1.equals( g3 ) );
}
catch( Exception e ) { System.out.println( " Exception thrown: " ); }
try {
System.out.println( "\n Test " + makeTwoDigits() + ": Making a fourth new BrobInt [same as g3 but truncated]: " );
g4 = new BrobInt( g04String );
}
catch( Exception e ) { System.out.println( " Exception thrown: " ); }
try {
System.out.println( " expecting: " + g04String + "\n" +
" and got: " + g4.toString() );
}
catch( Exception e ) { System.out.println( " Exception thrown: " ); }
try {
System.out.println( " Test " + makeTwoDigits() + ": Comparing equality of g3 and g4 [detect different length prior to detecting different digit]: " );
System.out.println( " expecting: false\n" + " and got: " + g3.equals( g4 ) );
}
catch( Exception e ) { System.out.println( " Exception thrown: " ); }
try {
System.out.println( "\n Test " + makeTwoDigits() + ": Making a fifth new BrobInt, checking BrobInt.ZERO: " );
g5 = new BrobInt( "0" );
}
catch( Exception e ) { System.out.println( " Exception thrown: " ); }
try {
System.out.println( " expecting: " + BrobInt.ZERO + "\n" +
" and got: " + g5.toString() );
}
catch( Exception e ) { System.out.println( " Exception thrown: " ); }
try {
System.out.println( "\n Test " + makeTwoDigits() + ": Making a sixth new BrobInt, checking BrobInt.ONE: " );
g6 = new BrobInt( "1" );
}
catch( Exception e ) { System.out.println( " Exception thrown: " ); }
try {
System.out.println( " expecting: " + BrobInt.ONE + "\n" +
" and got: " + g6.toString() );
}
catch( Exception e ) { System.out.println( " Exception thrown: " ); }
try {
System.out.println( "\n Test " + makeTwoDigits() + ": Making a seventh new BrobInt, checking BrobInt.TEN: " );
g7 = new BrobInt( g07String );
}
catch( Exception e ) { System.out.println( " Exception thrown: " ); }
try {
System.out.println( " expecting: " + BrobInt.TEN + "\n" +
" and got: " + g7.toString() );
}
catch( Exception e ) { System.out.println( " Exception thrown: " ); }
System.out.println( "\n\n TESTING VALUEOF( LONG ) METHOD:\n" +
" ===============================" );
System.out.println( "\n Test " + makeTwoDigits() + ": Creating several long type values to check the 'valueOf()' method: " );
long long01 = Long.MAX_VALUE;
long long02 = Long.MIN_VALUE;
long long03 = 1234567890;
try {
System.out.println( " expecting: " + Long.MAX_VALUE + "\n" +
" and got: " + long01 );
}
catch( Exception e ) { System.out.println( " Exception thrown: " ); }
try {
System.out.println( " expecting: " + Long.MIN_VALUE + "\n" +
" and got: " + long02 );
}
catch( Exception e ) { System.out.println( " Exception thrown: " ); }
try {
System.out.println( " expecting: 1234567890\n" +
" and got: " + long03 );
}
catch( Exception e ) { System.out.println( " Exception thrown: " ); }
try {
System.out.println( " Test " + makeTwoDigits() + ": Now testing 'valueOf()' method: " );
g8 = BrobInt.valueOf( long01 );
g9 = BrobInt.valueOf( long02 );
g10 = BrobInt.valueOf( long03 );
}
catch( Exception e ) { System.out.println( " Exception thrown: " ); }
try {
System.out.println( " expecting: " + Long.MAX_VALUE + "\n" +
" and got: " + g8.toString() );
}
catch( Exception e ) { System.out.println( " Exception thrown: " ); }
try {
System.out.println( " expecting: " + Long.MIN_VALUE + "\n" +
" and got: " + g9.toString() );
}
catch( Exception e ) { System.out.println( " Exception thrown: " ); }
try {
System.out.println( " expecting: 1234567890\n" +
" and got: " + g10.toString() );
}
catch( Exception e ) { System.out.println( " Exception thrown: " ); }
System.out.println( "\n\n TESTING ADDBYTE() AND ADDINT() METHODS:\n" +
" =======================================" );
try {
System.out.println( "\n Test " + makeTwoDigits() + ": Making an eleventh and twelfth new BrobInt, calling addByte method: " );
g11 = new BrobInt( g11String );
}
catch( Exception e ) { System.out.println( " Exception thrown: " ); }
try {
System.out.println( " expecting: 10\n" +
" and got: " + g11.toString() );
}
catch( Exception e ) { System.out.println( " Exception thrown: " ); }
try {
g12 = new BrobInt( g12String );
}
catch( Exception e ) { System.out.println( " Exception thrown: " ); }
try {
System.out.println( " expecting: 20\n" +
" and got: " + g12.toString() );
}
catch( Exception e ) { System.out.println( " Exception thrown: " ); }
try {
System.out.println( " Test " + makeTwoDigits() + ": Adding g11 and g12: " );
System.out.println( " expecting: 30 and got " + g11.add( g12 ) );
}
catch( Exception e ) { System.out.println( " Exception thrown: " ); }
System.out.println( "\n Test " + makeTwoDigits() + ": Making a thirteenth new BrobInt, calling add methods: " );
try {
g13 = new BrobInt( g13String );
}
catch( Exception e ) { System.out.println( " Exception thrown: " ); }
try {
System.out.println( " expecting: 234567\n" +
" and got: " + g13.toString() );
}
catch( Exception e ) { System.out.println( " Exception thrown: " ); }
try {
System.out.println( " Test " + makeTwoDigits() + ": Adding g11 and g13 [10 + 234567] using bytes: " );
System.out.println( " expecting: 234577\n" +
" and got: " + g11.add( g13 ) );
}
catch( Exception e ) { System.out.println( " Exception thrown: " ); }
try {
System.out.println( " Test " + makeTwoDigits() + ": Adding g11 and g13 [10 + 234567] using ints: " );
System.out.println( " expecting: 234577\n" +
" and got: " + g11.add( g13 ) );
}
catch( Exception e ) { System.out.println( " Exception thrown: " ); }
try {
System.out.println( " Test " + makeTwoDigits() + ": Adding g13 and g11 [234567 + 10] using bytes: " );
System.out.println( " expecting: 234577\n" +
" and got: " + g13.add( g11 ) );
}
catch( Exception e ) { System.out.println( " Exception thrown: " ); }
try {
System.out.println( " Test " + makeTwoDigits() + ": Adding g13 and g11 [234567 + 10] using ints: " );
System.out.println( " expecting: 234577\n" +
" and got: " + g13.add( g11 ) );
}
catch( Exception e ) { System.out.println( " Exception thrown: " ); }
System.out.println( "\n Test " + makeTwoDigits() + ": Making a fourteenth new BrobInt, calling add methods: " );
try {
g14 = new BrobInt( g14String );
}
catch( Exception e ) { System.out.println( " Exception thrown: " ); }
try {
System.out.println( " expecting: -234567\n" +
" and got: " + g14.toString() );
System.out.println( "\n Test " + makeTwoDigits() + ": Making a fifteenth new BrobInt, calling add methods: " );
}
catch( Exception e ) { System.out.println( " Exception thrown: " ); }
try {
g15 = new BrobInt( g15String );
}
catch( Exception e ) { System.out.println( " Exception thrown: " ); }
try {
System.out.println( " expecting: -10\n" +
" and got: " + g15.toString() );
}
catch( Exception e ) { System.out.println( " Exception thrown: " ); }
try {
System.out.println( " Test " + makeTwoDigits() + ": Adding g14 and g15 [-234567 + -10] using bytes: " );
System.out.println( " expecting: -234577\n" +
" and got: " + g14.add( g15 ) );
}
catch( Exception e ) { System.out.println( " Exception thrown: " ); }
try {
System.out.println( " Test " + makeTwoDigits() + ": Adding g14 and g15 [-234567 + -10] using ints: " );
System.out.println( " expecting: -234577\n" +
" and got: " + g14.add( g15 ) );
}
catch( Exception e ) { System.out.println( " Exception thrown: " ); }
try {
System.out.println( " Test " + makeTwoDigits() + ": Adding g15 and g14 [-10 + -234567] using bytes: " );
System.out.println( " expecting: -234577\n" +
" and got: " + g15.add( g14 ) );
}
catch( Exception e ) { System.out.println( " Exception thrown: " ); }
try {
System.out.println( " Test " + makeTwoDigits() + ": Adding g15 and g14 [-10 + -234567] using ints: " );
System.out.println( " expecting: -234577\n" +
" and got: " + g15.add( g14 ) );
}
catch( Exception e ) { System.out.println( " Exception thrown: " ); }
System.out.println( "\n Test " + makeTwoDigits() + ": Making a sixteenth new BrobInt, calling add methods: " );
try {
g16 = new BrobInt( g16String );
System.out.println( " expecting: -999999\n" +
" and got: " + g16.toString() );
}
catch( Exception e ) { System.out.println( " Exception thrown: " ); }
try {
System.out.println( " Test " + makeTwoDigits() + ": Adding g14 and g16 [-234567 + -999999] using bytes: " );
System.out.println( " expecting: -1234566\n" +
" and got: " + g14.add( g16 ) );
}
catch( Exception e ) { System.out.println( " Exception thrown: " ); }
try {
System.out.println( " Test " + makeTwoDigits() + ": Adding g14 and g16 [-234567 + -999999] using ints: " );
System.out.println( " expecting: -1234566\n" +
" and got: " + g14.add( g16 ) );
}
catch( Exception e ) { System.out.println( " Exception thrown: " ); }
try {
System.out.println( " Test " + makeTwoDigits() + ": Adding g16 and g14 [-999999 + -234567] using bytes: " );
System.out.println( " expecting: -1234566\n" +
" and got: " + g16.add( g14 ) );
}
catch( Exception e ) { System.out.println( " Exception thrown: " ); }
try {
System.out.println( " Test " + makeTwoDigits() + ": Adding g16 and g14 [-999999 + -234567] using ints: " );
System.out.println( " expecting: -1234566\n" +
" and got: " + g16.add( g14 ) );
}
catch( Exception e ) { System.out.println( " Exception thrown: " ); }
try {
System.out.println( "\n Test " + makeTwoDigits() + ": Adding g1 and g4 using bytes: " );
System.out.println( " expecting: 144127909719725076806064402568842359092656528233967026820237074760\n" +
" and got: " + g1.add( g4 ) );
}
catch( Exception e ) { System.out.println( " Exception thrown: " ); }
try {
System.out.println( "\n Test " + makeTwoDigits() + ": Adding g4 and g1 using ints: " );
System.out.println( " expecting: 144127909719725076806064402568842359092656528233967026820237074760\n" +
" and got: " + g4.add( g1 ) );
}
catch( Exception e ) { System.out.println( " Exception thrown: " ); }
System.out.println( "\n\n TESTING COMPARETO() METHOD:\n" +
" ===========================" );
try {
System.out.println( "\n Test " + makeTwoDigits() + ": Checking compareTo() method on g1 and g2: " );
System.out.println( " expecting: 0\n" +
" and got: " + g1.compareTo( g2 ) );
}
catch( Exception e ) { System.out.println( " Exception thrown: " ); }
try {
System.out.println( "\n Test " + makeTwoDigits() + ": Checking compareTo() method on g2 and g1: " );
System.out.println( " expecting: 0\n" +
" and got: " + g2.compareTo( g1 ) );
}
catch( Exception e ) { System.out.println( " Exception thrown: " ); }
try {
System.out.println( "\n Test " + makeTwoDigits() + ": Checking compareTo() method on g1 and g3: " );
System.out.println( " expecting: positive value\n" +
" and got: " + g1.compareTo( g3 ) );
}
catch( Exception e ) { System.out.println( " Exception thrown: " ); }
try {
System.out.println( "\n Test " + makeTwoDigits() + ": Checking compareTo() method on g3 and g1: " );
System.out.println( " expecting: negative value\n" +
" and got: " + g3.compareTo( g1 ) );
}
catch( Exception e ) { System.out.println( " Exception thrown: " ); }
try {
System.out.println( "\n Test " + makeTwoDigits() + ": Checking compareTo() method on g3 and g4: " );
System.out.println( " expecting: positive value\n" +
" and got: " + g3.compareTo( g4 ) );
}
catch( Exception e ) { System.out.println( " Exception thrown: " ); }
System.out.println( "\n\n TESTING SUBTRACTBYTE() METHOD:\n" +
" ==============================" );
System.out.println( "\n Test " + makeTwoDigits() + ": Subtracting g13 take away g11 [234567 - 10] using bytes: " );
try {
System.out.println( " expecting: 234557\n" +
" and got: " + g13.subtract( g11 ) );
}
catch( Exception e ) { System.out.println( " Exception thrown: " ); }
System.out.println( "\n Test " + makeTwoDigits() + ": Subtracting g11 take away g13 [10 - 234567] using bytes: " );
try {
System.out.println( " expecting: -234557\n" +
" and got: " + g11.subtract( g13 ) );
}
catch( Exception e ) { System.out.println( " Exception thrown: " ); }
System.out.println( "\n Test " + makeTwoDigits() + ": Subtracting g13 take away g15 [234567 - (-10)] using bytes: " );
try {
System.out.println( " expecting: 234577\n" +
" and got: " + g13.subtract( g15 ) );
}
catch( Exception e ) { System.out.println( " Exception thrown: " ); }
System.out.println( "\n Test " + makeTwoDigits() + ": Subtracting g15 take away g13 [(-10) - 234567] using bytes: " );
try {
System.out.println( " expecting: -234577\n" +
" and got: " + g15.subtract( g13 ) );
}
catch( Exception e ) { System.out.println( " Exception thrown: " ); }
System.out.println( "\n Test " + makeTwoDigits() + ": Subtracting g14 take away g16 [(-234567) - (-999999)] using bytes: " );
try {
System.out.println( " expecting: 765432\n" +
" and got: " + g14.subtract( g16 ) );
}
catch( Exception e ) { System.out.println( " Exception thrown: " ); }
System.out.println( "\n Test " + makeTwoDigits() + ": Subtracting g16 take away g14 [(-999999) - (-234567)] using bytes: " );
try {
System.out.println( " expecting: -765432\n" +
" and got: " + g16.subtract( g14 ) );
}
catch( Exception e ) { System.out.println( " Exception thrown: " ); }
System.out.println( "\n Test " + makeTwoDigits() + ": Making a seventeenth new BrobInt: " );
try {
g17 = new BrobInt( g17String );
System.out.println( " expecting: 765\n" +
" and got: " + g17.toString() );
}
catch( Exception e ) { System.out.println( " Exception thrown: " ); }
System.out.println( "\n Test " + makeTwoDigits() + ": Making a eightteenth new BrobInt: " );
try {
g18 = new BrobInt( g18String );
System.out.println( " expecting: 23\n" +
" and got: " + g18.toString() );
}
catch( Exception e ) { System.out.println( " Exception thrown: " ); }
System.out.println( "\n Test " + makeTwoDigits() + ": Making a nineteenth new BrobInt: " );
try {
g19 = new BrobInt( g19String );
System.out.println( " expecting: 56789\n" +
" and got: " + g19.toString() );
}
catch( Exception e ) { System.out.println( " Exception thrown: " ); }
System.out.println( "\n Test " + makeTwoDigits() + ": Making a twentieth new BrobInt: " );
try {
g20 = new BrobInt( g20String );
System.out.println( " expecting: 37\n" +
" and got: " + g20.toString() );
}
catch( Exception e ) { System.out.println( " Exception thrown: " ); }
System.out.println( "\n Test " + makeTwoDigits() + ": Subtracting g20 take away g18 [37 - 23] using bytes: " );
try {
System.out.println( " expecting: 14\n" +
" and got: " + g20.subtract( g18 ) );
}
catch( Exception e ) { System.out.println( " Exception thrown: " + e.toString() ); }
System.out.println( "\n Test " + makeTwoDigits() + ": Subtracting g18 take away g20 [23 - 37] using bytes: " );
try {
System.out.println( " expecting: -14\n" +
" and got: " + g18.subtract( g20 ) );
}
catch( Exception e ) { System.out.println( " Exception thrown: " + e.toString() ); }
System.out.println( "\n Test " + makeTwoDigits() + ": Subtracting g1 take away g1 [too long to list] using bytes: " );
try {
System.out.println( " expecting: 000000000000000000000000000000000000000000000000000000000000000000\n" +
" and got: " + g1.subtract( g1 ) );
}
catch( Exception e ) { System.out.println( " Exception thrown: " ); }
System.out.println( "\n\n TESTING MULTIPLY() METHOD:\n" +
" ==========================" );
System.out.println( "\n Test " + makeTwoDigits() + ": Multiplying g7 by g12 [10 * 20]: " );
try {
System.out.println( " expecting: 200\n" +
" and got: " + g7.multiply( g12 ) );
}
catch( Exception e ) { System.out.println( " Exception thrown: " + e.toString() ); }
System.out.println( "\n Test " + makeTwoDigits() + ": Multiplying g17 by g18 [765 * 23]: " );
try {
System.out.println( " expecting: 17595\n" +
" and got: " + g17.multiply( g18 ) );
}
catch( Exception e ) { System.out.println( " Exception thrown: " + e.toString() ); }
System.out.println( "\n Test " + makeTwoDigits() + ": Multiplying g18 by g20 [23 * 37]: " );
try {
System.out.println( " expecting: 851\n" +
" and got: " + g18.multiply( g20 ) );
}
catch( Exception e ) { System.out.println( " Exception thrown: " + e.toString() ); }
System.out.println( "\n Test " + makeTwoDigits() + ": Multiplying g19 by g20 [56789 * 37]: " );
try {
System.out.println( " expecting: 2101193\n" +
" and got: " + g19.multiply( g20 ) );
}
catch( Exception e ) { System.out.println( " Exception thrown: " + e.toString() ); }
System.out.println( "\n Test " + makeTwoDigits() + ": Multiplying g18 by g17 [23 * 765]: " );
try {
System.out.println( " expecting: 17595\n" +
" and got: " + g18.multiply( g17 ) );
}
catch( Exception e ) { System.out.println( " Exception thrown: " + e.toString() ); }
System.out.println( "\n Test " + makeTwoDigits() + ": Multiplying g17 by g19 [765 * 56789]: " );
try {
System.out.println( " expecting: 43443585\n" +
" and got: " + g17.multiply( g19 ) );
}
catch( Exception e ) { System.out.println( " Exception thrown: " + e.toString() ); }
System.out.println( "\n Test " + makeTwoDigits() + ": Multiplying g14 by g18 [-234567 * 23]: " );
try {
System.out.println( " expecting: -5395041\n" +
" and got: " + g14.multiply( g18 ) );
}
catch( Exception e ) { System.out.println( " Exception thrown: " + e.toString() ); }
System.out.println( "\n Test " + makeTwoDigits() + ": Multiplying g18 by g14 [23 * -234567]: " );
try {
System.out.println( " expecting: -5395041\n" +
" and got: " + g18.multiply( g14 ) );
}
catch( Exception e ) { System.out.println( " Exception thrown: " + e.toString() ); }
System.out.println( "\n Test " + makeTwoDigits() + ": Multiplying g1 by g4:\n" +
" 144127909719710664015092431502440849849506284148982076191826176553\n" +
" 14412790971971066401509243150244084984950628410898207");
try {
System.out.println( " expecting: 2077285436017306769697707308539031996620483564822094960119979421402123963227779392443205060360059497074989285293140471\n" +
" and got: " + g1.multiply( g4 ) );
}
catch( Exception e ) { System.out.println( " Exception thrown: " + e.toString() ); }
System.out.println( "\n\n TESTING DIVIDE() METHOD:\n" +
" ========================" );
System.out.println( "\n Test " + makeTwoDigits() + ": Dividing g19 by g20 [56789 / 37]: " );
try {
System.out.println( " expecting: 1534\n" +
" and got: " + g19.divide( g20 ) );
}
catch( Exception e ) { System.out.println( " Exception thrown: " + e.toString() ); }
System.out.println( "\n Test " + makeTwoDigits() + ": Dividing g20 by g19 [37 / 56789]: " );
try {
System.out.println( " expecting: 0\n" +
" and got: " + g20.divide( g19 ) );
}
catch( Exception e ) { System.out.println( " Exception thrown: " + e.toString() ); }
System.out.println( "\n Test " + makeTwoDigits() + ": Dividing g20 by g20 [37 / 37]: " );
try {
System.out.println( " expecting: 1\n" +
" and got: " + g20.divide( g20 ) );
}
catch( Exception e ) { System.out.println( " Exception thrown: " + e.toString() ); }
System.out.println( "\n Test " + makeTwoDigits() + ": Dividing g20 by zero [37 / 0]: " );
try {
System.out.println( " expecting: exception\n" +
" and got: " + g20.divide( BrobInt.ZERO ) );
}
catch( Exception e ) { System.out.println( " Exception thrown: " + e.toString() ); }
System.out.println( "\n Test " + makeTwoDigits() + ": Dividing zero by g20 [0 / 37]: " );
try {
System.out.println( " expecting: 0\n" +
" and got: " + BrobInt.ZERO.divide( g20 ) );
}
catch( Exception e ) { System.out.println( " Exception thrown: " + e.toString() ); }
System.out.println( "\n Test " + makeTwoDigits() + ": Making a new BrobInt g21: " );
try {
g21 = new BrobInt( g21String );
System.out.println( " expecting: 14412790971971066401509243150\n" +
" and got: " + g21.toString() );
}
catch( Exception e ) { System.out.println( " Exception thrown: " ); }
System.out.println( "\n Test " + makeTwoDigits() + ": Making a new BrobInt g22: " );
try {
g22 = new BrobInt( g22String );
System.out.println( " expecting: 412790971971\n" +
" and got: " + g22.toString() );
}
catch( Exception e ) { System.out.println( " Exception thrown: " ); }
System.out.println( "\n Test " + makeTwoDigits() + ": Dividing g21 by g22 [14412790971971066401509243150 / 412790971971]: " );
try {
System.out.println( " expecting: 34915470421149654\n" +
" and got: " + g21.divide( g22 ) );
}
catch( Exception e ) { System.out.println( " Exception thrown: " + e.toString() ); }
System.out.println( "\n Test " + makeTwoDigits() + ": Dividing 23 by 4 [23 / 4]: " );
try {
BrobInt g23 = new BrobInt( "23" );
BrobInt g24 = new BrobInt( "4" );
System.out.println( " expecting: 5\n" +
" and got: " + g23.divide( g24 ) );
}
catch( Exception e ) { System.out.println( " Exception thrown: " + e.toString() ); }
System.out.println( "\n Test " + makeTwoDigits() + ": Dividing 100 by 33 [100 / 33]: " );
try {
BrobInt g24 = new BrobInt( "100" );
BrobInt g25= new BrobInt( "33" );
System.out.println( " expecting: 3\n" +
" and got: " + g24.divide( g25 ) );
}
catch( Exception e ) { System.out.println( " Exception thrown: " + e.toString() ); }
System.out.println( "\n\n TESTING REMAINDER() METHOD:\n" +
" ===========================" );
System.out.println( "\n Test " + makeTwoDigits() + ": Mod'ing g19 by g20 [56789 % 37]: " );
try {
System.out.println( " expecting: 31\n" +
" and got: " + g19.remainder( g20 ) );
}
catch( Exception e ) { System.out.println( " Exception thrown: " + e.toString() ); }
System.out.println( "\n Test " + makeTwoDigits() + ": Mod'ing g21 by g22 [14412790971971066401509243150 % 412790971971]: " );
try {
System.out.println( " expecting: 11598895116\n" +
" and got: " + g21.remainder( g22 ) );
}
catch( Exception e ) { System.out.println( " Exception thrown: " + e.toString() ); }
System.out.println( "\n Test " + makeTwoDigits() + ": Mod'ing 23 by 4 [23 % 4]: " );
try {
BrobInt g26 = new BrobInt( "23" );
BrobInt g27 = new BrobInt( "4" );
System.out.println( " expecting: 3\n" +
" and got: " + g26.remainder( g27 ) );
}
catch( Exception e ) { System.out.println( " Exception thrown: " + e.toString() ); }
System.out.println( "\n Test " + makeTwoDigits() + ": Mod'ing 100 by 33 [100 % 33]: " );
try {
BrobInt g28 = new BrobInt( "100" );
BrobInt g29 = new BrobInt( "33" );
System.out.println( " expecting: 1\n" +
" and got: " + g28.remainder( g29 ) );
}
catch( Exception e ) { System.out.println( " Exception thrown: " + e.toString() ); }
System.exit( 0 );
}
}
| 48.434959 | 170 | 0.490922 |
b4cd9956e03e44de6c0f247976555384cb23cace | 3,105 | package org.adrianl.demospring.controller;
import lombok.RequiredArgsConstructor;
import org.adrianl.demospring.dto.ProyectoDTO;
import org.adrianl.demospring.dto.RepositorioDTO;
import org.adrianl.demospring.mapper.RepositorioMapper;
import org.adrianl.demospring.model.Login;
import org.adrianl.demospring.model.Proyecto;
import org.adrianl.demospring.model.Repositorio;
import org.adrianl.demospring.repository.RepositorioRepository;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequiredArgsConstructor
public class RepositorioController {
private final RepositorioRepository repositorioRepository;
private final RepositorioMapper repositorioMapper;
@GetMapping("/repositorios")
public ResponseEntity<?> obtenerTodos() {
List<Repositorio> result = repositorioRepository.findAll();
if (result.isEmpty()) {
return ResponseEntity.notFound().build(); //404 no hay usuarios
} else {
return ResponseEntity.ok(result); //200
}
}
@GetMapping("/repositorio/{id}")
public ResponseEntity<?> obtenerUno(@PathVariable Long id) {
Repositorio result = repositorioRepository.findById(id).orElse(null);
if (result == null)
return ResponseEntity.notFound().build(); //404 no hay usuarios
else
return ResponseEntity.ok(result); //200
}
/*
@PostMapping("/repositorio")
public ResponseEntity<?> nuevoRepositorio(@RequestBody Repositorio nuevo) {
Repositorio saved = repositorioRepository.save(nuevo);
return ResponseEntity.status(HttpStatus.CREATED).body(saved); //201 usuario insertado
}
*/
@PostMapping("/repositorio")
public ResponseEntity<RepositorioDTO> nuevoRepositorio(@RequestBody RepositorioDTO repositorioDTO) {
try {
Repositorio repositorio = repositorioMapper.fromDTO(repositorioDTO);
Repositorio repositorioInsertado = repositorioRepository.save(repositorio);
return ResponseEntity.ok(repositorioMapper.toDTO(repositorioInsertado));
} catch (Exception e) {
System.out.println(e.getMessage());
throw new RuntimeException("Insertar, Error al insertar el repositorio. Campos incorrectos " + e.getMessage());
}
}
@PutMapping("/repositorio/{id}")
public ResponseEntity<?> editarRepositorio(@RequestBody Repositorio editar, @PathVariable Long id) {
return repositorioRepository.findById(id).map(p -> {
p.setNombre(editar.getNombre());
return ResponseEntity.ok(repositorioRepository.save(p)); //200
}).orElseGet(() -> {
return ResponseEntity.notFound().build(); //404 not found
});
}
@DeleteMapping("/repositorio/{id}")
public ResponseEntity<?> borrarRepositorio(@PathVariable Long id) {
repositorioRepository.deleteById(id);
return ResponseEntity.noContent().build(); //204 sin contenido
}
}
| 39.303797 | 123 | 0.704992 |
b0b11b5dc6d95398377936c32484071cc4941685 | 2,402 | package com.coolweather.android;
import android.content.Intent;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
public class SignIn extends AppCompatActivity {
private SharedPreferences pref;
private SharedPreferences.Editor editor;
@BindView(R.id.signin_account_edt)EditText account;
@BindView(R.id.signin_password_edt)EditText password;
@BindView(R.id.back_button)Button back;
@BindView(R.id.remember_pass_cb)CheckBox remember;
@BindView(R.id.signin_warning)LinearLayout warn;
@BindView(R.id.signin_warning_tv)TextView warnTextview;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activtity_sign_in);
pref= PreferenceManager.getDefaultSharedPreferences(this);
ButterKnife.bind(this);
boolean isRemember=pref.getBoolean("remember_password",false);
if (isRemember){
String acc=pref.getString("account","");
String pass=pref.getString("password","");
account.setText(acc);
password.setText(pass);
remember.setChecked(true);
}
}
@OnClick(R.id.create_account_ly)
void createClick(){
startActivity(new Intent(SignIn.this,CreateAccount.class));
}
@OnClick(R.id.reset_password_ly)
void resetClick(){
startActivity(new Intent(SignIn.this,ResetPassword.class));
}
@OnClick(R.id.signin_btn)
void signinClick(){
String acc=account.getText().toString();
String pass=password.getText().toString();
editor=pref.edit();
if (remember.isChecked()){
editor.putBoolean("remember_password",true);
editor.putString("account",acc);
editor.putString("password",pass);
}else {
editor.clear();
}
editor.apply();
startActivity(new Intent(SignIn.this,MainActivity.class));
}
}
| 29.292683 | 70 | 0.699833 |
9c1ce13b0f0bb9cd772dc682a248bb225f36b0b2 | 1,414 | package com.faravy.adapter;
import java.util.ArrayList;
import com.faravy.icare.R;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
public class HealthTipsCustomAdapter extends ArrayAdapter<String> {
// Variable Declaration
Activity mContext = null;
ArrayList<String> mNameList = null;
ArrayList<String> mTipsList = null;
public HealthTipsCustomAdapter(Activity context,
ArrayList<String> eNameList, ArrayList<String> eTipsList) {
super(context, R.layout.activity_health_tips_single_row, eNameList);
this.mContext = context;
this.mNameList = eNameList;
this.mTipsList = eTipsList;
}
@SuppressLint({ "ViewHolder", "InflateParams" })
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater mInflater = mContext.getLayoutInflater();
View rowView = mInflater.inflate(
R.layout.activity_health_tips_single_row, null, true);
// definition - gives variable a reference
TextView mTvName = (TextView) rowView
.findViewById(R.id.tvHealthTipsName);
TextView mTvList = (TextView) rowView
.findViewById(R.id.tvHealthTipsTips);
// set text in view
mTvName.setText(mNameList.get(position));
mTvList.setText(mTipsList.get(position));
return rowView;
}
}
| 26.679245 | 72 | 0.772984 |
8ad5ed1170f88ce611828355469aca33db57b32b | 6,861 | package parisnanterre.fr.lexify.connection;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.List;
import parisnanterre.fr.lexify.application.MainActivity;
import parisnanterre.fr.lexify.R;
import parisnanterre.fr.lexify.database.DatabaseUser;
import parisnanterre.fr.lexify.database.User;
import static parisnanterre.fr.lexify.application.MainActivity.currentUser;
public class SignInActivity extends Activity {
User currentUser = null;
final DatabaseUser db = new DatabaseUser(this);
Button btn_signin;
Button btn_playnoaccount;
Button btn_signup;
EditText edt_pseudo;
EditText edt_pass;
TextView txt_errors;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_signin);
btn_signin = (Button) findViewById(R.id.signin_btn_login);
btn_signup = (Button) findViewById(R.id.signin_btn_signup);
edt_pseudo = (EditText) findViewById(R.id.signin_edt_name);
edt_pass = (EditText) findViewById(R.id.signin_edt_password);
txt_errors = (TextView) findViewById(R.id.signin_txt_errors);
btn_signup.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i = new Intent(getApplicationContext(), SignUpActivity.class);
startActivity(i);
}
});
btn_signin.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
SignIn(v);
}
});
//Toast toast = Toast.makeText(this, lastUser, Toast.LENGTH_SHORT);
//toast.show();
}
public void SignIn(View v) {
/*
String pseudo = edt_pseudo.getText().toString();
String pass = edt_pass.getText().toString();
txt_errors.setText("");
if (pseudo.length() == 0) {
txt_errors.append(getResources().getString(R.string.enterpseudo));
}
if (pass.length() == 0) {
txt_errors.append(getResources().getString(R.string.enterpassword));
}
if (txt_errors.length() == 0) {
List<User> users = db.getAllUsers();
for (User u : users) {
if (u.get_pseudo().equals(pseudo) && u.get_pass().equals(pass)) {
MainActivity.currentUser = u;
}
}
if (MainActivity.currentUser == null) {
txt_errors.append(getResources().getString(R.string.nofindaccount));
} else {
Context context = getApplicationContext();
CharSequence text = getResources().getString(R.string.SucessConnexion);
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
updateUserInfo();
Intent i = new Intent();
i.setClass(this, MainActivity.class);
startActivity(i);
}
}
*/
}
public void updateUserInfo(){
/*try{
FileInputStream fileInputStream = getApplicationContext().openFileInput("user.json");
ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream);
//checks if json is empty by checking the content and file size
//if yes, fills the userList with users from the local DB
//else, fills it with the json file content
if (objectInputStream.toString().equals("{}") || objectInputStream.available()==0){
final DatabaseUser db = new DatabaseUser(this);
List<User> tmplist = db.getAllUsers();
final int size = tmplist.size();
for (int i = 0; i < size; i++) {
userList.put(tmplist.get(i).get_id(), tmplist.get(i));
}
}
else{
//userList is a Hashmap<Integer,User> where the key is the _id from the User object
userList = (HashMap<Integer,User>) objectInputStream.readObject();
}
MainActivity.currentUser = userList.get(this.currentUser.get_id());
objectInputStream.close();
fileInputStream.close();
Toast toast_tmp = Toast.makeText(getApplicationContext(), String.valueOf(MainActivity.currentUser.get_gamesPlayed()), Toast.LENGTH_SHORT);
toast_tmp.show();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (ClassCastException e ) {
e.printStackTrace();
}*/
/*
try {
SharedPreferences appSharedPrefs = PreferenceManager.getDefaultSharedPreferences(this.getApplicationContext());
Gson gson = new Gson();
String json = appSharedPrefs.getString("userList", "");
Type type = new TypeToken<HashMap<Integer, User>>(){}.getType();
//userList is a Hashmap<Integer,User> where the key is the _id from the User object
userList = gson.fromJson(json, type);
if (json.equals("") || userList.isEmpty()) {
final DatabaseUser db = new DatabaseUser(this);
List<User> tmplist = db.getAllUsers();
final int size = tmplist.size();
for (int i = 0; i < size; i++) {
userList.put(tmplist.get(i).get_id(), tmplist.get(i));
}
}
//Put in the global variable CurrentUser the value of the just logged in user
MainActivity.currentUser = userList.get(this.currentUser.get_id());
Toast toast_tmp = Toast.makeText(getApplicationContext(), String.valueOf(MainActivity.currentUser.get_gamesPlayed()), Toast.LENGTH_SHORT);
toast_tmp.show();
} catch (Exception e ){
e.printStackTrace();
}
*/
}
}
| 35.734375 | 150 | 0.613759 |
aff659f38a14e80cc38829502a44e168bee13fc5 | 797 | /* https://binarysearch.com/problems/Tree-Sum-Count */
import java.util.ArrayList;
/**
* public class Tree {
* int val;
* Tree left;
* Tree right;
* }
*/
class Solution {
int sumsToK = 0;
public int solve(Tree root, int k) {
ArrayList<Integer> path = new ArrayList<>();
dfs(root, k, path);
return sumsToK;
}
private void dfs(Tree root, int k, ArrayList<Integer> path) {
if (root == null)
return;
path.add(root.val);
dfs(root.left, k, path);
dfs(root.right, k, path);
int sum = 0;
for (int i = path.size() - 1; i >= 0; i--) {
sum += path.get(i);
if (sum == k) {
sumsToK++;
}
}
path.remove(path.size() - 1);
}
}
| 22.138889 | 65 | 0.484316 |
8c8e0e0e1b10899c1e2b5c6d02ab996facf097d0 | 807 | // Copyright (c) FIRST and other WPILib contributors.
// Open Source Software; you can modify and/or share it under the terms of
// the WPILib BSD license file in the root directory of this project.
package frc.robot;
import edu.wpi.first.wpilibj.XboxController;
import edu.wpi.first.wpilibj2.command.button.Button;
enum Pov {
UP(0),
UP_RIGHT(45),
RIGHT(90),
DOWN_RIGHT(135),
DOWN(180),
DOWN_LEFT(225),
LEFT(270),
UP_LEFT(315);
private final int angle;
Pov(int angle) {
this.angle = angle;
}
public int getAngle() {
return angle;
}
}
/**
* Add your docs here.
*/
public class PovButton extends Button {
public PovButton(XboxController controller, Pov pov) {
super(() -> controller.getPOV() == pov.getAngle());
}
}
| 20.692308 | 74 | 0.648079 |
3209db3f7580ba8ef2c6f008284b6b372b76d31e | 2,337 | package lc.datastruct.hash;
import lc.DisplayUtil;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
/**
* @Desc 349. 两个数组的交集
* @Author wuzh
* @Date 2021/4/20
*/
public class N0349 {
public static void main(String[] args) {
// 输入
int[] nums1 = {2, 1, 3};
int[] nums2 = {2, 3};
DisplayUtil.display(nums1);
DisplayUtil.display(nums2);
// 计算
int[] result = solution3(nums1, nums2);
// 输出
DisplayUtil.display(result);
}
// 解法1:暴力法
// 按顺序,在两个数组里一一对比即可
// 略。
public static int[] solution1(int[] nums1, int[] nums2) {
return null;
}
// 解法2:哈希表
public static int[] solution2(int[] nums1, int[] nums2) {
if (nums1 == null || nums1.length == 0 || nums2== null || nums2.length == 0) {
return new int[0];
}
// 1.构建表1
HashSet<Integer> set1 = new HashSet<>();
for (Integer n1 : nums1) {
set1.add(n1);
}
// 2.构建结果集
HashSet<Integer> set2 = new HashSet<>();
for (Integer n2 : nums2) {
if (set1.contains(n2)) {
set2.add(n2);
}
}
// 3.构造结果数组
int[] resultArr = new int[set2.size()];
int index = 0;
for (Integer s2 : set2) {
resultArr[index++] = s2;
}
return resultArr;
}
// 解法3:排序 + 双指针
public static int[] solution3(int[] nums1, int[] nums2) {
if (nums1 == null || nums1.length == 0 || nums2== null || nums2.length == 0) {
return new int[0];
}
// 1.排序
Arrays.sort(nums1);
Arrays.sort(nums2);
int p1 = 0;
int p2 = 0;
// 双指针取公共集
HashSet<Integer> set = new HashSet<>();
while (p1 < nums1.length && p2 < nums2.length) {
if (nums1[p1] == nums2[p2]) {
set.add(nums1[p1]);
p1++;
p2++;
} else if (nums1[p1] < nums2[p2]) {
p1++;
} else {
p2++;
}
}
// 3.构造结果数组
int[] resultArr = new int[set.size()];
int index = 0;
for (Integer s2 : set) {
resultArr[index++] = s2;
}
return resultArr;
}
}
| 22.471154 | 86 | 0.460419 |
a28ac876a2d59d088a8dc02495f3af344d9fed09 | 8,906 | /*******************************************************************************
* * Copyright 2012 Impetus Infotech.
* *
* * 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.impetus.kundera.configure.schema.api;
import java.util.List;
import java.util.Map;
import com.impetus.kundera.PersistenceProperties;
import com.impetus.kundera.configure.ClientProperties.DataStore;
import com.impetus.kundera.configure.ClientProperties.DataStore.Connection;
import com.impetus.kundera.configure.ClientProperties.DataStore.Schema;
import com.impetus.kundera.configure.schema.TableInfo;
import com.impetus.kundera.metadata.model.PersistenceUnitMetadata;
import com.impetus.kundera.persistence.EntityManagerFactoryImpl.KunderaMetadata;
import com.impetus.kundera.utils.KunderaCoreUtils;
/**
* Abstract Schema Manager has abstract method to handle
* {@code SchemaOperationType}.
*
* @author Kuldeep.Kumar
*
*/
public abstract class AbstractSchemaManager
{
/** The pu metadata variable. */
protected PersistenceUnitMetadata puMetadata;
/** The port variable. */
protected String port;
/** The host variable . */
protected String[] hosts;
/** The kundera_client variable. */
protected String clientFactory;
/** The database name variable. */
protected String databaseName;
/** The table infos variable . */
protected List<TableInfo> tableInfos;
/** The operation variable. */
protected String operation;
/** for kundera.show property */
protected boolean showQuery;
protected List<Schema> schemas = null;
protected Connection conn = null;
protected DataStore dataStore = null;
protected Map<String, Object> externalProperties;
protected String userName = null;
protected String password = null;
protected final KunderaMetadata kunderaMetadata;
/**
* Initialise with configured client factory.
*
* @param clientFactory
* specific client factory.
* @param externalProperties
*/
protected AbstractSchemaManager(String clientFactory, Map<String, Object> externalProperties,
final KunderaMetadata kunderaMetadata)
{
this.clientFactory = clientFactory;
this.externalProperties = externalProperties;
this.kunderaMetadata = kunderaMetadata;
}
/**
* Export schema handles the handleOperation method.
*
* @param hbase
*/
protected void exportSchema(final String persistenceUnit, List<TableInfo> tables)
{
// Get persistence unit metadata
this.puMetadata = kunderaMetadata.getApplicationMetadata().getPersistenceUnitMetadata(persistenceUnit);
String paramString = externalProperties != null ? (String) externalProperties
.get(PersistenceProperties.KUNDERA_CLIENT_FACTORY) : null;
if (clientFactory != null
&& ((clientFactory.equalsIgnoreCase(puMetadata.getProperties().getProperty(
PersistenceProperties.KUNDERA_CLIENT_FACTORY))) || (paramString != null && clientFactory
.equalsIgnoreCase(paramString))))
{
readConfigProperties(puMetadata);
// invoke handle operation.
if (operation != null && initiateClient())
{
tableInfos = tables;
handleOperations(tables);
}
}
}
/**
* @param pu
*/
private void readConfigProperties(final PersistenceUnitMetadata puMetadata)
{
String hostName = null;
String portName = null;
String operationType = null;
String schemaName = null;
if (externalProperties != null)
{
portName = (String) externalProperties.get(PersistenceProperties.KUNDERA_PORT);
hostName = (String) externalProperties.get(PersistenceProperties.KUNDERA_NODES);
userName = (String) externalProperties.get(PersistenceProperties.KUNDERA_USERNAME);
password = (String) externalProperties.get(PersistenceProperties.KUNDERA_PASSWORD);
schemaName = (String) externalProperties.get(PersistenceProperties.KUNDERA_KEYSPACE);
// get type of schema of operation.
operationType = (String) externalProperties.get(PersistenceProperties.KUNDERA_DDL_AUTO_PREPARE);
showQuery = KunderaCoreUtils.isShowQueryEnabled(externalProperties, puMetadata.getPersistenceUnitName(), kunderaMetadata);
}
if (portName == null)
portName = puMetadata.getProperties().getProperty(PersistenceProperties.KUNDERA_PORT);
if (hostName == null)
hostName = puMetadata.getProperties().getProperty(PersistenceProperties.KUNDERA_NODES);
if (schemaName == null)
schemaName = puMetadata.getProperties().getProperty(PersistenceProperties.KUNDERA_KEYSPACE);
// get type of schema of operation.
if (operationType == null)
operationType = puMetadata.getProperty(PersistenceProperties.KUNDERA_DDL_AUTO_PREPARE);
/* if (!showQuery)
showQuery = Boolean.parseBoolean(puMetadata.getProperties().getProperty(
PersistenceProperties.KUNDERA_SHOW_QUERY));
*/
if (userName == null)
{
userName = puMetadata.getProperty(PersistenceProperties.KUNDERA_USERNAME);
password = puMetadata.getProperty(PersistenceProperties.KUNDERA_PASSWORD);
}
String[] hostArray = hostName.split(",");
hosts = new String[hostArray.length];
for (int i = 0; i < hostArray.length; i++)
{
hosts[i] = hostArray[i].trim();
}
this.port = portName;
this.databaseName = schemaName;
this.operation = operationType;
}
/**
* Initiate client to initialize with client specific schema.
*
* @return true, if successful
*/
protected abstract boolean initiateClient();
/**
* Validates the schema.
*
* @param tableInfos
* the table infos
*/
protected abstract void validate(List<TableInfo> tableInfos);
/**
* Update.
*
* @param tableInfos
* the table infos
*/
protected abstract void update(List<TableInfo> tableInfos);
/**
* Creates the.
*
* @param tableInfos
* the table infos
*/
protected abstract void create(List<TableInfo> tableInfos);
/**
* Create_drop.
*
* @param tableInfos
* the table infos
*/
protected abstract void create_drop(List<TableInfo> tableInfos);
/**
* handleOperations method handles the all operation on the basis of
* operationType
*/
/**
* enum class for operation type
*/
/**
* The Enum ScheamOperationType.
*/
public enum SchemaOperationType
{
/** The createdrop. */
createdrop,
/** The create. */
create,
/** The validate. */
validate,
/** The update. */
update;
/**
* Gets the single instance of ScheamOperationType.
*
* @param operation
* the operation
* @return single instance of ScheamOperationType
*/
public static SchemaOperationType getInstance(String operation)
{
if (operation.equalsIgnoreCase("create-drop"))
{
return SchemaOperationType.createdrop;
}
return SchemaOperationType.valueOf(SchemaOperationType.class, operation);
}
}
/**
* Handle operations.
*
* @param tableInfos
* the table infos
*/
private void handleOperations(List<TableInfo> tableInfos)
{
SchemaOperationType operationType = SchemaOperationType.getInstance(operation);
switch (operationType)
{
case createdrop:
create_drop(tableInfos);
break;
case create:
create(tableInfos);
break;
case update:
update(tableInfos);
break;
case validate:
validate(tableInfos);
break;
}
}
}
| 32.385455 | 134 | 0.626656 |
896448a3dde37a31ed167bf49d034745d5185de2 | 4,474 | // Copyright (c) 2003-present, Jodd Team (http://jodd.org)
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
package jodd.petite;
import jodd.petite.def.CtorInjectionPoint;
import jodd.petite.def.DestroyMethodPoint;
import jodd.petite.def.InitMethodPoint;
import jodd.petite.def.MethodInjectionPoint;
import jodd.petite.def.PropertyInjectionPoint;
import jodd.petite.def.ProviderDefinition;
import jodd.petite.def.SetInjectionPoint;
import jodd.petite.resolver.CtorResolver;
import jodd.petite.resolver.DestroyMethodResolver;
import jodd.petite.resolver.InitMethodResolver;
import jodd.petite.resolver.MethodResolver;
import jodd.petite.resolver.PropertyResolver;
import jodd.petite.resolver.ProviderResolver;
import jodd.petite.resolver.ReferencesResolver;
import jodd.petite.resolver.SetResolver;
/**
* Holds all resolvers instances and offers delegate methods.
*/
public class PetiteResolvers {
protected final ReferencesResolver referencesResolver;
protected final CtorResolver ctorResolver;
protected final PropertyResolver propertyResolver;
protected final MethodResolver methodResolver;
protected final SetResolver setResolver;
protected final InitMethodResolver initMethodResolver;
protected final DestroyMethodResolver destroyMethodResolver;
protected final ProviderResolver providerResolver;
public PetiteResolvers(final ReferencesResolver referencesResolver) {
this.referencesResolver = referencesResolver;
this.ctorResolver = new CtorResolver(referencesResolver);
this.methodResolver = new MethodResolver(referencesResolver);
this.propertyResolver = new PropertyResolver(referencesResolver);
this.setResolver = new SetResolver();
this.initMethodResolver = new InitMethodResolver();
this.destroyMethodResolver = new DestroyMethodResolver();
this.providerResolver = new ProviderResolver();
}
// ---------------------------------------------------------------- delegates
/**
* Resolves constructor injection point.
*/
public CtorInjectionPoint resolveCtorInjectionPoint(final Class type) {
return ctorResolver.resolve(type, true);
}
/**
* Resolves property injection points.
*/
public PropertyInjectionPoint[] resolvePropertyInjectionPoint(final Class type, final boolean autowire) {
return propertyResolver.resolve(type, autowire);
}
/**
* Resolves method injection points.
*/
public MethodInjectionPoint[] resolveMethodInjectionPoint(final Class type) {
return methodResolver.resolve(type);
}
/**
* Resolves set injection points.
*/
public SetInjectionPoint[] resolveSetInjectionPoint(final Class type, final boolean autowire) {
return setResolver.resolve(type, autowire);
}
/**
* Resolves init method points.
*/
public InitMethodPoint[] resolveInitMethodPoint(final Class type) {
return initMethodResolver.resolve(type);
}
/**
* Resolves destroy method points.
*/
public DestroyMethodPoint[] resolveDestroyMethodPoint(final Class type) {
return destroyMethodResolver.resolve(type);
}
/**
* Resolves provider definition defined in a bean.
*/
public ProviderDefinition[] resolveProviderDefinitions(final Class type, final String name) {
return providerResolver.resolve(type, name);
}
} | 37.283333 | 106 | 0.781627 |
38b19028b03507014b882179f984bc55e8587f6f | 2,604 | package mage.cards.r;
import mage.abilities.TriggeredAbilityImpl;
import mage.abilities.costs.mana.GenericManaCost;
import mage.abilities.effects.common.CopyStackAbilityEffect;
import mage.abilities.effects.common.DoIfCostPaid;
import mage.abilities.mana.ActivatedManaAbilityImpl;
import mage.cards.CardImpl;
import mage.cards.CardSetInfo;
import mage.constants.CardType;
import mage.constants.Zone;
import mage.game.Game;
import mage.game.events.GameEvent;
import mage.game.stack.StackAbility;
import java.util.UUID;
/**
* @author LevelX2
*/
public final class RingsOfBrighthearth extends CardImpl {
public RingsOfBrighthearth(UUID ownerId, CardSetInfo setInfo) {
super(ownerId, setInfo, new CardType[]{CardType.ARTIFACT}, "{3}");
// Whenever you activate an ability, if it isn't a mana ability, you may pay {2}. If you do, copy that ability. You may choose new targets for the copy.
this.addAbility(new RingsOfBrighthearthTriggeredAbility());
}
private RingsOfBrighthearth(final RingsOfBrighthearth card) {
super(card);
}
@Override
public RingsOfBrighthearth copy() {
return new RingsOfBrighthearth(this);
}
}
class RingsOfBrighthearthTriggeredAbility extends TriggeredAbilityImpl {
RingsOfBrighthearthTriggeredAbility() {
super(Zone.BATTLEFIELD, new DoIfCostPaid(new CopyStackAbilityEffect(), new GenericManaCost(2)));
}
private RingsOfBrighthearthTriggeredAbility(final RingsOfBrighthearthTriggeredAbility ability) {
super(ability);
}
@Override
public RingsOfBrighthearthTriggeredAbility copy() {
return new RingsOfBrighthearthTriggeredAbility(this);
}
@Override
public boolean checkEventType(GameEvent event, Game game) {
return event.getType() == GameEvent.EventType.ACTIVATED_ABILITY;
}
@Override
public boolean checkTrigger(GameEvent event, Game game) {
if (!event.getPlayerId().equals(getControllerId())) {
return false;
}
StackAbility stackAbility = (StackAbility) game.getStack().getStackObject(event.getSourceId());
if (stackAbility == null || stackAbility.getStackAbility() instanceof ActivatedManaAbilityImpl) {
return false;
}
this.getEffects().setValue("stackAbility", stackAbility);
return true;
}
@Override
public String getRule() {
return "Whenever you activate an ability, if it isn't a mana ability, you may pay {2}. " +
"If you do, copy that ability. You may choose new targets for the copy.";
}
}
| 32.962025 | 160 | 0.71659 |
4220636b41917127451291e1532614311f878065 | 16,796 | /*
* Copyright 2016 Realm 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 io.realm;
import java.io.IOException;
import java.util.Locale;
import io.realm.log.RealmLog;
/**
* This class enumerate all potential errors related to using the Object Server or synchronizing data.
*/
public enum ErrorCode {
// See Client::Error in https://github.com/realm/realm-sync/blob/master/src/realm/sync/client.hpp#L1230
// See https://github.com/realm/realm-sync/blob/develop/src/realm/sync/protocol.hpp
// Catch-all
// The underlying type and error code should be part of the error message
UNKNOWN(Type.UNKNOWN, -1),
// Realm Java errors
IO_EXCEPTION(Type.JAVA, 0, Category.RECOVERABLE), // Some IO error while either contacting the server or reading the response
JSON_EXCEPTION(Type.AUTH, 1), // JSON input could not be parsed correctly
CLIENT_RESET(Type.PROTOCOL, 7), // Client Reset required. Don't change this value without modifying io_realm_internal_OsSharedRealm.cpp
// Connection level and protocol errors from the native Sync Client
CONNECTION_CLOSED(Type.PROTOCOL, 100, Category.RECOVERABLE), // Connection closed (no error)
OTHER_ERROR(Type.PROTOCOL, 101), // Other connection level error
UNKNOWN_MESSAGE(Type.PROTOCOL, 102), // Unknown type of input message
BAD_SYNTAX(Type.PROTOCOL, 103), // Bad syntax in input message head
LIMITS_EXCEEDED(Type.PROTOCOL, 104), // Limits exceeded in input message
WRONG_PROTOCOL_VERSION(Type.PROTOCOL, 105), // Wrong protocol version (CLIENT)
BAD_SESSION_IDENT(Type.PROTOCOL, 106), // Bad session identifier in input message
REUSE_OF_SESSION_IDENT(Type.PROTOCOL, 107), // Overlapping reuse of session identifier (BIND)
BOUND_IN_OTHER_SESSION(Type.PROTOCOL, 108), // Client file bound in other session (IDENT)
BAD_MESSAGE_ORDER(Type.PROTOCOL, 109), // Bad input message order
BAD_DECOMPRESSION(Type.PROTOCOL, 110), // Error in decompression (UPLOAD)
BAD_CHANGESET_HEADER_SYNTAX(Type.PROTOCOL, 111), // Bad server version in changeset header (DOWNLOAD)
BAD_CHANGESET_SIZE(Type.PROTOCOL, 112), // Bad size specified in changeset header (UPLOAD)
BAD_CHANGESETS(Type.PROTOCOL, 113), // Bad changesets (UPLOAD)
// Session level errors from the native Sync Client
SESSION_CLOSED(Type.PROTOCOL, 200, Category.RECOVERABLE), // Session closed (no error)
OTHER_SESSION_ERROR(Type.PROTOCOL, 201, Category.RECOVERABLE), // Other session level error
TOKEN_EXPIRED(Type.PROTOCOL, 202, Category.RECOVERABLE), // Access token expired
// Session fatal: Auth wrong. Cannot be fixed without a new User/SyncConfiguration.
BAD_AUTHENTICATION(Type.PROTOCOL, 203), // Bad user authentication (BIND, REFRESH)
ILLEGAL_REALM_PATH(Type.PROTOCOL, 204), // Illegal Realm path (BIND)
NO_SUCH_PATH(Type.PROTOCOL, 205), // No such Realm (BIND)
PERMISSION_DENIED(Type.PROTOCOL, 206), // Permission denied (BIND, REFRESH)
// Fatal: Wrong server/client versions. Trying to sync incompatible files or the file was corrupted.
BAD_SERVER_FILE_IDENT(Type.PROTOCOL, 207), // Bad server file identifier (IDENT)
BAD_CLIENT_FILE_IDENT(Type.PROTOCOL, 208), // Bad client file identifier (IDENT)
BAD_SERVER_VERSION(Type.PROTOCOL, 209), // Bad server version (IDENT, UPLOAD)
BAD_CLIENT_VERSION(Type.PROTOCOL, 210), // Bad client version (IDENT, UPLOAD)
DIVERGING_HISTORIES(Type.PROTOCOL, 211), // Diverging histories (IDENT)
BAD_CHANGESET(Type.PROTOCOL, 212), // Bad changeset (UPLOAD)
DISABLED_SESSION(Type.PROTOCOL, 213), // Disabled session
PARTIAL_SYNC_DISABLED(Type.PROTOCOL, 214), // Partial sync disabled (BIND)
UNSUPPORTED_SESSION_FEATURE(Type.PROTOCOL, 215), // Unsupported session-level feature
BAD_ORIGIN_FILE_IDENT(Type.PROTOCOL, 216), // Bad origin file identifier (UPLOAD)
BAD_CLIENT_FILE(Type.PROTOCOL, 217), // Synchronization no longer possible for client-side file
SERVER_FILE_DELETED(Type.PROTOCOL, 218), // Server file was deleted while session was bound to it
CLIENT_FILE_BLACKLISTED(Type.PROTOCOL, 219), // Client file has been blacklisted (IDENT)
USER_BLACKLISTED(Type.PROTOCOL, 220), // User has been blacklisted (BIND)
TRANSACT_BEFORE_UPLOAD(Type.PROTOCOL, 221), // Serialized transaction before upload completion
CLIENT_FILE_EXPIRED(Type.PROTOCOL, 222), // Client file has expired
// Sync Network Client errors.
// See https://github.com/realm/realm-sync/blob/master/src/realm/sync/client.hpp#L1230
CLIENT_CONNECTION_CLOSED(Type.SESSION, 100), // Connection closed (no error)
CLIENT_UNKNOWN_MESSAGE(Type.SESSION, 101), // Unknown type of input message
CLIENT_LIMITS_EXCEEDED(Type.SESSION, 103), // Limits exceeded in input message
CLIENT_BAD_SESSION_IDENT(Type.SESSION, 104), // Bad session identifier in input message
CLIENT_BAD_MESSAGE_ORDER(Type.SESSION, 105), // Bad input message order
CLIENT_BAD_CLIENT_FILE_IDENT(Type.SESSION, 106), // Bad client file identifier (IDENT)
CLIENT_BAD_PROGRESS(Type.SESSION, 107), // Bad progress information (DOWNLOAD)
CLIENT_BAD_CHANGESET_HEADER_SYNTAX(Type.SESSION, 108), // Bad syntax in changeset header (DOWNLOAD)
CLIENT_BAD_CHANGESET_SIZE(Type.SESSION, 109), // Bad changeset size in changeset header (DOWNLOAD)
CLIENT_BAD_ORIGIN_FILE_IDENT(Type.SESSION, 110), // Bad origin file identifier in changeset header (DOWNLOAD)
CLIENT_BAD_SERVER_VERSION(Type.SESSION, 111), // Bad server version in changeset header (DOWNLOAD)
CLIENT_BAD_CHANGESET(Type.SESSION, 112), // Bad changeset (DOWNLOAD)
CLIENT_BAD_REQUEST_IDENT(Type.SESSION, 113), // Bad request identifier (MARK)
CLIENT_BAD_ERROR_CODE(Type.SESSION, 114), // Bad error code (ERROR)
CLIENT_BAD_COMPRESSION(Type.SESSION, 115), // Bad compression (DOWNLOAD)
CLIENT_BAD_CLIENT_VERSION_DOWNLOAD(Type.SESSION, 116), // Bad last integrated client version in changeset header (DOWNLOAD)
CLIENT_SSL_SERVER_CERT_REJECTED(Type.SESSION, 117), // SSL server certificate rejected
CLIENT_PONG_TIMEOUT(Type.SESSION, 118), // Timeout on reception of PONG respone message
CLIENT_BAD_CLIENT_FILE_IDENT_SALT(Type.SESSION, 119), // Bad client file identifier salt (IDENT)
CLIENT_FILE_IDENT(Type.SESSION, 120), // Bad file identifier (ALLOC)
CLIENT_CONNECT_TIMEOUT(Type.SESSION, 121), // Sync connection was not fully established in time
CLIENT_BAD_TIMESTAMP(Type.SESSION, 122), // Bad timestamp (PONG)
CLIENT_BAD_PROTOCOL_FROM_SERVER(Type.SESSION, 123), // Bad or missing protocol version information from server
CLIENT_TOO_OLD_FOR_SERVER(Type.SESSION, 124), // Protocol version negotiation failed: Client is too old for server
CLIENT_TOO_NEW_FOR_SERVER(Type.SESSION, 125), // Protocol version negotiation failed: Client is too new for server
CLIENT_PROTOCOL_MISMATCH(Type.SESSION, 126), // Protocol version negotiation failed: No version supported by both client and server
CLIENT_BAD_STATE_MESSAGE(Type.SESSION, 127), // Bad values in state message (STATE)
CLIENT_MISSING_PROTOCOL_FEATURE(Type.SESSION, 128), // Requested feature missing in negotiated protocol version
CLIENT_BAD_SERIAL_TRANSACT_STATUS(Type.SESSION, 129), // Bad status of serialized transaction (TRANSACT)
CLIENT_BAD_OBJECT_ID_SUBSTITUTIONS(Type.SESSION, 130), // Bad encoded object identifier substitutions (TRANSACT)
CLIENT_HTTP_TUNNEL_FAILED(Type.SESSION, 131), // Failed to establish HTTP tunnel with configured proxy
// 300 - 599 Reserved for Standard HTTP error codes
MULTIPLE_CHOICES(Type.HTTP, 300),
MOVED_PERMANENTLY(Type.HTTP, 301),
FOUND(Type.HTTP, 302),
SEE_OTHER(Type.HTTP, 303),
NOT_MODIFIED(Type.HTTP, 304),
USE_PROXY(Type.HTTP, 305),
TEMPORARY_REDIRECT(Type.HTTP, 307),
PERMANENT_REDIRECT(Type.HTTP, 308),
BAD_REQUEST(Type.HTTP, 400),
UNAUTHORIZED(Type.HTTP, 401),
PAYMENT_REQUIRED(Type.HTTP, 402),
FORBIDDEN(Type.HTTP, 403),
NOT_FOUND(Type.HTTP, 404),
METHOD_NOT_ALLOWED(Type.HTTP, 405),
NOT_ACCEPTABLE(Type.HTTP, 406),
PROXY_AUTHENTICATION_REQUIRED(Type.HTTP, 407),
REQUEST_TIMEOUT(Type.HTTP, 408),
CONFLICT(Type.HTTP, 409),
GONE(Type.HTTP, 410),
LENGTH_REQUIRED(Type.HTTP, 411),
PRECONDITION_FAILED(Type.HTTP, 412),
PAYLOAD_TOO_LARGE(Type.HTTP, 413),
URI_TOO_LONG(Type.HTTP, 414),
UNSUPPORTED_MEDIA_TYPE(Type.HTTP, 415),
RANGE_NOT_SATISFIABLE(Type.HTTP, 416),
EXPECTATION_FAILED(Type.HTTP, 417),
MISDIRECTED_REQUEST(Type.HTTP, 421),
UNPROCESSABLE_ENTITY(Type.HTTP, 422),
LOCKED(Type.HTTP, 423),
FAILED_DEPENDENCY(Type.HTTP, 424),
UPGRADE_REQUIRED(Type.HTTP, 426),
PRECONDITION_REQUIRED(Type.HTTP, 428),
TOO_MANY_REQUESTS(Type.HTTP, 429),
REQUEST_HEADER_FIELDS_TOO_LARGE(Type.HTTP, 431),
UNAVAILABLE_FOR_LEGAL_REASONS(Type.HTTP, 451),
INTERNAL_SERVER_ERROR(Type.HTTP, 500),
NOT_IMPLEMENTED(Type.HTTP, 501),
BAD_GATEWAY(Type.HTTP, 502),
SERVICE_UNAVAILABLE(Type.HTTP, 503),
GATEWAY_TIMEOUT(Type.HTTP, 504),
HTTP_VERSION_NOT_SUPPORTED(Type.HTTP, 505),
VARIANT_ALSO_NEGOTIATES(Type.HTTP, 506),
INSUFFICIENT_STORAGE(Type.HTTP, 507),
LOOP_DETECTED(Type.HTTP, 508),
NOT_EXTENDED(Type.HTTP, 510),
NETWORK_AUTHENTICATION_REQUIRED(Type.HTTP, 511),
// Realm Authentication Server response errors (600 - 699)
INVALID_PARAMETERS(Type.AUTH, 601),
MISSING_PARAMETERS(Type.AUTH, 602),
INVALID_CREDENTIALS(Type.AUTH, 611),
UNKNOWN_ACCOUNT(Type.AUTH, 612),
EXISTING_ACCOUNT(Type.AUTH, 613),
ACCESS_DENIED(Type.AUTH, 614),
EXPIRED_REFRESH_TOKEN(Type.AUTH, 615),
INVALID_HOST(Type.AUTH, 616),
REALM_NOT_FOUND(Type.AUTH, 617),
UNKNOWN_USER(Type.AUTH, 618),
WRONG_REALM_TYPE(Type.AUTH, 619), // The Realm found on the server is of different type than the one requested.
// Other Realm Object Server response errors
EXPIRED_PERMISSION_OFFER(Type.AUTH, 701),
AMBIGUOUS_PERMISSION_OFFER_TOKEN(Type.AUTH, 702),
FILE_MAY_NOT_BE_SHARED(Type.AUTH, 703),
SERVER_MISCONFIGURATION(Type.AUTH, 801),
// Generic system errors we want to enumerate specifically
CONNECTION_RESET_BY_PEER(Type.CONNECTION, 104, Category.RECOVERABLE), // ECONNRESET: Connection reset by peer
CONNECTION_SOCKET_SHUTDOWN(Type.CONNECTION, 110, Category.RECOVERABLE), // ESHUTDOWN: Can't send after socket shutdown
CONNECTION_REFUSED(Type.CONNECTION, 111, Category.RECOVERABLE), // ECONNREFUSED: Connection refused
CONNECTION_ADDRESS_IN_USE(Type.CONNECTION, 112, Category.RECOVERABLE), // EADDRINUSE: Address already i use
CONNECTION_CONNECTION_ABORTED(Type.CONNECTION, 113, Category.RECOVERABLE), // ECONNABORTED: Connection aborted
MISC_END_OF_INPUT(Type.MISC, 1), // End of input
MISC_PREMATURE_END_OF_INPUT(Type.MISC, 2), // Premature end of input. That is, end of input at an unexpected, or illegal place in an input stream.
MISC_DELIMITER_NOT_FOUND(Type.MISC, 3); // Delimiter not found
private final String type;
private final int code;
private final Category category;
ErrorCode(String type, int errorCode) {
this(type, errorCode, Category.FATAL);
}
ErrorCode(String type, int errorCode, Category category) {
this.type = type;
this.code = errorCode;
this.category = category;
}
@Override
public String
toString() {
return super.toString() + "(" + type + ":" + code + ")";
}
/**
* Returns the numerical value for this error code. Note that an error is only uniquely
* identified by the {@code (type:value)} pair.
*
* @return the error code as an unique {@code int} value.
*/
public int intValue() {
return code;
}
/**
* Returns the getCategory of the error.
* <p>
* Errors come in 2 categories: FATAL, RECOVERABLE
* <p>
* FATAL: The session cannot be recovered and needs to be re-created. A likely cause is that the User does not
* have access to this Realm. Check that the {@link SyncConfiguration} is correct.
* <p>
* RECOVERABLE: Temporary error. The session will automatically try to recover as soon as possible.
* <p>
*
* @return the severity of the error.
*/
public Category getCategory() {
return category;
}
/**
* Returns the type of error. Note that an error is only uniquely identified by the
* {@code (type:value)} pair.
*
* @return the type of error.
*/
public String getType() {
return type;
}
/**
* Converts a native error to the appropriate Java equivalent
*
* @param type type of error. This is normally the C++ category.
* @param errorCode specific code within the type
*
* @return the Java error representing the native error. This method will never throw, so in case
* a Java error does not exists. {@link #UNKNOWN} will be returned.
*/
public static ErrorCode fromNativeError(String type, int errorCode) {
ErrorCode[] errorCodes = values();
for (int i = 0; i < errorCodes.length; i++) {
ErrorCode error = errorCodes[i];
if (error.intValue() == errorCode && error.type.equals(type)) {
return error;
}
}
RealmLog.warn(String.format(Locale.US, "Unknown error code: '%s:%d'", type, errorCode));
return UNKNOWN;
}
/**
* Helper method for mapping between {@link Exception} and {@link ErrorCode}.
* @param exception to be mapped as an {@link ErrorCode}.
* @return mapped {@link ErrorCode}.
*/
public static ErrorCode fromException(Exception exception) {
// IOException are recoverable (with exponential backoff)
if (exception instanceof IOException) {
return ErrorCode.IO_EXCEPTION;
} else {
return ErrorCode.UNKNOWN;
}
}
public static class Type {
public static final String AUTH = "auth"; // Errors from the Realm Object Server
public static final String CONNECTION = "realm.basic_system"; // Connection/System errors from the native Sync Client
public static final String DEPRECATED = "deprecated"; // Deprecated errors
public static final String HTTP = "http"; // Errors from the HTTP layer
public static final String JAVA = "java"; // Errors from the Java layer
public static final String MISC = "realm.util.misc_ext"; // Misc errors from the native Sync Client
public static final String PROTOCOL = "realm::sync::ProtocolError"; // Protocol level errors from the native Sync Client
public static final String SESSION = "realm::sync::Client::Error"; // Session level errors from the native Sync Client
public static final String UNKNOWN = "unknown"; // Catch-all category
}
public enum Category {
FATAL, // Abort session as soon as possible
RECOVERABLE, // Still possible to recover the session by either rebinding or providing the required information.
}
}
| 54.006431 | 157 | 0.671827 |
3f58839835a3b32a8d9e79801911dfdf1270148e | 13,413 | /*
* This file is generated by jOOQ.
*/
package com.oneops.crawler.jooq.cms;
import com.oneops.crawler.jooq.cms.tables.CmCi;
import com.oneops.crawler.jooq.cms.tables.CmCiAttributes;
import com.oneops.crawler.jooq.cms.tables.CmCiRelationAttributes;
import com.oneops.crawler.jooq.cms.tables.CmCiRelations;
import com.oneops.crawler.jooq.cms.tables.CmCiState;
import com.oneops.crawler.jooq.cms.tables.CmNsOpt;
import com.oneops.crawler.jooq.cms.tables.CmOpsActionState;
import com.oneops.crawler.jooq.cms.tables.CmOpsActions;
import com.oneops.crawler.jooq.cms.tables.CmOpsProcState;
import com.oneops.crawler.jooq.cms.tables.CmOpsProcedures;
import com.oneops.crawler.jooq.cms.tables.CmsCiEventQueue;
import com.oneops.crawler.jooq.cms.tables.CmsEventQueue;
import com.oneops.crawler.jooq.cms.tables.CmsEventType;
import com.oneops.crawler.jooq.cms.tables.CmsLock;
import com.oneops.crawler.jooq.cms.tables.CmsVars;
import com.oneops.crawler.jooq.cms.tables.DjApprovalStates;
import com.oneops.crawler.jooq.cms.tables.DjDeployment;
import com.oneops.crawler.jooq.cms.tables.DjDeploymentRfc;
import com.oneops.crawler.jooq.cms.tables.DjDeploymentRfcStates;
import com.oneops.crawler.jooq.cms.tables.DjDeploymentStateHist;
import com.oneops.crawler.jooq.cms.tables.DjDeploymentStates;
import com.oneops.crawler.jooq.cms.tables.DjDpmtApprovals;
import com.oneops.crawler.jooq.cms.tables.DjNsOpt;
import com.oneops.crawler.jooq.cms.tables.DjReleaseRevLabel;
import com.oneops.crawler.jooq.cms.tables.DjReleaseStates;
import com.oneops.crawler.jooq.cms.tables.DjReleases;
import com.oneops.crawler.jooq.cms.tables.DjRfcCi;
import com.oneops.crawler.jooq.cms.tables.DjRfcCiActions;
import com.oneops.crawler.jooq.cms.tables.DjRfcCiAttributes;
import com.oneops.crawler.jooq.cms.tables.DjRfcRelation;
import com.oneops.crawler.jooq.cms.tables.DjRfcRelationAttributes;
import com.oneops.crawler.jooq.cms.tables.MdClassActions;
import com.oneops.crawler.jooq.cms.tables.MdClassAttributes;
import com.oneops.crawler.jooq.cms.tables.MdClassRelations;
import com.oneops.crawler.jooq.cms.tables.MdClasses;
import com.oneops.crawler.jooq.cms.tables.MdRelationAttributes;
import com.oneops.crawler.jooq.cms.tables.MdRelations;
import com.oneops.crawler.jooq.cms.tables.NsNamespaces;
import com.oneops.crawler.jooq.cms.tables.NsOpt;
import com.oneops.crawler.jooq.cms.tables.NsOptTag;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javax.annotation.Generated;
import org.jooq.Catalog;
import org.jooq.Sequence;
import org.jooq.Table;
import org.jooq.impl.SchemaImpl;
/**
* This class is generated by jOOQ.
*/
@Generated(
value = {
"http://www.jooq.org",
"jOOQ version:3.10.0"
},
comments = "This class is generated by jOOQ"
)
@SuppressWarnings({ "all", "unchecked", "rawtypes" })
public class Kloopzcm extends SchemaImpl {
private static final long serialVersionUID = 960604328;
/**
* The reference instance of <code>kloopzcm</code>
*/
public static final Kloopzcm KLOOPZCM = new Kloopzcm();
/**
* The table <code>kloopzcm.cm_ci</code>.
*/
public final CmCi CM_CI = com.oneops.crawler.jooq.cms.tables.CmCi.CM_CI;
/**
* The table <code>kloopzcm.cm_ci_attributes</code>.
*/
public final CmCiAttributes CM_CI_ATTRIBUTES = com.oneops.crawler.jooq.cms.tables.CmCiAttributes.CM_CI_ATTRIBUTES;
/**
* The table <code>kloopzcm.cm_ci_relation_attributes</code>.
*/
public final CmCiRelationAttributes CM_CI_RELATION_ATTRIBUTES = com.oneops.crawler.jooq.cms.tables.CmCiRelationAttributes.CM_CI_RELATION_ATTRIBUTES;
/**
* The table <code>kloopzcm.cm_ci_relations</code>.
*/
public final CmCiRelations CM_CI_RELATIONS = com.oneops.crawler.jooq.cms.tables.CmCiRelations.CM_CI_RELATIONS;
/**
* The table <code>kloopzcm.cm_ci_state</code>.
*/
public final CmCiState CM_CI_STATE = com.oneops.crawler.jooq.cms.tables.CmCiState.CM_CI_STATE;
/**
* The table <code>kloopzcm.cm_ns_opt</code>.
*/
public final CmNsOpt CM_NS_OPT = com.oneops.crawler.jooq.cms.tables.CmNsOpt.CM_NS_OPT;
/**
* The table <code>kloopzcm.cm_ops_action_state</code>.
*/
public final CmOpsActionState CM_OPS_ACTION_STATE = com.oneops.crawler.jooq.cms.tables.CmOpsActionState.CM_OPS_ACTION_STATE;
/**
* The table <code>kloopzcm.cm_ops_actions</code>.
*/
public final CmOpsActions CM_OPS_ACTIONS = com.oneops.crawler.jooq.cms.tables.CmOpsActions.CM_OPS_ACTIONS;
/**
* The table <code>kloopzcm.cm_ops_proc_state</code>.
*/
public final CmOpsProcState CM_OPS_PROC_STATE = com.oneops.crawler.jooq.cms.tables.CmOpsProcState.CM_OPS_PROC_STATE;
/**
* The table <code>kloopzcm.cm_ops_procedures</code>.
*/
public final CmOpsProcedures CM_OPS_PROCEDURES = com.oneops.crawler.jooq.cms.tables.CmOpsProcedures.CM_OPS_PROCEDURES;
/**
* The table <code>kloopzcm.cms_ci_event_queue</code>.
*/
public final CmsCiEventQueue CMS_CI_EVENT_QUEUE = com.oneops.crawler.jooq.cms.tables.CmsCiEventQueue.CMS_CI_EVENT_QUEUE;
/**
* The table <code>kloopzcm.cms_event_queue</code>.
*/
public final CmsEventQueue CMS_EVENT_QUEUE = com.oneops.crawler.jooq.cms.tables.CmsEventQueue.CMS_EVENT_QUEUE;
/**
* The table <code>kloopzcm.cms_event_type</code>.
*/
public final CmsEventType CMS_EVENT_TYPE = com.oneops.crawler.jooq.cms.tables.CmsEventType.CMS_EVENT_TYPE;
/**
* The table <code>kloopzcm.cms_lock</code>.
*/
public final CmsLock CMS_LOCK = com.oneops.crawler.jooq.cms.tables.CmsLock.CMS_LOCK;
/**
* The table <code>kloopzcm.cms_vars</code>.
*/
public final CmsVars CMS_VARS = com.oneops.crawler.jooq.cms.tables.CmsVars.CMS_VARS;
/**
* The table <code>kloopzcm.dj_approval_states</code>.
*/
public final DjApprovalStates DJ_APPROVAL_STATES = com.oneops.crawler.jooq.cms.tables.DjApprovalStates.DJ_APPROVAL_STATES;
/**
* The table <code>kloopzcm.dj_deployment</code>.
*/
public final DjDeployment DJ_DEPLOYMENT = com.oneops.crawler.jooq.cms.tables.DjDeployment.DJ_DEPLOYMENT;
/**
* The table <code>kloopzcm.dj_deployment_rfc</code>.
*/
public final DjDeploymentRfc DJ_DEPLOYMENT_RFC = com.oneops.crawler.jooq.cms.tables.DjDeploymentRfc.DJ_DEPLOYMENT_RFC;
/**
* The table <code>kloopzcm.dj_deployment_rfc_states</code>.
*/
public final DjDeploymentRfcStates DJ_DEPLOYMENT_RFC_STATES = com.oneops.crawler.jooq.cms.tables.DjDeploymentRfcStates.DJ_DEPLOYMENT_RFC_STATES;
/**
* The table <code>kloopzcm.dj_deployment_state_hist</code>.
*/
public final DjDeploymentStateHist DJ_DEPLOYMENT_STATE_HIST = com.oneops.crawler.jooq.cms.tables.DjDeploymentStateHist.DJ_DEPLOYMENT_STATE_HIST;
/**
* The table <code>kloopzcm.dj_deployment_states</code>.
*/
public final DjDeploymentStates DJ_DEPLOYMENT_STATES = com.oneops.crawler.jooq.cms.tables.DjDeploymentStates.DJ_DEPLOYMENT_STATES;
/**
* The table <code>kloopzcm.dj_dpmt_approvals</code>.
*/
public final DjDpmtApprovals DJ_DPMT_APPROVALS = com.oneops.crawler.jooq.cms.tables.DjDpmtApprovals.DJ_DPMT_APPROVALS;
/**
* The table <code>kloopzcm.dj_ns_opt</code>.
*/
public final DjNsOpt DJ_NS_OPT = com.oneops.crawler.jooq.cms.tables.DjNsOpt.DJ_NS_OPT;
/**
* The table <code>kloopzcm.dj_release_rev_label</code>.
*/
public final DjReleaseRevLabel DJ_RELEASE_REV_LABEL = com.oneops.crawler.jooq.cms.tables.DjReleaseRevLabel.DJ_RELEASE_REV_LABEL;
/**
* The table <code>kloopzcm.dj_release_states</code>.
*/
public final DjReleaseStates DJ_RELEASE_STATES = com.oneops.crawler.jooq.cms.tables.DjReleaseStates.DJ_RELEASE_STATES;
/**
* The table <code>kloopzcm.dj_releases</code>.
*/
public final DjReleases DJ_RELEASES = com.oneops.crawler.jooq.cms.tables.DjReleases.DJ_RELEASES;
/**
* The table <code>kloopzcm.dj_rfc_ci</code>.
*/
public final DjRfcCi DJ_RFC_CI = com.oneops.crawler.jooq.cms.tables.DjRfcCi.DJ_RFC_CI;
/**
* The table <code>kloopzcm.dj_rfc_ci_actions</code>.
*/
public final DjRfcCiActions DJ_RFC_CI_ACTIONS = com.oneops.crawler.jooq.cms.tables.DjRfcCiActions.DJ_RFC_CI_ACTIONS;
/**
* The table <code>kloopzcm.dj_rfc_ci_attributes</code>.
*/
public final DjRfcCiAttributes DJ_RFC_CI_ATTRIBUTES = com.oneops.crawler.jooq.cms.tables.DjRfcCiAttributes.DJ_RFC_CI_ATTRIBUTES;
/**
* The table <code>kloopzcm.dj_rfc_relation</code>.
*/
public final DjRfcRelation DJ_RFC_RELATION = com.oneops.crawler.jooq.cms.tables.DjRfcRelation.DJ_RFC_RELATION;
/**
* The table <code>kloopzcm.dj_rfc_relation_attributes</code>.
*/
public final DjRfcRelationAttributes DJ_RFC_RELATION_ATTRIBUTES = com.oneops.crawler.jooq.cms.tables.DjRfcRelationAttributes.DJ_RFC_RELATION_ATTRIBUTES;
/**
* The table <code>kloopzcm.md_class_actions</code>.
*/
public final MdClassActions MD_CLASS_ACTIONS = com.oneops.crawler.jooq.cms.tables.MdClassActions.MD_CLASS_ACTIONS;
/**
* The table <code>kloopzcm.md_class_attributes</code>.
*/
public final MdClassAttributes MD_CLASS_ATTRIBUTES = com.oneops.crawler.jooq.cms.tables.MdClassAttributes.MD_CLASS_ATTRIBUTES;
/**
* The table <code>kloopzcm.md_class_relations</code>.
*/
public final MdClassRelations MD_CLASS_RELATIONS = com.oneops.crawler.jooq.cms.tables.MdClassRelations.MD_CLASS_RELATIONS;
/**
* The table <code>kloopzcm.md_classes</code>.
*/
public final MdClasses MD_CLASSES = com.oneops.crawler.jooq.cms.tables.MdClasses.MD_CLASSES;
/**
* The table <code>kloopzcm.md_relation_attributes</code>.
*/
public final MdRelationAttributes MD_RELATION_ATTRIBUTES = com.oneops.crawler.jooq.cms.tables.MdRelationAttributes.MD_RELATION_ATTRIBUTES;
/**
* The table <code>kloopzcm.md_relations</code>.
*/
public final MdRelations MD_RELATIONS = com.oneops.crawler.jooq.cms.tables.MdRelations.MD_RELATIONS;
/**
* The table <code>kloopzcm.ns_namespaces</code>.
*/
public final NsNamespaces NS_NAMESPACES = com.oneops.crawler.jooq.cms.tables.NsNamespaces.NS_NAMESPACES;
/**
* The table <code>kloopzcm.ns_opt</code>.
*/
public final NsOpt NS_OPT = com.oneops.crawler.jooq.cms.tables.NsOpt.NS_OPT;
/**
* The table <code>kloopzcm.ns_opt_tag</code>.
*/
public final NsOptTag NS_OPT_TAG = com.oneops.crawler.jooq.cms.tables.NsOptTag.NS_OPT_TAG;
/**
* No further instances allowed
*/
private Kloopzcm() {
super("kloopzcm", null);
}
/**
* {@inheritDoc}
*/
@Override
public Catalog getCatalog() {
return DefaultCatalog.DEFAULT_CATALOG;
}
@Override
public final List<Sequence<?>> getSequences() {
List result = new ArrayList();
result.addAll(getSequences0());
return result;
}
private final List<Sequence<?>> getSequences0() {
return Arrays.<Sequence<?>>asList(
Sequences.CM_PK_SEQ,
Sequences.DJ_PK_SEQ,
Sequences.EVENT_PK_SEQ,
Sequences.LOG_PK_SEQ,
Sequences.MD_PK_SEQ,
Sequences.NS_PK_SEQ);
}
@Override
public final List<Table<?>> getTables() {
List result = new ArrayList();
result.addAll(getTables0());
return result;
}
private final List<Table<?>> getTables0() {
return Arrays.<Table<?>>asList(
CmCi.CM_CI,
CmCiAttributes.CM_CI_ATTRIBUTES,
CmCiRelationAttributes.CM_CI_RELATION_ATTRIBUTES,
CmCiRelations.CM_CI_RELATIONS,
CmCiState.CM_CI_STATE,
CmNsOpt.CM_NS_OPT,
CmOpsActionState.CM_OPS_ACTION_STATE,
CmOpsActions.CM_OPS_ACTIONS,
CmOpsProcState.CM_OPS_PROC_STATE,
CmOpsProcedures.CM_OPS_PROCEDURES,
CmsCiEventQueue.CMS_CI_EVENT_QUEUE,
CmsEventQueue.CMS_EVENT_QUEUE,
CmsEventType.CMS_EVENT_TYPE,
CmsLock.CMS_LOCK,
CmsVars.CMS_VARS,
DjApprovalStates.DJ_APPROVAL_STATES,
DjDeployment.DJ_DEPLOYMENT,
DjDeploymentRfc.DJ_DEPLOYMENT_RFC,
DjDeploymentRfcStates.DJ_DEPLOYMENT_RFC_STATES,
DjDeploymentStateHist.DJ_DEPLOYMENT_STATE_HIST,
DjDeploymentStates.DJ_DEPLOYMENT_STATES,
DjDpmtApprovals.DJ_DPMT_APPROVALS,
DjNsOpt.DJ_NS_OPT,
DjReleaseRevLabel.DJ_RELEASE_REV_LABEL,
DjReleaseStates.DJ_RELEASE_STATES,
DjReleases.DJ_RELEASES,
DjRfcCi.DJ_RFC_CI,
DjRfcCiActions.DJ_RFC_CI_ACTIONS,
DjRfcCiAttributes.DJ_RFC_CI_ATTRIBUTES,
DjRfcRelation.DJ_RFC_RELATION,
DjRfcRelationAttributes.DJ_RFC_RELATION_ATTRIBUTES,
MdClassActions.MD_CLASS_ACTIONS,
MdClassAttributes.MD_CLASS_ATTRIBUTES,
MdClassRelations.MD_CLASS_RELATIONS,
MdClasses.MD_CLASSES,
MdRelationAttributes.MD_RELATION_ATTRIBUTES,
MdRelations.MD_RELATIONS,
NsNamespaces.NS_NAMESPACES,
NsOpt.NS_OPT,
NsOptTag.NS_OPT_TAG);
}
}
| 36.848901 | 156 | 0.71878 |
7153f60876c765c8ba36df82f0526e2b6300db11 | 8,037 | package org.oskari.map.userlayer.service;
import fi.nls.oskari.domain.map.OskariLayer;
import fi.nls.oskari.domain.map.userlayer.UserLayer;
import fi.nls.oskari.domain.map.userlayer.UserLayerData;
import fi.nls.oskari.domain.map.wfs.WFSLayerOptions;
import fi.nls.oskari.log.LogFactory;
import fi.nls.oskari.log.Logger;
import fi.nls.oskari.map.geometry.WKTHelper;
import fi.nls.oskari.map.layer.OskariLayerService;
import fi.nls.oskari.map.layer.OskariLayerServiceMybatisImpl;
import fi.nls.oskari.map.layer.formatters.LayerJSONFormatterUSERLAYER;
import fi.nls.oskari.service.ServiceException;
import fi.nls.oskari.service.ServiceRuntimeException;
import fi.nls.oskari.util.ConversionHelper;
import fi.nls.oskari.util.JSONHelper;
import fi.nls.oskari.util.PropertyUtil;
import org.geotools.data.simple.SimpleFeatureCollection;
import org.geotools.data.simple.SimpleFeatureIterator;
import org.geotools.geometry.jts.ReferencedEnvelope;
import org.geotools.referencing.CRS;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.opengis.feature.simple.SimpleFeature;
import org.opengis.feature.simple.SimpleFeatureType;
import org.opengis.feature.type.PropertyDescriptor;
import org.opengis.referencing.FactoryException;
import org.opengis.referencing.crs.CoordinateReferenceSystem;
import org.opengis.referencing.operation.TransformException;
import org.oskari.geojson.GeoJSON;
import org.oskari.geojson.GeoJSONWriter;
import org.oskari.map.userlayer.input.KMLParser;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
public class UserLayerDataService {
private static final Logger log = LogFactory.getLogger(UserLayerDataService.class);
private static final OskariLayerService mapLayerService = new OskariLayerServiceMybatisImpl();
private static final LayerJSONFormatterUSERLAYER FORMATTER = new LayerJSONFormatterUSERLAYER();
private static final String USERLAYER_BASELAYER_ID = "userlayer.baselayer.id";
private static final String USERLAYER_MAXFEATURES_COUNT = "userlayer.maxfeatures.count";
private static final int USERLAYER_MAX_FEATURES_COUNT = PropertyUtil.getOptional(USERLAYER_MAXFEATURES_COUNT, -1);
private static final String DEFAULT_LOCALES_LANGUAGE = "en";
private static final int USERLAYER_BASE_LAYER_ID = PropertyUtil.getOptional(USERLAYER_BASELAYER_ID, -1);
public static UserLayer createUserLayer(SimpleFeatureCollection fc,
String uuid, String name, String desc, String source, String style) {
final SimpleFeatureType ft = fc.getSchema();
final UserLayer userLayer = new UserLayer();
userLayer.setUuid(uuid);
userLayer.setLayer_name(ConversionHelper.getString(name, ft.getTypeName()));
userLayer.setLayer_desc(ConversionHelper.getString(desc, ""));
userLayer.setLayer_source(ConversionHelper.getString(source, ""));
WFSLayerOptions wfsOptions = userLayer.getWFSLayerOptions();
wfsOptions.setDefaultFeatureStyle(JSONHelper.createJSONObject(style));
userLayer.setFields(parseFields(ft));
userLayer.setWkt(getWGS84ExtentAsWKT(fc));
return userLayer;
}
private static String getWGS84ExtentAsWKT(SimpleFeatureCollection fc) {
try {
CoordinateReferenceSystem wgs84 = CRS.decode("EPSG:4326", true);
ReferencedEnvelope extentWGS84 = fc.getBounds().transform(wgs84, true);
return WKTHelper.getBBOX(extentWGS84.getMinX(),
extentWGS84.getMinY(),
extentWGS84.getMaxX(),
extentWGS84.getMaxY());
} catch (FactoryException | TransformException e) {
// This shouldn't really happen since EPSG:4326 shouldn't be problematic
// and transforming into it should always work. But if it does happen
// there's probably something wrong with the geometries of the features
throw new ServiceRuntimeException("Failed to transform bounding extent", e);
}
}
private static JSONArray parseFields(SimpleFeatureType schema) {
// parse FeatureType schema to JSONArray to keep same order in fields as in the imported file
JSONArray jsfields = new JSONArray();
try {
Collection<PropertyDescriptor> types = schema.getDescriptors();
for (PropertyDescriptor type : types) {
JSONObject obj = new JSONObject();
String name = type.getName().getLocalPart();
obj.put("name", name);
obj.put("type", type.getType().getBinding().getSimpleName());
// don't add locale for geometry
if (!KMLParser.KML_GEOM.equals(name)){
JSONObject locales = new JSONObject();
// use name as default localized value
String localizedName = name;
// KML handling
if (KMLParser.KML_NAME.equals(name)){
localizedName = "Name";
} else if (KMLParser.KML_DESC.equals(name)){
localizedName = "Description";
}
locales.put(DEFAULT_LOCALES_LANGUAGE, localizedName);
obj.put("locales", locales);
}
jsfields.put(obj);
}
} catch (Exception ex) {
log.error(ex, "Couldn't parse field schema");
}
return jsfields;
}
public static List<UserLayerData> createUserLayerData(SimpleFeatureCollection fc, String uuid)
throws UserLayerException {
List<UserLayerData> userLayerDataList = new ArrayList<>();
try (SimpleFeatureIterator it = fc.features()) {
while (it.hasNext()) {
SimpleFeature f = it.next();
if (f.getDefaultGeometry() == null) {
continue;
}
userLayerDataList.add(toUserLayerData(f, uuid));
if (USERLAYER_MAX_FEATURES_COUNT != -1 && userLayerDataList.size() == USERLAYER_MAX_FEATURES_COUNT) {
break;
}
}
}
return userLayerDataList;
}
private static UserLayerData toUserLayerData(SimpleFeature f, String uuid) throws UserLayerException {
try {
JSONObject geoJSON = new GeoJSONWriter().writeFeature(f);
String id = geoJSON.optString(GeoJSON.ID);
JSONObject geometry = geoJSON.getJSONObject(GeoJSON.GEOMETRY);
String geometryJson = geometry.toString();
JSONObject properties = geoJSON.optJSONObject(GeoJSON.PROPERTIES);
UserLayerData userLayerData = new UserLayerData();
userLayerData.setUuid(uuid);
userLayerData.setFeature_id(id);
userLayerData.setGeometry(geometryJson);
userLayerData.setProperty_json(properties);
return userLayerData;
} catch (JSONException e) {
throw new UserLayerException("Failed to encode feature as GeoJSON", UserLayerException.ErrorType.INVALID_FEATURE); //no geometry
}
}
/**
* Returns the base WFS-layer for userlayers
*/
public static OskariLayer getBaseLayer() {
if (USERLAYER_BASE_LAYER_ID == -1) {
log.error("Userlayer baseId not defined. Please define", USERLAYER_BASELAYER_ID,
"property with value pointing to the baselayer in database.");
return null;
}
return mapLayerService.find(USERLAYER_BASE_LAYER_ID);
}
public static JSONObject parseUserLayer2JSON(UserLayer ulayer, String srs) {
return parseUserLayer2JSON(ulayer, srs, PropertyUtil.getDefaultLanguage());
}
public static JSONObject parseUserLayer2JSON(final UserLayer layer, final String srs, final String lang) {
OskariLayer baseLayer = getBaseLayer();
return FORMATTER.getJSON(baseLayer,layer, srs, lang);
}
}
| 46.189655 | 140 | 0.680229 |
8889076e753682941117b8a63b9843a0e9a28a0d | 3,585 | /* Copyright (C) 2012 Tim Boudreau
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.netbeans.modules.nodejs.json;
import java.io.IOException;
import java.util.Map;
import java.io.InputStream;
import java.util.List;
import org.junit.Test;
import static org.junit.Assert.*;
import org.netbeans.modules.nodejs.json.SimpleJSONParser.JsonException;
/**
*
* @author Tim Boudreau
*/
public class SimpleJSONParserTest {
@Test
public void testParse () throws IOException, JsonException {
for (int i = 0; i < 11; i++) {
parseJSON( "package_" + i + ".json" );
}
for (int i = 0; i < 4; i++) {
try {
parseJSON( "bad_" + (i + 1) + ".json" );
fail( "bad_" + i + " should not have been parsed" );
} catch ( JsonException e ) {
System.out.println( e.getMessage() );
}
}
}
@Test
public void testIntAndBool () throws Exception {
String t = "{ \"foo\": 23, \"bar\": true, \"baz\" : [5,10,15,20], \"quux\": [true,false,false,true] }";
Map<String, Object> m = new SimpleJSONParser().parse( t );
assertNotNull( m.get( "foo" ) );
assertNotNull( m.get( "bar" ) );
assertNotNull( m.get( "baz" ) );
assertNotNull( m.get( "quux" ) );
assertTrue( m.get( "foo" ) instanceof Integer );
assertTrue( m.get( "bar" ) instanceof Boolean );
assertTrue( m.get( "baz" ) instanceof List );
assertTrue( m.get( "baz" ) instanceof List );
CharSequence nue = new SimpleJSONParser().toJSON( m );
Map<String, Object> m1 = new SimpleJSONParser().parse( nue );
assertEquals( m, m1 );
}
private void parseJSON ( String what ) throws IOException, JsonException {
System.out.println( "-------------------------------" );
InputStream in = SimpleJSONParserTest.class.getResourceAsStream( what );
assertNotNull( "Test data missing: " + what, in );
Map<String, Object> m = new SimpleJSONParser().parse( in, "UTF-8" );
CharSequence seq = SimpleJSONParser.out( m );
System.out.println( seq );
System.out.println( "-------------------------------" );
Map<String, Object> reconstituted = new SimpleJSONParser().parse( seq );
assertMapsEqual( m, reconstituted );
}
private static void assertMapsEqual ( Map<String, Object> a, Map<String, Object> b ) {
boolean match = a.equals( b );
if (!match) {
fail( "No match:\n" + a + "\n" + b );
}
}
}
| 41.686047 | 112 | 0.625662 |
08915d4ff5c1113b9373e35c3444a034097c5cb6 | 4,017 | package uk.bl.monitrix.model;
import java.util.List;
/**
* The known host list interface. Provides read/query access to the list of
* crawled hosts.
* @author Rainer Simon <[email protected]>
*/
public interface KnownHostList {
/**
* Returns the total number of known hosts.
* @return the number of hosts
*/
public long count();
/**
* Returns the number of host that had at least one URL successfully resolved.
* @return the number of successfully crawled hosts.
*/
public long countSuccessful();
/**
* Returns the maximum average delay that was encountered over all hosts.
* @return the maximum average delay
*/
public long getMaxFetchDuration();
/**
* Checks if the specified hostname is already in the known hosts list.
* @param hostname the hostname
* @return <code>true</code> if the host is already in the list
*/
public boolean isKnown(String hostname);
/**
* Retrieves the host information for a specific host from the list.
* @param hostname the hostname
* @return the known host record
*/
public KnownHost getKnownHost(String hostname);
/**
* Searches the host list with the specified (e.g. keyword) query.
* Refer to documentation of specific implementations for the types of
* queries supported!
* @param query the search query
* @param limit the max number of results to return
* @param offset the result page offset
* @return the search result
*/
public SearchResult searchHosts(String query, int limit, int offset);
/**
* Returns the hosts registered under a specific top-level domain, with pagination.
* @param tld the top-level domain
* @param limit the pagination limit
* @param offset the pagination offset
* @return the search result
*/
public SearchResult searchByTopLevelDomain(String tld, int limit, int offset);
/**
* Returns the hosts within a specific average delay bracket.
* @param min the minimum average delay
* @param max the maximum average delay
* @param limit the pagination limit
* @param offset the pagination offset
* @return the search result
*/
public SearchResult searchByAverageFetchDuration(long min, long max, int limit, int offset);
/**
* Returns the hosts within a specified average retry rate bracket.
* @param min the minimum number of retries
* @param max the maximum number of retries
* @param limit the pagination limit
* @param offset the pagination offset
* @return the search result
*/
public SearchResult searchByAverageRetries(int min, int max, int limit, int offset);
/**
* Returns the hosts where the percentage of robots.txt-precluded fetch attempt lies within
* a specified range.
* @param min the minimum robots.txt-block percentage
* @param max the maximum robots.txt-block percentage
* @param limit the pagination limit
* @param offset the pagination offset
* @return the search result
*/
public SearchResult searchByRobotsBlockPercentage(double min, double max, int limit, int offset);
/**
* Returns the hosts where the percentage of redirects (HTTP 3xx) lies within
* a specified range.
* @param min the minimum redirect percentage
* @param max the maximum redirect percentage
* @param limit the pagination limit
* @param offset the pagination offset
* @return the search result
*/
public SearchResult searchByRedirectPercentage(double min, double max, int limit, int offset);
/**
* Retruns the names of the hosts which have been crawled since the
* specified timestamp.
* @param since the timestamp
* @return the list of hosts visited since the timestamp
*/
public List<KnownHost> getCrawledHosts(long since);
/**
* Returns the top-level domains encountered during the crawl.
* @return the list of top-level domains
*/
public List<String> getTopLevelDomains();
/**
* Counts the number of hosts registered under a specific top-level domain.
* @param tld the top level domain
* @return
*/
public long countForTopLevelDomain(String tld);
}
| 31.382813 | 98 | 0.727657 |
8bcda7e650305fead7c5cd846b6ed4a385bc4c50 | 15,360 | package com.refinedmods.refinedpipes.setup;
import com.refinedmods.refinedpipes.RefinedPipes;
import com.refinedmods.refinedpipes.RefinedPipesBlockEntities;
import com.refinedmods.refinedpipes.RefinedPipesBlocks;
import com.refinedmods.refinedpipes.RefinedPipesContainerMenus;
import com.refinedmods.refinedpipes.network.pipe.attachment.AttachmentFactory;
import com.refinedmods.refinedpipes.network.pipe.attachment.AttachmentRegistry;
import com.refinedmods.refinedpipes.network.pipe.energy.EnergyPipeType;
import com.refinedmods.refinedpipes.network.pipe.fluid.FluidPipeType;
import com.refinedmods.refinedpipes.network.pipe.item.ItemPipeType;
import com.refinedmods.refinedpipes.render.FluidPipeBlockEntityRenderer;
import com.refinedmods.refinedpipes.render.ItemPipeBlockEntityRenderer;
import com.refinedmods.refinedpipes.render.PipeBakedModel;
import com.refinedmods.refinedpipes.screen.ExtractorAttachmentScreen;
import net.minecraft.client.gui.screens.MenuScreens;
import net.minecraft.client.renderer.ItemBlockRenderTypes;
import net.minecraft.client.renderer.RenderType;
import net.minecraft.client.renderer.blockentity.BlockEntityRenderers;
import net.minecraft.client.resources.model.BakedModel;
import net.minecraft.client.resources.model.ModelResourceLocation;
import net.minecraft.resources.ResourceLocation;
import net.minecraftforge.client.event.ModelBakeEvent;
import net.minecraftforge.client.event.ModelRegistryEvent;
import net.minecraftforge.client.model.ForgeModelBakery;
import net.minecraftforge.eventbus.api.SubscribeEvent;
import net.minecraftforge.fml.event.lifecycle.FMLClientSetupEvent;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
public final class ClientSetup {
private static final Logger LOGGER = LogManager.getLogger(ClientSetup.class);
private ClientSetup() {
}
@SubscribeEvent
public static void registerSpecialModels(ModelRegistryEvent ev) {
for (AttachmentFactory factory : AttachmentRegistry.INSTANCE.all()) {
LOGGER.debug("Registering attachment model {}", factory.getModelLocation());
ForgeModelBakery.addSpecialModel(factory.getModelLocation());
}
for (String type : new String[]{"item", "fluid", "energy"}) {
ForgeModelBakery.addSpecialModel(new ResourceLocation(RefinedPipes.ID + ":block/pipe/" + type + "/basic/core"));
ForgeModelBakery.addSpecialModel(new ResourceLocation(RefinedPipes.ID + ":block/pipe/" + type + "/basic/extension"));
ForgeModelBakery.addSpecialModel(new ResourceLocation(RefinedPipes.ID + ":block/pipe/" + type + "/basic/straight"));
ForgeModelBakery.addSpecialModel(new ResourceLocation(RefinedPipes.ID + ":block/pipe/" + type + "/improved/core"));
ForgeModelBakery.addSpecialModel(new ResourceLocation(RefinedPipes.ID + ":block/pipe/" + type + "/improved/extension"));
ForgeModelBakery.addSpecialModel(new ResourceLocation(RefinedPipes.ID + ":block/pipe/" + type + "/improved/straight"));
ForgeModelBakery.addSpecialModel(new ResourceLocation(RefinedPipes.ID + ":block/pipe/" + type + "/advanced/core"));
ForgeModelBakery.addSpecialModel(new ResourceLocation(RefinedPipes.ID + ":block/pipe/" + type + "/advanced/extension"));
ForgeModelBakery.addSpecialModel(new ResourceLocation(RefinedPipes.ID + ":block/pipe/" + type + "/advanced/straight"));
if (type.equals("fluid") || type.equals("energy")) {
ForgeModelBakery.addSpecialModel(new ResourceLocation(RefinedPipes.ID + ":block/pipe/" + type + "/elite/core"));
ForgeModelBakery.addSpecialModel(new ResourceLocation(RefinedPipes.ID + ":block/pipe/" + type + "/elite/extension"));
ForgeModelBakery.addSpecialModel(new ResourceLocation(RefinedPipes.ID + ":block/pipe/" + type + "/elite/straight"));
ForgeModelBakery.addSpecialModel(new ResourceLocation(RefinedPipes.ID + ":block/pipe/" + type + "/ultimate/core"));
ForgeModelBakery.addSpecialModel(new ResourceLocation(RefinedPipes.ID + ":block/pipe/" + type + "/ultimate/extension"));
ForgeModelBakery.addSpecialModel(new ResourceLocation(RefinedPipes.ID + ":block/pipe/" + type + "/ultimate/straight"));
}
}
ForgeModelBakery.addSpecialModel(new ResourceLocation(RefinedPipes.ID + ":block/pipe/attachment/inventory_attachment"));
}
@SubscribeEvent
public static void onClientSetup(FMLClientSetupEvent e) {
MenuScreens.register(RefinedPipesContainerMenus.EXTRACTOR_ATTACHMENT, ExtractorAttachmentScreen::new);
ItemBlockRenderTypes.setRenderLayer(RefinedPipesBlocks.BASIC_ITEM_PIPE, RenderType.cutout());
ItemBlockRenderTypes.setRenderLayer(RefinedPipesBlocks.IMPROVED_ITEM_PIPE, RenderType.cutout());
ItemBlockRenderTypes.setRenderLayer(RefinedPipesBlocks.ADVANCED_ITEM_PIPE, RenderType.cutout());
ItemBlockRenderTypes.setRenderLayer(RefinedPipesBlocks.BASIC_FLUID_PIPE, RenderType.cutout());
ItemBlockRenderTypes.setRenderLayer(RefinedPipesBlocks.IMPROVED_FLUID_PIPE, RenderType.cutout());
ItemBlockRenderTypes.setRenderLayer(RefinedPipesBlocks.ADVANCED_FLUID_PIPE, RenderType.cutout());
ItemBlockRenderTypes.setRenderLayer(RefinedPipesBlocks.ELITE_FLUID_PIPE, RenderType.cutout());
ItemBlockRenderTypes.setRenderLayer(RefinedPipesBlocks.ULTIMATE_FLUID_PIPE, RenderType.cutout());
BlockEntityRenderers.register(RefinedPipesBlockEntities.BASIC_ITEM_PIPE, ctx -> new ItemPipeBlockEntityRenderer());
BlockEntityRenderers.register(RefinedPipesBlockEntities.IMPROVED_ITEM_PIPE, ctx -> new ItemPipeBlockEntityRenderer());
BlockEntityRenderers.register(RefinedPipesBlockEntities.ADVANCED_ITEM_PIPE, ctx -> new ItemPipeBlockEntityRenderer());
BlockEntityRenderers.register(RefinedPipesBlockEntities.BASIC_FLUID_PIPE, ctx -> new FluidPipeBlockEntityRenderer());
BlockEntityRenderers.register(RefinedPipesBlockEntities.IMPROVED_FLUID_PIPE, ctx -> new FluidPipeBlockEntityRenderer());
BlockEntityRenderers.register(RefinedPipesBlockEntities.ADVANCED_FLUID_PIPE, ctx -> new FluidPipeBlockEntityRenderer());
BlockEntityRenderers.register(RefinedPipesBlockEntities.ELITE_FLUID_PIPE, ctx -> new FluidPipeBlockEntityRenderer());
BlockEntityRenderers.register(RefinedPipesBlockEntities.ULTIMATE_FLUID_PIPE, ctx -> new FluidPipeBlockEntityRenderer());
}
@SubscribeEvent
public static void onModelBake(ModelBakeEvent e) {
Map<ResourceLocation, BakedModel> attachmentModels = new HashMap<>();
for (AttachmentFactory factory : AttachmentRegistry.INSTANCE.all()) {
attachmentModels.put(factory.getId(), e.getModelRegistry().get(factory.getModelLocation()));
}
Map<ResourceLocation, PipeBakedModel> pipeModels = new HashMap<>();
pipeModels.put(ItemPipeType.BASIC.getId(), new PipeBakedModel(
e.getModelRegistry().get(new ResourceLocation(RefinedPipes.ID + ":block/pipe/item/basic/core")),
e.getModelRegistry().get(new ResourceLocation(RefinedPipes.ID + ":block/pipe/item/basic/extension")),
e.getModelRegistry().get(new ResourceLocation(RefinedPipes.ID + ":block/pipe/item/basic/straight")),
e.getModelRegistry().get(new ResourceLocation(RefinedPipes.ID + ":block/pipe/attachment/inventory_attachment")),
attachmentModels
));
pipeModels.put(ItemPipeType.IMPROVED.getId(), new PipeBakedModel(
e.getModelRegistry().get(new ResourceLocation(RefinedPipes.ID + ":block/pipe/item/improved/core")),
e.getModelRegistry().get(new ResourceLocation(RefinedPipes.ID + ":block/pipe/item/improved/extension")),
e.getModelRegistry().get(new ResourceLocation(RefinedPipes.ID + ":block/pipe/item/improved/straight")),
e.getModelRegistry().get(new ResourceLocation(RefinedPipes.ID + ":block/pipe/attachment/inventory_attachment")),
attachmentModels
));
pipeModels.put(ItemPipeType.ADVANCED.getId(), new PipeBakedModel(
e.getModelRegistry().get(new ResourceLocation(RefinedPipes.ID + ":block/pipe/item/advanced/core")),
e.getModelRegistry().get(new ResourceLocation(RefinedPipes.ID + ":block/pipe/item/advanced/extension")),
e.getModelRegistry().get(new ResourceLocation(RefinedPipes.ID + ":block/pipe/item/advanced/straight")),
e.getModelRegistry().get(new ResourceLocation(RefinedPipes.ID + ":block/pipe/attachment/inventory_attachment")),
attachmentModels
));
pipeModels.put(FluidPipeType.BASIC.getId(), new PipeBakedModel(
e.getModelRegistry().get(new ResourceLocation(RefinedPipes.ID + ":block/pipe/fluid/basic/core")),
e.getModelRegistry().get(new ResourceLocation(RefinedPipes.ID + ":block/pipe/fluid/basic/extension")),
e.getModelRegistry().get(new ResourceLocation(RefinedPipes.ID + ":block/pipe/fluid/basic/straight")),
e.getModelRegistry().get(new ResourceLocation(RefinedPipes.ID + ":block/pipe/attachment/inventory_attachment")),
attachmentModels
));
pipeModels.put(FluidPipeType.IMPROVED.getId(), new PipeBakedModel(
e.getModelRegistry().get(new ResourceLocation(RefinedPipes.ID + ":block/pipe/fluid/improved/core")),
e.getModelRegistry().get(new ResourceLocation(RefinedPipes.ID + ":block/pipe/fluid/improved/extension")),
e.getModelRegistry().get(new ResourceLocation(RefinedPipes.ID + ":block/pipe/fluid/improved/straight")),
e.getModelRegistry().get(new ResourceLocation(RefinedPipes.ID + ":block/pipe/attachment/inventory_attachment")),
attachmentModels
));
pipeModels.put(FluidPipeType.ADVANCED.getId(), new PipeBakedModel(
e.getModelRegistry().get(new ResourceLocation(RefinedPipes.ID + ":block/pipe/fluid/advanced/core")),
e.getModelRegistry().get(new ResourceLocation(RefinedPipes.ID + ":block/pipe/fluid/advanced/extension")),
e.getModelRegistry().get(new ResourceLocation(RefinedPipes.ID + ":block/pipe/fluid/advanced/straight")),
e.getModelRegistry().get(new ResourceLocation(RefinedPipes.ID + ":block/pipe/attachment/inventory_attachment")),
attachmentModels
));
pipeModels.put(FluidPipeType.ELITE.getId(), new PipeBakedModel(
e.getModelRegistry().get(new ResourceLocation(RefinedPipes.ID + ":block/pipe/fluid/elite/core")),
e.getModelRegistry().get(new ResourceLocation(RefinedPipes.ID + ":block/pipe/fluid/elite/extension")),
e.getModelRegistry().get(new ResourceLocation(RefinedPipes.ID + ":block/pipe/fluid/elite/straight")),
e.getModelRegistry().get(new ResourceLocation(RefinedPipes.ID + ":block/pipe/attachment/inventory_attachment")),
attachmentModels
));
pipeModels.put(FluidPipeType.ULTIMATE.getId(), new PipeBakedModel(
e.getModelRegistry().get(new ResourceLocation(RefinedPipes.ID + ":block/pipe/fluid/ultimate/core")),
e.getModelRegistry().get(new ResourceLocation(RefinedPipes.ID + ":block/pipe/fluid/ultimate/extension")),
e.getModelRegistry().get(new ResourceLocation(RefinedPipes.ID + ":block/pipe/fluid/ultimate/straight")),
e.getModelRegistry().get(new ResourceLocation(RefinedPipes.ID + ":block/pipe/attachment/inventory_attachment")),
attachmentModels
));
pipeModels.put(EnergyPipeType.BASIC.getId(), new PipeBakedModel(
e.getModelRegistry().get(new ResourceLocation(RefinedPipes.ID + ":block/pipe/energy/basic/core")),
e.getModelRegistry().get(new ResourceLocation(RefinedPipes.ID + ":block/pipe/energy/basic/extension")),
e.getModelRegistry().get(new ResourceLocation(RefinedPipes.ID + ":block/pipe/energy/basic/straight")),
e.getModelRegistry().get(new ResourceLocation(RefinedPipes.ID + ":block/pipe/attachment/inventory_attachment")),
attachmentModels
));
pipeModels.put(EnergyPipeType.IMPROVED.getId(), new PipeBakedModel(
e.getModelRegistry().get(new ResourceLocation(RefinedPipes.ID + ":block/pipe/energy/improved/core")),
e.getModelRegistry().get(new ResourceLocation(RefinedPipes.ID + ":block/pipe/energy/improved/extension")),
e.getModelRegistry().get(new ResourceLocation(RefinedPipes.ID + ":block/pipe/energy/improved/straight")),
e.getModelRegistry().get(new ResourceLocation(RefinedPipes.ID + ":block/pipe/attachment/inventory_attachment")),
attachmentModels
));
pipeModels.put(EnergyPipeType.ADVANCED.getId(), new PipeBakedModel(
e.getModelRegistry().get(new ResourceLocation(RefinedPipes.ID + ":block/pipe/energy/advanced/core")),
e.getModelRegistry().get(new ResourceLocation(RefinedPipes.ID + ":block/pipe/energy/advanced/extension")),
e.getModelRegistry().get(new ResourceLocation(RefinedPipes.ID + ":block/pipe/energy/advanced/straight")),
e.getModelRegistry().get(new ResourceLocation(RefinedPipes.ID + ":block/pipe/attachment/inventory_attachment")),
attachmentModels
));
pipeModels.put(EnergyPipeType.ELITE.getId(), new PipeBakedModel(
e.getModelRegistry().get(new ResourceLocation(RefinedPipes.ID + ":block/pipe/energy/elite/core")),
e.getModelRegistry().get(new ResourceLocation(RefinedPipes.ID + ":block/pipe/energy/elite/extension")),
e.getModelRegistry().get(new ResourceLocation(RefinedPipes.ID + ":block/pipe/energy/elite/straight")),
e.getModelRegistry().get(new ResourceLocation(RefinedPipes.ID + ":block/pipe/attachment/inventory_attachment")),
attachmentModels
));
pipeModels.put(EnergyPipeType.ULTIMATE.getId(), new PipeBakedModel(
e.getModelRegistry().get(new ResourceLocation(RefinedPipes.ID + ":block/pipe/energy/ultimate/core")),
e.getModelRegistry().get(new ResourceLocation(RefinedPipes.ID + ":block/pipe/energy/ultimate/extension")),
e.getModelRegistry().get(new ResourceLocation(RefinedPipes.ID + ":block/pipe/energy/ultimate/straight")),
e.getModelRegistry().get(new ResourceLocation(RefinedPipes.ID + ":block/pipe/attachment/inventory_attachment")),
attachmentModels
));
on: for (ResourceLocation id : e.getModelRegistry().keySet()) {
for (Entry<ResourceLocation, PipeBakedModel> entry : pipeModels.entrySet()) {
if (isPipeModel(id, entry.getKey())) {
e.getModelRegistry().put(id, entry.getValue());
continue on;
}
}
}
}
private static boolean isPipeModel(ResourceLocation modelId, ResourceLocation pipeId) {
return modelId instanceof ModelResourceLocation
&& modelId.getNamespace().equals(RefinedPipes.ID)
&& modelId.getPath().equals(pipeId.getPath())
&& !((ModelResourceLocation) modelId).getVariant().equals("inventory");
}
}
| 69.818182 | 136 | 0.723307 |
8121949712d0daf9b29b407c4eac8259dab8a3fb | 10,235 | package org.apereo.cas.services;
import org.apereo.cas.authentication.principal.Principal;
import org.apereo.cas.authentication.principal.Service;
import org.apereo.cas.util.CollectionUtils;
import org.apereo.cas.util.scripting.ExecutableCompiledGroovyScript;
import org.apereo.cas.util.scripting.ScriptingUtils;
import org.apereo.cas.util.spring.ApplicationContextProvider;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
/**
* Return a collection of allowed attributes for the principal, but additionally,
* offers the ability to rename attributes on a per-service level.
*
* @author Misagh Moayyed
* @since 4.1.0
*/
@Slf4j
@ToString(callSuper = true)
@Setter
@EqualsAndHashCode(callSuper = true)
@NoArgsConstructor
@JsonInclude(JsonInclude.Include.NON_DEFAULT)
public class ReturnMappedAttributeReleasePolicy extends AbstractRegisteredServiceAttributeReleasePolicy {
private static final long serialVersionUID = -6249488544306639050L;
private Map<String, Object> allowedAttributes = new TreeMap<>();
@JsonCreator
public ReturnMappedAttributeReleasePolicy(@JsonProperty("allowedAttributes") final Map<String, Object> attributes) {
this.allowedAttributes = attributes;
}
private static void mapSingleAttributeDefinition(final String attributeName,
final String mappedAttributeName,
final Object attributeValue,
final Map<String, List<Object>> resolvedAttributes,
final Map<String, List<Object>> attributesToRelease) {
val matcherInline = ScriptingUtils.getMatcherForInlineGroovyScript(mappedAttributeName);
val matcherFile = ScriptingUtils.getMatcherForExternalGroovyScript(mappedAttributeName);
if (matcherInline.find()) {
val inlineGroovy = matcherInline.group(1);
fetchAttributeValueAsInlineGroovyScript(attributeName, resolvedAttributes, attributesToRelease, inlineGroovy);
} else if (matcherFile.find()) {
val file = matcherFile.group();
fetchAttributeValueFromExternalGroovyScript(attributeName, resolvedAttributes, attributesToRelease, file);
} else {
mapSimpleSingleAttributeDefinition(attributeName, mappedAttributeName,
attributeValue, attributesToRelease, resolvedAttributes);
}
}
private static void fetchAttributeValueFromExternalGroovyScript(final String attributeName,
final Map<String, List<Object>> resolvedAttributes,
final Map<String, List<Object>> attributesToRelease,
final String file) {
ApplicationContextProvider.getScriptResourceCacheManager()
.ifPresentOrElse(cacheMgr -> {
val script = cacheMgr.resolveScriptableResource(file, attributeName, file);
if (script != null) {
fetchAttributeValueFromScript(script, attributeName, resolvedAttributes, attributesToRelease);
}
},
() -> {
throw new RuntimeException("No groovy script cache manager is available to execute attribute mappings");
});
}
private static void fetchAttributeValueAsInlineGroovyScript(final String attributeName,
final Map<String, List<Object>> resolvedAttributes,
final Map<String, List<Object>> attributesToRelease,
final String inlineGroovy) {
ApplicationContextProvider.getScriptResourceCacheManager()
.ifPresentOrElse(cacheMgr -> {
val script = cacheMgr.resolveScriptableResource(inlineGroovy, attributeName, inlineGroovy);
fetchAttributeValueFromScript(script, attributeName, resolvedAttributes, attributesToRelease);
},
() -> {
throw new RuntimeException("No groovy script cache manager is available to execute attribute mappings");
});
}
private static void mapSimpleSingleAttributeDefinition(final String attributeName,
final String mappedAttributeName,
final Object attributeValue,
final Map<String, List<Object>> attributesToRelease,
final Map<String, List<Object>> resolvedAttributes) {
if (attributeValue != null) {
LOGGER.debug("Found attribute [{}] in the list of allowed attributes, mapped to the name [{}]",
attributeName, mappedAttributeName);
val values = CollectionUtils.toCollection(attributeValue, ArrayList.class);
attributesToRelease.put(mappedAttributeName, values);
} else if (resolvedAttributes.containsKey(mappedAttributeName)) {
val mappedValue = resolvedAttributes.get(mappedAttributeName);
LOGGER.debug("Reusing existing already-remapped attribute [{}] with value [{}]", mappedAttributeName, mappedValue);
attributesToRelease.put(mappedAttributeName, mappedValue);
} else {
LOGGER.warn("Could not find value for mapped attribute [{}] that is based off of [{}] in the allowed attributes list. "
+ "Ensure the original attribute [{}] is retrieved and contains at least a single value. Attribute [{}] "
+ "will and can not be released without the presence of a value.", mappedAttributeName, attributeName,
attributeName, mappedAttributeName);
}
}
private static void fetchAttributeValueFromScript(final ExecutableCompiledGroovyScript script,
final String attributeName,
final Map<String, List<Object>> resolvedAttributes,
final Map<String, List<Object>> attributesToRelease) {
val args = CollectionUtils.wrap("attributes", resolvedAttributes, "logger", LOGGER);
script.setBinding(args);
val result = script.execute(args.values().toArray(), Object.class, false);
if (result != null) {
LOGGER.debug("Mapped attribute [{}] to [{}] from script", attributeName, result);
attributesToRelease.put(attributeName, CollectionUtils.wrapList(result));
} else {
LOGGER.warn("Groovy-scripted attribute returned no value for [{}]", attributeName);
}
}
/**
* Gets the allowed attributes.
*
* @return the allowed attributes
*/
public Map<String, Object> getAllowedAttributes() {
return new TreeMap<>(this.allowedAttributes);
}
@Override
public Map<String, List<Object>> getAttributesInternal(final Principal principal,
final Map<String, List<Object>> attrs,
final RegisteredService registeredService,
final Service selectedService) {
return authorizeReleaseOfAllowedAttributes(principal, attrs, registeredService, selectedService);
}
@Override
public List<String> determineRequestedAttributeDefinitions() {
return new ArrayList<>(getAllowedAttributes().keySet());
}
/**
* Authorize release of allowed attributes map.
* Map each entry in the allowed list into an array first
* by the original key, value and the original entry itself.
* Then process the array to populate the map for allowed attributes.
*
* @param principal the principal
* @param attrs the attributes
* @param registeredService the registered service
* @param selectedService the selected service
* @return the map
*/
protected Map<String, List<Object>> authorizeReleaseOfAllowedAttributes(final Principal principal,
final Map<String, List<Object>> attrs,
final RegisteredService registeredService,
final Service selectedService) {
val resolvedAttributes = new TreeMap<String, List<Object>>(String.CASE_INSENSITIVE_ORDER);
resolvedAttributes.putAll(attrs);
val attributesToRelease = new HashMap<String, List<Object>>();
getAllowedAttributes().forEach((attributeName, value) -> {
val mappedAttributes = CollectionUtils.wrap(value);
LOGGER.trace("Attempting to map allowed attribute name [{}]", attributeName);
val attributeValue = resolvedAttributes.get(attributeName);
mappedAttributes.forEach(mapped -> {
val mappedAttributeName = mapped.toString();
LOGGER.debug("Mapping attribute [{}] to [{}] with value [{}]",
attributeName, mappedAttributeName, attributeValue);
mapSingleAttributeDefinition(attributeName, mappedAttributeName,
attributeValue, resolvedAttributes, attributesToRelease);
});
});
return attributesToRelease;
}
}
| 52.757732 | 131 | 0.612408 |
84cf9172e9996cdd7c0ffebf0c09b068a8b89224 | 4,724 | package com.daxton.customdisplay.listener.mythicmobs;
import com.daxton.customdisplay.CustomDisplay;
import com.daxton.customdisplay.api.entity.Convert;
import com.daxton.customdisplay.api.player.PlayerTrigger;
import com.daxton.customdisplay.manager.MobManager;
import com.daxton.customdisplay.manager.PlaceholderManager;
import io.lumine.xikage.mythicmobs.api.bukkit.events.MythicMobDeathEvent;
import io.lumine.xikage.mythicmobs.api.bukkit.events.MythicMobLootDropEvent;
import io.lumine.xikage.mythicmobs.api.bukkit.events.MythicMobSpawnEvent;
import io.lumine.xikage.mythicmobs.mobs.ActiveMob;
import io.lumine.xikage.mythicmobs.spawning.random.RandomSpawner;
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
public class MythicMobSpawnListener implements Listener {
@EventHandler
public void onMythicMobSpawn(MythicMobSpawnEvent event){
try {
ActiveMob activeMob = event.getMob();
double mobLevel = event.getMobLevel();
//CustomDisplay.getCustomDisplay().getLogger().info("LEVLE:"+event.getMobLevel()+" : "+activeMob.getLevel());
if(activeMob != null){
String mobID = activeMob.getMobType();
String uuidString = activeMob.getUniqueId().toString();
//用UUID字串儲存MMID
MobManager.mythicMobs_mobID_Map.put(uuidString, mobID);
//用UUID字串儲存MM等級
MobManager.mythicMobs_Level_Map.put(uuidString, String.valueOf(mobLevel));
//用UUID字串儲存MMID
MobManager.mythicMobs_ActiveMob_Map.put(uuidString, activeMob);
}
}catch (NoSuchMethodError error){
//
}
}
@EventHandler
public void onMythicMobDeath(MythicMobDeathEvent event){
LivingEntity target = (LivingEntity) event.getEntity();
LivingEntity killer = event.getKiller();
Player player;
player = Convert.convertKillerPlayer(killer);
try {
if(player != null){
String mobID = event.getMob().getMobType();
String item = "Air";
if(event.getDrops().size() > 0){
item = "";
for(int i = 0;i < event.getDrops().size();i++){
if(i == 0){
if(!event.getDrops().get(i).getItemMeta().getDisplayName().isEmpty()){
item = event.getDrops().get(i).getItemMeta().getDisplayName();
}else {
item = event.getDrops().get(i).getI18NDisplayName();
}
}else {
if(!event.getDrops().get(i).getItemMeta().getDisplayName().isEmpty()){
item = item + "," + event.getDrops().get(i).getItemMeta().getDisplayName();
}else {
item = item + "," + event.getDrops().get(i).getI18NDisplayName();
}
}
}
}
String uuidString = player.getUniqueId().toString();
PlaceholderManager.getCd_Placeholder_Map().put(uuidString+"<cd_player_kill_mythic_mob_item>",item);
PlaceholderManager.getCd_Placeholder_Map().put(uuidString+"<cd_mythic_kill_mob_id>",mobID);
PlayerTrigger.onPlayer(player, target, "~onmmobdeath");
if(!(item.contains("Air"))){
PlayerTrigger.onPlayer(player, target, "~onmmobdropitem");
}
}
}catch (NoSuchMethodError error){
//
}
}
@EventHandler
public void onMythicMobLootDrop(MythicMobLootDropEvent event){
LivingEntity target = (LivingEntity) event.getEntity();
LivingEntity livingEntity = event.getKiller();
if(livingEntity instanceof Player){
Player player = (Player) livingEntity;
String uuidString = livingEntity.getUniqueId().toString();
PlaceholderManager.getCd_Placeholder_Map().put(uuidString+"<cd_player_kill_mythic_mob_exp>",String.valueOf(event.getExp()));
PlaceholderManager.getCd_Placeholder_Map().put(uuidString+"<cd_player_kill_mythic_mob_money>",String.valueOf(event.getMoney()));
if(event.getExp() != 0){
PlayerTrigger.onPlayer(player, target, "~onmmobdropexp");
}
if(event.getMoney() != 0){
PlayerTrigger.onPlayer(player, target, "~onmmobdropmoney");
}
}
}
}
| 38.096774 | 140 | 0.593353 |
dddc0c6d975338f647118c6438612cd38b4ed0ea | 389 | package xyz.tiancaikai.gulimall.product.dao;
import xyz.tiancaikai.gulimall.product.entity.AttrGroupEntity;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper;
/**
* 属性分组
*
* @author tiancaikai
* @email [email protected]
* @date 2020-09-09 09:39:19
*/
@Mapper
public interface AttrGroupDao extends BaseMapper<AttrGroupEntity> {
}
| 21.611111 | 67 | 0.773779 |
63dcabd37497202f86c9efeaa4f3933cc0f811a3 | 924 | package software.amazon.awssdk.eventstreamrpc;
import com.google.gson.Gson;
import software.amazon.awssdk.crt.eventstream.Header;
import java.nio.charset.StandardCharsets;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.function.Supplier;
public class GreengrassConnectMessageSupplier {
public static Supplier<CompletableFuture<MessageAmendInfo>> connectMessageSupplier(String authToken) {
return () -> {
final List<Header> headers = new LinkedList<>();
GreengrassEventStreamConnectMessage connectMessage = new GreengrassEventStreamConnectMessage();
connectMessage.setAuthToken(authToken);
String payload = new Gson().toJson(connectMessage);
return CompletableFuture.completedFuture(new MessageAmendInfo(headers, payload.getBytes(StandardCharsets.UTF_8)));
};
}
}
| 38.5 | 126 | 0.752165 |
80b8f93be3ff81cd9cbe9af6bf4644915fd7a91c | 7,617 | /**
* Copyright 2005-2014 The Kuali Foundation
*
* Licensed under the Educational Community 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.opensource.org/licenses/ecl2.php
*
* 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.kuali.rice.krad.datadictionary.validation.constraint;
import org.apache.commons.lang.StringUtils;
import org.kuali.rice.core.api.CoreConstants;
import org.kuali.rice.core.api.config.property.ConfigContext;
import org.kuali.rice.krad.datadictionary.parse.BeanTag;
import org.kuali.rice.krad.datadictionary.parse.BeanTagAttribute;
import org.kuali.rice.krad.datadictionary.parse.BeanTags;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
/**
* DatePatternConstraint constrains a field to only allow dates which are part of the formats
* defined in the system. Constraining a field all these formats is often not appropriate for
* fields, and you may want to constrain the input to a subset of the allowed formats in the system.
* This can be done by setting the allowed formats to this subset (see BasicDatePatternConstraint
* bean for example)
*
* @author Kuali Rice Team ([email protected])
*/
@BeanTags({@BeanTag(name = "datePatternConstraint-bean", parent = "DatePatternConstraint"),
@BeanTag(name = "basicDatePatternConstraint-bean", parent = "BasicDatePatternConstraint")})
public class DatePatternConstraint extends ValidDataPatternConstraint {
private List<String> allowedFormats;
/**
* Returns a regex representing all the allowed formats in the system. If allowedFormats is
* supplied, returns a regex representing only those formats.
*
* @see org.kuali.rice.krad.datadictionary.validation.constraint.ValidDataPatternConstraint#getRegexString()
*/
@Override
protected String getRegexString() {
List<String> dateFormatParams = parseConfigValues(ConfigContext.getCurrentContextConfig().getProperty(
CoreConstants.STRING_TO_DATE_FORMATS));
if (allowedFormats != null && !allowedFormats.isEmpty()) {
if (dateFormatParams.containsAll(allowedFormats)) {
dateFormatParams = allowedFormats;
} else {
//throw new Exception("Some of these formats do not exist in configured allowed date formats: " + allowedFormats.toString());
}
}
if (dateFormatParams.isEmpty()) {
//exception
}
String regex = "";
int i = 0;
for (String format : dateFormatParams) {
if (i == 0) {
regex = "(^" + convertDateFormatToRegex(format.trim()) + "$)";
} else {
regex = regex + "|(^" + convertDateFormatToRegex(format.trim()) + "$)";
}
i++;
}
return regex;
}
/**
* Converts a date format supplied to the appropriate date format regex equivalent
*
* @param format
* @return
*/
private String convertDateFormatToRegex(String format) {
format = format.replace("\\", "\\\\").replace(".", "\\.").replace("-", "\\-").replace("+", "\\+").replace("(",
"\\(").replace(")", "\\)").replace("[", "\\[").replace("]", "\\]").replace("|", "\\|").replace("yyyy",
"((19|2[0-9])[0-9]{2})").replace("yy", "([0-9]{2})").replaceAll("M{4,}",
"([@]+)") //"(January|February|March|April|May|June|July|August|September|October|November|December)")
.replace("MMM", "([@]{3})") //"(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)")
.replace("MM", "(0[1-9]|1[012])").replace("M", "(0?[1-9]|1[012])").replace("dd",
"(0[1-9]|[12][0-9]|3[01])").replace("d", "(0?[1-9]|[12][0-9]|3[01])").replace("hh",
"(1[0-2]|0[1-9])").replace("h", "(1[0-2]|0?[1-9])").replace("HH", "(2[0-3]|1[0-9]|0[0-9])")
.replace("H", "(2[0-3]|1[0-9]|0?[0-9])").replace("kk", "(2[0-4]|1[0-9]|0[1-9])").replace("k",
"(2[0-4]|1[0-9]|0?[1-9])").replace("KK", "(1[01]|0[0-9])").replace("K", "(1[01]|0?[0-9])")
.replace("mm", "([0-5][0-9])").replace("m", "([1-5][0-9]|0?[0-9])").replace("ss", "([0-5][0-9])")
.replace("s", "([1-5][0-9]|0?[0-9])").replace("SSS", "([0-9][0-9][0-9])").replace("SS",
"([0-9][0-9][0-9]?)").replace("S", "([0-9][0-9]?[0-9]?)").replaceAll("E{4,}",
"([@]+)")//"(Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday)")
.replaceAll("E{1,3}", "([@]{3})")//"(Mon|Tue|Wed|Thu|Fri|Sat|Sun)")
.replace("DDD", "(3[0-6][0-5]|[1-2][0-9][0-9]|0[0-9][1-9])").replace("DD",
"(3[0-6][0-5]|[1-2][0-9][0-9]|0?[0-9][1-9])").replace("D",
"(3[0-6][0-5]|[1-2][0-9][0-9]|0?[0-9]?[1-9])").replace("F", "([1-5])").replace("ww",
"(5[0-3]|[1-4][0-9]|0[1-9])").replace("w", "(5[0-3]|[1-4][0-9]|[1-9])").replace("W", "([1-5])")
.replaceAll("z{4,}", "([@]+)").replaceAll("z{1,3}", "([@]{1,4})").replaceAll("a{1,}", "([aApP][mM])")
.replaceAll("G{1,}", "([aA][dD]|[bB][cC])").replace(" ", "\\s").replace("@", "a-zA-Z");
return format;
}
/**
* The dateTime config vars are ';' seperated.
*
* @param configValue
* @return
*/
private List<String> parseConfigValues(String configValue) {
if (configValue == null || "".equals(configValue)) {
return Collections.emptyList();
}
return Arrays.asList(configValue.split(";"));
}
/**
* @return the allowedFormats
*/
@BeanTagAttribute(name = "allowedFormats", type = BeanTagAttribute.AttributeType.LISTVALUE)
public List<String> getAllowedFormats() {
return this.allowedFormats;
}
/**
* Sets the alloweFormats for this constraint, this must be a subset of the system configured
* formats for a date - this list should be used for most fields where you are expecting a user
* to enter a date in a specific format
*
* @param allowedFormats the allowedFormats to set
*/
public void setAllowedFormats(List<String> allowedFormats) {
this.allowedFormats = allowedFormats;
}
/**
* This overridden method ...
*
* @see org.kuali.rice.krad.datadictionary.validation.constraint.ValidDataPatternConstraint#getValidationMessageParams()
*/
@Override
public List<String> getValidationMessageParams() {
if (validationMessageParams == null) {
validationMessageParams = new ArrayList<String>();
if (allowedFormats != null && !allowedFormats.isEmpty()) {
validationMessageParams.add(StringUtils.join(allowedFormats, ", "));
} else {
List<String> dateFormatParams = parseConfigValues(ConfigContext.getCurrentContextConfig().getProperty(
CoreConstants.STRING_TO_DATE_FORMATS));
validationMessageParams.add(StringUtils.join(dateFormatParams, ", "));
}
}
return validationMessageParams;
}
}
| 46.163636 | 141 | 0.587502 |
63d4bafb9e21cdf5cb84f09da27eb2ba8f45e718 | 4,933 | package com.wavesplatform.wallet.ui.zxing;
import android.content.Context;
import android.content.res.Configuration;
import android.view.Surface;
import android.view.WindowManager;
public class RotationUtil {
private int _deviceRotationSetting;
private int _deviceOrientation;
public RotationUtil(Context context) {
WindowManager windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
Configuration config = context.getResources().getConfiguration();
// Determine rotation
int r = windowManager.getDefaultDisplay().getRotation();
// Determine default orientation
if (((r == Surface.ROTATION_0 || r == Surface.ROTATION_180) && config.orientation == Configuration.ORIENTATION_LANDSCAPE)
|| ((r == Surface.ROTATION_90 || r == Surface.ROTATION_270) && config.orientation == Configuration.ORIENTATION_PORTRAIT)) {
_deviceOrientation = Configuration.ORIENTATION_LANDSCAPE;
} else {
_deviceOrientation = Configuration.ORIENTATION_PORTRAIT;
}
_deviceRotationSetting = r;
}
public boolean flipWidthAndHeight() {
switch (_deviceRotationSetting) {
case Surface.ROTATION_0:
// Rotated 90 degrees compared to ZXing's default mode if device is in
// portrait mode.
// Flip if in native portrait mode
return _deviceOrientation == Configuration.ORIENTATION_PORTRAIT;
case Surface.ROTATION_90:
// Rotated 0 degrees compared to ZXing's default mode if device is in
// portrait mode
// Flip if in native landscape mode
return _deviceOrientation == Configuration.ORIENTATION_LANDSCAPE;
case Surface.ROTATION_180:
// Rotated 270 degrees compared to ZXing's default mode if device is in
// portrait mode
// Flip if in portrait mode
return _deviceOrientation == Configuration.ORIENTATION_PORTRAIT;
case Surface.ROTATION_270:
// Rotated 180 degrees compared to ZXing's default mode if device is in
// portrait mode
// Flip if in native landscape mode
return _deviceOrientation == Configuration.ORIENTATION_LANDSCAPE;
default:
return false;
}
}
public int getDisplayOrientationForCameraParameters() {
if (_deviceOrientation == Configuration.ORIENTATION_PORTRAIT) {
switch (_deviceRotationSetting) {
case Surface.ROTATION_0:
return 90;
case Surface.ROTATION_90:
return 0;
case Surface.ROTATION_180:
return 270;
case Surface.ROTATION_270:
return 180;
default:
return 0;
}
} else {
switch (_deviceRotationSetting) {
case Surface.ROTATION_0:
return 0;
case Surface.ROTATION_90:
return 270;
case Surface.ROTATION_180:
return 180;
case Surface.ROTATION_270:
return 90;
default:
return 0;
}
}
}
public byte[] rotateImageData(byte[] data, int width, int height) {
switch (getDisplayOrientationForCameraParameters()) {
case 0:
return data;
case 90:
return rotate90(data, width, height);
case 180:
return rotate180(data, width, height);
case 270:
return rotate270(data, width, height);
default:
return data;
}
}
private static byte[] rotate90(byte[] data, int width, int height) {
byte[] rotatedData = new byte[data.length];
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++)
rotatedData[x * height + height - y - 1] = data[x + y * width];
}
return rotatedData;
}
private static byte[] rotate270(byte[] data, int width, int height) {
byte[] rotatedData = new byte[data.length];
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++)
rotatedData[(width - x - 1) * height + y] = data[x + y * width];
}
return rotatedData;
}
private static byte[] rotate180(byte[] data, int width, int height) {
byte[] rotatedData = new byte[data.length];
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++)
rotatedData[(width - x - 1) + width * (height - y - 1)] = data[x + y * width];
}
return rotatedData;
}
} | 37.946154 | 139 | 0.556862 |
0a9344d1242869dca9a845cf23b046f84018c6b8 | 494 | package com.aweolumidedavid.covid19stat.service;
import com.aweolumidedavid.covid19stat.model.SuppliesToTheCountry;
import java.util.List;
import java.util.Optional;
public interface SuppliesToTheCountryService {
List<SuppliesToTheCountry> getSupplyDetails();
Optional<SuppliesToTheCountry> findById(Long id);
SuppliesToTheCountry save(SuppliesToTheCountry suppliesToTheCountry);
SuppliesToTheCountry findBySupplierName(String supplierName);
void delete(Long id);
}
| 24.7 | 73 | 0.815789 |
81c2592430ff7b70e3e02d4cab571ea02683a1ff | 2,610 | /*
* Copyright 2014 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gradle.platform.base.component;
import org.gradle.api.Incubating;
import org.gradle.language.base.LanguageSourceSet;
import org.gradle.model.ModelMap;
import org.gradle.model.internal.core.ModelMaps;
import org.gradle.model.internal.core.MutableModelNode;
import org.gradle.model.internal.type.ModelType;
import org.gradle.platform.base.Binary;
import org.gradle.platform.base.BinarySpec;
import org.gradle.platform.base.GeneralComponentSpec;
import org.gradle.platform.base.component.internal.DefaultComponentSpec;
/**
* Base class that may be used for custom {@link GeneralComponentSpec} implementations. However, it is generally better to use an
* interface annotated with {@link org.gradle.model.Managed} and not use an implementation class at all.
*/
@Incubating
public class BaseComponentSpec extends DefaultComponentSpec implements GeneralComponentSpec {
private static final ModelType<BinarySpec> BINARY_SPEC_MODEL_TYPE = ModelType.of(BinarySpec.class);
private static final ModelType<Binary> BINARY_MODEL_TYPE = ModelType.of(Binary.class);
private static final ModelType<LanguageSourceSet> LANGUAGE_SOURCE_SET_MODEL_TYPE = ModelType.of(LanguageSourceSet.class);
private final MutableModelNode binaries;
private final MutableModelNode sources;
public BaseComponentSpec() {
MutableModelNode modelNode = getInfo().modelNode;
binaries = ModelMaps.addModelMapNode(modelNode, BINARY_SPEC_MODEL_TYPE, "binaries");
sources = ModelMaps.addModelMapNode(modelNode, LANGUAGE_SOURCE_SET_MODEL_TYPE, "sources");
}
@Override
public ModelMap<LanguageSourceSet> getSources() {
return ModelMaps.toView(sources, LANGUAGE_SOURCE_SET_MODEL_TYPE);
}
@Override
public ModelMap<BinarySpec> getBinaries() {
return ModelMaps.toView(binaries, BINARY_SPEC_MODEL_TYPE);
}
@Override
public Iterable<Binary> getVariants() {
return ModelMaps.toView(binaries, BINARY_MODEL_TYPE);
}
}
| 41.428571 | 129 | 0.772414 |
488fa3c0ce87987f48f7f895d136ca49520bae6b | 1,062 | package ch.rasc.jsonp;
import java.util.Map;
import jakarta.json.Json;
import jakarta.json.stream.JsonGenerator;
public class StreamWrite {
public static void main(String[] args) {
var properties = Map.of(JsonGenerator.PRETTY_PRINTING, Boolean.FALSE);
try (JsonGenerator jg = Json.createGeneratorFactory(properties)
.createGenerator(System.out)) {
jg.writeStartObject()
.write("id", 1234)
.write("active", true)
.write("name", "Duke")
.writeNull("password")
.writeStartArray("roles")
.write("admin")
.write("user")
.write("operator")
.writeEnd()
.writeStartArray("phoneNumbers")
.writeStartObject()
.write("type", "mobile")
.write("number", "111-111-1111")
.writeEnd()
.writeStartObject()
.write("type", "home")
.write("number", "222-222-2222")
.writeEnd()
.writeEnd()
.writeEnd();
}
}
}
| 27.230769 | 74 | 0.541431 |
fc44ebc2965c95139754d283aa9aef62817a7d70 | 4,652 | package com.mytoy.starter.tools;
import org.apache.commons.lang3.StringUtils;
import java.util.ArrayList;
import java.util.List;
public class MyString {
/**
* 下划线转驼峰
*/
public static String underline2Camel(String str) {
if (StringUtils.isNotBlank(str)) {
char[] chars = str.toCharArray();
boolean flag = false;
char[] newChars = new char[chars.length];
int index = 0;
for (char aChar : chars) {
if (aChar == ' ') continue;
if (aChar == '_') {
flag = true;
continue;
}
if (flag) {
if (aChar > 'a' && aChar < 'z') aChar -= 32;
flag = false;
}
newChars[index] = aChar;
index++;
}
str = String.valueOf(newChars).substring(0, index);
}
return str;
}
public static String underline2CamelAndFirstUpper(String str) {
str = underline2Camel(str);
if (null != str && !"".equals(str.trim())) {
char[] chars = str.toCharArray();
for (int i = 0; i < chars.length; i++) {
if (i == 0) {
if (chars[0] >= 'a' && chars[0] <= 'z') {
chars[0] -= 32;
}
break;
}
}
str = new String(chars);
}
return str;
}
/**
* 驼峰转下划线
*/
public static String camel2Underline(String str) {
if (StringUtils.isNotBlank(str)) {
char[] chars = str.toCharArray();
char[] newChars = new char[2 * chars.length];
int index = 0;
for (char aChar : chars) {
if (aChar >= 'A' && aChar <= 'Z') {
aChar += 32;
newChars[index] = '_';
index++;
}
newChars[index] = aChar;
index++;
}
str = String.valueOf(newChars).substring(0, index);
}
return str;
}
public static boolean equals(String str1, String str2) {
if (null != str1 && null != str2 && str1.equals(str2)) return true;
return false;
}
public static boolean isNotBlank(String string) {
if (null != string && !"".equals(string.trim())) return true;
return false;
}
public static boolean isBlank(String string) {
return !isNotBlank(string);
}
public static String delComma(String str) {
if (isNotBlank(str)) {
str = str.replaceAll(",,", ",");
if (str.contains(",,")) delComma(str);
}
return str;
}
public static String choice(String str1, String str2) {
if (isNotBlank(str1)) return str1;
return str2;
}
public static Boolean contains(String str1, String str2) {
if (isNotBlank(str1)) str1.contains(str2);
return false;
}
public static String[] split4Line(String str) {
if (isNotBlank(str))
return MyArrays.delBlank(str.split("\\r?\\n", -1));
return new String[]{};
}
public static String next(List<String> list, String str) {
if (MyCollection.isNotEmpty(list) && isNotBlank(str) && list.contains(str)) {
int i = list.indexOf(str);
if (i < list.size() - 1) {
return list.get(i + 1);
}
}
return "";
}
public static List<Integer> getIndex4Pattern(String str, String pattern) {
List<Integer> integers = new ArrayList<>();
if (isNotBlank(str)) {
String[] split = str.split(pattern);
int i = 0;
for (String s : split) {
if (!"".equals(s)) {
i += s.length();
}
integers.add(i);
i += 1;
}
Integer integer = integers.get(integers.size() - 1);
if (integer < str.length()) {
for (int j = integer; j < str.length(); j++) {
integers.add(j);
}
}
}
return integers.subList(0, integers.size() - 1);
}
public static List<String> splitAndDeleteBlank(String str, String s) {
List<String> list = new ArrayList<>();
if (isNotBlank(str)) {
String[] split = str.split(s);
if (MyArrays.isNotEmpty(split)) for (String s1 : split) if (isNotBlank(s1)) list.add(s1);
}
return list;
}
}
| 30.012903 | 101 | 0.468401 |
8e5e2f1b32dc5ea00622923113ef78f093c3e47e | 1,384 | package com.huyunit.sample.andfix;
import android.content.Context;
import android.util.Log;
import com.alipay.euler.andfix.patch.PatchManager;
import com.huyunit.sample.util.UiUtils;
import java.io.IOException;
/**
* author: bobo
* create time: 2017/11/14 下午7:39
* email: [email protected]
*/
public class AndFixPatchManager {
private static AndFixPatchManager instance = null;
private static PatchManager patchManager = null;
private AndFixPatchManager(){}
public static AndFixPatchManager getInstance(){
if(instance == null) {
synchronized (AndFixPatchManager.class){
if(instance == null){
instance = new AndFixPatchManager();
}
}
}
return instance;
}
public void initPatch(Context context){
patchManager = new PatchManager(context);
patchManager.init(UiUtils.getVersionName(context));
patchManager.loadPatch();
}
public void addPatch(String path){
try {
if(patchManager != null) {
Log.e("andfix", patchManager.toString());
Log.e("andfix", "addPatch()=" + path);
patchManager.addPatch(path);
Log.e("andfix", "addPatch()=" + path);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
| 25.163636 | 59 | 0.593931 |
1e3c90716caa2070fefcdb4e5def1f805c50a61f | 3,078 | /*
* The MIT License (MIT)
*
* Copyright (c) 2017-2018 Yegor Bugayenko
*
* 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 NON-INFRINGEMENT. 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.cactoos.func;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeoutException;
import org.cactoos.iterable.Endless;
import org.cactoos.scalar.And;
import org.hamcrest.MatcherAssert;
import org.hamcrest.Matchers;
import org.junit.Test;
/**
* Test case for {@link TimedFunc}.
* @since 0.29.3
* @checkstyle JavadocMethodCheck (500 lines)
*/
public final class TimedFuncTest {
@Test(expected = TimeoutException.class)
public void functionGetsInterrupted() throws Exception {
final long period = 100L;
new TimedFunc<Boolean, Boolean>(
input -> {
return new And(
new Endless<>(() -> input)
).value();
},
period
).apply(true);
}
@Test
@SuppressWarnings("PMD.AvoidCatchingGenericException")
public void futureTaskIsCancelled() {
final long period = 50L;
final long time = 2000L;
final Future<Boolean> future = Executors.newSingleThreadExecutor()
.submit(
() -> {
Thread.sleep(time);
return true;
}
);
try {
new TimedFunc<Boolean, Boolean>(
period,
input -> future
).apply(true);
// @checkstyle IllegalCatchCheck (1 line)
} catch (final Exception exp) {
MatcherAssert.assertThat(
future.isCancelled(),
Matchers.equalTo(true)
);
}
}
@Test
public void functionIsExecuted() throws Exception {
final long period = 3000L;
MatcherAssert.assertThat(
new TimedFunc<Boolean, Boolean>(
input -> true,
period
).apply(true),
Matchers.equalTo(true)
);
}
}
| 32.744681 | 80 | 0.62898 |
7a821d9ec09e1e05a29210339d1a6ca0ab44a247 | 342 | package subway.view;
import java.util.Scanner;
public class InputView {
private final Scanner scanner;
public InputView(Scanner scanner) { this.scanner = scanner; }
public String userStringInput(String userInput){
System.out.println();
System.out.println(userInput);
return scanner.nextLine();
}
}
| 21.375 | 65 | 0.687135 |
8d39fba128457f928057dc8c177026c9d8a513b9 | 3,714 | /*
* Copyright 2020 Red Hat, Inc. and/or its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.kie.kogito.explainability.rest;
import java.util.Collections;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.http.ContentType;
import org.junit.jupiter.api.Test;
import org.kie.kogito.explainability.api.ExplainabilityRequestDto;
import org.kie.kogito.explainability.api.ExplainabilityResultDto;
import org.kie.kogito.explainability.api.ModelIdentifierDto;
import static io.restassured.RestAssured.given;
import static org.junit.jupiter.api.Assertions.assertEquals;
@QuarkusTest
public class ExplainabilityApiV1Test {
private static final ObjectMapper MAPPER = new ObjectMapper();
private static final String executionId = "test";
private static final String serviceUrl = "http://localhost:8080";
@Test
public void testEndpointWithRequest() throws JsonProcessingException {
ModelIdentifierDto modelIdentifierDto = new ModelIdentifierDto("dmn", "namespace:name");
String body = MAPPER.writeValueAsString(new ExplainabilityRequestDto(executionId, serviceUrl, modelIdentifierDto, Collections.emptyMap(), Collections.emptyMap()));
ExplainabilityResultDto result = given()
.contentType(ContentType.JSON)
.body(body)
.when()
.post("/v1/explain")
.as(ExplainabilityResultDto.class);
assertEquals(executionId, result.getExecutionId());
}
@Test
public void testEndpointWithBadRequests() throws JsonProcessingException {
ExplainabilityRequestDto[] badRequests = new ExplainabilityRequestDto[]{
new ExplainabilityRequestDto(null, serviceUrl, new ModelIdentifierDto("test", "test"), Collections.emptyMap(), Collections.emptyMap()),
new ExplainabilityRequestDto(executionId, serviceUrl, new ModelIdentifierDto("", "test"), Collections.emptyMap(), Collections.emptyMap()),
new ExplainabilityRequestDto(executionId, serviceUrl, new ModelIdentifierDto("test", ""), Collections.emptyMap(), Collections.emptyMap()),
new ExplainabilityRequestDto(executionId, serviceUrl, null, Collections.emptyMap(), Collections.emptyMap()),
new ExplainabilityRequestDto(executionId, "", new ModelIdentifierDto("test", "test"), Collections.emptyMap(), Collections.emptyMap()),
new ExplainabilityRequestDto(executionId, null, new ModelIdentifierDto("test", "test"), Collections.emptyMap(), Collections.emptyMap()),
new ExplainabilityRequestDto(null, null, null, Collections.emptyMap(), Collections.emptyMap()),
};
for (int i = 0; i < badRequests.length; i++) {
String body = MAPPER.writeValueAsString(badRequests[i]);
given()
.contentType(ContentType.JSON)
.body(body)
.when()
.post("/v1/explain")
.then()
.statusCode(400);
}
}
}
| 45.851852 | 171 | 0.696015 |
766f74eb1a44b59001700630486ef74911eabe81 | 48,932 | package com.vimukti.accounter.web.client.ui.vendors;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import com.google.gwt.core.client.GWT;
import com.google.gwt.dom.client.Style.Unit;
import com.google.gwt.event.dom.client.ChangeEvent;
import com.google.gwt.event.dom.client.ChangeHandler;
import com.google.gwt.event.logical.shared.ValueChangeEvent;
import com.google.gwt.event.logical.shared.ValueChangeHandler;
import com.google.gwt.user.client.ui.Label;
import com.vimukti.accounter.web.client.AccounterAsyncCallback;
import com.vimukti.accounter.web.client.Global;
import com.vimukti.accounter.web.client.core.AccounterCoreType;
import com.vimukti.accounter.web.client.core.AddNewButton;
import com.vimukti.accounter.web.client.core.ClientAccount;
import com.vimukti.accounter.web.client.core.ClientAccounterClass;
import com.vimukti.accounter.web.client.core.ClientAddress;
import com.vimukti.accounter.web.client.core.ClientCashPurchase;
import com.vimukti.accounter.web.client.core.ClientCurrency;
import com.vimukti.accounter.web.client.core.ClientFinanceDate;
import com.vimukti.accounter.web.client.core.ClientPurchaseOrder;
import com.vimukti.accounter.web.client.core.ClientTAXCode;
import com.vimukti.accounter.web.client.core.ClientTransaction;
import com.vimukti.accounter.web.client.core.ClientTransactionItem;
import com.vimukti.accounter.web.client.core.ClientVendor;
import com.vimukti.accounter.web.client.core.IAccounterCore;
import com.vimukti.accounter.web.client.core.ValidationResult;
import com.vimukti.accounter.web.client.core.Lists.PurchaseOrdersAndItemReceiptsList;
import com.vimukti.accounter.web.client.exception.AccounterException;
import com.vimukti.accounter.web.client.exception.AccounterExceptions;
import com.vimukti.accounter.web.client.ui.Accounter;
import com.vimukti.accounter.web.client.ui.GwtDisclosurePanel;
import com.vimukti.accounter.web.client.ui.StyledPanel;
import com.vimukti.accounter.web.client.ui.UIUtils;
import com.vimukti.accounter.web.client.ui.combo.IAccounterComboSelectionChangeHandler;
import com.vimukti.accounter.web.client.ui.core.AccounterValidator;
import com.vimukti.accounter.web.client.ui.core.EditMode;
import com.vimukti.accounter.web.client.ui.core.IPrintableView;
import com.vimukti.accounter.web.client.ui.core.TaxItemsForm;
import com.vimukti.accounter.web.client.ui.edittable.TransactionsTree;
import com.vimukti.accounter.web.client.ui.edittable.tables.VendorAccountTransactionTable;
import com.vimukti.accounter.web.client.ui.edittable.tables.VendorItemTransactionTable;
import com.vimukti.accounter.web.client.ui.forms.AmountLabel;
import com.vimukti.accounter.web.client.ui.forms.CheckboxItem;
import com.vimukti.accounter.web.client.ui.forms.DynamicForm;
import com.vimukti.accounter.web.client.ui.forms.TextAreaItem;
import com.vimukti.accounter.web.client.ui.forms.TextItem;
import com.vimukti.accounter.web.client.ui.widgets.DateValueChangeHandler;
/**
* @author vimukti1
*
*/
public class CashPurchaseView extends
AbstractVendorTransactionView<ClientCashPurchase> implements
IPrintableView {
protected DynamicForm vendorForm;
protected DynamicForm termsForm;
public List<String> selectedComboList;
private ArrayList<DynamicForm> listforms;
protected Label titlelabel;
private TextAreaItem billToAreaItem;
protected VendorAccountTransactionTable vendorAccountTransactionTable;
protected VendorItemTransactionTable vendorItemTransactionTable;
protected AddNewButton accountTableButton, itemTableButton;
protected GwtDisclosurePanel accountsDisclosurePanel, itemsDisclosurePanel;
private TextItem checkNoText;
private CheckboxItem printCheck;
private boolean isChecked = false;
TransactionsTree<PurchaseOrdersAndItemReceiptsList> transactionsTree;
private StyledPanel accountFlowPanel;
private StyledPanel itemsFlowPanel;
// private WarehouseAllocationTable inventoryTransactionTable;
// private DisclosurePanel inventoryDisclosurePanel;
public CashPurchaseView() {
super(ClientTransaction.TYPE_CASH_PURCHASE);
this.getElement().setId("CashPurchaseView");
}
protected CashPurchaseView(int type) {
super(type);
}
@Override
protected void createControls() {
titlelabel = new Label(messages.cashPurchase());
titlelabel.setStyleName("label-title");
// titlelabel.setHeight("50px");
listforms = new ArrayList<DynamicForm>();
transactionDateItem = createTransactionDateItem();
transactionDateItem
.addDateValueChangeHandler(new DateValueChangeHandler() {
@Override
public void onDateValueChange(ClientFinanceDate date) {
if (date != null) {
deliveryDateItem.setEnteredDate(date);
setTransactionDate(date);
}
}
});
// transactionDateItem.setWidth(100);
transactionNumber = createTransactionNumberItem();
locationCombo = createLocationCombo();
DynamicForm dateNoForm = new DynamicForm("dateNoForm");
dateNoForm.setStyleName("datenumber-panel");
if (!isTemplate) {
dateNoForm.add(transactionDateItem, transactionNumber);
}
StyledPanel datepanel = new StyledPanel("datepanel");
datepanel.add(dateNoForm);
datepanel.getElement().getStyle().setPaddingRight(25, Unit.PX);
StyledPanel labeldateNoLayout = new StyledPanel("labeldateNoLayout");
// labeldateNoLayout.add(titlelabel);
labeldateNoLayout.add(datepanel);
if (this.isInViewMode())
// --the form need to be disabled here
dateNoForm.setEnabled(false);
// formItems.add(transactionDateItem);
// formItems.add(transactionNumber);
vendorCombo = createVendorComboItem(messages.payeeName(Global.get()
.Vendor()));
vendorCombo.setRequired(false);
// vendorCombo.setWidth(100);
contactCombo = createContactComboItem();
// contactCombo.setWidth(100);
billToAreaItem = new TextAreaItem(messages.billTo(), "billToAreaItem");
// billToAreaItem.setWidth(100);
billToAreaItem.setDisabled(true);
phoneSelect = new TextItem(messages.phone(), "phoneSelect");
phoneSelect.setToolTip(messages.phoneNumberOf(this.getAction()
.getCatagory()));
// phoneSelect.setWidth(100);
if (isInViewMode())
phoneSelect.setEnabled(false);
vendorForm = UIUtils.form(Global.get().Vendor());
// vendorForm.setWidth("100%");
vendorForm.add(vendorCombo, contactCombo, phoneSelect, billToAreaItem);
// vendorForm.getCellFormatter().setWidth(0, 0, "160px");
// formItems.add(contactCombo);
// formItems.add(billToCombo);
payFromCombo = createPayFromCombo(messages.payFrom());
// payFromCombo.setWidth(100);
// payFromCombo.setPopupWidth("500px");
// checkNo = createCheckNumberItem(messages.chequeNo());
// checkNo.setDisabled(true);
// checkNo.setWidth(100);
deliveryDateItem = createTransactionDeliveryDateItem();
// deliveryDateItem.setWidth(100);
paymentMethodCombo = createPaymentMethodSelectItem();
// paymentMethodCombo.setWidth(100);
paymentMethodCombo
.addSelectionChangeHandler(new IAccounterComboSelectionChangeHandler<String>() {
@Override
public void selectedComboBoxItem(String selectItem) {
paymentMethodSelected(paymentMethodCombo
.getSelectedValue());
}
});
printCheck = new CheckboxItem(messages.toBePrinted(), "printCheck");
printCheck.setValue(true);
// printCheck.setWidth(100);
printCheck.setEnabled(false);
printCheck.addChangeHandler(new ValueChangeHandler<Boolean>() {
@Override
public void onValueChange(ValueChangeEvent<Boolean> event) {
isChecked = event.getValue();
if (isChecked) {
if (printCheck.getValue().toString()
.equalsIgnoreCase("true")) {
checkNoText.setValue(messages.toBePrinted());
checkNoText.setEnabled(false);
} else {
if (payFromCombo.getValue() == null)
checkNoText.setValue(messages.toBePrinted());
else if (transaction != null) {
checkNoText.setValue(transaction.getCheckNumber());
}
}
} else
checkNoText.setValue("");
checkNoText.setEnabled(true);
}
});
checkNoText = new TextItem(messages.chequeNo(), "checkNoText");
checkNoText.setValue(messages.toBePrinted());
// checkNoText.setWidth(100);
if (paymentMethodCombo.getSelectedValue() != null
&& !paymentMethodCombo.getSelectedValue().equals(
UIUtils.getpaymentMethodCheckBy_CompanyType(messages
.check())))
checkNoText.setEnabled(false);
checkNoText.addChangeHandler(new ChangeHandler() {
@Override
public void onChange(ChangeEvent event) {
checkNumber = checkNoText.getValue().toString();
}
});
termsForm = new DynamicForm("termsForm");
if (locationTrackingEnabled)
termsForm.add(locationCombo);
// termsForm.setWidth("100%");
if (isTemplate) {
termsForm.add(paymentMethodCombo, printCheck, checkNoText,
payFromCombo);
} else {
termsForm.add(paymentMethodCombo, printCheck, checkNoText,
payFromCombo, deliveryDateItem);
}
classListCombo = createAccounterClassListCombo();
if (isTrackClass() && !isClassPerDetailLine()) {
termsForm.add(classListCombo);
}
// termsForm.getCellFormatter().getElement(0, 0).setAttribute(
// messages.width(), "203px");
// formItems.add(checkNo);
// formItems.add(deliveryDateItem);
Label lab2 = new Label(messages.itemsAndExpenses());
// menuButton = createAddNewButton();
netAmount = new AmountLabel(
messages.currencyNetAmount(getBaseCurrency().getFormalName()),
getBaseCurrency());
netAmount.setDefaultValue("£0.00");
netAmount.setEnabled(false);
transactionTotalNonEditableText = createTransactionTotalNonEditableItem(getCompany()
.getPrimaryCurrency());
foreignCurrencyamountLabel = createForeignCurrencyAmountLable(getCompany()
.getPrimaryCurrency());
vatTotalNonEditableText = new TaxItemsForm();// createVATTotalNonEditableItem();
vatinclusiveCheck = getVATInclusiveCheckBox();
taxCodeSelect = createTaxCodeSelectItem();
transactionsTree = new TransactionsTree<PurchaseOrdersAndItemReceiptsList>(
this) {
HashMap<ClientTransactionItem, ClientTransactionItem> clonesObjs = new HashMap<ClientTransactionItem, ClientTransactionItem>();
@Override
public void updateTransactionTotal() {
if (currencyWidget != null) {
setCurrencyFactor(currencyWidget.getCurrencyFactor());
}
CashPurchaseView.this.updateNonEditableItems();
}
@Override
public void setTransactionDate(ClientFinanceDate transactionDate) {
CashPurchaseView.this.setTransactionDate(transactionDate);
}
@Override
public boolean isinViewMode() {
return !(CashPurchaseView.this.isInViewMode());
}
@Override
public void addToMap(ClientTransaction estimate) {
List<ClientTransactionItem> transactionItems = transaction
.getTransactionItems();
List<ClientTransactionItem> estTItems = estimate
.getTransactionItems();
for (ClientTransactionItem clientTransactionItem : transactionItems) {
for (ClientTransactionItem estTItem : estTItems) {
if (clientTransactionItem.getReferringTransactionItem() == estTItem
.getID()) {
clonesObjs.put(estTItem, clientTransactionItem);
break;
}
}
}
}
@Override
public void onSelectionChange(ClientTransaction result,
boolean isSelected) {
List<ClientTransactionItem> transactionItems = result
.getTransactionItems();
for (ClientTransactionItem transactionItem : transactionItems) {
if (!isSelected) {
// De SELECTED
ClientTransactionItem cloned = clonesObjs
.get(transactionItem);
vendorItemTransactionTable.delete(cloned);
transaction.getTransactionItems().remove(cloned);
continue;
}
// SELECTED
ClientTransactionItem tItem = transactionItem.clone();
tItem.setID(0l);
tItem.setLineTotal(tItem.getLineTotal()
/ getCurrencyFactor());
tItem.setDiscount(tItem.getDiscount() / getCurrencyFactor());
tItem.setUnitPrice(tItem.getUnitPrice()
/ getCurrencyFactor());
tItem.setVATfraction(tItem.getVATfraction()
/ getCurrencyFactor());
tItem.setReferringTransactionItem(transactionItem.getID());
tItem.setTransaction(transaction);
if (vatinclusiveCheck != null) {
tItem.setAmountIncludeTAX(vatinclusiveCheck.getValue());
}
if (tItem.getType() == ClientTransactionItem.TYPE_ACCOUNT) {
tItem.setType(ClientTransactionItem.TYPE_ITEM);
tItem.setAccount(0L);
}
int emptyRows = 0;
for (ClientTransactionItem cItem : vendorItemTransactionTable
.getAllRows()) {
if (cItem.isEmpty()) {
vendorItemTransactionTable.delete(cItem);
emptyRows++;
}
}
vendorItemTransactionTable.add(tItem);
while (emptyRows > 1) {
vendorItemTransactionTable
.add(vendorItemTransactionTable.getEmptyRow());
emptyRows--;
}
transaction.getTransactionItems().add(tItem);
clonesObjs.put(transactionItem, tItem);
ClientTAXCode selectedValue = taxCodeSelect
.getSelectedValue();
if (selectedValue == null
&& !getPreferences().isTaxPerDetailLine()) {
taxCodeSelected(getCompany().getTAXCode(
tItem.getTaxCode()));
}
}
vendorItemTransactionTable.updateTotals();
}
};
vendorAccountTransactionTable = new VendorAccountTransactionTable(
isTrackTax(), isTaxPerDetailLine(), isTrackDiscounts(),
isDiscountPerDetailLine(), this, isCustomerAllowedToAdd(),
isTrackClass(), isClassPerDetailLine()) {
@Override
protected void updateNonEditableItems() {
if (currencyWidget != null) {
setCurrencyFactor(currencyWidget.getCurrencyFactor());
}
CashPurchaseView.this.updateNonEditableItems();
}
@Override
public boolean isShowPriceWithVat() {
return CashPurchaseView.this.isShowPriceWithVat();
}
@Override
protected boolean isInViewMode() {
return CashPurchaseView.this.isInViewMode();
}
@Override
protected boolean isTrackJob() {
return CashPurchaseView.this.isTrackJob();
}
@Override
protected void updateDiscountValues(ClientTransactionItem row) {
if (discountField.getPercentage() != null
&& discountField.getPercentage() != 0) {
row.setDiscount(discountField.getPercentage());
}
CashPurchaseView.this.updateNonEditableItems();
}
};
vendorAccountTransactionTable.setEnabled(!isInViewMode());
this.accountFlowPanel = new StyledPanel("accountFlowPanel");
accountsDisclosurePanel = (GwtDisclosurePanel) GWT
.create(GwtDisclosurePanel.class);
accountsDisclosurePanel.setTitle(messages.ItemizebyAccount());
accountFlowPanel.add(vendorAccountTransactionTable);
accountsDisclosurePanel.setContent(accountFlowPanel);
accountsDisclosurePanel.setOpen(true);
// accountsDisclosurePanel.setWidth("100%");
vendorItemTransactionTable = new VendorItemTransactionTable(
isTrackTax(), isTaxPerDetailLine(), isTrackDiscounts(),
isDiscountPerDetailLine(), this, isCustomerAllowedToAdd(),
isTrackClass(), isClassPerDetailLine()) {
@Override
protected void updateNonEditableItems() {
if (currencyWidget != null) {
setCurrencyFactor(currencyWidget.getCurrencyFactor());
}
CashPurchaseView.this.updateNonEditableItems();
}
@Override
public boolean isShowPriceWithVat() {
return CashPurchaseView.this.isShowPriceWithVat();
}
@Override
protected boolean isInViewMode() {
return CashPurchaseView.this.isInViewMode();
}
@Override
protected boolean isTrackJob() {
return CashPurchaseView.this.isTrackJob();
}
@Override
protected void updateDiscountValues(ClientTransactionItem row) {
if (discountField.getPercentage() != null
&& discountField.getPercentage() != 0) {
row.setDiscount(discountField.getPercentage());
}
CashPurchaseView.this.updateNonEditableItems();
}
@Override
protected int getTransactionType() {
return ClientTransaction.TYPE_CASH_PURCHASE;
}
};
vendorItemTransactionTable.setEnabled(!isInViewMode());
currencyWidget = createCurrencyFactorWidget();
this.itemsFlowPanel = new StyledPanel("itemsFlowPanel");
itemsDisclosurePanel = (GwtDisclosurePanel) GWT
.create(GwtDisclosurePanel.class);
itemsDisclosurePanel.setTitle(messages.ItemizebyProductService());
itemsFlowPanel.add(vendorItemTransactionTable);
itemsDisclosurePanel.setContent(itemsFlowPanel);
// itemsDisclosurePanel.setWidth("100%");
// Inventory table..
// inventoryTransactionTable = new WarehouseAllocationTable();
// inventoryTransactionTable.setDesable(isInViewMode());
//
// FlowPanel inventoryFlowPanel = new FlowPanel();
// inventoryDisclosurePanel = new
// DisclosurePanel("Warehouse Allocation");
// inventoryFlowPanel.add(inventoryTransactionTable);
// inventoryDisclosurePanel.setContent(inventoryFlowPanel);
// inventoryDisclosurePanel.setWidth("100%");
// ---Inverntory table-----
memoTextAreaItem = createMemoTextAreaItem();
// memoTextAreaItem.setWidth(100);
// refText = createRefereceText();
// refText.setWidth(100);
DynamicForm memoForm = new DynamicForm("memoForm");
// memoForm.setWidth("100%");
memoForm.add(memoTextAreaItem);
discountField = getDiscountField();
StyledPanel totalForm = new StyledPanel("totalForm");
totalForm.setStyleName("boldtext");
StyledPanel leftVLay = new StyledPanel("leftVLay");
leftVLay.add(vendorForm);
StyledPanel rightVLay = new StyledPanel("rightVLay");
// rightVLay.setWidth("100%");
rightVLay.add(termsForm);
if (isMultiCurrencyEnabled()) {
rightVLay.add(currencyWidget);
currencyWidget.setEnabled(!isInViewMode());
}
DynamicForm form = new DynamicForm("form");
StyledPanel bottomLayout = new StyledPanel("bottomLayout");
StyledPanel bottompanel = new StyledPanel("bottompanel");
DynamicForm transactionTotalForm = new DynamicForm(
"transactionTotalForm");
if (isTrackTax() && isTrackPaidTax()) {
DynamicForm netAmountForm = new DynamicForm("netAmountForm");
netAmountForm.add(netAmount);
totalForm.add(netAmountForm);
totalForm.add(vatTotalNonEditableText);
if (isMultiCurrencyEnabled()) {
transactionTotalForm.add(transactionTotalNonEditableText,
foreignCurrencyamountLabel);
} else {
transactionTotalForm.add(transactionTotalNonEditableText);
}
StyledPanel vpanel = new StyledPanel("vpanel");
vpanel.add(totalForm);
bottomLayout.add(memoForm);
if (!isTaxPerDetailLine()) {
// taxCodeSelect.setVisible(isInViewMode());
form.add(taxCodeSelect);
}
form.add(vatinclusiveCheck);
bottomLayout.add(form);
if (isTrackDiscounts()) {
if (!isDiscountPerDetailLine()) {
form.add(discountField);
bottomLayout.add(form);
}
}
bottomLayout.add(totalForm);
bottompanel.add(vpanel);
bottompanel.add(bottomLayout);
// StyledPanel vPanel = new StyledPanel();
// vPanel.add(menuButton);
// vPanel.add(memoForm);
// vPanel.setWidth("100%");
//
// bottomLayout.add(vPanel);
// bottomLayout.add(vatCheckform);
// bottomLayout.setCellHorizontalAlignment(vatCheckform,
// HasHorizontalAlignment.ALIGN_RIGHT);
// bottomLayout.add(totalForm);
// bottomLayout.setCellHorizontalAlignment(totalForm,
// HasHorizontalAlignment.ALIGN_RIGHT);
} else {
memoForm.setStyleName("align-form");
bottomLayout.add(memoForm);
if (isMultiCurrencyEnabled()) {
transactionTotalForm.add(transactionTotalNonEditableText,
foreignCurrencyamountLabel);
} else {
transactionTotalForm.add(transactionTotalNonEditableText);
}
if (isTrackDiscounts()) {
if (!isDiscountPerDetailLine()) {
form.add(discountField);
bottomLayout.add(form);
}
}
bottomLayout.add(totalForm);
bottompanel.add(bottomLayout);
}
totalForm.add(transactionTotalForm);
StyledPanel mainVLay = new StyledPanel("mainVLay");
mainVLay.add(titlelabel);
mainVLay.add(voidedPanel);
mainVLay.add(labeldateNoLayout);
StyledPanel topHLay = getTopLayout();
if (topHLay != null) {
topHLay.add(leftVLay);
topHLay.add(rightVLay);
mainVLay.add(topHLay);
} else {
mainVLay.add(leftVLay);
mainVLay.add(rightVLay);
}
// mainVLay.add(lab2);
mainVLay.add(transactionsTree);
mainVLay.add(accountsDisclosurePanel.getPanel());
mainVLay.add(itemsDisclosurePanel.getPanel());
mainVLay.add(bottompanel);
// setOverflow(Overflow.SCROLL);
this.add(mainVLay);
// addChild(mainVLay);
/* Adding dynamic forms in list */
listforms.add(dateNoForm);
listforms.add(vendorForm);
listforms.add(termsForm);
listforms.add(memoForm);
listforms.add(transactionTotalForm);
// if (UIUtils.isMSIEBrowser())
// resetFormView();
if (isMultiCurrencyEnabled()) {
foreignCurrencyamountLabel.hide();
}
initViewType();
// settabIndexes();
}
protected StyledPanel getTopLayout() {
StyledPanel topHLay = new StyledPanel("topHLay");
topHLay.addStyleName("fields-panel");
return topHLay;
}
@Override
protected void accountSelected(ClientAccount account) {
if (account == null) {
payFromCombo.setValue("");
return;
}
this.payFromAccount = account;
payFromCombo.setComboItem(payFromAccount);
if (account != null
&& paymentMethod.equalsIgnoreCase(messages.cheque())
&& isInViewMode()) {
ClientCashPurchase cashPurchase = transaction;
// setCheckNumber();
}
}
@Override
protected void initTransactionViewData() {
if (transaction == null) {
setData(new ClientCashPurchase());
} else {
if (currencyWidget != null) {
if (transaction.getCurrency() > 1) {
this.currency = getCompany().getCurrency(
transaction.getCurrency());
} else {
this.currency = getCompany().getPrimaryCurrency();
}
this.currencyFactor = transaction.getCurrencyFactor();
currencyWidget.setSelectedCurrency(this.currency);
// currencyWidget.currencyChanged(this.currency);
currencyWidget.setCurrencyFactor(transaction
.getCurrencyFactor());
currencyWidget.setEnabled(!isInViewMode());
}
ClientVendor vendor = getCompany().getVendor(
transaction.getVendor());
vendorCombo.setValue(vendor);
this.vendor = vendor;
vendorItemTransactionTable.setPayee(vendor);
selectedVendor(vendor);
contactSelected(transaction.getContact());
phoneSelect.setValue(transaction.getPhone());
this.billingAddress = transaction.getVendorAddress();
if (billingAddress != null) {
billToAreaItem.setValue(getValidAddress(billingAddress));
} else
billToAreaItem.setValue("");
// paymentMethodSelected(cashPurchaseToBeEdited.getPaymentMethod()
// !=
// null ? cashPurchaseToBeEdited
// .getPaymentMethod()
// : "");
paymentMethodCombo.setComboItem(transaction.getPaymentMethod());
if (transaction.getPaymentMethod().equals(messages.check())) {
printCheck.setEnabled(!isInViewMode());
checkNoText.setEnabled(!isInViewMode());
} else {
printCheck.setEnabled(false);
checkNoText.setEnabled(false);
}
if (transaction.getCheckNumber() != null) {
if (transaction.getCheckNumber().equals(messages.toBePrinted())) {
checkNoText.setValue(messages.toBePrinted());
printCheck.setValue(true);
} else {
checkNoText.setValue(transaction.getCheckNumber());
printCheck.setValue(false);
}
}
accountSelected(getCompany().getAccount(transaction.getPayFrom()));
// transactionDateItem.setEnteredDate(cashPurchaseToBeEdited.get)
initMemoAndReference();
netAmount.setAmount(transaction.getNetAmount());
if (getPreferences().isTrackPaidTax()) {
if (getPreferences().isTaxPerDetailLine()) {
vatTotalNonEditableText.setTransaction(transaction);
} else {
selectTAXCode();
}
}
if (transaction.getTransactionItems() != null) {
if (isTrackDiscounts()) {
if (!isDiscountPerDetailLine()) {
this.discountField
.setPercentage(getdiscount(transaction
.getTransactionItems()));
}
}
}
if (isTrackClass()) {
if (!isClassPerDetailLine()) {
this.accounterClass = getClassForTransactionItem(transaction
.getTransactionItems());
if (accounterClass != null) {
this.classListCombo.setComboItem(accounterClass);
classSelected(accounterClass);
}
}
}
// if (isTrackTax()) {
// if (isTaxPerDetailLine()) {
// netAmountLabel.setAmount(transaction.getNetAmount());
// taxTotalNonEditableText.setAmount(transaction.getTotal()
// - transaction.getNetAmount());
// } else {
// this.taxCode =
// getTaxCodeForTransactionItems(this.transactionItems);
// if (taxCode != null) {
// this.taxCodeSelect
// .setComboItem(getTaxCodeForTransactionItems(this.transactionItems));
// }
// this.taxTotalNonEditableText.setValue(String
// .valueOf(transaction.getTaxTotla()));
// }
// }
//
transactionTotalNonEditableText
.setAmount(getAmountInBaseCurrency(transaction.getTotal()));
foreignCurrencyamountLabel.setAmount(transaction.getTotal());
if (vatinclusiveCheck != null) {
setAmountIncludeChkValue(isAmountIncludeTAX());
}
}
if (locationTrackingEnabled)
locationSelected(getCompany()
.getLocation(transaction.getLocation()));
super.initTransactionViewData();
initPayFromAccounts();
accountsDisclosurePanel.setOpen(checkOpen(
transaction.getTransactionItems(),
ClientTransactionItem.TYPE_ACCOUNT, true));
itemsDisclosurePanel.setOpen(checkOpen(
transaction.getTransactionItems(),
ClientTransactionItem.TYPE_ITEM, false));
if (isMultiCurrencyEnabled()) {
updateAmountsFromGUI();
}
}
private void selectedVendor(ClientVendor vendor) {
if (vendor == null) {
return;
}
updatePurchaseOrderOrItemReceipt(vendor);
if (!transaction.isTemplate()) {
getPurchaseOrdersAndItemReceipt();
}
super.vendorSelected(vendor);
}
private void updatePurchaseOrderOrItemReceipt(ClientVendor vendor) {
if (this.getVendor() != null && this.getVendor() != vendor) {
ClientCashPurchase ent = this.transaction;
if (ent != null && ent.getVendor() == vendor.getID()) {
this.vendorAccountTransactionTable
.setRecords(getAccountTransactionItems(ent
.getTransactionItems()));
this.vendorItemTransactionTable
.setRecords(getItemTransactionItems(ent
.getTransactionItems()));
} else if (ent != null && ent.getVendor() != vendor.getID()) {
this.vendorAccountTransactionTable.resetRecords();
this.vendorAccountTransactionTable.updateTotals();
this.vendorItemTransactionTable.updateTotals();
}
}
}
@Override
protected void vendorSelected(ClientVendor vendor) {
if (vendor == null) {
return;
}
vendorItemTransactionTable.setPayee(vendor);
transactionsTree.clear();
if (this.getVendor() != null && this.getVendor() != vendor) {
ClientCashPurchase ent = this.transaction;
if (ent != null && ent.getVendor() == vendor.getID()) {
this.vendorAccountTransactionTable
.setRecords(getAccountTransactionItems(ent
.getTransactionItems()));
this.vendorItemTransactionTable
.setRecords(getItemTransactionItems(ent
.getTransactionItems()));
} else if (ent != null && ent.getVendor() != vendor.getID()) {
this.vendorAccountTransactionTable.resetRecords();
this.vendorAccountTransactionTable.updateTotals();
this.vendorItemTransactionTable.updateTotals();
}
}
super.vendorSelected(vendor);
if (vendor == null) {
return;
}
if (vendor.getPhoneNo() != null)
phoneSelect.setValue(vendor.getPhoneNo());
else
phoneSelect.setValue("");
billingAddress = getAddress(ClientAddress.TYPE_BILL_TO);
if (billingAddress != null) {
billToAreaItem.setValue(getValidAddress(billingAddress));
} else
billToAreaItem.setValue("");
long code = vendor.getTAXCode();
if (code == 0 && taxCodeSelect != null) {
code = Accounter.getCompany().getDefaultTaxCode();
taxCodeSelect.setComboItem(getCompany().getTAXCode(code));
}
long currency = vendor.getCurrency();
if (currency != 0) {
ClientCurrency clientCurrency = getCompany().getCurrency(currency);
currencyWidget.setSelectedCurrencyFactorInWidget(clientCurrency,
transactionDateItem.getDate().getDate());
} else {
ClientCurrency clientCurrency = getCompany().getPrimaryCurrency();
if (clientCurrency != null) {
currencyWidget.setSelectedCurrency(clientCurrency);
}
}
vendorAccountTransactionTable.setTaxCode(code, false);
vendorItemTransactionTable.setTaxCode(code, false);
if (isMultiCurrencyEnabled()) {
super.setCurrency(getCompany().getCurrency(vendor.getCurrency()));
setCurrencyFactor(currencyWidget.getCurrencyFactor());
updateAmountsFromGUI();
}
getPurchaseOrdersAndItemReceipt();
}
@Override
protected void paymentMethodSelected(String paymentMethod) {
if (paymentMethod == null)
return;
if (paymentMethod != null) {
this.paymentMethod = paymentMethod;
if (paymentMethod.equalsIgnoreCase(messages.cheque())) {
printCheck.setEnabled(true);
checkNoText.setEnabled(true);
} else {
// paymentMethodCombo.setComboItem(paymentMethod);
printCheck.setEnabled(false);
checkNoText.setEnabled(false);
}
}
}
// private void setDisableStateForCheckNo(String paymentMethod) {
//
// if (paymentMethod.equalsIgnoreCase(messages.cheque())) {
// checkNo.setDisabled(false);
// } else {
// checkNo.setValue("");
// checkNo.setDisabled(true);
//
// }
// if (isInViewMode()) {
// if (paymentMethod.equalsIgnoreCase(messages.cheque())) {
// checkNo.setDisabled(false);
// } else {
// checkNo.setDisabled(true);
// }
// }
// }
@Override
public void saveAndUpdateView() {
updateTransaction();
super.saveAndUpdateView();
createAlterObject();
}
@Override
public ClientCashPurchase saveView() {
ClientCashPurchase saveView = super.saveView();
if (saveView != null) {
updateTransaction();
transaction.setPurchaseOrders(new ArrayList<ClientPurchaseOrder>());
List<ClientTransactionItem> tItems = transaction
.getTransactionItems();
Iterator<ClientTransactionItem> iterator = tItems.iterator();
while (iterator.hasNext()) {
ClientTransactionItem next = iterator.next();
if (next.getReferringTransactionItem() != 0) {
iterator.remove();
}
}
}
return saveView;
}
@Override
protected void updateTransaction() {
super.updateTransaction();
// Setting Type
transaction.setType(ClientTransaction.TYPE_CASH_PURCHASE);
if (this.getVendor() != null) {
// Setting Vendor
transaction.setVendor(this.getVendor().getID());
}
// Setting Contact
if (contact != null)
transaction.setContact(this.contact);
// Setting Address
if (billingAddress != null)
transaction.setVendorAddress((billingAddress));
// Setting Phone
// if (phoneNo != null)
transaction.setPhone(phoneSelect.getValue().toString());
// Setting Payment Methods
transaction.setPaymentMethod(paymentMethodCombo.getValue().toString());
if (checkNoText.getValue() != null
&& !checkNoText.getValue().equals("")) {
transaction.setCheckNumber(getCheckValue());
} else
transaction.setCheckNumber("");
// transaction.setIsToBePrinted(isChecked);
// Setting Pay From Account
transaction
.setPayFrom(payFromCombo.getSelectedValue() != null ? payFromCombo
.getSelectedValue().getID() : 0);
// transaction
// .setCheckNumber(getCheckNoValue() ==
// ClientWriteCheck.IS_TO_BE_PRINTED ? "0"
// : getCheckNoValue() + "");
// Setting Delivery date
if (deliveryDateItem.getEnteredDate() != null)
transaction.setDeliveryDate(deliveryDateItem.getEnteredDate()
.getDate());
// Setting Total
transaction.setTotal(vendorAccountTransactionTable.getGrandTotal()
+ vendorItemTransactionTable.getGrandTotal());
// Setting Memo
transaction.setMemo(getMemoTextAreaItem());
// Setting Reference
// cashPurchase.setReference(getRefText());
if (currency != null)
transaction.setCurrency(currency.getID());
transaction.setCurrencyFactor(currencyWidget.getCurrencyFactor());
// if (getCompany().getPreferences().isInventoryEnabled()
// && getCompany().getPreferences().iswareHouseEnabled())
// transaction.setWareHouseAllocations(inventoryTransactionTable
// .getAllRows());
if (isTrackDiscounts()) {
if (discountField.getPercentage() != 0.0
&& transactionItems != null) {
for (ClientTransactionItem item : transactionItems) {
item.setDiscount(discountField.getPercentage());
}
}
}
List<ClientTransaction> selectedRecords = transactionsTree
.getSelectedRecords();
List<ClientPurchaseOrder> orders = new ArrayList<ClientPurchaseOrder>();
for (ClientTransaction clientTransaction : selectedRecords) {
if (clientTransaction instanceof ClientPurchaseOrder) {
orders.add((ClientPurchaseOrder) clientTransaction);
}
}
transaction.setPurchaseOrders(orders);
transaction.setNetAmount(netAmount.getAmount());
if (isTrackPaidTax()) {
setAmountIncludeTAX();
}
}
private String getCheckValue() {
String value;
if (!isInViewMode()) {
if (checkNoText.getValue().equals(messages.toBePrinted())) {
value = String.valueOf(messages.toBePrinted());
} else
value = String.valueOf(checkNoText.getValue());
} else {
String checknumber;
checknumber = this.checkNumber;
if (checknumber == null) {
checknumber = messages.toBePrinted();
}
if (checknumber.equals(messages.toBePrinted()))
value = messages.toBePrinted();
else
value = String.valueOf(checknumber);
}
return value;
}
public void createAlterObject() {
saveOrUpdate(transaction);
}
@Override
protected void initMemoAndReference() {
memoTextAreaItem.setDisabled(true);
setMemoTextAreaItem(transaction.getMemo());
// setRefText(((ClientCashPurchase) transactionObject).getReference());
}
@Override
public void updateNonEditableItems() {
if (vendorAccountTransactionTable == null
|| vendorItemTransactionTable == null) {
return;
}
ClientTAXCode tax = taxCodeSelect.getSelectedValue();
if (tax != null) {
for (ClientTransactionItem item : vendorAccountTransactionTable
.getRecords()) {
item.setTaxCode(tax.getID());
}
for (ClientTransactionItem item : vendorItemTransactionTable
.getRecords()) {
item.setTaxCode(tax.getID());
}
}
double lineTotal = vendorAccountTransactionTable.getLineTotal()
+ vendorItemTransactionTable.getLineTotal();
double grandTotal = vendorAccountTransactionTable.getGrandTotal()
+ vendorItemTransactionTable.getGrandTotal();
netAmount.setAmount(lineTotal);
if (getCompany().getPreferences().isTrackPaidTax()) {
List<ClientTransaction> selectedRecords = transactionsTree
.getSelectedRecords();
if (!isInViewMode()) {
List<ClientPurchaseOrder> orders = new ArrayList<ClientPurchaseOrder>();
for (ClientTransaction clientTransaction : selectedRecords) {
if (clientTransaction instanceof ClientPurchaseOrder) {
orders.add((ClientPurchaseOrder) clientTransaction);
}
}
transaction.setPurchaseOrders(orders);
}
if (transaction.getTransactionItems() != null && !isInViewMode()) {
transaction.setTransactionItems(vendorAccountTransactionTable
.getAllRows());
transaction.getTransactionItems().addAll(
vendorItemTransactionTable.getAllRows());
}
if (currency != null) {
transaction.setCurrency(currency.getID());
}
vatTotalNonEditableText.setTransaction(transaction);
}
transactionTotalNonEditableText
.setAmount(getAmountInBaseCurrency(grandTotal));
foreignCurrencyamountLabel.setAmount(grandTotal);
}
@Override
public ValidationResult validate() {
ValidationResult result = super.validate();
// Validations
// 1. isValidTransactionDate?
// 2. isInPreventPostingBeforeDate?
// 3. form validations
// 4. isValidDueOrDeliveryDate?
// 5. isBlankTransaction?
// 6. validateGrid?
// if (!AccounterValidator.isValidTransactionDate(transactionDate)) {
// result.addError(transactionDate,
// messages.invalidateTransactionDate());
// }
if (AccounterValidator.isInPreventPostingBeforeDate(transactionDate)) {
result.addError(transactionDate, messages.invalidateDate());
}
result.add(vendorForm.validate());
result.add(termsForm.validate());
if (!AccounterValidator.isValidDueOrDelivaryDates(
deliveryDateItem.getEnteredDate(), this.transactionDate)) {
result.addError(deliveryDateItem,
messages.the() + " " + messages.deliveryDate() + " " + " "
+ messages.cannotbeearlierthantransactiondate());
}
boolean isSelected = transactionsTree.validateTree();
if (!isSelected) {
if (transaction.getTotal() <= 0
&& vendorAccountTransactionTable.isEmpty()
&& vendorItemTransactionTable.isEmpty()) {
result.addError(this,
messages.transactiontotalcannotbe0orlessthan0());
}
result.add(vendorAccountTransactionTable.validateGrid());
result.add(vendorItemTransactionTable.validateGrid());
} else {
boolean hasTransactionItems = false;
for (ClientTransactionItem clientTransactionItem : getAllTransactionItems()) {
if (clientTransactionItem.getAccount() != 0
|| clientTransactionItem.getItem() != 0) {
hasTransactionItems = true;
continue;
}
}
if (hasTransactionItems) {
result.add(vendorAccountTransactionTable.validateGrid());
result.add(vendorItemTransactionTable.validateGrid());
} else {
transaction
.setTransactionItems(new ArrayList<ClientTransactionItem>());
}
}
if (!isSelected && isTrackTax() && isTrackPaidTax()
&& !isTaxPerDetailLine()) {
if (taxCodeSelect != null
&& taxCodeSelect.getSelectedValue() == null) {
result.addError(taxCodeSelect,
messages.pleaseSelect(messages.taxCode()));
}
} else if (isSelected && isTrackTax() && isTrackPaidTax()
&& !isTaxPerDetailLine()
&& !transaction.getTransactionItems().isEmpty()) {
if (taxCodeSelect != null
&& taxCodeSelect.getSelectedValue() == null) {
result.addError(taxCodeSelect,
messages.pleaseSelect(messages.taxCode()));
}
}
return result;
}
protected void getPurchaseOrdersAndItemReceipt() {
if (this.rpcUtilService == null
|| !getPreferences().isPurchaseOrderEnabled())
return;
if (getVendor() == null) {
Accounter.showError(messages.pleaseSelectThePayee(Global.get()
.Vendor()));
} else {
AccounterAsyncCallback<ArrayList<PurchaseOrdersAndItemReceiptsList>> callback = new AccounterAsyncCallback<ArrayList<PurchaseOrdersAndItemReceiptsList>>() {
@Override
public void onException(AccounterException caught) {
// Accounter.showError(FinanceApplication.constants()
// .noPurchaseOrderAndItemReceiptForVendor()
// + vendor.getName());
return;
}
@Override
public void onResultSuccess(
ArrayList<PurchaseOrdersAndItemReceiptsList> result) {
if (result == null) {
onFailure(new Exception());
} else {
List<ClientPurchaseOrder> salesAndEstimates = transaction
.getPurchaseOrders();
if (transaction.getID() != 0 && !result.isEmpty()) {
ArrayList<PurchaseOrdersAndItemReceiptsList> estimatesList = new ArrayList<PurchaseOrdersAndItemReceiptsList>();
ArrayList<ClientTransaction> notAvailableEstimates = new ArrayList<ClientTransaction>();
for (ClientTransaction clientTransaction : salesAndEstimates) {
boolean isThere = false;
for (PurchaseOrdersAndItemReceiptsList estimatesalesorderlist : result) {
if (estimatesalesorderlist
.getTransactionId() == clientTransaction
.getID()) {
estimatesList
.add(estimatesalesorderlist);
isThere = true;
}
}
if (!isThere) {
notAvailableEstimates
.add(clientTransaction);
}
}
if (transaction.isDraft()) {
for (ClientTransaction clientTransaction : notAvailableEstimates) {
salesAndEstimates.remove(clientTransaction);
}
}
for (PurchaseOrdersAndItemReceiptsList estimatesAndSalesOrdersList : estimatesList) {
result.remove(estimatesAndSalesOrdersList);
}
}
transactionsTree.setAllrows(result,
transaction.getID() == 0 ? true
: salesAndEstimates.isEmpty());
if (transaction.getPurchaseOrders() != null) {
transactionsTree
.setRecords(new ArrayList<ClientTransaction>(
transaction.getPurchaseOrders()));
}
transactionsTree.setEnabled(!isInViewMode());
refreshTransactionGrid();
}
}
};
this.rpcUtilService.getPurchasesAndItemReceiptsList(getVendor()
.getID(), callback);
}
// if (vendor == null)
// Accounter.showError("Please Select the Vendor");
// else
// new VendorBillListDialog(this).show();
}
@Override
public List<DynamicForm> getForms() {
return listforms;
}
/**
* call this method to set focus in View
*/
@Override
public void setFocus() {
this.vendorCombo.setFocus();
}
@Override
public void deleteFailed(AccounterException caught) {
}
@Override
public void deleteSuccess(IAccounterCore result) {
}
@Override
public void fitToSize(int height, int width) {
super.fitToSize(height, width);
}
@Override
protected void onLoad() {
}
@Override
public void onEdit() {
AccounterAsyncCallback<Boolean> editCallBack = new AccounterAsyncCallback<Boolean>() {
@Override
public void onException(AccounterException caught) {
Accounter.showError(AccounterExceptions.getErrorString(caught));
}
@Override
public void onResultSuccess(Boolean result) {
if (result)
enableFormItems();
}
};
AccounterCoreType type = UIUtils.getAccounterCoreType(transaction
.getType());
this.rpcDoSerivce.canEdit(type, transaction.id, editCallBack);
}
protected void enableFormItems() {
setMode(EditMode.EDIT);
vendorCombo.setEnabled(!isInViewMode());
transactionDateItem.setEnabled(!isInViewMode());
transactionNumber.setEnabled(!isInViewMode());
paymentMethodCombo.setEnabled(!isInViewMode());
if (printCheck.getValue().toString().equalsIgnoreCase("true")) {
checkNoText.setValue(messages.toBePrinted());
}
deliveryDateItem.setEnabled(!isInViewMode());
vendorAccountTransactionTable.setEnabled(!isInViewMode());
vendorItemTransactionTable.setEnabled(!isInViewMode());
accountTableButton.setEnabled(!isInViewMode());
itemTableButton.setEnabled(!isInViewMode());
memoTextAreaItem.setDisabled(isInViewMode());
discountField.setEnabled(!isInViewMode());
if (locationTrackingEnabled) {
locationCombo.setEnabled(!isInViewMode());
}
if (taxCodeSelect != null) {
taxCodeSelect.setEnabled(!isInViewMode());
}
if (currencyWidget != null) {
currencyWidget.setEnabled(!isInViewMode());
}
if (classListCombo != null) {
classListCombo.setEnabled(!isInViewMode());
}
transactionsTree.setEnabled(!isInViewMode());
super.onEdit();
}
protected void initViewType() {
}
@Override
public void print() {
updateTransaction();
UIUtils.downloadAttachment(transaction.getID(),
ClientTransaction.TYPE_CASH_PURCHASE);
}
@Override
public void printPreview() {
}
@Override
protected Double getTransactionTotal() {
return this.transactionTotalNonEditableText.getAmount();
}
private void resetFormView() {
// vendorForm.getCellFormatter().setWidth(0, 1, "200px");
// vendorForm.setWidth("75%");
// refText.setWidth("200px");
}
@Override
protected String getViewTitle() {
return messages.cashPurchases();
}
@Override
protected void taxCodeSelected(ClientTAXCode taxCode) {
this.taxCode = taxCode;
if (taxCode != null) {
taxCodeSelect.setComboItem(taxCode);
vendorAccountTransactionTable.setTaxCode(taxCode.getID(), true);
vendorItemTransactionTable.setTaxCode(taxCode.getID(), true);
} else {
taxCodeSelect.setValue("");
}
}
@Override
protected void addAllRecordToGrid(
List<ClientTransactionItem> transactionItems) {
vendorAccountTransactionTable
.setAllRows(getAccountTransactionItems(transactionItems));
vendorItemTransactionTable
.setAllRows(getItemTransactionItems(transactionItems));
refreshTransactionGrid();
}
@Override
protected void removeAllRecordsFromGrid() {
vendorAccountTransactionTable.removeAllRecords();
vendorItemTransactionTable.removeAllRecords();
}
@Override
protected void addNewData(ClientTransactionItem transactionItem) {
vendorAccountTransactionTable.add(transactionItem);
}
@Override
public List<ClientTransactionItem> getAllTransactionItems() {
List<ClientTransactionItem> list = new ArrayList<ClientTransactionItem>();
list.addAll(vendorAccountTransactionTable.getRecords());
list.addAll(vendorItemTransactionTable.getRecords());
return list;
}
@Override
protected void refreshTransactionGrid() {
vendorAccountTransactionTable.updateTotals();
vendorItemTransactionTable.updateTotals();
transactionsTree.updateTransactionTreeItemTotals();
}
private void settabIndexes() {
vendorCombo.setTabIndex(1);
contactCombo.setTabIndex(2);
phoneSelect.setTabIndex(3);
billToAreaItem.setTabIndex(4);
transactionDateItem.setTabIndex(5);
transactionNumber.setTabIndex(6);
paymentMethodCombo.setTabIndex(7);
payFromCombo.setTabIndex(8);
checkNoText.setTabIndex(9);
deliveryDateItem.setTabIndex(10);
memoTextAreaItem.setTabIndex(11);
// menuButton.setTabIndex(12);
if (saveAndCloseButton != null)
saveAndCloseButton.setTabIndex(13);
if (saveAndNewButton != null)
saveAndNewButton.setTabIndex(14);
cancelButton.setTabIndex(15);
}
@Override
protected void addAccountTransactionItem(ClientTransactionItem item) {
vendorAccountTransactionTable.add(item);
}
@Override
protected void addItemTransactionItem(ClientTransactionItem item) {
vendorItemTransactionTable.add(item);
}
@Override
public void updateAmountsFromGUI() {
modifyForeignCurrencyTotalWidget();
vendorAccountTransactionTable.updateAmountsFromGUI();
vendorItemTransactionTable.updateAmountsFromGUI();
}
public void modifyForeignCurrencyTotalWidget() {
String formalName = currencyWidget.getSelectedCurrency()
.getFormalName();
if (currencyWidget.isShowFactorField()) {
foreignCurrencyamountLabel.hide();
} else {
foreignCurrencyamountLabel.show();
foreignCurrencyamountLabel.setTitle(messages
.currencyTotal(formalName));
foreignCurrencyamountLabel.setCurrency(currencyWidget
.getSelectedCurrency());
}
netAmount.setTitle(messages.currencyNetAmount(formalName));
netAmount.setCurrency(currencyWidget.getSelectedCurrency());
}
@Override
protected void updateDiscountValues() {
if (discountField.getPercentage() != null) {
vendorItemTransactionTable.setDiscount(discountField
.getPercentage());
vendorAccountTransactionTable.setDiscount(discountField
.getPercentage());
} else {
discountField.setPercentage(0d);
}
}
private boolean isCustomerAllowedToAdd() {
if (transaction != null) {
List<ClientTransactionItem> transactionItems = transaction
.getTransactionItems();
for (ClientTransactionItem clientTransactionItem : transactionItems) {
if (clientTransactionItem.isBillable()
|| clientTransactionItem.getCustomer() != 0) {
return true;
}
}
}
if (getPreferences().isBillableExpsesEnbldForProductandServices()
&& getPreferences()
.isProductandSerivesTrackingByCustomerEnabled()) {
return true;
}
return false;
}
@Override
protected void classSelected(ClientAccounterClass accounterClass) {
this.accounterClass = accounterClass;
if (accounterClass != null) {
classListCombo.setComboItem(accounterClass);
vendorAccountTransactionTable
.setClass(accounterClass.getID(), true);
vendorItemTransactionTable.setClass(accounterClass.getID(), true);
} else {
classListCombo.setValue("");
}
}
@Override
public boolean allowEmptyTransactionItems() {
return true;
}
@Override
public boolean canPrint() {
EditMode mode = getMode();
if (mode == EditMode.CREATE || mode == EditMode.EDIT
|| data.getSaveStatus() == ClientTransaction.STATUS_DRAFT) {
return false;
} else {
return true;
}
}
@Override
public boolean canExportToCsv() {
return false;
}
@Override
protected void createButtons() {
super.createButtons();
accountTableButton = getAccountAddNewButton();
itemTableButton = getItemAddNewButton();
addButton(accountFlowPanel, accountTableButton);
addButton(itemsFlowPanel, itemTableButton);
}
@Override
protected void clearButtons() {
super.clearButtons();
removeButton(itemsFlowPanel, itemTableButton);
removeButton(accountFlowPanel, accountTableButton);
}
}
| 30.774843 | 159 | 0.731709 |
31ecaa2c1c58f3bb2e5810a9aa8587a628362bcf | 238 | package net.minecraft.server;
public interface ArmorMaterial {
int a(EnumItemSlot enumitemslot);
int b(EnumItemSlot enumitemslot);
int a();
SoundEffect b();
RecipeItemStack c();
float e();
float f();
}
| 12.526316 | 37 | 0.642857 |
fac35099090e821220eb2ddaefd473a72b4e2181 | 5,356 | /**
* Copyright © 2020-2021 ForgeRock AS ([email protected])
*
* 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 uk.org.openbanking.datamodel.service.converter.payment;
import uk.org.openbanking.datamodel.payment.*;
import static uk.org.openbanking.datamodel.service.converter.payment.OBConsentAuthorisationConverter.*;
import static uk.org.openbanking.datamodel.service.converter.payment.OBFileConverter.toOBFile1;
import static uk.org.openbanking.datamodel.service.converter.payment.OBFileConverter.toOBFile2;
import static uk.org.openbanking.datamodel.service.converter.payment.OBFileConverter.toOBWriteFile2DataInitiation;
public class OBWriteFileConsentConverter {
public static OBWriteFileConsent1 toOBWriteFileConsent1(OBWriteFileConsent2 obWriteFileConsent2) {
return (new OBWriteFileConsent1())
.data(toOBWriteDataFileConsent1(obWriteFileConsent2.getData()));
}
public static OBWriteFileConsent1 toOBWriteFileConsent1(OBWriteFileConsent3 writeFileConsent) {
return (new OBWriteFileConsent1())
.data(toOBWriteDataFileConsent1(writeFileConsent.getData()));
}
public static OBWriteFileConsent2 toOBWriteFileConsent2(OBWriteFileConsent1 obWriteFileConsent1) {
return (new OBWriteFileConsent2())
.data(toOBWriteDataFileConsent2(obWriteFileConsent1.getData()));
}
public static OBWriteFileConsent2 toOBWriteFileConsent2(OBWriteFileConsent3 obWriteFileConsent3) {
return (new OBWriteFileConsent2())
.data(toOBWriteDataFileConsent2(obWriteFileConsent3.getData()));
}
public static OBWriteFileConsent3 toOBWriteFileConsent3(OBWriteFileConsent1 obWriteFileConsent1) {
return obWriteFileConsent1 == null ? null : (new OBWriteFileConsent3())
.data(toOBWriteFileConsent3Data(obWriteFileConsent1.getData()));
}
public static OBWriteFileConsent3 toOBWriteFileConsent3(OBWriteFileConsent2 obWriteFileConsent2) {
return (new OBWriteFileConsent3())
.data(toOBWriteFileConsent3Data(obWriteFileConsent2.getData()));
}
public static OBWriteFile2 toOBWriteFile2(OBWriteFile1 obWriteFile1) {
return (new OBWriteFile2())
.data(toOBWriteFile2Data(obWriteFile1.getData()));
}
public static OBWriteDataFileConsent1 toOBWriteDataFileConsent1(OBWriteDataFileConsent2 data) {
return data == null ? null : (new OBWriteDataFileConsent1())
.initiation(toOBFile1(data.getInitiation()))
.authorisation(data.getAuthorisation());
}
public static OBWriteDataFileConsent1 toOBWriteDataFileConsent1(OBWriteFileConsent3Data data) {
return data == null ? null : (new OBWriteDataFileConsent1())
.initiation(toOBFile1(data.getInitiation()))
.authorisation(toOBAuthorisation1(data.getAuthorisation()));
}
public static OBWriteDataFileConsent2 toOBWriteDataFileConsent2(OBWriteDataFileConsent1 data) {
return data == null ? null : (new OBWriteDataFileConsent2())
.initiation(toOBFile2(data.getInitiation()))
.authorisation(data.getAuthorisation());
}
public static OBWriteDataFileConsent2 toOBWriteDataFileConsent2(OBWriteFileConsent3Data data) {
return data == null ? null : (new OBWriteDataFileConsent2())
.initiation(toOBFile2(data.getInitiation()))
.authorisation(toOBAuthorisation1(data.getAuthorisation()));
}
public static OBWriteDataFile2 toOBWriteDataFile2(OBWriteDataFile1 data) {
return data == null ? null : (new OBWriteDataFile2())
.consentId(data.getConsentId())
.initiation(toOBFile2(data.getInitiation()));
}
public static OBWriteFile2Data toOBWriteFile2Data(OBWriteDataFile1 data) {
return data == null ? null : (new OBWriteFile2Data())
.consentId(data.getConsentId())
.initiation(toOBWriteFile2DataInitiation(data.getInitiation()));
}
public static OBWriteFileConsent3Data toOBWriteFileConsent3Data(OBWriteDataFileConsent1 data) {
return data == null ? null : (new OBWriteFileConsent3Data())
.initiation(toOBWriteFile2DataInitiation(data.getInitiation()))
.authorisation(toOBWriteDomesticConsent4DataAuthorisation(data.getAuthorisation()))
.scASupportData(null);
}
public static OBWriteFileConsent3Data toOBWriteFileConsent3Data(OBWriteDataFileConsent2 data) {
return data == null ? null : (new OBWriteFileConsent3Data())
.initiation(toOBWriteFile2DataInitiation(data.getInitiation()))
.authorisation(toOBWriteDomesticConsent4DataAuthorisation(data.getAuthorisation()))
.scASupportData(null);
}
}
| 47.821429 | 114 | 0.723861 |
d71e9888f2812db0a567bda83616409b6381fb76 | 1,545 | /**
*
*/
package com.client;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.model.Conditional;
import com.model.Logical;
import com.model.Maths;
import com.model.ObjectAccess;
import com.model.Regex;
import com.model.StringOperation;
/**
* @author Ashwin
*
*/
public class Test {
private static ApplicationContext context;
/**
* @param args
*/
public static void main(String[] args) {
context = new ClassPathXmlApplicationContext("spring.xml");
Maths maths = context.getBean("math", Maths.class);
maths.display();
StringOperation operation = context.getBean("str", StringOperation.class);
System.out.println("\nString : " + operation.getStr());
Logical logical = context.getBean("logic", Logical.class);
System.out.println("\nLogical : " + logical.isAns());
Conditional conditional = context.getBean("conditional", Conditional.class);
System.out.println("\nConditional : " + conditional.getAns());
Regex regex = context.getBean("regex", Regex.class);
System.out.println("\nRegex : " + regex.isFlag());
System.out.println("Regex valisd string : " + regex.isValidString());
ObjectAccess access = context.getBean("objectAccess", ObjectAccess.class);
System.out.println("\nStringOperation object value : " + access.getStrValue());
System.out.println("Upper case : " + access.getUpper());
System.out.println("Lower case : " + access.getLower());
}
}
| 30.294118 | 82 | 0.702265 |
c837d60c8339eadf862c42b465539d6c4d0255a3 | 283 | package com.springdatarest.dataRepos;
import com.springdatarest.models.LandLord;
import org.springframework.data.repository.PagingAndSortingRepository;
/**
* Created by mac on 6/29/17.
*/
public interface LandLordRepository extends PagingAndSortingRepository<LandLord, Long> {
}
| 25.727273 | 88 | 0.816254 |
8a8ef718ba85407774cce50bfd64c80896c0b92c | 22,428 | package TestScript.B2B;
import org.testng.ITestContext;
import org.testng.annotations.Test;
import org.openqa.selenium.*;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.Select;
import org.openqa.selenium.support.ui.WebDriverWait;
import java.text.SimpleDateFormat;
import java.util.Date;
import CommonFunction.B2BCommon;
import CommonFunction.B2CCommon;
import CommonFunction.Common;
import CommonFunction.HMCCommon;
import Logger.Dailylog;
import Pages.B2BPage;
import Pages.HMCPage;
import TestScript.SuperTestClass;
public class NA16415Test extends SuperTestClass {
private String HMCWebUrl;
public String WebURL;
public String HMCUsername;
public String HMCPassword;
public NA16415Test(String Store) {
this.Store = Store;
this.testName = "NA-16415";
}
@Test(alwaysRun = true, groups = {"browsegroup", "uxui", "e2e", "b2b","compatibility"})
public void NA16415(ITestContext ctx) {
try {
this.prepareTest();
HMCPage page1 = new HMCPage(driver);
B2BPage page2 = new B2BPage(driver);
HMCWebUrl = testData.HMC.getHomePageUrl();
WebURL = testData.B2B.getLoginUrl();
HMCUsername = testData.HMC.getLoginId();
HMCPassword = testData.HMC.getPassword();
// int timeout = 1000;
String partNo = null;
float pricePLP = 0;
float pricePDP = 0;
float priceCart1 = 0;
float priceOrder = 0;
float priceTotal = 0;
float priceTax = 0;
String firstQuoteNum = null;
String secondQuoutNum = null;
String repId = "2900718028";
String CartURL = "";
String country = Store.toLowerCase();
String catelog = "Nemo Master Multi Country Product Catalog - Online";
String B2BUnit = testData.B2B.getB2BUnit();
System.out.println(country + ":" + B2BUnit);
String username_builder = country + "[email protected]";
String username_approver = country + "[email protected]";
Boolean isContract = true;
By byLocator7 = By.id("approveId");
By byLocator11 = By
.xpath("//div[@id='ui-datepicker-div']//tr[last()]/td/a");
By byLocator12 = By.xpath("//li[@class='menu_level_2']//span");
By byLocator8 = By
.xpath("//div[@id='bundleAlert']//div[@class='modal-content']");
By HMCLogin = By.id("Main_user");
Dailylog.logInfoDB(1, "Test run for: " + country, Store, testName);
if (country.equals("au")) {
CartURL = "https://pre-c-hybris.lenovo.com/le/adobe_global/au/en/1213654197/cart";
} else if (country.equals("us")) {
CartURL = "https://pre-c-hybris.lenovo.com/le/1213348423/us/en/1213577815/cart";
}
if (Browser.toLowerCase().equals("ie")) {
Common.NavigateToUrl(driver, Browser, HMCWebUrl);
} else {
driver.get(HMCWebUrl);
}
if (isAlertPresent() == true) {
Alert alert = driver.switchTo().alert();
alert.accept();
}
Thread.sleep(5000);
HMCCommon.Login(page1, testData);
driver.navigate().refresh();
HMCCommon.SetQuoteEnabledOnB2B(page1, driver, B2BUnit);
page1.Home_EndSessionLink.click();
if (Browser.toLowerCase().equals("firefox")
|| Browser.toLowerCase().equals("ie")) {
driver.get(WebURL.replaceAll("LIeCommerce:M0C0v0n3L!@", ""));
} else {
driver.get(WebURL);
}
B2BCommon.Login(page2, username_builder, "1q2w3e4r");
page2.HomePage_productsLink.click();
Thread.sleep(5000);
page2.HomePage_Laptop.click();
page2.productPage_agreementsAndContract.click();
try {
page2.productPage_raidoContractButton.click();
} catch (Exception e) {
isContract = false;
}
if (isContract) {
if (Common.isElementExist(driver,
By.xpath("//img[@title='Add to Cart']"))) {
assert B2BCommon
.verifyContractLabel(page2.HomePage_contractLable);
assert page2.ProductPage_addAccessories.isDisplayed();
assert page2.productPage_addToCart.isDisplayed();
pricePLP = GetPriceValue(page2.ProductPage_PriceOnPLP
.getText());
partNo = page2.ProductPage_PartNoOnPLP.getText();
Dailylog.logInfoDB(2, "PLP price is: " + pricePLP, Store,
testName);
Dailylog.logInfoDB(3, "part No is: " + partNo, Store,
testName);
page2.ProductPage_details.click();
Thread.sleep(8000);
assert page2.PDPPage_AddtoCart.isDisplayed();
assert page2.PDPPage_AddAccessories.isDisplayed();
pricePDP = GetPriceValue(page2.PDPPage_ProductPrice
.getText());
Dailylog.logInfoDB(4, "PDP price is: " + pricePDP, Store,
testName);
try {
Thread.sleep(8000);
page2.PDPPage_AddtoCart.click();
} catch (ElementNotVisibleException e) {
driver.navigate().refresh();
Thread.sleep(8000);
page2.PDPPage_AddtoCart.click();
} catch (TimeoutException e) {
driver.navigate().refresh();
Thread.sleep(8000);
page2.PDPPage_AddtoCart.click();
} catch (NoSuchElementException e) {
driver.navigate().refresh();
Thread.sleep(8000);
page2.PDPPage_AddtoCart.click();
}
if (Browser.toLowerCase().equals("ie")) {
((JavascriptExecutor) driver)
.executeScript("scroll(0,250)");
WebElement IEaddtoCart = driver.findElement(By
.xpath("//img[@title='Add to Cart']/.."));
IEaddtoCart.click();
}
page2.productPage_AlertAddToCart.click();
Thread.sleep(8000);
page2.ProductPage_AlertGoToCart.click();
try {
Thread.sleep(5000);
page2.cartPage_RequestQuoteBtn.isDisplayed();
page2.CartPage_Price1.isDisplayed();
} catch (NoSuchElementException e) {
driver.navigate().refresh();
Thread.sleep(5000);
} catch (TimeoutException e) {
driver.navigate().refresh();
Thread.sleep(5000);
}
page2.cartPage_RequestQuoteBtn.click();
try {
Thread.sleep(5000);
page2.cartPage_RepIDBox.sendKeys(repId);
} catch (ElementNotVisibleException e) {
driver.navigate().refresh();
Thread.sleep(5000);
page2.cartPage_RequestQuoteBtn.click();
page2.cartPage_RepIDBox.sendKeys(repId);
}
page2.cartPage_SubmitQuote.click();
firstQuoteNum = page2.cartPage_QuoteNumber.getText();
Dailylog.logInfoDB(5, "first quote number is: "
+ firstQuoteNum, Store, testName);
page2.CartPage_HomeLink.click();
page2.HomePage_productsLink.click();
Thread.sleep(5000);
page2.HomePage_Laptop.click();
page2.productPage_agreementsAndContract.click();
page2.productPage_raidoContractButton.click();
/*
* if(Common.isElementExsit(driver,By.id(""))){
* page2.MenuProduct.click(); Thread.sleep(5000);
* page2.Desktop.click(); }
*/
page2.ProductPage_addAccessories.click();
Thread.sleep(2000);
if (driver.getCurrentUrl().equals(CartURL)) {
Thread.sleep(5000);
} else {
driver.get(CartURL);
}
try {
page2.cartPage_RequestQuoteBtn.isDisplayed();
page2.CartPage_Price1.isDisplayed();
} catch (NoSuchElementException e) {
driver.navigate().refresh();
Thread.sleep(5000);
} catch (TimeoutException e) {
driver.navigate().refresh();
Thread.sleep(5000);
}
priceCart1 = GetPriceValue(page2.CartPage_Price1.getText());
Dailylog.logInfoDB(6, "Cart price is: " + priceCart1,
Store, testName);
page2.cartPage_RequestQuoteBtn.click();
try {
Thread.sleep(5000);
page2.cartPage_RepIDBox.sendKeys(repId);
} catch (ElementNotVisibleException e) {
driver.navigate().refresh();
Thread.sleep(5000);
page2.cartPage_RequestQuoteBtn.click();
page2.cartPage_RepIDBox.sendKeys(repId);
}
page2.cartPage_SubmitQuote.click();
secondQuoutNum = page2.cartPage_QuoteNumber.getText();
Dailylog.logInfoDB(7, "second quote number is: "
+ secondQuoutNum, Store, testName);
} else {
Dailylog.logInfoDB(20, "No product can be used", Store,
testName);
assert false;
}
} else {
if (Common.isElementExist(driver,
By.xpath("//img[@title='Customize and buy']"))) {
assert B2BCommon
.verifyContractLabel(page2.HomePage_contractLable);
assert page2.HomePage_Customize.isDisplayed();
pricePLP = GetPriceValue(page2.ProductPage_PriceOnPLP
.getText());
partNo = page2.ProductPage_PartNoOnPLP.getText();
Dailylog.logInfoDB(2, "PLP price is: " + pricePLP, Store,
testName);
Dailylog.logInfoDB(3, "part No is: " + partNo, Store,
testName);
page2.ProductPage_details.click();
Thread.sleep(3000);
if (driver.findElement(
By.xpath("//button[text()='Customize']"))
.isDisplayed()) {
System.out.println("here is ------");
driver.findElement(
By.xpath("(//button[@class='close' and text()='×'])[2]"))
.click();
Thread.sleep(5000);
}
pricePDP = GetPriceValue(page2.PDPPage_ProductPrice_CTO
.getText());
Dailylog.logInfoDB(4, "PDP price is: " + pricePDP, Store,
testName);
try {
Thread.sleep(8000);
page2.Agreement_agreementsAddToCart.click();
} catch (ElementNotVisibleException e) {
driver.navigate().refresh();
Thread.sleep(8000);
page2.Agreement_agreementsAddToCart.click();
} catch (TimeoutException e) {
driver.navigate().refresh();
Thread.sleep(8000);
page2.Agreement_agreementsAddToCart.click();
} catch (NoSuchElementException e) {
driver.navigate().refresh();
Thread.sleep(8000);
page2.Agreement_agreementsAddToCart.click();
}
if (driver.getCurrentUrl().equals(CartURL)) {
Thread.sleep(5000);
} else if (driver.getCurrentUrl().contains("cart")) {
page2.Agreement_addToCartAccessoryBtn.click();
Thread.sleep(5000);
}
try {
Thread.sleep(5000);
page2.cartPage_RequestQuoteBtn.isDisplayed();
page2.CartPage_Price1.isDisplayed();
} catch (NoSuchElementException e) {
driver.navigate().refresh();
Thread.sleep(5000);
} catch (TimeoutException e) {
driver.navigate().refresh();
Thread.sleep(5000);
}
page2.cartPage_RequestQuoteBtn.click();
try {
Thread.sleep(5000);
page2.cartPage_RepIDBox.sendKeys(repId);
} catch (ElementNotVisibleException e) {
driver.navigate().refresh();
Thread.sleep(5000);
page2.cartPage_RequestQuoteBtn.click();
page2.cartPage_RepIDBox.sendKeys(repId);
}
page2.cartPage_SubmitQuote.click();
firstQuoteNum = page2.cartPage_QuoteNumber.getText();
Dailylog.logInfoDB(5, "first quote number is: "
+ firstQuoteNum, Store, testName);
page2.CartPage_HomeLink.click();
page2.HomePage_productsLink.click();
Thread.sleep(5000);
page2.HomePage_Laptop.click();
page2.productPage_agreementsAndContract.click();
page2.HomePage_Customize.click();
Thread.sleep(3000);
if (driver.findElement(
By.xpath("//button[text()='Customize']"))
.isDisplayed()) {
System.out.println("here is ------");
driver.findElement(
By.xpath("(//button[@class='close' and text()='×'])[2]"))
.click();
Thread.sleep(5000);
}
try {
Thread.sleep(8000);
page2.Agreement_agreementsAddToCart.click();
} catch (ElementNotVisibleException e) {
driver.navigate().refresh();
Thread.sleep(8000);
page2.Agreement_agreementsAddToCart.click();
} catch (TimeoutException e) {
driver.navigate().refresh();
Thread.sleep(8000);
page2.Agreement_agreementsAddToCart.click();
} catch (NoSuchElementException e) {
driver.navigate().refresh();
Thread.sleep(8000);
page2.Agreement_agreementsAddToCart.click();
}
if (driver.getCurrentUrl().equals(CartURL)) {
Thread.sleep(5000);
} else if (driver.getCurrentUrl().contains("cart")) {
page2.Agreement_addToCartAccessoryBtn.click();
Thread.sleep(5000);
}
try {
page2.cartPage_RequestQuoteBtn.isDisplayed();
page2.CartPage_Price1.isDisplayed();
} catch (NoSuchElementException e) {
driver.navigate().refresh();
Thread.sleep(5000);
} catch (TimeoutException e) {
driver.navigate().refresh();
Thread.sleep(5000);
}
priceCart1 = GetPriceValue(page2.CartPage_Price1.getText());
Dailylog.logInfoDB(6, "Cart price is: " + priceCart1,
Store, testName);
page2.cartPage_RequestQuoteBtn.click();
try {
Thread.sleep(5000);
page2.cartPage_RepIDBox.sendKeys(repId);
} catch (ElementNotVisibleException e) {
driver.navigate().refresh();
Thread.sleep(5000);
page2.cartPage_RequestQuoteBtn.click();
page2.cartPage_RepIDBox.sendKeys(repId);
}
page2.cartPage_SubmitQuote.click();
secondQuoutNum = page2.cartPage_QuoteNumber.getText();
Dailylog.logInfoDB(7, "second quote number is: "
+ secondQuoutNum, Store, testName);
} else {
Dailylog.logInfoDB(20, "No product can be used", Store,
testName);
assert false;
}
}
page2.homepage_MyAccount.click();
Thread.sleep(5000);
/*
* if(!Common.isElementExsit(driver,byLocator12)){
* Thread.sleep(3000); } driver.findElement(byLocator12).click();
*/
page2.myAccountPage_ViewQuotehistory.click();
driver.findElement(By.linkText(firstQuoteNum)).click();
Select sel = new Select(driver.findElement(byLocator7));
sel.selectByValue(username_approver.toUpperCase());
page2.placeOrderPage_sendApproval.click();
Common.sleep(5000);
driver.findElement(By.linkText(secondQuoutNum)).click();
driver.findElement(
By.xpath("//select[@id='approveId']/option[@value='"
+ username_approver.toUpperCase() + "']")).click();
page2.placeOrderPage_sendApproval.click();
page2.homepage_Signout.click();
B2BCommon.Login(page2, username_approver, "1q2w3e4r");
page2.homepage_MyAccount.click();
Thread.sleep(5000);
/*
* if(!Common.isElementExsit(driver,byLocator12)){
* Thread.sleep(3000); } driver.findElement(byLocator12).click();
*/
page2.myAccountPage_viewQuoteRequireApproval.click();
Thread.sleep(10000);
try {
driver.findElement(By.id(firstQuoteNum)).click();
} catch (Exception e) {
page2.ApprovalDashBoard_Search.click();
driver.findElement(By.id(firstQuoteNum)).click();
}
page2.QuotePage_clickRejectButton.click();
driver.findElement(By.id(secondQuoutNum)).click();
page2.QuotePage_clickApproveButton.click();
Dailylog.logInfoDB(8, firstQuoteNum + " has been rejected, "
+ secondQuoutNum + " has been approved", Store, testName);
page2.homepage_Signout.click();
B2BCommon.Login(page2, username_builder, "1q2w3e4r");
page2.homepage_MyAccount.click();
Thread.sleep(8000);
/*
* if(!Common.isElementExsit(driver,byLocator12)){
* Thread.sleep(3000); } driver.findElement(byLocator12).click();
*/
page2.myAccountPage_ViewQuotehistory.click();
By byLocatorsFirstQuoteStatus = By.xpath("//a[text()='"
+ firstQuoteNum + "']/../../td[3]/p");
By byLocatorsSecondQuoteStatus = By.xpath("//a[text()='"
+ secondQuoutNum + "']/../../td[3]/p");
assert driver.findElement(byLocatorsFirstQuoteStatus).getText()
.equals("INTERNALREJECTED");
assert driver.findElement(byLocatorsSecondQuoteStatus).getText()
.equals("INTERNALAPPROVED");
driver.findElement(By.linkText(secondQuoutNum)).click();
page2.cartPage_ConvertToOrderBtn.click();
Dailylog.logInfoDB(9, "Starting covert quote to order", Store,
testName);
Thread.sleep(5000);
if (Store.toLowerCase().equals("us")) {
B2BCommon.fillB2BShippingInfo(driver, page2, "us",
"test000001", "test000001", "Georgia", "1535 Broadway",
"New York", "New York", "10036-4077", "2129450100");
} else if (Store.toLowerCase().equals("au")) {
B2BCommon.fillB2BShippingInfo(driver, page2, "au",
"test000001", "test000001", "adobe_global",
"62 Streeton Dr", "RIVETT",
"Australian Capital Territory", "2611", "2123981900");
}
// 23 ,Enter the required fields of shipping address and select the
// shipping method,then click *Continue* to go to payment step of
// checkout.
Thread.sleep(3000);
page2.shippingPage_ContinueToPayment.click();
new WebDriverWait(driver, 500)
.until(ExpectedConditions
.elementToBeClickable(page2.paymentPage_ContinueToPlaceOrder));
Thread.sleep(3000);
if (Common.isElementExist(driver, By.id("group-shipping-address"))) {
page2.shippingPage_validateFromOk.click();
}
page2.paymentPage_PurchaseOrder.click();
Thread.sleep(8000);
page2.paymentPage_purchaseNum.clear();
page2.paymentPage_purchaseNum.sendKeys("123456");
/*
* SimpleDateFormat dataFormat = new SimpleDateFormat("MM/dd/YYYY");
* //page2.paymentPage_purchaseDate.sendKeys(dataFormat.format(new
* Date()).toString()); if(Common.isElementExist(driver,By.xpath(
* "//div[@id='ui-datepicker-div']//tr[last()]/td/a"))){
* driver.findElements
* (byLocator11).get(driver.findElements(byLocator11
* ).size()-1).click(); }
*/
page2.purchaseDate.click();
driver.findElements(byLocator11)
.get(driver.findElements(byLocator11).size() - 1).click();
Thread.sleep(8000);
B2BCommon.fillDefaultB2bBillingAddress (driver,page2, testData);
// page2.paymentPage_ContinueToPlaceOrder.click();
Thread.sleep(5000);
if (Common.isElementExist(driver, By.id("resellerID"))) {
page2.placeOrderPage_ResellerID.sendKeys(repId);
}
Common.scrollToElement(driver, page2.placeOrderPage_Terms);
page2.placeOrderPage_Terms.click();
driver.findElement(
By.xpath("//select[@id='approveId']/option[@value='"
+ username_approver.toUpperCase() + "']")).click();
page2.placeOrderPage_sendForApproval.click();
priceOrder = GetPriceValue(page2.OrderPage_subTotalPrice.getText());
priceTotal = GetPriceValue(page2.OrderPage_TotalPrice.getText());
if (Common
.isElementExist(
driver,
By.xpath("(.//*[@class='checkout-confirm-orderSummary-orderTotals-subTotal'])[2]"))) {
System.out.println(page2.OrderPage_TaxPrice.getText());
priceTax = GetPriceValue(page2.OrderPage_TaxPrice.getText());
} else {
priceTax = 0;
}
/* if(Common.isElementExsit(driver,By.xpath("(./ *//*
* [@class=
* 'checkout-confirm-orderSummary-orderTotals-subTotal'])[2]"))){
* priceShipping
* = Common.
* GetPriceValue
* (
* page2.TaxPrice
* .getText());
* }else{
* priceTax = 0;
* }
*/
Dailylog.logInfoDB(10, "Price on order: " + priceOrder, Store,
testName);
assert (page2.placeOrderPage_OrderNumber.getText()
.equals(secondQuoutNum));
//assert (priceOrder == pricePDP) && (priceCart1 == priceOrder);// &&(pricePDP
// ==
// pricePLP);
Dailylog.logInfoDB(11, "Convert to order successfully", Store,
testName);
page2.homepage_Signout.click();
B2BCommon.Login(page2, username_approver, "1q2w3e4r");
page2.homepage_MyAccount.click();
Thread.sleep(5000);
/*
* if(!Common.isElementExsit(driver,byLocator12)){
* Thread.sleep(3000); } driver.findElement(byLocator12).click();
*/
page2.myAccountPage_viewOrderRequireApproval.click();
try {
driver.findElement(By.id(secondQuoutNum)).click();
} catch (Exception e) {
page2.ApprovalDashBoard_Search.click();
driver.findElement(By.id(secondQuoutNum)).click();
}
page2.QuotePage_clickApproveButton.click();
Thread.sleep(5000);
page2.homepage_Signout.click();
// driver.get(HMCWebUrl);
Thread.sleep(5000);
if (Browser.toLowerCase().equals("ie")) {
Common.NavigateToUrl(driver, Browser, HMCWebUrl);
} else {
driver.get(HMCWebUrl);
}
Thread.sleep(5000);
/*
* driver.manage().deleteAllCookies(); Thread.sleep(10000);
* driver.get(HMCWebUrl);
*/
if (Common.isElementExist(driver, HMCLogin)) {
HMCCommon.Login(page1, testData);
driver.navigate().refresh();
}
Dailylog.logInfoDB(12, "Price of Tax: " + priceTax, Store, testName);
Dailylog.logInfoDB(13, "Price of Total: " + priceTotal, Store,
testName);
// Common.SimulateB2BPrice(page1, driver, coun, country, catelog,
// B2BUnit, partNo, pricePDP);
HMCOrderCheck(page1, secondQuoutNum, priceTax, priceTotal);
} catch (Throwable e) {
handleThrowable(e, ctx);
}
}
public void HMCOrderCheck(HMCPage page1, String OrderNumber,
float TaxPrice, float ProductPrice) throws Exception {
By byLocators01 = By
.xpath("//div[contains(text(),'Incl. Tax:')]/../../td[5]//input");
Thread.sleep(5000);
page1.Home_Order.click();
page1.Home_Order_Orders.click();
page1.Home_Order_OrderID.clear();
page1.Home_Order_OrderID.sendKeys(OrderNumber);
page1.Home_Order_OrderSearch.click();
Thread.sleep(5000);
if (!page1.Home_Order_OrderStatus.getText().contains("Completed")) {
Thread.sleep(5000);
page1.Home_Order_OrderSearch.click();
}
assert page1.Home_Order_OrderStatus.getText().contains("Completed");
page1.Home_Order_OrderDetail.click();
// page1.OrderReload.click();
Thread.sleep(5000);
Dailylog.logInfoDB(14, "Order Status is Completed", Store, testName);
if (!Common.isElementExist(driver, byLocators01)) {
assert 0.0 == TaxPrice;
}
assert TaxPrice == GetPriceValue(page1.Home_Order_TaxPrice
.getAttribute("value"));
assert ProductPrice == GetPriceValue(page1.Home_Order_ProductPrice
.getAttribute("value"));
page1.Home_Order_OrderAdmin.click();
Thread.sleep(5000);
assert page1.Orders_OrderXML.getText().contains("xml");
}
public float GetPriceValue(String Price) {
if (Price.contains("FREE") || Price.contains("INCLUDED")) {
return 0;
}
Price = Price.replaceAll("\\$", "");
Price = Price.replaceAll("CAD", "");
Price = Price.replaceAll("$", "");
Price = Price.replaceAll(",", "");
Price = Price.replaceAll("\\*", "");
Price = Price.trim();
float priceValue;
priceValue = Float.parseFloat(Price);
return priceValue;
}
public boolean isAlertPresent() {
try {
driver.switchTo().alert();
return true;
} catch (NoAlertPresentException Ex) {
return false;
}
}
} | 35.487342 | 93 | 0.667068 |
9e89b7ba442adfcd8a5aea4532aa6e178b493bfc | 217 | package com.iwares.qbatis;
import java.util.List;
public interface ThinDao<DataType, KeyType> {
public DataType selectThin(KeyType id);
public List<DataType> selectThinConditional(Condition condition);
}
| 18.083333 | 69 | 0.769585 |
efea70fddca29148b036f82614843dab4a4a3b12 | 666 | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package planer;
/**
*
* @author PC
*/
public class Koordinate {
double k1;
double k2;
public Koordinate(double k1, double k2) {
this.k1 = k1;
this.k2 = k2;
}
public double getK1() {
return k1;
}
public void setK1(double k1) {
this.k1 = k1;
}
public double getK2() {
return k2;
}
public void setK2(double k2) {
this.k2 = k2;
}
}
| 17.076923 | 80 | 0.533033 |
9d2bd86abf9c40b6ccfc23efc71979d148add236 | 3,223 | package com.bmtc.svn.domain;
import java.sql.Timestamp;
import com.bmtc.boc.domain.BocBaseDO;
/**
* SVN用户权限信息类
* @author lpf7161
*
*/
public class SvnUserAuthz extends BocBaseDO {
/**
* svn用户权限id
*/
private long id;
/**
* svn用户权限
*/
private String svnUserAuthz;
/**
* svn路径
*/
private String svnPath;
/**
* svn用户id
*/
private long svnUserId;
/**
* svn库id
*/
private long svnRepoId;
/**
* svn库名
*/
private String svnRepoName;
/**
* 审批状态
* 0:待审批,1:已审批
*/
private long status;
/**
* svn用户权限创建时间
*/
private Timestamp svnUserAuthzCreateDate = SvnUserAuthz.getNowTimestamp();
/**
* svn用户权限修改时间
*/
private Timestamp svnUserAuthzModifyDate = SvnUserAuthz.getNowTimestamp();
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getSvnUserAuthz() {
return svnUserAuthz;
}
public void setSvnUserAuthz(String svnUserAuthz) {
this.svnUserAuthz = svnUserAuthz;
}
public String getSvnPath() {
return svnPath;
}
public void setSvnPath(String svnPath) {
this.svnPath = svnPath;
}
public long getSvnUserId() {
return svnUserId;
}
public void setSvnUserId(long svnUserId) {
this.svnUserId = svnUserId;
}
public long getSvnRepoId() {
return svnRepoId;
}
public void setSvnRepoId(long svnRepoId) {
this.svnRepoId = svnRepoId;
}
public long getStatus() {
return status;
}
public void setStatus(long status) {
this.status = status;
}
public Timestamp getSvnUserAuthzCreateDate() {
return svnUserAuthzCreateDate;
}
public void setSvnUserAuthzCreateDate(Timestamp svnUserAuthzCreateDate) {
this.svnUserAuthzCreateDate = SvnUserAuthz.getNowTimestamp();
}
public Timestamp getSvnUserAuthzModifyDate() {
return svnUserAuthzModifyDate;
}
public void setSvnUserAuthzModifyDate(Timestamp svnUserAuthzModifyDate) {
this.svnUserAuthzModifyDate = SvnUserAuthz.getNowTimestamp();
}
public String getSvnRepoName() {
return svnRepoName;
}
public void setSvnRepoName(String svnRepoName) {
this.svnRepoName = svnRepoName;
}
@Override
public String toString() {
return "SvnUserAuthz [id=" + id + ", svnUserAuthz=" + svnUserAuthz
+ ", svnPath=" + svnPath + ", svnUserId=" + svnUserId
+ ", svnRepoId=" + svnRepoId + ", svnRepoName=" + svnRepoName
+ ", status=" + status + ", svnUserAuthzCreateDate="
+ svnUserAuthzCreateDate + ", svnUserAuthzModifyDate="
+ svnUserAuthzModifyDate + "]";
}
public SvnUserAuthz(long id, String svnUserAuthz, String svnPath,
long svnUserId, long svnRepoId, String svnRepoName, long status,
Timestamp svnUserAuthzCreateDate, Timestamp svnUserAuthzModifyDate) {
super();
this.id = id;
this.svnUserAuthz = svnUserAuthz;
this.svnPath = svnPath;
this.svnUserId = svnUserId;
this.svnRepoId = svnRepoId;
this.svnRepoName = svnRepoName;
this.status = status;
this.svnUserAuthzCreateDate = svnUserAuthzCreateDate;
this.svnUserAuthzModifyDate = svnUserAuthzModifyDate;
}
public SvnUserAuthz() {
super();
}
}
| 19.773006 | 76 | 0.670804 |
3bde5608472486f30c815fbdc4c3d5b0d6c3d1ef | 263 | package edu.uoc.lti.deeplink.content;
import lombok.Builder;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
/**
* @author Created by [email protected]
*/
@Getter
@Setter
@ToString
@Builder
public class Embed {
private final String html;
}
| 14.611111 | 37 | 0.756654 |
3ee3eaf0fe2157fe61959a4b6b04b842a221d1d2 | 776 |
package com.krishagni.catissueplus.core.biospecimen.repository;
import java.util.Date;
import java.util.List;
import com.krishagni.catissueplus.core.biospecimen.domain.Participant;
import com.krishagni.catissueplus.core.biospecimen.events.PmiDetail;
import com.krishagni.catissueplus.core.common.repository.Dao;
public interface ParticipantDao extends Dao<Participant> {
public Participant getByUid(String uid);
public Participant getByEmpi(String empi);
public List<Participant> getByLastNameAndBirthDate(String lname, Date dob);
public List<Participant> getByPmis(List<PmiDetail> pmis);
public List<Long> getParticipantIdsByPmis(List<PmiDetail> pmis);
public boolean isUidUnique(String uid);
public boolean isPmiUnique(String siteName, String mrn);
}
| 28.740741 | 76 | 0.814433 |
ddf1cb001819dc762daafa2b3482e6a286cbf8c8 | 1,346 | /* $Id$ */
package com.linkedin.parseq.example.simple;
import com.linkedin.parseq.Engine;
import com.linkedin.parseq.Task;
import com.linkedin.parseq.example.common.AbstractExample;
import com.linkedin.parseq.example.common.ExampleUtil;
import com.linkedin.parseq.example.common.MockService;
import java.util.concurrent.TimeUnit;
import static com.linkedin.parseq.Tasks.timeoutWithError;
import static com.linkedin.parseq.example.common.ExampleUtil.fetchUrl;
/**
* @author Chris Pettitt ([email protected])
*/
public class TimeoutWithErrorExample extends AbstractExample
{
public static void main(String[] args) throws Exception
{
new TimeoutWithErrorExample().runExample();
}
@Override
protected void doRunExample(final Engine engine) throws Exception
{
final MockService<String> httpClient = getService();
final Task<String> fetch = fetchUrl(httpClient, "http://www.google.com");
final Task<String> fetchWithTimeout =
timeoutWithError(50, TimeUnit.MILLISECONDS, fetch);
engine.run(fetchWithTimeout);
fetchWithTimeout.await();
System.out.println(!fetchWithTimeout.isFailed()
? "Received result: " + fetchWithTimeout.get()
: "Error: " + fetchWithTimeout.getError());
ExampleUtil.printTracingResults(fetchWithTimeout);
}
}
| 29.911111 | 77 | 0.732541 |
c689ead1a5bda388d025ec723c27a4fa18cbf989 | 724 | package com.zl.way.city.api.model;
public class WayCityResponse {
private Integer id;
private String name;
private String adcode;
private String citycode;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAdcode() {
return adcode;
}
public void setAdcode(String adcode) {
this.adcode = adcode;
}
public String getCitycode() {
return citycode;
}
public void setCitycode(String citycode) {
this.citycode = citycode;
}
}
| 16.088889 | 46 | 0.585635 |
e33c695810a936b6d95355a0b812a1aedb6104fb | 2,290 | package org.folio.rest.utils.nameresolver;
import io.vertx.core.Context;
import io.vertx.core.Future;
import io.vertx.core.buffer.Buffer;
import io.vertx.core.json.JsonObject;
import io.vertx.core.logging.Logger;
import io.vertx.core.logging.LoggerFactory;
import io.vertx.ext.web.client.HttpRequest;
import io.vertx.ext.web.client.WebClient;
import java.util.Map;
import org.apache.commons.lang3.ObjectUtils;
import org.folio.okapi.common.XOkapiHeaders;
public class OrgaizationNameResolver {
private static final Logger logger = LoggerFactory.getLogger(OrgaizationNameResolver.class);
private static final String ORGANIZATION_ENDPOINT = "/organizations-storage/organizations/";
private OrgaizationNameResolver() {
throw new IllegalStateException("Utility class");
}
public static Future<String> resolveName(
String organizationId, Map<String, String> okapiHeaders, Context vertxContext) {
Future<String> future = Future.future();
if (organizationId == null) {
return Future.succeededFuture();
}
String endpoint = ORGANIZATION_ENDPOINT + organizationId;
WebClient webClient = WebClient.create(vertxContext.owner());
String url =
ObjectUtils.firstNonNull(
okapiHeaders.get(XOkapiHeaders.URL_TO), okapiHeaders.get(XOkapiHeaders.URL))
+ endpoint;
HttpRequest<Buffer> request = webClient.getAbs(url);
okapiHeaders.forEach(request::putHeader);
request.putHeader("accept", "application/json");
request.send(
ar -> {
if (ar.succeeded()) {
if (ar.result().statusCode() == 200) {
JsonObject orgaJson = ar.result().bodyAsJsonObject();
String orgaName = orgaJson.getString("name");
logger.info("Found organization name " + orgaName + " for id " + organizationId);
future.complete(orgaName);
} else {
logger.warn(
"Failure while looking for organization name for id "
+ organizationId
+ ". Will proceed without setting orga name.",
ar.cause());
future.complete();
}
} else {
future.fail(ar.cause());
}
});
return future;
}
}
| 34.179104 | 95 | 0.653275 |
6abb2f41a576f6814651324e48efaa1b8066fc17 | 4,611 | package net.tslat.aoawikihelpermod.dataprintouts;
import net.minecraft.command.ICommandSender;
import net.minecraft.entity.EntityLiving;
import net.minecraft.item.ItemStack;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.text.TextComponentString;
import net.minecraft.world.World;
import net.minecraft.world.storage.loot.LootPool;
import net.minecraft.world.storage.loot.LootTable;
import net.minecraftforge.fml.common.FMLCommonHandler;
import net.minecraftforge.fml.common.ObfuscationReflectionHelper;
import net.minecraftforge.fml.common.registry.EntityEntry;
import net.minecraftforge.fml.common.registry.ForgeRegistries;
import net.tslat.aoa3.advent.AdventOfAscension;
import net.tslat.aoawikihelpermod.AoAWikiHelperMod;
import net.tslat.aoawikihelpermod.loottables.AccessibleLootTable;
import org.apache.commons.io.IOUtils;
import java.io.File;
import java.io.PrintWriter;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
public class DataPrintoutWriter {
public static File configDir = null;
private static PrintWriter writer = null;
public static void writeItemEntityDropsList(ICommandSender sender, ItemStack targetStack, boolean copyToClipboard) {
if (writer != null) {
sender.sendMessage(new TextComponentString("You're already outputting data! Wait a moment and try again"));
return;
}
String fileName = targetStack.getItem().getItemStackDisplayName(targetStack) + " Output Trades.txt";
ArrayList<String> entities = new ArrayList<String>();
World world = FMLCommonHandler.instance().getMinecraftServerInstance().getWorld(0);
Method lootTableMethod = ObfuscationReflectionHelper.findMethod(EntityLiving.class, "func_184647_J", ResourceLocation.class);
enableWriter(fileName);
for (EntityEntry entry : ForgeRegistries.ENTITIES.getValuesCollection()) {
if (!EntityLiving.class.isAssignableFrom(entry.getEntityClass()))
continue;
EntityLiving entity = (EntityLiving)entry.newInstance(world);
LootTable table;
try {
ResourceLocation tableLocation = (ResourceLocation)lootTableMethod.invoke(entity);
if (tableLocation == null)
continue;
table = world.getLootTableManager().getLootTableFromLocation(tableLocation);
}
catch (Exception e) {
continue;
}
if (table == LootTable.EMPTY_LOOT_TABLE)
continue;
List<LootPool> pools = ObfuscationReflectionHelper.getPrivateValue(LootTable.class, table, "field_186466_c");
AccessibleLootTable accessibleTable = new AccessibleLootTable(pools, "");
for (AccessibleLootTable.AccessibleLootPool pool : accessibleTable.pools) {
for (AccessibleLootTable.AccessibleLootEntry poolEntry : pool.lootEntries) {
if (poolEntry.item == targetStack.getItem())
entities.add(entity.getDisplayName().getUnformattedText());
}
}
}
if (entities.size() >= 15) {
write("Click 'Expand' to see a list of mobs that drop " + targetStack.getItem().getItemStackDisplayName(targetStack));
write("<div class=\"mw-collapsible mw-collapsed\">");
}
entities.sort(Comparator.naturalOrder());
entities.forEach(e -> write("* [[" + e + "]]"));
disableWriter();
sender.sendMessage(AoAWikiHelperMod.generateInteractiveMessagePrintout("Printed out " + entities.size() + " entities that drop ", new File(configDir, fileName), targetStack.getDisplayName(), copyToClipboard && AoAWikiHelperMod.copyFileToClipboard(new File(configDir, fileName)) ? ". Copied to clipboard" : ""));
}
public static void writeData(String name, List<String> data, ICommandSender sender, boolean copyToClipboard) {
String fileName = name + " Printout " + AdventOfAscension.version + ".txt";
enableWriter(fileName);
data.forEach(DataPrintoutWriter::write);
disableWriter();
sender.sendMessage(AoAWikiHelperMod.generateInteractiveMessagePrintout("Generated data file: ", new File(configDir, fileName), name, copyToClipboard && AoAWikiHelperMod.copyFileToClipboard(new File(configDir, fileName)) ? ". Copied to clipboard" : ""));
}
private static void enableWriter(final String fileName) {
configDir = AoAWikiHelperMod.prepConfigDir("Data Printouts");
File streamFile = new File(configDir, fileName);
try {
if (streamFile.exists())
streamFile.delete();
streamFile.createNewFile();
writer = new PrintWriter(streamFile);
}
catch (Exception e) {}
}
private static void disableWriter() {
if (writer != null)
IOUtils.closeQuietly(writer);
writer = null;
}
private static void write(String line) {
if (writer != null)
writer.println(line);
}
}
| 35.744186 | 313 | 0.763826 |
1464092b2571dc77624433fc833558d129ae0500 | 33,353 | /*
* Copyright 2013 The Netty Project
*
* The Netty Project licenses this file to you under the Apache License,
* version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package io.netty.util.internal;
import io.netty.util.internal.logging.InternalLogger;
import io.netty.util.internal.logging.InternalLoggerFactory;
import sun.misc.Unsafe;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.nio.Buffer;
import java.nio.ByteBuffer;
import java.security.AccessController;
import java.security.PrivilegedAction;
import static io.netty.util.internal.ObjectUtil.checkNotNull;
/**
* The {@link PlatformDependent} operations which requires access to {@code sun.misc.*}.
*/
final class PlatformDependent0 {
private static final InternalLogger logger = InternalLoggerFactory.getInstance(PlatformDependent0.class);
private static final long ADDRESS_FIELD_OFFSET;
private static final long BYTE_ARRAY_BASE_OFFSET;
private static final Constructor<?> DIRECT_BUFFER_CONSTRUCTOR;
private static final boolean IS_EXPLICIT_NO_UNSAFE = explicitNoUnsafe0();
private static final Method ALLOCATE_ARRAY_METHOD;
private static final int JAVA_VERSION = javaVersion0();
private static final boolean IS_ANDROID = isAndroid0();
private static final Object INTERNAL_UNSAFE;
static final Unsafe UNSAFE;
// constants borrowed from murmur3
static final int HASH_CODE_ASCII_SEED = 0xc2b2ae35;
static final int HASH_CODE_C1 = 0xcc9e2d51;
static final int HASH_CODE_C2 = 0x1b873593;
/**
* Limits the number of bytes to copy per {@link Unsafe#copyMemory(long, long, long)} to allow safepoint polling
* during a large copy.
*/
private static final long UNSAFE_COPY_THRESHOLD = 1024L * 1024L;
private static final boolean UNALIGNED;
static {
final ByteBuffer direct;
Field addressField = null;
Method allocateArrayMethod = null;
Unsafe unsafe;
Object internalUnsafe = null;
if (isExplicitNoUnsafe()) {
direct = null;
addressField = null;
unsafe = null;
internalUnsafe = null;
} else {
direct = ByteBuffer.allocateDirect(1);
// attempt to access field Unsafe#theUnsafe
final Object maybeUnsafe = AccessController.doPrivileged(new PrivilegedAction<Object>() {
@Override
public Object run() {
try {
final Field unsafeField = Unsafe.class.getDeclaredField("theUnsafe");
Throwable cause = ReflectionUtil.trySetAccessible(unsafeField);
if (cause != null) {
return cause;
}
// the unsafe instance
return unsafeField.get(null);
} catch (NoSuchFieldException e) {
return e;
} catch (SecurityException e) {
return e;
} catch (IllegalAccessException e) {
return e;
}
}
});
// the conditional check here can not be replaced with checking that maybeUnsafe
// is an instanceof Unsafe and reversing the if and else blocks; this is because an
// instanceof check against Unsafe will trigger a class load and we might not have
// the runtime permission accessClassInPackage.sun.misc
if (maybeUnsafe instanceof Exception) {
unsafe = null;
logger.debug("sun.misc.Unsafe.theUnsafe: unavailable", (Exception) maybeUnsafe);
} else {
unsafe = (Unsafe) maybeUnsafe;
logger.debug("sun.misc.Unsafe.theUnsafe: available");
}
// ensure the unsafe supports all necessary methods to work around the mistake in the latest OpenJDK
// https://github.com/netty/netty/issues/1061
// http://www.mail-archive.com/[email protected]/msg00698.html
if (unsafe != null) {
final Unsafe finalUnsafe = unsafe;
final Object maybeException = AccessController.doPrivileged(new PrivilegedAction<Object>() {
@Override
public Object run() {
try {
finalUnsafe.getClass().getDeclaredMethod(
"copyMemory", Object.class, long.class, Object.class, long.class, long.class);
return null;
} catch (NoSuchMethodException e) {
return e;
} catch (SecurityException e) {
return e;
}
}
});
if (maybeException == null) {
logger.debug("sun.misc.Unsafe.copyMemory: available");
} else {
// Unsafe.copyMemory(Object, long, Object, long, long) unavailable.
unsafe = null;
logger.debug("sun.misc.Unsafe.copyMemory: unavailable", (Throwable) maybeException);
}
}
if (unsafe != null) {
final Unsafe finalUnsafe = unsafe;
// attempt to access field Buffer#address
final Object maybeAddressField = AccessController.doPrivileged(new PrivilegedAction<Object>() {
@Override
public Object run() {
try {
final Field field = Buffer.class.getDeclaredField("address");
// Use Unsafe to read value of the address field. This way it will not fail on JDK9+ which
// will forbid changing the access level via reflection.
final long offset = finalUnsafe.objectFieldOffset(field);
final long address = finalUnsafe.getLong(direct, offset);
// if direct really is a direct buffer, address will be non-zero
if (address == 0) {
return null;
}
return field;
} catch (NoSuchFieldException e) {
return e;
} catch (SecurityException e) {
return e;
}
}
});
if (maybeAddressField instanceof Field) {
addressField = (Field) maybeAddressField;
logger.debug("java.nio.Buffer.address: available");
} else {
logger.debug("java.nio.Buffer.address: unavailable", (Throwable) maybeAddressField);
// If we cannot access the address of a direct buffer, there's no point of using unsafe.
// Let's just pretend unsafe is unavailable for overall simplicity.
unsafe = null;
}
}
if (unsafe != null) {
// There are assumptions made where ever BYTE_ARRAY_BASE_OFFSET is used (equals, hashCodeAscii, and
// primitive accessors) that arrayIndexScale == 1, and results are undefined if this is not the case.
long byteArrayIndexScale = unsafe.arrayIndexScale(byte[].class);
if (byteArrayIndexScale != 1) {
logger.debug("unsafe.arrayIndexScale is {} (expected: 1). Not using unsafe.", byteArrayIndexScale);
unsafe = null;
}
}
}
UNSAFE = unsafe;
if (unsafe == null) {
ADDRESS_FIELD_OFFSET = -1;
BYTE_ARRAY_BASE_OFFSET = -1;
UNALIGNED = false;
DIRECT_BUFFER_CONSTRUCTOR = null;
ALLOCATE_ARRAY_METHOD = null;
} else {
Constructor<?> directBufferConstructor;
long address = -1;
try {
final Object maybeDirectBufferConstructor =
AccessController.doPrivileged(new PrivilegedAction<Object>() {
@Override
public Object run() {
try {
final Constructor<?> constructor =
direct.getClass().getDeclaredConstructor(long.class, int.class);
Throwable cause = ReflectionUtil.trySetAccessible(constructor);
if (cause != null) {
return cause;
}
return constructor;
} catch (NoSuchMethodException e) {
return e;
} catch (SecurityException e) {
return e;
}
}
});
if (maybeDirectBufferConstructor instanceof Constructor<?>) {
address = UNSAFE.allocateMemory(1);
// try to use the constructor now
try {
((Constructor<?>) maybeDirectBufferConstructor).newInstance(address, 1);
directBufferConstructor = (Constructor<?>) maybeDirectBufferConstructor;
logger.debug("direct buffer constructor: available");
} catch (InstantiationException e) {
directBufferConstructor = null;
} catch (IllegalAccessException e) {
directBufferConstructor = null;
} catch (InvocationTargetException e) {
directBufferConstructor = null;
}
} else {
logger.debug(
"direct buffer constructor: unavailable",
(Throwable) maybeDirectBufferConstructor);
directBufferConstructor = null;
}
} finally {
if (address != -1) {
UNSAFE.freeMemory(address);
}
}
DIRECT_BUFFER_CONSTRUCTOR = directBufferConstructor;
ADDRESS_FIELD_OFFSET = objectFieldOffset(addressField);
BYTE_ARRAY_BASE_OFFSET = UNSAFE.arrayBaseOffset(byte[].class);
boolean unaligned;
Object maybeUnaligned = AccessController.doPrivileged(new PrivilegedAction<Object>() {
@Override
public Object run() {
try {
Class<?> bitsClass =
Class.forName("java.nio.Bits", false, getSystemClassLoader());
Method unalignedMethod = bitsClass.getDeclaredMethod("unaligned");
Throwable cause = ReflectionUtil.trySetAccessible(unalignedMethod);
if (cause != null) {
return cause;
}
return unalignedMethod.invoke(null);
} catch (NoSuchMethodException e) {
return e;
} catch (SecurityException e) {
return e;
} catch (IllegalAccessException e) {
return e;
} catch (ClassNotFoundException e) {
return e;
} catch (InvocationTargetException e) {
return e;
}
}
});
if (maybeUnaligned instanceof Boolean) {
unaligned = (Boolean) maybeUnaligned;
logger.debug("java.nio.Bits.unaligned: available, {}", unaligned);
} else {
String arch = SystemPropertyUtil.get("os.arch", "");
//noinspection DynamicRegexReplaceableByCompiledPattern
unaligned = arch.matches("^(i[3-6]86|x86(_64)?|x64|amd64)$");
Throwable t = (Throwable) maybeUnaligned;
logger.debug("java.nio.Bits.unaligned: unavailable {}", unaligned, t);
}
UNALIGNED = unaligned;
if (javaVersion() >= 9) {
Object maybeException = AccessController.doPrivileged(new PrivilegedAction<Object>() {
@Override
public Object run() {
try {
// Java9 has jdk.internal.misc.Unsafe and not all methods are propagated to
// sun.misc.Unsafe
Class<?> internalUnsafeClass = getClassLoader(PlatformDependent0.class)
.loadClass("jdk.internal.misc.Unsafe");
Method method = internalUnsafeClass.getDeclaredMethod("getUnsafe");
return method.invoke(null);
} catch (Throwable e) {
return e;
}
}
});
if (!(maybeException instanceof Throwable)) {
internalUnsafe = maybeException;
final Object finalInternalUnsafe = internalUnsafe;
maybeException = AccessController.doPrivileged(new PrivilegedAction<Object>() {
@Override
public Object run() {
try {
return finalInternalUnsafe.getClass().getDeclaredMethod(
"allocateUninitializedArray", Class.class, int.class);
} catch (NoSuchMethodException e) {
return e;
} catch (SecurityException e) {
return e;
}
}
});
if (maybeException instanceof Method) {
try {
Method m = (Method) maybeException;
byte[] bytes = (byte[]) m.invoke(finalInternalUnsafe, byte.class, 8);
assert bytes.length == 8;
allocateArrayMethod = m;
} catch (IllegalAccessException e) {
maybeException = e;
} catch (InvocationTargetException e) {
maybeException = e;
}
}
}
if (maybeException instanceof Throwable) {
logger.debug("jdk.internal.misc.Unsafe.allocateUninitializedArray(int): unavailable",
(Throwable) maybeException);
} else {
logger.debug("jdk.internal.misc.Unsafe.allocateUninitializedArray(int): available");
}
} else {
logger.debug("jdk.internal.misc.Unsafe.allocateUninitializedArray(int): unavailable prior to Java9");
}
ALLOCATE_ARRAY_METHOD = allocateArrayMethod;
}
INTERNAL_UNSAFE = internalUnsafe;
logger.debug("java.nio.DirectByteBuffer.<init>(long, int): {}",
DIRECT_BUFFER_CONSTRUCTOR != null ? "available" : "unavailable");
}
static boolean isExplicitNoUnsafe() {
return IS_EXPLICIT_NO_UNSAFE;
}
private static boolean explicitNoUnsafe0() {
final boolean noUnsafe = SystemPropertyUtil.getBoolean("io.netty.noUnsafe", false);
logger.debug("-Dio.netty.noUnsafe: {}", noUnsafe);
if (noUnsafe) {
logger.debug("sun.misc.Unsafe: unavailable (io.netty.noUnsafe)");
return true;
}
// Legacy properties
boolean tryUnsafe;
if (SystemPropertyUtil.contains("io.netty.tryUnsafe")) {
tryUnsafe = SystemPropertyUtil.getBoolean("io.netty.tryUnsafe", true);
} else {
tryUnsafe = SystemPropertyUtil.getBoolean("org.jboss.netty.tryUnsafe", true);
}
if (!tryUnsafe) {
logger.debug("sun.misc.Unsafe: unavailable (io.netty.tryUnsafe/org.jboss.netty.tryUnsafe)");
return true;
}
return false;
}
static boolean isUnaligned() {
return UNALIGNED;
}
static boolean hasUnsafe() {
return UNSAFE != null;
}
static boolean unalignedAccess() {
return UNALIGNED;
}
static void throwException(Throwable cause) {
// JVM has been observed to crash when passing a null argument. See https://github.com/netty/netty/issues/4131.
UNSAFE.throwException(checkNotNull(cause, "cause"));
}
static boolean hasDirectBufferNoCleanerConstructor() {
return DIRECT_BUFFER_CONSTRUCTOR != null;
}
static ByteBuffer reallocateDirectNoCleaner(ByteBuffer buffer, int capacity) {
return newDirectBuffer(UNSAFE.reallocateMemory(directBufferAddress(buffer), capacity), capacity);
}
static ByteBuffer allocateDirectNoCleaner(int capacity) {
return newDirectBuffer(UNSAFE.allocateMemory(capacity), capacity);
}
static boolean hasAllocateArrayMethod() {
return ALLOCATE_ARRAY_METHOD != null;
}
static byte[] allocateUninitializedArray(int size) {
try {
return (byte[]) ALLOCATE_ARRAY_METHOD.invoke(INTERNAL_UNSAFE, byte.class, size);
} catch (IllegalAccessException e) {
throw new Error(e);
} catch (InvocationTargetException e) {
throw new Error(e);
}
}
static ByteBuffer newDirectBuffer(long address, int capacity) {
ObjectUtil.checkPositiveOrZero(capacity, "capacity");
try {
return (ByteBuffer) DIRECT_BUFFER_CONSTRUCTOR.newInstance(address, capacity);
} catch (Throwable cause) {
// Not expected to ever throw!
if (cause instanceof Error) {
throw (Error) cause;
}
throw new Error(cause);
}
}
static long directBufferAddress(ByteBuffer buffer) {
return getLong(buffer, ADDRESS_FIELD_OFFSET);
}
static long byteArrayBaseOffset() {
return BYTE_ARRAY_BASE_OFFSET;
}
static Object getObject(Object object, long fieldOffset) {
return UNSAFE.getObject(object, fieldOffset);
}
static int getInt(Object object, long fieldOffset) {
return UNSAFE.getInt(object, fieldOffset);
}
private static long getLong(Object object, long fieldOffset) {
return UNSAFE.getLong(object, fieldOffset);
}
static long objectFieldOffset(Field field) {
return UNSAFE.objectFieldOffset(field);
}
static byte getByte(long address) {
return UNSAFE.getByte(address);
}
static short getShort(long address) {
return UNSAFE.getShort(address);
}
static int getInt(long address) {
return UNSAFE.getInt(address);
}
static long getLong(long address) {
return UNSAFE.getLong(address);
}
static byte getByte(byte[] data, int index) {
return UNSAFE.getByte(data, BYTE_ARRAY_BASE_OFFSET + index);
}
static short getShort(byte[] data, int index) {
return UNSAFE.getShort(data, BYTE_ARRAY_BASE_OFFSET + index);
}
static int getInt(byte[] data, int index) {
return UNSAFE.getInt(data, BYTE_ARRAY_BASE_OFFSET + index);
}
static long getLong(byte[] data, int index) {
return UNSAFE.getLong(data, BYTE_ARRAY_BASE_OFFSET + index);
}
static void putByte(long address, byte value) {
UNSAFE.putByte(address, value);
}
static void putShort(long address, short value) {
UNSAFE.putShort(address, value);
}
static void putInt(long address, int value) {
UNSAFE.putInt(address, value);
}
static void putLong(long address, long value) {
UNSAFE.putLong(address, value);
}
static void putByte(byte[] data, int index, byte value) {
UNSAFE.putByte(data, BYTE_ARRAY_BASE_OFFSET + index, value);
}
static void putShort(byte[] data, int index, short value) {
UNSAFE.putShort(data, BYTE_ARRAY_BASE_OFFSET + index, value);
}
static void putInt(byte[] data, int index, int value) {
UNSAFE.putInt(data, BYTE_ARRAY_BASE_OFFSET + index, value);
}
static void putLong(byte[] data, int index, long value) {
UNSAFE.putLong(data, BYTE_ARRAY_BASE_OFFSET + index, value);
}
static void copyMemory(long srcAddr, long dstAddr, long length) {
//UNSAFE.copyMemory(srcAddr, dstAddr, length);
while (length > 0) {
long size = Math.min(length, UNSAFE_COPY_THRESHOLD);
UNSAFE.copyMemory(srcAddr, dstAddr, size);
length -= size;
srcAddr += size;
dstAddr += size;
}
}
static void copyMemory(Object src, long srcOffset, Object dst, long dstOffset, long length) {
//UNSAFE.copyMemory(src, srcOffset, dst, dstOffset, length);
while (length > 0) {
long size = Math.min(length, UNSAFE_COPY_THRESHOLD);
UNSAFE.copyMemory(src, srcOffset, dst, dstOffset, size);
length -= size;
srcOffset += size;
dstOffset += size;
}
}
static void setMemory(long address, long bytes, byte value) {
UNSAFE.setMemory(address, bytes, value);
}
static void setMemory(Object o, long offset, long bytes, byte value) {
UNSAFE.setMemory(o, offset, bytes, value);
}
static boolean equals(byte[] bytes1, int startPos1, byte[] bytes2, int startPos2, int length) {
if (length <= 0) {
return true;
}
final long baseOffset1 = BYTE_ARRAY_BASE_OFFSET + startPos1;
final long baseOffset2 = BYTE_ARRAY_BASE_OFFSET + startPos2;
int remainingBytes = length & 7;
final long end = baseOffset1 + remainingBytes;
for (long i = baseOffset1 - 8 + length, j = baseOffset2 - 8 + length; i >= end; i -= 8, j -= 8) {
if (UNSAFE.getLong(bytes1, i) != UNSAFE.getLong(bytes2, j)) {
return false;
}
}
if (remainingBytes >= 4) {
remainingBytes -= 4;
if (UNSAFE.getInt(bytes1, baseOffset1 + remainingBytes) !=
UNSAFE.getInt(bytes2, baseOffset2 + remainingBytes)) {
return false;
}
}
if (remainingBytes >= 2) {
return UNSAFE.getChar(bytes1, baseOffset1) == UNSAFE.getChar(bytes2, baseOffset2) &&
(remainingBytes == 2 || bytes1[startPos1 + 2] == bytes2[startPos2 + 2]);
}
return bytes1[startPos1] == bytes2[startPos2];
}
static int equalsConstantTime(byte[] bytes1, int startPos1, byte[] bytes2, int startPos2, int length) {
long result = 0;
final long baseOffset1 = BYTE_ARRAY_BASE_OFFSET + startPos1;
final long baseOffset2 = BYTE_ARRAY_BASE_OFFSET + startPos2;
final int remainingBytes = length & 7;
final long end = baseOffset1 + remainingBytes;
for (long i = baseOffset1 - 8 + length, j = baseOffset2 - 8 + length; i >= end; i -= 8, j -= 8) {
result |= UNSAFE.getLong(bytes1, i) ^ UNSAFE.getLong(bytes2, j);
}
switch (remainingBytes) {
case 7:
return ConstantTimeUtils.equalsConstantTime(result |
(UNSAFE.getInt(bytes1, baseOffset1 + 3) ^ UNSAFE.getInt(bytes2, baseOffset2 + 3)) |
(UNSAFE.getChar(bytes1, baseOffset1 + 1) ^ UNSAFE.getChar(bytes2, baseOffset2 + 1)) |
(UNSAFE.getByte(bytes1, baseOffset1) ^ UNSAFE.getByte(bytes2, baseOffset2)), 0);
case 6:
return ConstantTimeUtils.equalsConstantTime(result |
(UNSAFE.getInt(bytes1, baseOffset1 + 2) ^ UNSAFE.getInt(bytes2, baseOffset2 + 2)) |
(UNSAFE.getChar(bytes1, baseOffset1) ^ UNSAFE.getChar(bytes2, baseOffset2)), 0);
case 5:
return ConstantTimeUtils.equalsConstantTime(result |
(UNSAFE.getInt(bytes1, baseOffset1 + 1) ^ UNSAFE.getInt(bytes2, baseOffset2 + 1)) |
(UNSAFE.getByte(bytes1, baseOffset1) ^ UNSAFE.getByte(bytes2, baseOffset2)), 0);
case 4:
return ConstantTimeUtils.equalsConstantTime(result |
(UNSAFE.getInt(bytes1, baseOffset1) ^ UNSAFE.getInt(bytes2, baseOffset2)), 0);
case 3:
return ConstantTimeUtils.equalsConstantTime(result |
(UNSAFE.getChar(bytes1, baseOffset1 + 1) ^ UNSAFE.getChar(bytes2, baseOffset2 + 1)) |
(UNSAFE.getByte(bytes1, baseOffset1) ^ UNSAFE.getByte(bytes2, baseOffset2)), 0);
case 2:
return ConstantTimeUtils.equalsConstantTime(result |
(UNSAFE.getChar(bytes1, baseOffset1) ^ UNSAFE.getChar(bytes2, baseOffset2)), 0);
case 1:
return ConstantTimeUtils.equalsConstantTime(result |
(UNSAFE.getByte(bytes1, baseOffset1) ^ UNSAFE.getByte(bytes2, baseOffset2)), 0);
default:
return ConstantTimeUtils.equalsConstantTime(result, 0);
}
}
static boolean isZero(byte[] bytes, int startPos, int length) {
if (length <= 0) {
return true;
}
final long baseOffset = BYTE_ARRAY_BASE_OFFSET + startPos;
int remainingBytes = length & 7;
final long end = baseOffset + remainingBytes;
for (long i = baseOffset - 8 + length; i >= end; i -= 8) {
if (UNSAFE.getLong(bytes, i) != 0) {
return false;
}
}
if (remainingBytes >= 4) {
remainingBytes -= 4;
if (UNSAFE.getInt(bytes, baseOffset + remainingBytes) != 0) {
return false;
}
}
if (remainingBytes >= 2) {
return UNSAFE.getChar(bytes, baseOffset) == 0 &&
(remainingBytes == 2 || bytes[startPos + 2] == 0);
}
return bytes[startPos] == 0;
}
static int hashCodeAscii(byte[] bytes, int startPos, int length) {
int hash = HASH_CODE_ASCII_SEED;
final long baseOffset = BYTE_ARRAY_BASE_OFFSET + startPos;
final int remainingBytes = length & 7;
final long end = baseOffset + remainingBytes;
for (long i = baseOffset - 8 + length; i >= end; i -= 8) {
hash = hashCodeAsciiCompute(UNSAFE.getLong(bytes, i), hash);
}
switch(remainingBytes) {
case 7:
return ((hash * HASH_CODE_C1 + hashCodeAsciiSanitize(UNSAFE.getByte(bytes, baseOffset)))
* HASH_CODE_C2 + hashCodeAsciiSanitize(UNSAFE.getShort(bytes, baseOffset + 1)))
* HASH_CODE_C1 + hashCodeAsciiSanitize(UNSAFE.getInt(bytes, baseOffset + 3));
case 6:
return (hash * HASH_CODE_C1 + hashCodeAsciiSanitize(UNSAFE.getShort(bytes, baseOffset)))
* HASH_CODE_C2 + hashCodeAsciiSanitize(UNSAFE.getInt(bytes, baseOffset + 2));
case 5:
return (hash * HASH_CODE_C1 + hashCodeAsciiSanitize(UNSAFE.getByte(bytes, baseOffset)))
* HASH_CODE_C2 + hashCodeAsciiSanitize(UNSAFE.getInt(bytes, baseOffset + 1));
case 4:
return hash * HASH_CODE_C1 + hashCodeAsciiSanitize(UNSAFE.getInt(bytes, baseOffset));
case 3:
return (hash * HASH_CODE_C1 + hashCodeAsciiSanitize(UNSAFE.getByte(bytes, baseOffset)))
* HASH_CODE_C2 + hashCodeAsciiSanitize(UNSAFE.getShort(bytes, baseOffset + 1));
case 2:
return hash * HASH_CODE_C1 + hashCodeAsciiSanitize(UNSAFE.getShort(bytes, baseOffset));
case 1:
return hash * HASH_CODE_C1 + hashCodeAsciiSanitize(UNSAFE.getByte(bytes, baseOffset));
default:
return hash;
}
}
static int hashCodeAsciiCompute(long value, int hash) {
// masking with 0x1f reduces the number of overall bits that impact the hash code but makes the hash
// code the same regardless of character case (upper case or lower case hash is the same).
return hash * HASH_CODE_C1 +
// Low order int
hashCodeAsciiSanitize((int) value) * HASH_CODE_C2 +
// High order int
(int) ((value & 0x1f1f1f1f00000000L) >>> 32);
}
static int hashCodeAsciiSanitize(int value) {
return value & 0x1f1f1f1f;
}
static int hashCodeAsciiSanitize(short value) {
return value & 0x1f1f;
}
static int hashCodeAsciiSanitize(byte value) {
return value & 0x1f;
}
static ClassLoader getClassLoader(final Class<?> clazz) {
if (System.getSecurityManager() == null) {
return clazz.getClassLoader();
} else {
return AccessController.doPrivileged(new PrivilegedAction<ClassLoader>() {
@Override
public ClassLoader run() {
return clazz.getClassLoader();
}
});
}
}
static ClassLoader getContextClassLoader() {
if (System.getSecurityManager() == null) {
return Thread.currentThread().getContextClassLoader();
} else {
return AccessController.doPrivileged(new PrivilegedAction<ClassLoader>() {
@Override
public ClassLoader run() {
return Thread.currentThread().getContextClassLoader();
}
});
}
}
static ClassLoader getSystemClassLoader() {
if (System.getSecurityManager() == null) {
return ClassLoader.getSystemClassLoader();
} else {
return AccessController.doPrivileged(new PrivilegedAction<ClassLoader>() {
@Override
public ClassLoader run() {
return ClassLoader.getSystemClassLoader();
}
});
}
}
static int addressSize() {
return UNSAFE.addressSize();
}
static long allocateMemory(long size) {
return UNSAFE.allocateMemory(size);
}
static void freeMemory(long address) {
UNSAFE.freeMemory(address);
}
static long reallocateMemory(long address, long newSize) {
return UNSAFE.reallocateMemory(address, newSize);
}
static boolean isAndroid() {
return IS_ANDROID;
}
private static boolean isAndroid0() {
boolean android;
try {
Class.forName("android.app.Application", false, getSystemClassLoader());
android = true;
} catch (Throwable ignored) {
// Failed to load the class uniquely available in Android.
android = false;
}
if (android) {
logger.debug("Platform: Android");
}
return android;
}
static int javaVersion() {
return JAVA_VERSION;
}
private static int javaVersion0() {
final int majorVersion;
if (isAndroid0()) {
majorVersion = 6;
} else {
majorVersion = majorVersionFromJavaSpecificationVersion();
}
logger.debug("Java version: {}", majorVersion);
return majorVersion;
}
// Package-private for testing only
static int majorVersionFromJavaSpecificationVersion() {
return majorVersion(SystemPropertyUtil.get("java.specification.version", "1.6"));
}
// Package-private for testing only
static int majorVersion(final String javaSpecVersion) {
final String[] components = javaSpecVersion.split("\\.");
final int[] version = new int[components.length];
for (int i = 0; i < components.length; i++) {
version[i] = Integer.parseInt(components[i]);
}
if (version[0] == 1) {
assert version[1] >= 6;
return version[1];
} else {
return version[0];
}
}
private PlatformDependent0() {
}
}
| 40.378935 | 119 | 0.554103 |
f7c92efbb064652d86fd20b34089f718077ff7f2 | 210 | package com.globallypaid.exception;
public class ForbiddenException extends GloballyPaidException {
public ForbiddenException(Integer code, String message, Throwable e) {
super(code, message, e);
}
}
| 23.333333 | 72 | 0.77619 |
2a74f1b04eb38faa4e204ef0f2c40762423cfdc8 | 200 | package objects;
public class Person extends GameObject {
int hp;
Weapon weapon;
public Room room;
boolean isDead() {
if (hp <= 0) {
return true;
}
return false;
}
}
| 11.764706 | 41 | 0.59 |
a364f6faf52af2f3c729bcf966f28d135b6c9c68 | 4,935 | /*
* Copyright 2014 - 2021 Blazebit.
*
* 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.blazebit.persistence.testsuite.base;
import com.blazebit.persistence.testsuite.base.jpa.AbstractJpaPersistenceTest;
import com.blazebit.persistence.testsuite.base.jpa.cleaner.DatabaseCleaner;
import org.eclipse.persistence.config.PersistenceUnitProperties;
import org.eclipse.persistence.internal.jpa.EntityManagerFactoryProvider;
import org.eclipse.persistence.internal.jpa.EntityManagerSetupImpl;
import org.eclipse.persistence.sessions.factories.SessionManager;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import java.sql.Connection;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
/**
*
* @author Christian Beikov
* @since 1.0.0
*/
public abstract class AbstractPersistenceTest extends AbstractJpaPersistenceTest {
@Override
protected Properties applyProperties(Properties properties) {
// properties.put("eclipselink.ddl-generation", "drop-and-create-tables");
properties.put("eclipselink.cache.shared.default", "false");
properties.put("eclipselink.logging.logger", "JavaLogger");
properties.put("eclipselink.logging.parameters", "true");
// Disable the session part of the logging
properties.put("eclipselink.logging.session", "false");
// Give the session a easy name so we can have normal logging config
properties.put("eclipselink.session-name", "default");
properties.put(PersistenceUnitProperties.SESSION_CUSTOMIZER, SchemaModifyingSessionCustomizer.class.getName());
if (getSchemaMode() == SchemaMode.JPA) {
SchemaModifyingSessionCustomizer.setSchemaName(getTargetSchema());
}
return properties;
}
@Override
protected boolean supportsMapKeyDeReference() {
return true;
}
@Override
protected boolean supportsInverseSetCorrelationJoinsSubtypesWhenJoined() {
return true;
}
@Override
protected void addIgnores(DatabaseCleaner applicableCleaner) {
applicableCleaner.addIgnoredTable("SEQUENCE");
}
@Override
protected Connection getConnection(EntityManager em) {
EntityTransaction tx = em.getTransaction();
boolean startedTransaction = !tx.isActive();
if (startedTransaction) {
tx.begin();
}
return em.unwrap(Connection.class);
}
@Override
protected void clearSchemaUsingJpa() {
Map<String, EntityManagerSetupImpl> emSetupImpls = EntityManagerFactoryProvider.getEmSetupImpls();
Map<String, EntityManagerSetupImpl> copy = new HashMap<>(emSetupImpls);
emSetupImpls.clear();
SessionManager manager = SessionManager.getManager();
for (EntityManagerSetupImpl emSetupImpl : copy.values()) {
manager.getSessions().remove(emSetupImpl.getSessionName());
}
try {
super.clearSchemaUsingJpa();
} finally {
emSetupImpls.putAll(copy);
for (EntityManagerSetupImpl emSetupImpl : copy.values()) {
manager.addSession(emSetupImpl.getSession());
}
}
}
@Override
protected EntityManagerFactory repopulateSchema() {
Map<String, EntityManagerSetupImpl> emSetupImpls = EntityManagerFactoryProvider.getEmSetupImpls();
Map<String, EntityManagerSetupImpl> copy = new HashMap<>(emSetupImpls);
emSetupImpls.clear();
SessionManager manager = SessionManager.getManager();
for (EntityManagerSetupImpl emSetupImpl : copy.values()) {
manager.getSessions().remove(emSetupImpl.getSessionName());
}
try {
return super.repopulateSchema();
} finally {
emSetupImpls.putAll(copy);
for (EntityManagerSetupImpl emSetupImpl : copy.values()) {
manager.addSession(emSetupImpl.getSession());
}
}
}
@Override
protected JpaProviderFamily getJpaProviderFamily() {
return JpaProviderFamily.ECLIPSELINK;
}
@Override
protected int getJpaProviderMajorVersion() {
throw new UnsupportedOperationException();
}
@Override
protected int getJpaProviderMinorVersion() {
throw new UnsupportedOperationException();
}
}
| 36.021898 | 119 | 0.700507 |
527f9a0cce1b7d20e8bafeab13d93b74e9b5f835 | 1,196 | /*
Copyright 2015 HJOW
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 hjow.hgtable.jscript;
import java.io.Serializable;
/**
* <p>스크립트에서, 특수한 명령어를 입력한 경우 반환되는 구분용 객체를 만들 때 쓰는 클래스입니다.</p>
*
* @author HJOW
*
*/
public class SpecialOrder implements Serializable
{
private static final long serialVersionUID = 7275222984704184123L;
private String order;
public SpecialOrder()
{
}
public SpecialOrder(String order)
{
this.order = order;
}
public String getOrder()
{
return order;
}
public void setOrder(String order)
{
this.order = order;
}
@Override
public String toString()
{
return "special://" + order;
}
}
| 21.357143 | 73 | 0.698161 |
868d015d3b9af024254baba6900773f9431a8066 | 1,248 | // This file is auto-generated, don't edit it. Thanks.
package com.antgroup.antchain.openapi.blockchain.models;
import com.aliyun.tea.*;
public class ALiYunChainConfigOption extends TeaModel {
// config_option
@NameInMap("config_option")
public String configOption;
// show_name
@NameInMap("show_name")
public String showName;
// enable
@NameInMap("enable")
public Boolean enable;
public static ALiYunChainConfigOption build(java.util.Map<String, ?> map) throws Exception {
ALiYunChainConfigOption self = new ALiYunChainConfigOption();
return TeaModel.build(map, self);
}
public ALiYunChainConfigOption setConfigOption(String configOption) {
this.configOption = configOption;
return this;
}
public String getConfigOption() {
return this.configOption;
}
public ALiYunChainConfigOption setShowName(String showName) {
this.showName = showName;
return this;
}
public String getShowName() {
return this.showName;
}
public ALiYunChainConfigOption setEnable(Boolean enable) {
this.enable = enable;
return this;
}
public Boolean getEnable() {
return this.enable;
}
}
| 25.469388 | 96 | 0.676282 |
4cbd129f025a55ea1422468ad3993d6b152beef9 | 4,253 | package ru.rsmu.olympreg.utils.restconnector;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.tapestry5.ioc.annotations.Inject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ru.rsmu.olympreg.dao.SystemPropertyDao;
import ru.rsmu.olympreg.entities.system.StoredPropertyName;
import ru.rsmu.olympreg.utils.restconnector.examsapimodel.ExamFacade;
import ru.rsmu.olympreg.utils.restconnector.examsapimodel.ExamResult;
import ru.rsmu.olympreg.utils.restconnector.examsapimodel.PersonInfo;
import ru.rsmu.olympreg.utils.restconnector.examsapimodel.TesteeExamInfo;
import java.io.IOException;
import java.util.*;
/**
* @author leonid.
*/
public class TempolwConnector extends BaseRestApiConnector {
private Logger log = LoggerFactory.getLogger( TempolwConnector.class );
public static final String ALL_EXAMS_METHOD = "rest/exam/list";
public static final String UPCOMING_EXAMS_METHOD = "rest/exam/list/upcoming";
public static final String ADD_PARTICIPANTS_METHOD = "rest/exam/{id}/participants";
public static final String GET_RESULTS_METHOD = "rest/exam/{id}/results";
@Inject
private SystemPropertyDao systemPropertyDao;
ObjectMapper mapper = new ObjectMapper();
@Override
public String getServiceUrl() {
return systemPropertyDao.getProperty( StoredPropertyName.TEMPOLW_SYSTEM_URL );
}
@Override
public String getAuthorizationMethod() {
return "Basic";
}
@Override
public String getAuthorizationToken() {
String username = systemPropertyDao.getProperty( StoredPropertyName.TEMPOLW_USER );
String password = systemPropertyDao.getProperty( StoredPropertyName.TEMPOLW_PASSWORD );
String token = username + ":" + password;
return new String( Base64.getEncoder().encode( token.getBytes() ) );
}
@Override
public Logger getLogger() {
return log;
}
public List<ExamFacade> getUpcomingExams() {
return getExamsByMethod( UPCOMING_EXAMS_METHOD );
}
public List<TesteeExamInfo> sendPersonToExam( long examExtarnalId, List<PersonInfo> personInfos ) {
String method = ADD_PARTICIPANTS_METHOD.replace( "{id}", String.valueOf( examExtarnalId ) );
String payload = null;
try {
payload = mapper.writeValueAsString( personInfos );
} catch (JsonProcessingException e) {
log.error( "JSON can't create the payload", e );
return Collections.emptyList();
}
String answer = callMethod( method, null, payload );
if ( answer != null ) {
try {
return mapper.readValue( answer, new TypeReference<List<TesteeExamInfo>>() {});
} catch (IOException e) {
log.error( "JSON can't parse the response", e );
}
}
return Collections.emptyList();
}
public ExamResult getExamResult( long examId, int pageSize, int firstResult ) {
String method = GET_RESULTS_METHOD.replace( "{id}", String.valueOf( examId ) );
Map<String, String> parameters = new HashMap<>();
parameters.put( "pageSize", String.valueOf( pageSize ) );
parameters.put( "firstResult", String.valueOf( firstResult ) );
String answer = callMethod( method, parameters );
if ( answer != null ) {
try {
return mapper.readValue( answer, ExamResult.class );
} catch (IOException e) {
log.error( "JSON can't parse the response", e );
}
}
return null;
}
public List<ExamFacade> getAllExams() {
return getExamsByMethod( ALL_EXAMS_METHOD );
}
private List<ExamFacade> getExamsByMethod( String method ) {
String answer = callMethod( method, null );
if ( answer != null ) {
try {
return mapper.readValue( answer, new TypeReference<List<ExamFacade>>() {} );
} catch (IOException e) {
log.error( "JSON can't parse the response", e );
}
}
return Collections.emptyList();
}
}
| 36.042373 | 103 | 0.665413 |
fbfceb446b755b6bba6bc9357fd6ae222cae1a52 | 3,304 | package com.febs.shangpin.controller;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.febs.common.annotation.ControllerEndpoint;
import com.febs.common.controller.BaseController;
import com.febs.common.entity.FebsResponse;
import com.febs.common.entity.QueryRequest;
import com.febs.shangpin.entity.ShangpinSku;
import com.febs.shangpin.service.IShangpinSkuService;
import com.wuwenze.poi.ExcelKit;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import javax.validation.constraints.NotBlank;
import java.util.List;
import java.util.Map;
/**
* 商品SKU Controller
*
* @author liubaixing1
* @date 2020-05-22 01:11:56
*/
@Slf4j
@Validated
@RestController
@RequestMapping("shangpinSku")
public class ShangpinSkuController extends BaseController {
@Autowired
private IShangpinSkuService shangpinSkuService;
@GetMapping("")
@RequiresPermissions("shangpinSku:list")
public FebsResponse getAllShangpinSkus(ShangpinSku shangpinSku) {
return new FebsResponse().success().data(shangpinSkuService.findShangpinSkus(shangpinSku));
}
@GetMapping("/list")
@RequiresPermissions("shangpinSku:list")
public FebsResponse shangpinSkuList(QueryRequest request, ShangpinSku shangpinSku) {
Map<String, Object> dataTable = getDataTable(this.shangpinSkuService.findShangpinSkus(request, shangpinSku));
return new FebsResponse().success().data(dataTable);
}
@ControllerEndpoint(operation = "新增ShangpinSku", exceptionMessage = "新增ShangpinSku失败")
@PostMapping("")
@RequiresPermissions("shangpinSku:add")
public FebsResponse addShangpinSku(@Valid ShangpinSku shangpinSku) {
this.shangpinSkuService.createShangpinSku(shangpinSku);
return new FebsResponse().success();
}
@ControllerEndpoint(operation = "删除ShangpinSku", exceptionMessage = "删除ShangpinSku失败")
@GetMapping("delete/{ids}")
@RequiresPermissions("shangpinSku:delete")
public FebsResponse deleteShangpinSku(@NotBlank(message = "{required}") @PathVariable String ids) {
String[] id = ids.split(StringPool.COMMA);
this.shangpinSkuService.deleteShangpinSku(id);
return new FebsResponse().success();
}
@ControllerEndpoint(operation = "修改ShangpinSku", exceptionMessage = "修改ShangpinSku失败")
@PostMapping("/update")
@RequiresPermissions("shangpinSku:update")
public FebsResponse updateShangpinSku(ShangpinSku shangpinSku) {
this.shangpinSkuService.updateShangpinSku(shangpinSku);
return new FebsResponse().success();
}
@ControllerEndpoint(exceptionMessage = "导出Excel失败")
@GetMapping("excel")
@RequiresPermissions("shangpinSku:export")
public void export(QueryRequest queryRequest, ShangpinSku shangpinSku, HttpServletResponse response) {
List<ShangpinSku> shangpinSkus = this.shangpinSkuService.findShangpinSkus(queryRequest, shangpinSku).getRecords();
ExcelKit.$Export(ShangpinSku.class, response).downXlsx(shangpinSkus, false);
}
}
| 38.870588 | 122 | 0.766646 |
51c514873436d690176949fecd5cb22bb3935939 | 798 | package com.chutneytesting.jira.xrayapi;
public class XrayEvidence {
private String data;
private String filename;
private String contentType;
public XrayEvidence(String data, String filename, String contentType) {
this.data = data;
this.filename = filename;
this.contentType = contentType;
}
public String getData() {
return data;
}
public void setData(String data) {
this.data = data;
}
public String getFilename() {
return filename;
}
public void setFilename(String filename) {
this.filename = filename;
}
public String getContentType() {
return contentType;
}
public void setContentType(String contentType) {
this.contentType = contentType;
}
}
| 20.461538 | 75 | 0.635338 |
fb56413596747bf5b9ed908f87afbe18709ef848 | 2,153 | package io.choerodon.test.manager.app.service.impl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import io.choerodon.core.exception.CommonException;
import io.choerodon.test.manager.app.service.FileService;
import io.choerodon.test.manager.app.service.TestCycleCaseAttachmentRelUploadService;
import io.choerodon.test.manager.infra.dto.TestCycleCaseAttachmentRelDTO;
import io.choerodon.test.manager.infra.mapper.TestCycleCaseAttachmentRelMapper;
import io.choerodon.test.manager.infra.util.DBValidateUtil;
/**
* @author: 25499
* @date: 2019/12/16 17:28
* @description:
*/
@Service
public class TestCycleCaseAttachmentRelUploadServiceImpl implements TestCycleCaseAttachmentRelUploadService {
@Autowired
private TestCycleCaseAttachmentRelMapper testCycleCaseAttachmentRelMapper;
@Autowired
private FileService fileService;
@Override
public TestCycleCaseAttachmentRelDTO baseUpload(String bucketName, String fileName, MultipartFile file, Long attachmentLinkId, String attachmentType, String comment) {
TestCycleCaseAttachmentRelDTO testCycleCaseAttachmentRelDTO = new TestCycleCaseAttachmentRelDTO();
testCycleCaseAttachmentRelDTO.setAttachmentLinkId(attachmentLinkId);
testCycleCaseAttachmentRelDTO.setAttachmentName(fileName);
testCycleCaseAttachmentRelDTO.setComment(comment);
ResponseEntity<String> response = fileService.uploadFile(bucketName, fileName, file);
if (response == null || response.getStatusCode() != HttpStatus.OK) {
throw new CommonException("error.attachment.upload");
}
testCycleCaseAttachmentRelDTO.setUrl(response.getBody());
testCycleCaseAttachmentRelDTO.setAttachmentType(attachmentType);
DBValidateUtil.executeAndvalidateUpdateNum(testCycleCaseAttachmentRelMapper::insert, testCycleCaseAttachmentRelDTO, 1, "error.attachment.insert");
return testCycleCaseAttachmentRelDTO;
}
}
| 45.808511 | 171 | 0.806317 |
e51d8f24ac1986bf574fa505767318376d6c8c90 | 5,731 | package com.github.bot.curiosone.core.nlp.raw;
import com.github.bot.curiosone.core.nlp.LEX;
import com.github.bot.curiosone.core.nlp.POS;
import edu.mit.jwi.item.IWordID;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
/**
* Stores a Word with its Syntax/Semantic information.
*/
public class RawWord {
/**
* Part of Speech of this RawWord.
*/
private POS pos;
/**
* Lexicographic type of this RawWord.
*/
private LEX lexType;
/**
* Lemma of this RawWord.
*/
private String lemma;
/**
* Stores the WordNet ID of this RawWord.
* @see IWordID
*/
private IWordID wordId;
/**
* Stores the glossary information.
*/
private String gloss;
/**
* Stores the number of occurrence.
*/
private int number;
/**
* Maps the Semantic Relations of this RawWord with other words.
*/
private Map<String, List<String>> relations;
/**
* Gets the WordID.
* @return the WordID
* @see IWordID
* @see #wordId
*/
public IWordID getWordId() {
return wordId;
}
/**
* Constructs an empty RawWord.
*/
public RawWord() {
relations = new HashMap<String, List<String>>();
}
/**
* Sets the WordID of this RawWord.
* @param wordId
* the word ID to be set
*/
public void setWordId(IWordID wordId) {
this.wordId = wordId;
}
/**
* Gets the POS of this RawWord.
* @return the POS value of this RawWord
*/
public POS getPos() {
return pos;
}
/**
* Sets the {@link #pos} of this RawWord.
* @param pos
* the POS value to be set
*/
public void setPos(POS pos) {
this.pos = pos;
}
/**
* Gets the LEX of this RawWord.
* @return the LEX value of this RawWord
*/
public LEX getLexType() {
return lexType;
}
/**
* Sets the {@link #lexType} of this RawWord.
* @param lexType
* the LEX value to be set
*/
public void setLexType(LEX lexType) {
this.lexType = lexType;
}
/**
* Gets the lemma of this RawWord.
* @return the lemma of this RawWord
*/
public String getLemma() {
return lemma;
}
/**
* Sets the lemma of this RawWord.
* @param lemma
* the String representation of the lemma to be set
* @see #lemma
*/
public void setLemma(String lemma) {
this.lemma = lemma;
}
/**
* Gets the gloss of this RawWord.
* @return the gloss of this RawWord
*/
public String getGloss() {
return gloss;
}
/**
* Sets the gloss of this RawWord.
* @param gloss
* String representation of the gloss to be set
*/
public void setGloss(String gloss) {
this.gloss = gloss;
}
/**
* Gets the number of occurrence of this RawWord.
* @return the number of occurrence of this RawWord
*/
public int getNum() {
return this.number;
}
/**
* Sets the number of occurrence of this RawWord.
* @param num
* the number of occurrence to be set
*/
public void setNum(int num) {
this.number = num;
}
/**
* Gets all the relations of this RawWord.
* @return a Map containing all the relations of this RawWord
*/
public Map<String, List<String>> getRelations() {
return relations;
}
/**
* Gets relations by String.
* Returns null, if no Relation by String is found.
* @param pointer
* the String representation of the source.
* This String is supposed to be a key in the #relations Map.
* @return a List containing all the Words in relation with the given Word
*/
public List<String> getRelationsByString(String pointer) {
return new ArrayList<String>(relations.getOrDefault(pointer, null));
}
/**
* Adds a new Relation to this RawWord.
* @param p
* the source of the new Relation
* @param v
* the target of the new Relation
*/
public void addRelation(String p, String v) {
this.relations.merge(
p, new ArrayList<String>(
Arrays.asList(v)), (v1,v2) -> {
v1.add(v);
return v1;
});
}
/**
* Sets the relations of this RawWord.
* @param relations
* the Map containing the relations of this RawWord to be set
* @see #relations
*/
public void setRelations(Map<String, List<String>> relations) {
this.relations.clear();
this.relations.putAll(relations);
}
/**
* Returns a String representation of this RawWord.
* @return a String representation of this RawWord
*
*/
@Override
public String toString() {
String out = "WordId = " + this.wordId
+ " Lemma = " + this.lemma
+ " POS = " + this.pos
+ " LextT = " + this.lexType
+ " Gloss = " + this.gloss
+ " Occurrence = " + this.number;
out += "\n" + relations.entrySet().toString();
return out;
}
/**
* Checks wheter this RawWord equals to the given object.
* @param obj
* the object to be compared against
* @return {@code true} if the given object represents the same RawWord of this instance;
{@code false} otherwise
*/
@Override
public boolean equals(Object obj) {
if (obj == null || !(obj instanceof RawWord)) {
return false;
}
if (obj == this) {
return true;
}
RawWord w = (RawWord) obj;
return this.getWordId().equals(w.getWordId());
}
/**
* Calculates the hashCode of this RawWord.
* The hashCode depends on the gloss of this RawWord.
* @return the hashCode of this RawWord
*/
@Override
public int hashCode() {
return Objects.hash(getGloss());
}
}
| 21.626415 | 92 | 0.604607 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.