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
3d90c0ecec30e4333d21a9c5444c9c3ef07a920d
1,375
package com.robot.carey.zenboserver; import android.util.Log; import java.net.InetAddress; import java.net.NetworkInterface; import java.net.ServerSocket; import java.net.SocketException; import java.util.Enumeration; public class GetIpAddress { public static String IP; public static int PORT; public static String getIP(){ return IP; } public static int getPort(){ return PORT; } public static void getLocalIpAddress(ServerSocket serverSocket){ try { for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();){ NetworkInterface intf = en.nextElement(); for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();){ InetAddress inetAddress = enumIpAddr.nextElement(); String mIP = inetAddress.getHostAddress().substring(0, 3); if(mIP.equals("120")){ IP = inetAddress.getHostAddress(); //获取本地IP PORT = serverSocket.getLocalPort(); //获取本地的PORT Log.e("IP",""+IP); Log.e("PORT",""+PORT); } } } } catch (SocketException e) { e.printStackTrace(); } } }
31.976744
116
0.577455
7a4968be6cf4d29308ba9929cb610a9173da6fc2
883
package com.etc.RentMarket.service; import java.util.List; import com.etc.RentMarket.entity.Usersdetail; /** * 地址管理服务层接口 * @author 陈伟杰 * */ public interface AddressService { /** * 查询用户的地址信息 * @param userName * @return */ List<Usersdetail> queryUserAddr(String userName); /** * 添加地址(用户详细信息) * @param userName 登录名 * @param userRealName 收货人 * @param userAddress 地址 * @param userPhone 手机 * @return */ boolean addAddr(String userName,String userRealName,String userAddress,String userPhone); /** * 修改地址 * @param userDetailId * @param userRealName * @param userAddress * @param userPhone * @return */ boolean updateAddr(int userDetailId,String userRealName,String userAddress,String userPhone); /** * 删除地址 * @param userDetailId * @return */ boolean deleteAddr(int userDetailId); }
19.195652
95
0.660249
aff4cb7961df3d2928ac1e4347995c89436d3170
949
package perobobbot.twitch.eventsub.api.event; import com.google.common.collect.ImmutableList; import lombok.EqualsAndHashCode; import lombok.NonNull; import lombok.ToString; import lombok.Value; import perobobbot.twitch.api.UserInfo; import java.time.Instant; @Value @EqualsAndHashCode(callSuper = true) @ToString(callSuper = true) public class PollBeginEvent extends PollEvent { @NonNull Instant endsAt; @java.beans.ConstructorProperties({"id", "broadcaster", "title", "choices", "bitsVoting", "channelPointsVoting", "startedAt","endsAt"}) public PollBeginEvent(@NonNull String id, @NonNull UserInfo broadcaster, @NonNull String title, @NonNull ImmutableList<PollChoices> choices, @NonNull Voting bitsVoting, @NonNull Voting channelPointsVoting, @NonNull Instant startedAt, @NonNull Instant endsAt) { super(id, broadcaster, title, choices, bitsVoting, channelPointsVoting, startedAt); this.endsAt = endsAt; } }
37.96
264
0.773446
615d51a1a0ee854d979022ea6be0b238827efe1d
820
package qub; public interface TakeWhileIteratorTests { static void test(TestRunner runner) { runner.testGroup(TakeWhileIterator.class, () -> { IteratorTests.test(runner, (Integer count, Boolean started) -> { final int additionalValues = 5; final Array<Integer> array = Array.createWithLength(count + additionalValues); for (int i = 0; i < array.getCount(); ++i) { array.set(i, i); } final Iterator<Integer> iterator = array.iterate().takeWhile((Integer value) -> value < count); if (started) { iterator.start(); } return iterator; }); }); } }
26.451613
111
0.478049
c4ac067e0ea62303c7b57e6564a2d274a37a9baf
877
/* * 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 dtatransferobjects; /** * * @author Jakir Hossain Riaz */ import java.util.Date; import org.springframework.format.annotation.DateTimeFormat; import org.springframework.web.multipart.MultipartFile; public class noticeuploadDTO { @DateTimeFormat(pattern= "dd/MM/yyyy") private String date; private MultipartFile[] filename; public String getDate() { return date; } public void setDate(String date) { this.date = date; } public MultipartFile[] getFilename() { return filename; } public void setFilename(MultipartFile[] filename) { this.filename = filename; } }
22.487179
80
0.660205
edbc4a7f57d139d8b52c79388523fe82c048ebd8
1,174
package com.smartgwt.mobile.client.widgets.events; import com.smartgwt.mobile.SGWTInternal; import com.smartgwt.mobile.client.internal.events.AbstractCancellableEvent; public class ShowContextMenuEvent extends AbstractCancellableEvent<ShowContextMenuHandler> { private static Type<ShowContextMenuHandler> TYPE = null; public static Type<ShowContextMenuHandler> getType() { if (TYPE == null) TYPE = new Type<ShowContextMenuHandler>(); return TYPE; } // Returns whether the event was cancelled. @SGWTInternal public static <S extends HasShowContextMenuHandlers> boolean _fire(S source) { if (TYPE == null) { return false; } else { final ShowContextMenuEvent event = new ShowContextMenuEvent(); source.fireEvent(event); return event.isCancelled(); } } private ShowContextMenuEvent() {} @Override public final Type<ShowContextMenuHandler> getAssociatedType() { assert TYPE != null; return TYPE; } @Override protected void dispatch(ShowContextMenuHandler handler) { handler.onShowContextMenu(this); } }
29.35
92
0.684838
0100e58af79d463e4a701486cc966dbee87d2e5f
3,302
/* * Copyright (c) 2022, Harald Kuhr * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * * 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. * * * Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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 com.twelvemonkeys.imageio.plugins.iff; import javax.imageio.IIOException; import java.io.DataInput; import java.io.DataOutput; import java.io.IOException; /** * DGBLChunk * * @author <a href="mailto:harald.kuhr@gmail.com">Harald Kuhr</a> * @version $Id: DGBLChunk.java,v 1.0 28.feb.2006 02:10:07 haku Exp$ */ final class DGBLChunk extends IFFChunk { /* // struct DGBL = { // // Size of source display // UWORD DisplayWidth,DisplayHeight; // // Type of compression // UWORD Compression; // // Pixel aspect, a ration w:h // UBYTE xAspect,yAspect; }; */ int displayWidth; int displayHeight; int compressionType; int xAspect; int yAspect; DGBLChunk(int chunkLength) { super(IFF.CHUNK_DGBL, chunkLength); } @Override void readChunk(final DataInput input) throws IOException { if (chunkLength != 8) { throw new IIOException("Unknown DBGL chunk length: " + chunkLength); } displayWidth = input.readUnsignedShort(); displayHeight = input.readUnsignedShort(); compressionType = input.readUnsignedShort(); xAspect = input.readUnsignedByte(); yAspect = input.readUnsignedByte(); } @Override void writeChunk(final DataOutput output) { throw new InternalError("Not implemented: writeChunk()"); } @Override public String toString() { return super.toString() + "{displayWidth=" + displayWidth + ", displayHeight=" + displayHeight + ", compression=" + compressionType + ", xAspect=" + xAspect + ", yAspect=" + yAspect + '}'; } }
32.058252
81
0.683525
a678fb21d4dad6204ddc966503508ec78dfcd9b3
880
package com.popupmc.areaspawnlite.config; import com.popupmc.areaspawnlite.AreaSpawnLite; import org.bukkit.Material; import java.util.ArrayList; import java.util.List; public class BlockList { public BlockList(List<String> materialStrs, AreaSpawnLite plugin) { this.plugin = plugin; for(String materialStr : materialStrs) { materialStr = materialStr.toUpperCase().replaceAll(" ", "_"); try { Material material = Material.valueOf(materialStr); this.materials.add(material); } catch (IllegalArgumentException ex) { plugin.getLogger().warning("Material " + materialStr + " doesn't exist, skipping..."); } } } public ArrayList<Material> materials = new ArrayList<>(); public AreaSpawnLite plugin; }
29.333333
103
0.6125
fa72eb534284e0ad3ef3aafc850d813dd4ae6a9f
1,376
package net.machina.collections.lists; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.ListIterator; public class ListsMain { public static void main(String[] args) { List<String> lista = new LinkedList<>(); lista.add("Wiesiek"); lista.add("Czesiek"); lista.add("Krzysiek"); System.out.println("----- Wypisanie listy (foreach) ------"); // to widzi programista for(String s : lista) { System.out.println(s); } System.out.println("----- Wypisanie listy (Iterator) -----"); // a to widzi maszyna wirtualna Javy Iterator<String> iter = lista.iterator(); while(iter.hasNext()) { System.out.println(iter.next()); } ListIterator<String> iter2 = lista.listIterator(); iter2.next(); iter2.add("Zenek"); System.out.println("----- Dodanie elementu z wykorzystaniem ListIterator -----"); for(String s : lista) { System.out.println(s); } ListIterator<String> iter3 = lista.listIterator(); iter3.next(); iter3.next(); iter3.remove(); System.out.println("----- Usuwanie elementu z wykorzystaniem ListIterator -----"); for(String s : lista) { System.out.println(s); } } }
29.276596
90
0.569041
3c74daea9b014f85d38299515eaead722920e97c
1,669
package edu.upenn.eCommerceCrawler; public class TreeTraversal { public List<Integer> postorderTraversal(TreeNode root) { LinkedList<Integer> result = new LinkedList<>(); Deque<TreeNode> stack = new ArrayDeque<>(); TreeNode p = root; while(!stack.isEmpty() || p != null) { if(p != null) { stack.push(p); result.addFirst(p.val); // Reverse the process of preorder p = p.right; // Reverse the process of preorder } else { TreeNode node = stack.pop(); p = node.left; // Reverse the process of preorder } } return result; } public List<Integer> inorderTraversal(TreeNode root) { List<Integer> result = new ArrayList<>(); Deque<TreeNode> stack = new ArrayDeque<>(); TreeNode p = root; while(!stack.isEmpty() || p != null) { if(p != null) { stack.push(p); p = p.left; } else { TreeNode node = stack.pop(); result.add(node.val); // Add after all left children p = node.right; } } return result; } public List<Integer> preorderTraversal(TreeNode root) { List<Integer> result = new ArrayList<>(); Deque<TreeNode> stack = new ArrayDeque<>(); TreeNode p = root; while(!stack.isEmpty() || p != null) { if(p != null) { stack.push(p); result.add(p.val); // Add before going to children p = p.left; } else { TreeNode node = stack.pop(); p = node.right; } } return result; } }
30.345455
72
0.519473
b050c9d0aae01947d291ddce0aa05f7f4f76d8cf
9,359
/* * 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 ComprasOnLine.servlets; import java.io.IOException; import java.util.ArrayList; import java.util.logging.Level; import java.util.logging.Logger; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import ComprasOnLine.modelosClases.Categoria; import ComprasOnLine.modelosClases.Producto; import ComprasOnLine.modelosServicios.ModeloCategoria; import ComprasOnLine.modelosServicios.ModeloProducto; import org.json.JSONException; /** * * @author Joseiba */ @WebServlet(name = "ServletProducto", urlPatterns = {"/ServletProducto"}) public class ServletProducto extends HttpServlet { ArrayList<Producto> listaProductos = new ArrayList<Producto>(); ArrayList<Categoria> listaCategorias = new ArrayList<Categoria>(); // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code."> /** * Handles the HTTP <code>GET</code> method. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String accion = request.getParameter("accion"); String redireccion = request.getParameter("redireccion"); String descripcion = request.getParameter("producto_descripcion_buscar"); System.out.println(descripcion); ModeloProducto modeloProducto = new ModeloProducto(); ModeloCategoria modeloCategoria = new ModeloCategoria(); System.out.println("accion:" + accion); if (accion == null || accion.equals("agregarCarrito") || accion.equals("login") || accion.equals("logout") || accion.equals("comprar")) { System.out.println("muestra el listado"); try { System.out.println("accion listar: " + accion); listaProductos = modeloProducto.listar(); listaCategorias = modeloCategoria.listar(); System.out.println(listaProductos.toString()); request.setAttribute("listaCategorias", listaCategorias); request.setAttribute("listaProductos", listaProductos); request.setAttribute("longitud", listaProductos.size()); RequestDispatcher rd = request.getRequestDispatcher(redireccion); rd.forward(request, response); if (accion.equals("comprar") ) { } } catch (JSONException ex) { Logger.getLogger(ServletProducto.class.getName()).log(Level.SEVERE, null, ex); } } else if (accion.equals("buscar")) { try { listaProductos = modeloProducto.buscar(descripcion); listaCategorias = modeloCategoria.listar(); request.setAttribute("listaCategorias", listaCategorias); request.setAttribute("listaProductos", listaProductos); request.setAttribute("longitud", listaProductos.size()); RequestDispatcher rd = request.getRequestDispatcher(redireccion); rd.forward(request, response); } catch (JSONException ex) { Logger.getLogger(ServletProducto.class.getName()).log(Level.SEVERE, null, ex); } } else if (accion.equals("filtrar")) { int id_categoria = Integer.parseInt(request.getParameter("producto_categoria_fil")); System.out.println("se filtra"); System.out.println(id_categoria); try { listaProductos = modeloProducto.filtrarProducto(id_categoria); listaCategorias = modeloCategoria.listar(); request.setAttribute("listaCategorias", listaCategorias); System.out.println(listaProductos); request.setAttribute("listaCategorias", listaCategorias); request.setAttribute("listaProductos", listaProductos); request.setAttribute("longitud", listaProductos.size()); RequestDispatcher rd = request.getRequestDispatcher(redireccion); rd.forward(request, response); } catch (JSONException ex) { Logger.getLogger(ServletProducto.class.getName()).log(Level.SEVERE, null, ex); } } else if (accion.equals("agregar")) { System.out.println("se tiene que mostrar el formulario de agregar"); try { listaCategorias = modeloCategoria.listar(); request.setAttribute("listaCategorias", listaCategorias); RequestDispatcher rd = request.getRequestDispatcher("agregarProducto.jsp"); rd.forward(request, response); } catch (JSONException ex) { Logger.getLogger(ServletProducto.class.getName()).log(Level.SEVERE, null, ex); } } else if (accion.equals("editar")) { System.out.println("se tiene que mostrar el formulario de editar"); try { Producto producto = modeloProducto.listar(Integer.parseInt(request.getParameter("id"))); listaCategorias = modeloCategoria.listar(); request.setAttribute("listaCategorias", listaCategorias); request.setAttribute("producto", producto); RequestDispatcher rd = request.getRequestDispatcher("modificarProducto.jsp"); rd.forward(request, response); } catch (JSONException ex) { Logger.getLogger(ServletProducto.class.getName()).log(Level.SEVERE, null, ex); } } else if (accion.equals("eliminar")) { System.out.println("elimina y muestra la lista de nuevo"); modeloProducto.eliminar(Integer.parseInt(request.getParameter("id"))); //verificar que se elimino response.sendRedirect("/ComprasOnLine/ServletProducto?redireccion="+redireccion); } } /** * Handles the HTTP <code>POST</code> method. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //processRequest(request, response); System.out.println("entro al dopost"); ModeloProducto modeloProducto = new ModeloProducto(); String accion = request.getParameter("accion"); String redireccion = request.getParameter("redireccion"); if (accion.equals("comprar")) {//se va al home System.out.println("se va al home"); request.setAttribute("listaCategorias", listaCategorias); request.setAttribute("listaProductos", listaProductos); request.setAttribute("longitud", listaProductos.size()); RequestDispatcher rd = request.getRequestDispatcher(redireccion); rd.forward(request, response); } String descripcion = request.getParameter("producto_descripcion"); int precio = Integer.parseInt(request.getParameter("producto_precio")); int categoria = Integer.parseInt(request.getParameter("producto_categoria")); int stock = Integer.parseInt(request.getParameter("producto_cantidad")); Producto producto = new Producto(0, descripcion, categoria, precio, stock); System.out.println("accion:" + accion); if (accion.equals("grabar")) { System.out.println("se graba u nuevo registro"); try { modeloProducto.agregar(producto); } catch (JSONException ex) { Logger.getLogger(ServletProducto.class.getName()).log(Level.SEVERE, null, ex); } response.sendRedirect("/ComprasOnLine/ServletProducto?redireccion="+redireccion); } else if (accion.equals("actualizar")) {//se actualiza System.out.println("se actualiza u nuevo registro"); int id = Integer.parseInt(request.getParameter("id_producto")); producto.setId(id); try { modeloProducto.actualizar(producto); } catch (Exception ex) { Logger.getLogger(ServletProducto.class.getName()).log(Level.SEVERE, null, ex); } response.sendRedirect("/ComprasOnLine/ServletProducto?redireccion="+redireccion); } } /** * Returns a short description of the servlet. * * @return a String containing servlet description */ @Override public String getServletInfo() { return "Short description"; }// </editor-fold> }
43.733645
145
0.640026
61f2487a23f6366e82afd2f52c9c1d21ee61ad19
2,931
package com.sparta.jm.controller; import com.sparta.jm.model.BugsBunny; import com.sparta.jm.model.ElmerFudd; import java.util.ArrayList; import java.util.List; import java.util.Random; public class GeneratingPopulation { private List<BugsBunny> rabbit = new ArrayList<>(); private List<ElmerFudd> hunter = new ArrayList<>(); private int bugsBunny = 1; //Male rabbits private int lolaBunny = 1; //Female rabbits private int maleHunter = 1; private int femaleHunter = 1; private int months = 0; private final int timeOfSimulation = 18; public void creatingSimulator() { rabbit.add(new BugsBunny(true)); rabbit.add(new BugsBunny(false)); hunter.add(new ElmerFudd(true)); hunter.add(new ElmerFudd(false)); } public void simulation() { creatingSimulator(); eachMonth(); } public List eachMonth() { List<BugsBunny> birthOfRabbit = new ArrayList<>(); List<BugsBunny> deathOfRabbit = new ArrayList<>(); List<ElmerFudd> birthOfHunter = new ArrayList<>(); List<BugsBunny> hunted = new ArrayList<>(); while (months <= timeOfSimulation) { for (BugsBunny bunny : rabbit) { if (bunny.getAge() >= 3 && bunny.isFemale()) for (int i = 0; i < new Random().nextInt(bunny.getBabies()) + 1; i++) birthOfRabbit.add(new BugsBunny()); if (bunny.getAge() == 12) deathOfRabbit.add(bunny); } for (ElmerFudd hunter : hunter) { if (hunter.getAge() >= 10 && hunter.isFemale() || (hunter.getMonthsSinceBreading() % 12) == 0) for (int j = 0; j < new Random().nextInt(hunter.getBabies()) + 1; j++) birthOfHunter.add(new ElmerFudd()); for (int i = 0; i < new Random().nextInt(hunter.getHunting()) + 1; i++) hunted.add(new BugsBunny()); } for (BugsBunny babyRabbit : birthOfRabbit) { if (babyRabbit.isFemale()) lolaBunny++; else bugsBunny++; } for (ElmerFudd hunter : birthOfHunter) { if (hunter.isFemale()) femaleHunter++; else maleHunter++; } months++; rabbit.removeAll(hunted); rabbit.removeAll(deathOfRabbit); rabbit.addAll(birthOfRabbit); hunter.addAll(birthOfHunter); System.out.println(months + ": Rabbits Died from old age: " + deathOfRabbit.size() + " Remaining: " + rabbit.size() + " Male population: " + bugsBunny + " Female population: " + lolaBunny + "\n" + "\n" + " Hunters alive: " + hunter.size() + " Rabbits hunted " + hunted.size() + " Female Hunters: " + femaleHunter + " Male Hunters " + maleHunter + "\n" ); } return rabbit; } }
41.871429
163
0.560901
40ac0fba9c7d4f6cacb893f253be80470a0d54b4
1,411
package cli.home; import cli.hospital.HospitalHomepage; import java.sql.SQLException; import java.util.Scanner; /** * Fill in * * @author Ratantej * @version 2.0 * @since 1.0 */ public class ViewProgramDetails { public ViewProgramDetails() throws SQLException { System.out.println(); System.out.println("The Hospital Management System designed by All Stars, is a state of the art patient " + "management and diagnosis system for Hospitals and Doctors across the board designed for \n" + "improving their operational efficiency and reducing costs by automating patient management. "); System.out.println(); System.out.println("Designed amd Created By: Ratantej, Roa, Alessandro, Ernest, Euan, Shysta, Justice"); System.out.println(); System.out.println("CSC 207 Project by All Stars. Copyright 2021. All Rights Reserved"); System.out.println(); System.out.println("1. Go back"); System.out.println(); int choice; while (true) { Scanner option = new Scanner(System.in); try { choice = option.nextInt(); } catch (Exception e) { choice = -1; } if ((choice != 1)) { System.out.println("Invalid Input!"); } else new Homepage(); } } }
31.355556
115
0.593196
e14462e67be630cc82f33a3d7ddf5b04f92f521d
1,130
package com.spring5.core.aop; import org.aspectj.lang.JoinPoint; import org.aspectj.lang.annotation.After; import org.aspectj.lang.annotation.AfterReturning; import org.aspectj.lang.annotation.AfterThrowing; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Before; import org.aspectj.lang.annotation.Pointcut; import java.util.Arrays; /** * @author lizheng * @date: 10:41 2018/12/23 * @Description: CalculationLogs */ @Aspect public class CalculationLogs { public CalculationLogs() { System.out.println("创建计算器切面"); } @Pointcut(value="execution(* com.spring5.core.bean.Calculation.*(..))") public void pointcut() {} @Before("pointcut()") public void before(JoinPoint point) { System.out.println("开始计算了: args = "+ Arrays.asList(point.getArgs())); } @After("pointcut()") public void after() { System.out.println("开始计算完了"); } @AfterReturning(value = "pointcut()", returning = "returning") public void afterReturning(Object returning) { System.out.println("结算结果:" + returning); } @AfterThrowing("pointcut()") public void exception() { System.out.println("异常了"); } }
23.061224
72
0.725664
617f7b5a47e772ab27781a4a0f5394d8ea3491b7
24,384
/* Copyright (c) 2013 OpenPlans. All rights reserved. * This code is licensed under the BSD New License, available at the root * application directory. */ package org.geogit.geotools.plumbing; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.URLDecoder; import java.util.Collection; import java.util.Iterator; import java.util.List; import javax.annotation.Nullable; import org.geogit.api.AbstractGeoGitOp; import org.geogit.api.FeatureBuilder; import org.geogit.api.NodeRef; import org.geogit.api.ProgressListener; import org.geogit.api.Ref; import org.geogit.api.RevFeature; import org.geogit.api.RevFeatureImpl; import org.geogit.api.RevFeatureType; import org.geogit.api.RevFeatureTypeImpl; import org.geogit.api.RevTree; import org.geogit.api.data.ForwardingFeatureCollection; import org.geogit.api.data.ForwardingFeatureIterator; import org.geogit.api.data.ForwardingFeatureSource; import org.geogit.api.hooks.Hookable; import org.geogit.api.plumbing.LsTreeOp; import org.geogit.api.plumbing.LsTreeOp.Strategy; import org.geogit.api.plumbing.ResolveFeatureType; import org.geogit.api.plumbing.RevObjectParse; import org.geogit.geotools.plumbing.GeoToolsOpException.StatusCode; import org.geogit.repository.WorkingTree; import org.geotools.data.DataStore; import org.geotools.data.FeatureSource; import org.geotools.data.Query; import org.geotools.factory.Hints; import org.geotools.feature.DecoratingFeature; import org.geotools.feature.FeatureCollection; import org.geotools.feature.FeatureIterator; import org.geotools.feature.NameImpl; import org.geotools.feature.simple.SimpleFeatureTypeBuilder; import org.geotools.feature.type.AttributeDescriptorImpl; import org.geotools.filter.identity.FeatureIdImpl; import org.geotools.jdbc.JDBCFeatureSource; import org.opengis.feature.Feature; import org.opengis.feature.simple.SimpleFeature; import org.opengis.feature.simple.SimpleFeatureType; import org.opengis.feature.type.AttributeDescriptor; import org.opengis.feature.type.FeatureType; import org.opengis.feature.type.PropertyDescriptor; import org.opengis.filter.identity.FeatureId; import com.google.common.base.Charsets; import com.google.common.base.Function; import com.google.common.base.Optional; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableList; import com.google.common.collect.Iterators; import com.google.common.collect.Lists; import com.vividsolutions.jts.geom.CoordinateSequenceFactory; import com.vividsolutions.jts.geom.impl.PackedCoordinateSequenceFactory; /** * Internal operation for importing tables from a GeoTools {@link DataStore}. * * @see DataStore */ @Hookable(name = "import") public class ImportOp extends AbstractGeoGitOp<RevTree> { private boolean all = false; private String table = null; /** * The path to import the data into */ private String destPath; /** * The name to use for the geometry descriptor, replacing the default one */ private String geomName; /** * The name of the attribute to use for defining feature id's */ private String fidAttribute; private DataStore dataStore; /** * Whether to remove previous objects in the destination path, in case they exist * */ private boolean overwrite = true; /** * If true, it does not overwrite, and modifies the existing features to have the same feature * type as the imported table */ private boolean alter; /** * If false, features will be added as they are, with their original feature type. If true, the * import operation will try to adapt them to the current default feature type, and if that is * not possible it will throw an exception */ private boolean adaptToDefaultFeatureType = true; private boolean usePaging = true; /** * Executes the import operation using the parameters that have been specified. Features will be * added to the working tree, and a new working tree will be constructed. Either {@code all} or * {@code table}, but not both, must be set prior to the import process. * * @return RevTree the new working tree */ @SuppressWarnings({ "rawtypes", "unchecked" }) @Override protected RevTree _call() { // check preconditions and get the actual list of type names to import final String[] typeNames = checkPreconditions(); for (int i = 0; i < typeNames.length; i++) { try { typeNames[i] = URLDecoder.decode(typeNames[i], Charsets.UTF_8.displayName()); } catch (UnsupportedEncodingException e) { // shouldn't reach here. } } ProgressListener progressListener = getProgressListener(); progressListener.started(); // use a local variable not to alter the command's state boolean overwrite = this.overwrite; if (alter) { overwrite = false; } final WorkingTree workTree = workingTree(); RevFeatureType destPathFeatureType = null; final boolean destPathProvided = destPath != null; if (destPathProvided) { destPathFeatureType = this.command(ResolveFeatureType.class).setRefSpec(destPath) .call().orNull(); // we delete the previous tree to honor the overwrite setting, but then turn it // to false. Otherwise, each table imported will overwrite the previous ones and // only the last one will be imported. if (overwrite) { try { workTree.delete(destPath); } catch (Exception e) { throw new GeoToolsOpException(e, StatusCode.UNABLE_TO_INSERT); } overwrite = false; } } int tableCount = 0; for (String typeName : typeNames) { { tableCount++; String tableName = String.format("%-16s", typeName); if (typeName.length() > 16) { tableName = tableName.substring(0, 13) + "..."; } progressListener.setDescription("Importing " + tableName + " (" + tableCount + "/" + typeNames.length + ")... "); } FeatureSource featureSource = getFeatureSource(typeName); SimpleFeatureType featureType = (SimpleFeatureType) featureSource.getSchema(); final String fidPrefix = featureType.getTypeName() + "."; String path; if (destPath == null) { path = featureType.getTypeName(); } else { NodeRef.checkValidPath(destPath); path = destPath; featureType = forceFeatureTypeName(featureType, path); } featureType = overrideGeometryName(featureType); featureSource = new ForceTypeAndFidFeatureSource<FeatureType, Feature>(featureSource, featureType, fidPrefix); boolean hasPrimaryKey = hasPrimaryKey(typeName); boolean forbidSorting = !usePaging || !hasPrimaryKey; ((ForceTypeAndFidFeatureSource) featureSource).setForbidSorting(forbidSorting); if (destPathFeatureType != null && adaptToDefaultFeatureType && !alter) { featureSource = new FeatureTypeAdapterFeatureSource<FeatureType, Feature>( featureSource, destPathFeatureType.type()); } ProgressListener taskProgress = subProgress(100.f / typeNames.length); if (overwrite) { try { workTree.delete(path); workTree.createTypeTree(path, featureType); } catch (Exception e) { throw new GeoToolsOpException(e, StatusCode.UNABLE_TO_INSERT); } } if (alter) { // first we modify the feature type and the existing features, if needed workTree.updateTypeTree(path, featureType); Iterator<Feature> transformedIterator = transformFeatures(featureType, path); try { final Integer collectionSize = collectionSize(featureSource); workTree.insert(path, transformedIterator, taskProgress, null, collectionSize); } catch (Exception e) { throw new GeoToolsOpException(StatusCode.UNABLE_TO_INSERT); } } try { insert(workTree, path, featureSource, taskProgress); } catch (GeoToolsOpException e) { throw e; } catch (Exception e) { throw new GeoToolsOpException(e, StatusCode.UNABLE_TO_INSERT); } } progressListener.setProgress(100.f); progressListener.complete(); return workTree.getTree(); } private boolean hasPrimaryKey(String typeName) { FeatureSource featureSource; try { featureSource = dataStore.getFeatureSource(typeName); } catch (Exception e) { throw new GeoToolsOpException(StatusCode.UNABLE_TO_GET_FEATURES); } if (featureSource instanceof JDBCFeatureSource) { return ((JDBCFeatureSource) featureSource).getPrimaryKey().getColumns().size() != 0; } return false; } private SimpleFeatureType overrideGeometryName(SimpleFeatureType featureType) { if (geomName == null) { return featureType; } SimpleFeatureTypeBuilder builder = new SimpleFeatureTypeBuilder(); List<AttributeDescriptor> newAttributes = Lists.newArrayList(); String oldGeomName = featureType.getGeometryDescriptor().getName().getLocalPart(); Collection<AttributeDescriptor> descriptors = featureType.getAttributeDescriptors(); for (AttributeDescriptor descriptor : descriptors) { String name = descriptor.getName().getLocalPart(); Preconditions.checkArgument(!name.equals(geomName), "The provided geom name is already in use by another attribute"); if (name.equals(oldGeomName)) { AttributeDescriptorImpl newDescriptor = new AttributeDescriptorImpl( descriptor.getType(), new NameImpl(geomName), descriptor.getMinOccurs(), descriptor.getMaxOccurs(), descriptor.isNillable(), descriptor.getDefaultValue()); newAttributes.add(newDescriptor); } else { newAttributes.add(descriptor); } } builder.setAttributes(newAttributes); builder.setName(featureType.getName()); builder.setCRS(featureType.getCoordinateReferenceSystem()); featureType = builder.buildFeatureType(); return featureType; } private SimpleFeatureType forceFeatureTypeName(SimpleFeatureType featureType, String path) { SimpleFeatureTypeBuilder builder = new SimpleFeatureTypeBuilder(); builder.setAttributes(featureType.getAttributeDescriptors()); builder.setName(new NameImpl(featureType.getName().getNamespaceURI(), path)); builder.setCRS(featureType.getCoordinateReferenceSystem()); featureType = builder.buildFeatureType(); return featureType; } private Iterator<Feature> transformFeatures(SimpleFeatureType featureType, String path) { String refspec = Ref.WORK_HEAD + ":" + path; Iterator<NodeRef> oldFeatures = command(LsTreeOp.class).setReference(refspec) .setStrategy(Strategy.FEATURES_ONLY).call(); RevFeatureType revFeatureType = RevFeatureTypeImpl.build(featureType); Iterator<Feature> transformedIterator = transformIterator(oldFeatures, revFeatureType); return transformedIterator; } private Integer collectionSize(@SuppressWarnings("rawtypes") FeatureSource featureSource) { final Integer collectionSize; { int fastCount; try { fastCount = featureSource.getCount(Query.ALL); } catch (IOException e) { throw new GeoToolsOpException(e, StatusCode.UNABLE_TO_GET_FEATURES); } collectionSize = -1 == fastCount ? null : Integer.valueOf(fastCount); } return collectionSize; } private String[] checkPreconditions() { if (dataStore == null) { throw new GeoToolsOpException(StatusCode.DATASTORE_NOT_DEFINED); } if ((table == null || table.isEmpty()) && !(all)) { throw new GeoToolsOpException(StatusCode.TABLE_NOT_DEFINED); } if (table != null && !table.isEmpty() && all) { throw new GeoToolsOpException(StatusCode.ALL_AND_TABLE_DEFINED); } String[] typeNames; if (all) { try { typeNames = dataStore.getTypeNames(); } catch (Exception e) { throw new GeoToolsOpException(StatusCode.UNABLE_TO_GET_NAMES); } if (typeNames.length == 0) { throw new GeoToolsOpException(StatusCode.NO_FEATURES_FOUND); } } else { SimpleFeatureType schema; try { schema = dataStore.getSchema(table); } catch (IOException e) { throw new GeoToolsOpException(StatusCode.TABLE_NOT_FOUND); } Preconditions.checkNotNull(schema); typeNames = new String[] { table }; } if (typeNames.length > 1 && alter && all) { throw new GeoToolsOpException(StatusCode.ALTER_AND_ALL_DEFINED); } return typeNames; } @SuppressWarnings({ "rawtypes", "unchecked" }) private FeatureSource getFeatureSource(String typeName) { FeatureSource featureSource; try { featureSource = dataStore.getFeatureSource(typeName); } catch (Exception e) { throw new GeoToolsOpException(StatusCode.UNABLE_TO_GET_FEATURES); } return new ForwardingFeatureSource(featureSource) { @Override public FeatureCollection getFeatures(Query query) throws IOException { final FeatureCollection features = super.getFeatures(query); return new ForwardingFeatureCollection(features) { @Override public FeatureIterator features() { final FeatureType featureType = getSchema(); final String fidPrefix = featureType.getName().getLocalPart() + "."; FeatureIterator iterator = delegate.features(); return new FidAndFtReplacerIterator(iterator, fidAttribute, fidPrefix, (SimpleFeatureType) featureType); } }; } }; } /** * Replaces the default geotools fid with the string representation of the value of an * attribute. * * If the specified attribute is null, does not exist or the value is null, an fid is created by * taking the default fid and removing the specified fidPrefix prefix from it. * * It also replaces the feature type. This is used to avoid identical feature types (in terms of * attributes) coming from different data sources (such as to shapefiles with different names) * being considered different for having a different name. It is used in this importer class to * decorate the name of the feature type when importing into a given tree, using the name of the * tree. * * The passed feature type should have the same attribute descriptions as the one to replace, * but no checking is performed to ensure that * */ private static class FidAndFtReplacerIterator extends ForwardingFeatureIterator<SimpleFeature> { private final String fidPrefix; private String attributeName; private SimpleFeatureType featureType; @SuppressWarnings("unchecked") public FidAndFtReplacerIterator(@SuppressWarnings("rawtypes") FeatureIterator iterator, final String attributeName, String fidPrefix, SimpleFeatureType featureType) { super(iterator); this.attributeName = attributeName; this.fidPrefix = fidPrefix; this.featureType = featureType; } @Override public SimpleFeature next() { SimpleFeature next = super.next(); if (attributeName == null) { String fid = next.getID(); if (fid.startsWith(fidPrefix)) { fid = fid.substring(fidPrefix.length()); } return new FidAndFtOverrideFeature(next, fid, featureType); } else { Object value = next.getAttribute(attributeName); Preconditions.checkNotNull(value); return new FidAndFtOverrideFeature(next, value.toString(), featureType); } } } private void insert(final WorkingTree workTree, final String path, @SuppressWarnings("rawtypes") final FeatureSource featureSource, final ProgressListener taskProgress) { final Query query = new Query(); CoordinateSequenceFactory coordSeq = new PackedCoordinateSequenceFactory(); query.getHints().add(new Hints(Hints.JTS_COORDINATE_SEQUENCE_FACTORY, coordSeq)); workTree.insert(path, featureSource, query, taskProgress); } private Iterator<Feature> transformIterator(Iterator<NodeRef> nodeIterator, final RevFeatureType newFeatureType) { Iterator<Feature> iterator = Iterators.transform(nodeIterator, new Function<NodeRef, Feature>() { @Override public Feature apply(NodeRef node) { return alter(node, newFeatureType); } }); return iterator; } /** * Translates a feature pointed by a node from its original feature type to a given one, using * values from those attributes that exist in both original and destination feature type. New * attributes are populated with null values * * @param node The node that points to the feature. No checking is performed to ensure the node * points to a feature instead of other type * @param featureType the destination feature type * @return a feature with the passed feature type and data taken from the input feature */ private Feature alter(NodeRef node, RevFeatureType featureType) { RevFeature oldFeature = command(RevObjectParse.class).setObjectId(node.objectId()) .call(RevFeature.class).get(); RevFeatureType oldFeatureType; oldFeatureType = command(RevObjectParse.class).setObjectId(node.getMetadataId()) .call(RevFeatureType.class).get(); ImmutableList<PropertyDescriptor> oldAttributes = oldFeatureType.sortedDescriptors(); ImmutableList<PropertyDescriptor> newAttributes = featureType.sortedDescriptors(); ImmutableList<Optional<Object>> oldValues = oldFeature.getValues(); List<Optional<Object>> newValues = Lists.newArrayList(); for (int i = 0; i < newAttributes.size(); i++) { int idx = oldAttributes.indexOf(newAttributes.get(i)); if (idx != -1) { Optional<Object> oldValue = oldValues.get(idx); newValues.add(oldValue); } else { newValues.add(Optional.absent()); } } RevFeature newFeature = RevFeatureImpl.build(ImmutableList.copyOf(newValues)); FeatureBuilder featureBuilder = new FeatureBuilder(featureType); Feature feature = featureBuilder.build(node.name(), newFeature); return feature; } /** * @param all if this is set, all tables from the data store will be imported * @return {@code this} */ public ImportOp setAll(boolean all) { this.all = all; return this; } /** * @param table if this is set, only the specified table will be imported from the data store * @return {@code this} */ public ImportOp setTable(String table) { this.table = table; return this; } /** * * @param overwrite If this is true, existing features will be overwritten in case they exist * and have the same path and Id than the features to import. If this is false, existing * features will not be overwritten, and a safe import is performed, where only those * features that do not already exists are added * @return {@code this} */ public ImportOp setOverwrite(boolean overwrite) { this.overwrite = overwrite; return this; } /** * * @param the attribute to use to create the feature id, if the default. */ public ImportOp setFidAttribute(String attribute) { this.fidAttribute = attribute; return this; } /** * @param force if true, it will change the default feature type of the tree we are importing * into and change all features under that tree to have that same feature type * @return {@code this} */ public ImportOp setAlter(boolean alter) { this.alter = alter; return this; } /** * * @param destPath the path to import to to. If not provided, it will be taken from the feature * type of the table to import. * @return {@code this} */ public ImportOp setDestinationPath(@Nullable String destPath) { Preconditions.checkArgument(destPath == null || !destPath.isEmpty()); this.destPath = destPath; return this; } /** * @param dataStore the data store to use for the import process * @return {@code this} */ public ImportOp setDataStore(DataStore dataStore) { this.dataStore = dataStore; return this; } private static final class FidAndFtOverrideFeature extends DecoratingFeature { private String fid; private SimpleFeatureType featureType; public FidAndFtOverrideFeature(SimpleFeature delegate, String fid, SimpleFeatureType featureType) { super(delegate); this.fid = fid; this.featureType = featureType; } @Override public SimpleFeatureType getType() { return featureType; } @Override public String getID() { return fid; } @Override public FeatureId getIdentifier() { return new FeatureIdImpl(fid); } } /** * Sets the name to use for the geometry descriptor. If not provided, the geometry name from the * source schema will be used. * * @param geomName */ public ImportOp setGeometryNameOverride(String geomName) { this.geomName = geomName; return this; } public ImportOp setUsePaging(boolean usePaging) { this.usePaging = usePaging; return this; } /** * Sets whether features will be added as they are, with their original feature type, or adapted * to the preexisting feature type of the destination tree. If true, the import operation will * try to adapt them to the current default feature type, and if that is not possible it will * throw an exception. Setting this parameter to true prevents the destination tree to have * mixed feature types. If importing onto a tree that doesn't exist, this has no effect at all, * since there is not previous feature type for that tree with which the features to import can * be compared * * @param forceFeatureType * @return {@code this} */ public ImportOp setAdaptToDefaultFeatureType(boolean adaptToDefaultFeatureType) { this.adaptToDefaultFeatureType = adaptToDefaultFeatureType; return this; } }
37.68779
100
0.639149
678e7ad271e8d355a54134c46a35824e4ea64ddd
132
class Example { public static void main(String args[]) { System.out.print("args"); } }
18.857143
47
0.454545
93e83a21b3302a728cfe6d4440fe69d8ae0f505b
17,350
/* * Copyright (c) 2015,robinjim(robinjim@126.com) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.robin.basis.controller.system; import com.robin.core.base.exception.ServiceException; import com.robin.core.base.exception.WebException; import com.robin.core.base.model.BaseObject; import com.robin.core.base.util.Const; import com.robin.core.base.util.StringUtils; import com.robin.core.collection.util.CollectionBaseConvert; import com.robin.core.query.util.PageQuery; import com.robin.core.web.controller.AbstractCrudDhtmlxController; import com.robin.core.web.util.Session; import com.robin.basis.model.system.SysOrg; import com.robin.basis.model.system.SysResource; import com.robin.basis.model.user.SysUser; import com.robin.basis.service.system.SysOrgService; import com.robin.basis.service.system.SysResourceService; import com.robin.basis.service.user.SysUserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.support.ResourceBundleMessageSource; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.util.*; @Controller @RequestMapping("/system/user") public class SysUserCrudController extends AbstractCrudDhtmlxController<SysUser, Long, SysUserService> { @Autowired private SysOrgService sysOrgService; @Autowired private SysResourceService sysResourceService; @Autowired private ResourceBundleMessageSource messageSource; @RequestMapping("/show") public String userList(HttpServletRequest request, HttpServletResponse response) { Session session=(Session)request.getSession().getAttribute(Const.SESSION); if(session.getOrgId()!=null){ request.setAttribute("orgId",session.getOrgId()); } request.setAttribute("resps",StringUtils.join(session.getResponsiblitys().toArray(),",")); return "/user/user_list"; } @RequestMapping("/list") @ResponseBody public Map<String, Object> listUser(HttpServletRequest request, HttpServletResponse response) { PageQuery query = wrapPageQuery(request); query.setSelectParamId("GET_SYSUSERINFO"); wrapQuery(request,query); doQuery(request,null, query); List<SysOrg> orgList = sysOrgService.queryByField("orgStatus", BaseObject.OPER_EQ, Const.VALID); setCode("ORG", orgList, "orgName", "id"); setCode("ACCOUNTTYPE"); filterListByCodeSet(query, "accountType", "ACCOUNTTYPE",null); filterListByCodeSet(query, "orgId", "ORG",messageSource.getMessage("title.defaultOrg",null,Locale.getDefault())); return wrapDhtmlxGridOutput(query); } @Override protected String wrapQuery(HttpServletRequest request, PageQuery query) { String orgIds = null; if (request.getParameter("orgId") != null && !request.getParameter("orgId").isEmpty()) { orgIds = sysOrgService.getSubIdByParentOrgId(Long.valueOf(request.getParameter("orgId"))); } query.getParameters().put("queryCondition", wrapQuery(request, orgIds)); return null; } @RequestMapping("/edit") @ResponseBody public Map<String, Object> editUser(HttpServletRequest request, HttpServletResponse response) { String id = request.getParameter("id"); return doEdit(Long.valueOf(id)); } @RequestMapping("/save") @ResponseBody public Map<String, Object> saveUser(HttpServletRequest request, HttpServletResponse response){ //check userAccount unique List<SysUser> list = this.service.queryByField("userAccount", BaseObject.OPER_EQ, request.getParameter("userAccount")); if (!list.isEmpty()) { return wrapError(new WebException(messageSource.getMessage("message.userNameExists", null, Locale.getDefault()))); } else { return doSave(wrapRequest(request)); } } @RequestMapping("/update") @ResponseBody public Map<String, Object> updateUser(HttpServletRequest request, HttpServletResponse response) { Long id = Long.valueOf(request.getParameter("id")); //check userAccount unique List<SysUser> list = this.service.queryByField("userAccount", BaseObject.OPER_EQ, request.getParameter("userAccount")); if ((list.size() == 1 && id.equals(list.get(0).getId())) || list.isEmpty()) { return doUpdate(wrapRequest(request), id); } else { return wrapError(new WebException(messageSource.getMessage("message.userNameExists", null, Locale.getDefault()))); } } @RequestMapping("/listorg") @ResponseBody public Map<String, Object> listUserOrg(HttpServletRequest request) { Map<String, Object> retMap = new HashMap<>(); if (request.getSession().getAttribute(Const.SESSION) != null) { Session session = (Session) request.getSession().getAttribute(Const.SESSION); PageQuery query = new PageQuery(); query.setPageSize(0); query.setSelectParamId("GETUSER_ORG"); query.setParameterArr(new Object[]{session.getUserId()}); service.queryBySelectId(query); retMap.put("options", query.getRecordSet()); wrapSuccess(retMap); } else { wrapFailed(retMap, messageSource.getMessage("login.require", null, Locale.getDefault())); } return retMap; } @RequestMapping("/delete") @ResponseBody public Map<String, Object> deleteUser(HttpServletRequest request, HttpServletResponse response) { Map<String,Object> retMap=new HashMap<>(); try{ Long[] ids = parseId(request.getParameter("ids")); service.deleteUsers(ids); wrapSuccess(retMap); }catch (Exception ex){ wrapFailed(retMap,ex); } return retMap; } @RequestMapping("/changepwd") @ResponseBody public Map<String, Object> changePassword(HttpServletRequest request, HttpServletResponse response) { Long id = Long.valueOf(request.getParameter("id")); Map<String, Object> retMap = new HashMap<>(); try { SysUser user = this.service.getEntity(id); if (user.getUserPassword() != null && !user.getUserPassword().isEmpty()) { if (request.getParameter("orgPwd") == null || !StringUtils.getMd5Encry(request.getParameter("orgPwd")).equals(user.getUserPassword())) { throw new WebException(messageSource.getMessage("message.passwordOriginNotMatch", null, Locale.getDefault())); } } user.setUserPassword(StringUtils.getMd5Encry(request.getParameter("newPwd"))); this.service.updateEntity(user); wrapSuccess(retMap); } catch (Exception ex) { wrapFailed(retMap, ex); } return retMap; } @RequestMapping("/active") @ResponseBody public Map<String, Object> activeUser(HttpServletRequest request, HttpServletResponse response) { Long id = Long.valueOf(request.getParameter("id")); Map<String, Object> retMap = new HashMap<>(); try { SysUser user = this.service.getEntity(id); if (user.getUserPassword() == null || user.getUserPassword().isEmpty()) { throw new ServiceException(messageSource.getMessage("message.passwordEmpty", null, Locale.getDefault())); } else { user.setUserStatus(Const.VALID); this.service.updateEntity(user); wrapSuccess(retMap); } } catch (ServiceException ex) { wrapFailed(retMap, ex); } return retMap; } public String wrapQuery(HttpServletRequest request, String orgIds) { StringBuilder builder = new StringBuilder(); if (request.getParameter("userName") != null && !"".equals(request.getParameter("userName"))) { builder.append(" and user_account like '%" + request.getParameter("userName") + "%'"); } if (request.getParameter("accountType") != null && !"".equals(request.getParameter("accountType"))) { builder.append(" and account_type =" + request.getParameter("accountType")); } if (orgIds != null && !orgIds.isEmpty()) { builder.append(" and org_id in (" + orgIds + ")"); } return builder.toString(); } @RequestMapping("/showright") public String userRight(HttpServletRequest request, HttpServletResponse response) { String userId = request.getParameter("userId"); request.setAttribute("userId", userId); return "user/show_right"; } @RequestMapping("listright") @ResponseBody public Map<String, Object> listUserRight(HttpServletRequest request, HttpServletResponse response) { Session session=(Session) request.getSession().getAttribute(Const.SESSION); String userId = request.getParameter("userId"); List<Map<String, Object>> retList = new ArrayList<Map<String, Object>>(); String sql = "select distinct(a.id) as id,a.res_name as name from t_sys_resource_info a,t_sys_resource_role_r b,t_sys_user_role_r c where a.id=b.res_id and b.role_id=c.role_id and c.user_id=? ORDER BY a.RES_CODE"; List<Long> resIdList = new ArrayList<Long>(); try { PageQuery query=new PageQuery(); query.setPageSize(0); if(session.getOrgId()==null){ query.setSelectParamId("GET_SYSRESOURCEBYRESP"); }else{ query.setSelectParamId("GET_ORGRESOURCEBYRESP"); } query.setParameterArr(new Object[]{Long.parseLong(userId)}); service.queryBySelectId(query); List<Map<String, Object>> list = query.getRecordSet(); for (Map<String, Object> map : list) { resIdList.add(Long.valueOf(map.get("id").toString())); } List<SysResource> resList = sysResourceService.queryByField("status", BaseObject.OPER_EQ, "1"); //正向方向赋权 List<Map<String, Object>> userRightList = service.queryBySql("select res_id as resId,assign_type as type from t_sys_resource_user_r where user_id=? and status=?", new Object[]{Long.valueOf(userId), "1"}); Map<String, List<Map<String, Object>>> typeMap = CollectionBaseConvert.convertToMapByParentKeyWithObjVal(userRightList, "type"); filterMenu(typeMap,resList,retList,resIdList); } catch (Exception ex) { ex.printStackTrace(); } Map<String, Object> retMaps = new HashMap<String, Object>(); retMaps.put("id", "0"); retMaps.put("text", "菜单"); retMaps.put("item", retList); return retMaps; } private void filterMenu(Map<String, List<Map<String, Object>>> typeMap,List<SysResource> resList,List<Map<String, Object>> retList,List<Long> resIdList){ List<Long> addList = new ArrayList<Long>(); List<Long> delList = new ArrayList<Long>(); Map<String, Object> rmap = new HashMap<String, Object>(); if (typeMap.containsKey("1")) { for (Map<String, Object> map : typeMap.get("1")) { addList.add(Long.valueOf(map.get("resId").toString())); } } if (typeMap.containsKey("2")) { for (Map<String, Object> map : typeMap.get("2")) { delList.add(Long.valueOf(map.get("resId").toString())); } } for (SysResource res : resList) { String pid = res.getPid().toString(); if ("0".equals(pid)) { Map<String, Object> tmap = new HashMap<String, Object>(); tmap.put("id", res.getId()); tmap.put("text", res.getName()); rmap.put(res.getId().toString(), tmap); retList.add(tmap); } else { if (rmap.containsKey(pid)) { Map<String, Object> tmpmap = (Map<String, Object>) rmap.get(pid); Map<String, Object> t2map = new HashMap<String, Object>(); t2map.put("id", res.getId()); t2map.put("text", res.getName()); if (resIdList.contains(res.getId())) { if (delList.contains(res.getId())) { t2map.put("style", "font-weight:bold;text-decoration:underline;color:#ee1010"); } else { t2map.put("checked", "1"); t2map.put("style", "font-weight:bold;text-decoration:underline"); } } else if (addList.contains(res.getId())) { t2map.put("checked", "1"); t2map.put("style", "font-weight:bold;color:#1010ee"); } if (!tmpmap.containsKey("item")) { List<Map<String, Object>> list1 = new ArrayList<Map<String, Object>>(); list1.add(t2map); tmpmap.put("item", list1); } else { List<Map<String, Object>> list1 = (List<Map<String, Object>>) tmpmap.get("item"); list1.add(t2map); } } } } } @RequestMapping("/assignright") @ResponseBody public Map<String, Object> assignRight(HttpServletRequest request, HttpServletResponse response) { Session session=(Session) request.getSession().getAttribute(Const.SESSION); String[] ids = request.getParameter("ids").split(","); String userId = request.getParameter("userId"); String sql = "select distinct(a.id) as id,a.res_name as name from t_sys_resource_info a,t_sys_resource_role_r b,t_sys_user_role_r c where a.id=b.res_id and b.role_id=c.role_id and c.user_id=? ORDER BY a.RES_CODE"; Map<String, Object> retMaps = new HashMap<String, Object>(); try { PageQuery query=new PageQuery(); query.setPageSize(0); if(session.getOrgId()==null){ query.setSelectParamId("GET_SYSRESOURCEBYRESP"); }else{ query.setSelectParamId("GET_ORGRESOURCEBYRESP"); } query.setParameterArr(new Object[]{Long.parseLong(userId)}); service.queryBySelectId(query); List<Map<String, Object>> list = query.getRecordSet(); List<String> delList = new ArrayList<String>(); SysResource queryVO=new SysResource(); queryVO.setOrgId(session.getOrgId()==null?0L:session.getOrgId()); queryVO.setStatus(Const.VALID); List<SysResource> avaiableList = sysResourceService.queryByVO(queryVO,null,null); Map<String, SysResource> resMap = new HashMap<String, SysResource>(); for (SysResource res : avaiableList) { if (res.getPid() != -1) { resMap.put(res.getId().toString(), res); } } for (Map<String, Object> map : list) { delList.add(map.get("id").toString()); } List<String> addList = new ArrayList<String>(); for (int i = 0; i < ids.length; i++) { if (resMap.containsKey(ids[i])) { addList.add(ids[i]); } } for (int i = 0; i < ids.length; i++) { int pos = delList.indexOf(ids[i]); int pos1 = addList.indexOf(ids[i]); if (pos != -1 && pos1 != -1) { delList.remove(pos); addList.remove(pos1); } } if (!delList.isEmpty() || !addList.isEmpty()) { //有权限修改 sysResourceService.updateUserResourceRight(userId, addList, delList); retMaps.put("success", "true"); } else { //no chage,ignore update retMaps.put("success", "false"); retMaps.put("message", "没有任何权限修改"); } } catch (ServiceException ex) { retMaps.put("success", "false"); retMaps.put("message", ex.getMessage()); } return retMaps; } }
45.064935
221
0.604092
b3e313d971d657142a4c23df0c1718a4ae5198fb
1,172
package com.agonyengine.config; import com.agonyengine.model.map.Direction; import com.agonyengine.model.command.impl.MoveCommand; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import javax.inject.Inject; @Configuration public class MovementConfiguration { private ApplicationContext applicationContext; @Inject public MovementConfiguration(ApplicationContext applicationContext) { this.applicationContext = applicationContext; } @Bean(name = "northCommand") public MoveCommand northCommand() { return new MoveCommand(Direction.NORTH, applicationContext); } @Bean(name = "eastCommand") public MoveCommand eastCommand() { return new MoveCommand(Direction.EAST, applicationContext); } @Bean(name = "southCommand") public MoveCommand southCommand() { return new MoveCommand(Direction.SOUTH, applicationContext); } @Bean(name = "westCommand") public MoveCommand westCommand() { return new MoveCommand(Direction.WEST, applicationContext); } }
29.3
73
0.748294
f3cbcdf230f3786336e7776c765db14048f13322
379
package org.tona.codechallenge.controllers.exceptions; import lombok.Getter; import lombok.Setter; public class DuplicatedMovieException extends Exception { private static final long serialVersionUID = 1L; public @Getter @Setter String title; public DuplicatedMovieException() { this(""); } public DuplicatedMovieException(String title) { this.title = title; } }
22.294118
57
0.773087
e8e23edd43a1ba4fdb132fc5790b22e8a21b4879
3,038
package jstat.maths.errorfunctions; import jstat.base.CommonConstants; import jstat.maths.functions.IVectorRealFunction; import org.nd4j.linalg.api.ndarray.INDArray; import org.nd4j.linalg.factory.Nd4j; /** * LogisticSSEVectorFunction implements * J = \sum */ public class LogisticSSEFunction implements ILossFunction { /** * Constructor */ public LogisticSSEFunction(IVectorRealFunction hypothesis ){ if(hypothesis == null){ throw new IllegalArgumentException("Hypothesis function cannot be null"); } this.hypothesis = hypothesis; } /** * Evaluate the error function using the given data, labels */ @Override public double evaluate(INDArray data, INDArray labels){ if(data.size(0) != labels.size(0)){ throw new IllegalArgumentException("Invalid number of data points and labels vector size"); } double result = 0.0; for(int rowIdx=0; rowIdx<data.size(0); ++rowIdx){ INDArray row = data.getRow(rowIdx); double y = labels.getDouble(rowIdx); double hypothesisValue = this.hypothesis.evaluate(row); //h is close to one if(Math.abs(hypothesisValue) - 1.0 < CommonConstants.getTol()){ //we plug a large error contribution if y is anything than one if( y != 1.){ result += 1.0; } } else if(Math.abs(hypothesisValue) < CommonConstants.getTol()){ // std::cout<<" log_h infinity"<<std::endl; //hval is zero. we only get contribution //if the label is not zero as well if( y > CommonConstants.getTol()){ result += 1.0; } } else{ //do it normally //calculate the logarithms and check if they are //infinite or nana double log_one_minus_h = Math.log(1. - hypothesisValue); double log_h = Math.log(hypothesisValue); result += y*log_h +(1.-y)*log_one_minus_h; } } return -result; } /** * Returns the gradients on the given data */ @Override public INDArray paramGradients(INDArray data, INDArray labels){ INDArray gradients = Nd4j.zeros(this.hypothesis.numCoeffs()); for(int rowIdx=0; rowIdx<data.size(0); ++rowIdx){ INDArray row = data.getRow(rowIdx); double diff = (labels.getDouble(rowIdx) - this.hypothesis.evaluate(row)); INDArray hypothesisGrads = this.hypothesis.coeffGradients(row); for(int coeff=0; coeff<this.hypothesis.numCoeffs(); ++coeff){ double grad = gradients.getDouble(coeff) -2.0*diff*hypothesisGrads.getDouble(coeff); gradients.putScalar(coeff, grad); } } return gradients; } private IVectorRealFunction hypothesis; }
29.211538
103
0.578341
8f573e5b206af6ef953899219c5fc6cb83a8875b
1,540
/* * Copyright 2021 kings1990(darkings1990@gmail.com) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.github.kings1990.plugin.fastrequest.action; import com.intellij.icons.AllIcons; import com.intellij.openapi.actionSystem.AnAction; import com.intellij.openapi.actionSystem.AnActionEvent; import com.intellij.openapi.actionSystem.LangDataKeys; import com.intellij.openapi.options.ShowSettingsUtil; import com.intellij.openapi.project.Project; import io.github.kings1990.plugin.fastrequest.util.MyResourceBundleUtil; import org.jetbrains.annotations.NotNull; public class OpenConfigAction extends AnAction { public OpenConfigAction() { super(MyResourceBundleUtil.getKey("ManageConfig"), MyResourceBundleUtil.getKey("ManageConfig"), AllIcons.General.Settings); } @Override public void actionPerformed(@NotNull AnActionEvent e) { Project project = e.getData(LangDataKeys.PROJECT); ShowSettingsUtil.getInstance().showSettingsDialog(project, "Restful Fast Request"); } }
38.5
131
0.775325
4c018250e21d450ce696347efb2360086655b6dc
61,770
package com.stripe.model; import com.google.gson.annotations.SerializedName; import com.stripe.Stripe; import com.stripe.exception.StripeException; import com.stripe.model.radar.Rule; import com.stripe.net.ApiResource; import com.stripe.net.RequestOptions; import com.stripe.param.ChargeCaptureParams; import com.stripe.param.ChargeCreateParams; import com.stripe.param.ChargeListParams; import com.stripe.param.ChargeRetrieveParams; import com.stripe.param.ChargeUpdateParams; import java.util.List; import java.util.Map; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.Setter; @Getter @Setter @EqualsAndHashCode(callSuper = false) public class Charge extends ApiResource implements MetadataStore<Charge>, BalanceTransactionSource { @SerializedName("alternate_statement_descriptors") AlternateStatementDescriptors alternateStatementDescriptors; /** * A positive integer representing how much to charge in the [smallest currency * unit](https://stripe.com/docs/currencies#zero-decimal) (e.g., 100 cents to charge $1.00 or 100 * to charge ¥100, a zero-decimal currency). The minimum amount is $0.50 US or [equivalent in * charge currency](https://stripe.com/docs/currencies#minimum-and-maximum-charge-amounts). The * amount value supports up to eight digits (e.g., a value of 99999999 for a USD charge of * $999,999.99). */ @SerializedName("amount") Long amount; /** * Amount in %s refunded (can be less than the amount attribute on the charge if a partial refund * was issued). */ @SerializedName("amount_refunded") Long amountRefunded; /** ID of the Connect application that created the charge. */ @SerializedName("application") @Getter(lombok.AccessLevel.NONE) @Setter(lombok.AccessLevel.NONE) ExpandableField<Application> application; /** * The application fee (if any) for the charge. [See the Connect * documentation](https://stripe.com/docs/connect/direct-charges#collecting-fees) for details. */ @SerializedName("application_fee") @Getter(lombok.AccessLevel.NONE) @Setter(lombok.AccessLevel.NONE) ExpandableField<ApplicationFee> applicationFee; /** * The amount of the application fee (if any) for the charge. [See the Connect * documentation](https://stripe.com/docs/connect/direct-charges#collecting-fees) for details. */ @SerializedName("application_fee_amount") Long applicationFeeAmount; /** Authorization code on the charge. */ @SerializedName("authorization_code") String authorizationCode; /** * ID of the balance transaction that describes the impact of this charge on your account balance * (not including refunds or disputes). */ @SerializedName("balance_transaction") @Getter(lombok.AccessLevel.NONE) @Setter(lombok.AccessLevel.NONE) ExpandableField<BalanceTransaction> balanceTransaction; @SerializedName("billing_details") PaymentMethod.BillingDetails billingDetails; /** * If the charge was created without capturing, this Boolean represents whether it is still * uncaptured or has since been captured. */ @SerializedName("captured") Boolean captured; /** Time at which the object was created. Measured in seconds since the Unix epoch. */ @SerializedName("created") Long created; /** * Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in * lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). */ @SerializedName("currency") String currency; /** ID of the customer this charge is for if one exists. */ @SerializedName("customer") @Getter(lombok.AccessLevel.NONE) @Setter(lombok.AccessLevel.NONE) ExpandableField<Customer> customer; /** An arbitrary string attached to the object. Often useful for displaying to users. */ @SerializedName("description") String description; /** * ID of an existing, connected Stripe account to transfer funds to if `transfer_data` was * specified in the charge request. */ @SerializedName("destination") @Getter(lombok.AccessLevel.NONE) @Setter(lombok.AccessLevel.NONE) ExpandableField<Account> destination; /** Details about the dispute if the charge has been disputed. */ @SerializedName("dispute") @Getter(lombok.AccessLevel.NONE) @Setter(lombok.AccessLevel.NONE) ExpandableField<Dispute> dispute; /** Whether the charge has been disputed. */ @SerializedName("disputed") Boolean disputed; /** * Error code explaining reason for charge failure if available (see [the errors * section](https://stripe.com/docs/api#errors) for a list of codes). */ @SerializedName("failure_code") String failureCode; /** Message to user further explaining reason for charge failure if available. */ @SerializedName("failure_message") String failureMessage; /** Information on fraud assessments for the charge. */ @SerializedName("fraud_details") FraudDetails fraudDetails; /** Unique identifier for the object. */ @Getter(onMethod_ = {@Override}) @SerializedName("id") String id; /** ID of the invoice this charge is for if one exists. */ @SerializedName("invoice") @Getter(lombok.AccessLevel.NONE) @Setter(lombok.AccessLevel.NONE) ExpandableField<Invoice> invoice; @SerializedName("level3") Level3 level3; /** * Has the value `true` if the object exists in live mode or the value `false` if the object * exists in test mode. */ @SerializedName("livemode") Boolean livemode; /** * Set of key-value pairs that you can attach to an object. This can be useful for storing * additional information about the object in a structured format. */ @Getter(onMethod_ = {@Override}) @SerializedName("metadata") Map<String, String> metadata; /** String representing the object's type. Objects of the same type share the same value. */ @SerializedName("object") String object; /** * The account (if any) the charge was made on behalf of without triggering an automatic transfer. * See the [Connect documentation](https://stripe.com/docs/connect/charges-transfers) for details. */ @SerializedName("on_behalf_of") @Getter(lombok.AccessLevel.NONE) @Setter(lombok.AccessLevel.NONE) ExpandableField<Account> onBehalfOf; /** ID of the order this charge is for if one exists. */ @SerializedName("order") @Getter(lombok.AccessLevel.NONE) @Setter(lombok.AccessLevel.NONE) ExpandableField<Order> order; /** * Details about whether the payment was accepted, and why. See [understanding * declines](https://stripe.com/docs/declines) for details. */ @SerializedName("outcome") Outcome outcome; /** `true` if the charge succeeded, or was successfully authorized for later capture. */ @SerializedName("paid") Boolean paid; /** ID of the PaymentIntent associated with this charge, if one exists. */ @SerializedName("payment_intent") String paymentIntent; /** ID of the payment method used in this charge. */ @SerializedName("payment_method") String paymentMethod; /** Details about the payment method at the time of the transaction. */ @SerializedName("payment_method_details") PaymentMethodDetails paymentMethodDetails; /** This is the email address that the receipt for this charge was sent to. */ @SerializedName("receipt_email") String receiptEmail; /** * This is the transaction number that appears on email receipts sent for this charge. This * attribute will be `null` until a receipt has been sent. */ @SerializedName("receipt_number") String receiptNumber; /** * This is the URL to view the receipt for this charge. The receipt is kept up-to-date to the * latest state of the charge, including any refunds. If the charge is for an Invoice, the receipt * will be stylized as an Invoice receipt. */ @SerializedName("receipt_url") String receiptUrl; /** * Whether the charge has been fully refunded. If the charge is only partially refunded, this * attribute will still be false. */ @SerializedName("refunded") Boolean refunded; /** A list of refunds that have been applied to the charge. */ @SerializedName("refunds") RefundCollection refunds; /** ID of the review associated with this charge if one exists. */ @SerializedName("review") @Getter(lombok.AccessLevel.NONE) @Setter(lombok.AccessLevel.NONE) ExpandableField<Review> review; /** Shipping information for the charge. */ @SerializedName("shipping") ShippingDetails shipping; /** * This is a legacy field that will be removed in the future. It contains the Source, Card, or * BankAccount object used for the charge. For details about the payment method used for this * charge, refer to `payment_method` or `payment_method_details` instead. */ @SerializedName("source") PaymentSource source; /** * The transfer ID which created this charge. Only present if the charge came from another Stripe * account. [See the Connect documentation](https://stripe.com/docs/connect/destination-charges) * for details. */ @SerializedName("source_transfer") @Getter(lombok.AccessLevel.NONE) @Setter(lombok.AccessLevel.NONE) ExpandableField<Transfer> sourceTransfer; /** * For card charges, use `statement_descriptor_suffix` instead. Otherwise, you can use this value * as the complete description of a charge on your customers’ statements. Must contain at least * one letter, maximum 22 characters. */ @SerializedName("statement_descriptor") String statementDescriptor; /** * Provides information about the charge that customers see on their statements. Concatenated with * the prefix (shortened descriptor) or statement descriptor that’s set on the account to form the * complete statement descriptor. Maximum 22 characters for the concatenated descriptor. */ @SerializedName("statement_descriptor_suffix") String statementDescriptorSuffix; /** The status of the payment is either `succeeded`, `pending`, or `failed`. */ @SerializedName("status") String status; /** * ID of the transfer to the `destination` account (only applicable if the charge was created * using the `destination` parameter). */ @SerializedName("transfer") @Getter(lombok.AccessLevel.NONE) @Setter(lombok.AccessLevel.NONE) ExpandableField<Transfer> transfer; /** * An optional dictionary including the account to automatically transfer to as part of a * destination charge. [See the Connect * documentation](https://stripe.com/docs/connect/destination-charges) for details. */ @SerializedName("transfer_data") TransferData transferData; /** * A string that identifies this transaction as part of a group. See the [Connect * documentation](https://stripe.com/docs/connect/charges-transfers#grouping-transactions) for * details. */ @SerializedName("transfer_group") String transferGroup; /** Get id of expandable `application` object. */ public String getApplication() { return (this.application != null) ? this.application.getId() : null; } public void setApplication(String id) { this.application = ApiResource.setExpandableFieldId(id, this.application); } /** Get expanded `application`. */ public Application getApplicationObject() { return (this.application != null) ? this.application.getExpanded() : null; } public void setApplicationObject(Application expandableObject) { this.application = new ExpandableField<Application>(expandableObject.getId(), expandableObject); } /** Get id of expandable `applicationFee` object. */ public String getApplicationFee() { return (this.applicationFee != null) ? this.applicationFee.getId() : null; } public void setApplicationFee(String id) { this.applicationFee = ApiResource.setExpandableFieldId(id, this.applicationFee); } /** Get expanded `applicationFee`. */ public ApplicationFee getApplicationFeeObject() { return (this.applicationFee != null) ? this.applicationFee.getExpanded() : null; } public void setApplicationFeeObject(ApplicationFee expandableObject) { this.applicationFee = new ExpandableField<ApplicationFee>(expandableObject.getId(), expandableObject); } /** Get id of expandable `balanceTransaction` object. */ public String getBalanceTransaction() { return (this.balanceTransaction != null) ? this.balanceTransaction.getId() : null; } public void setBalanceTransaction(String id) { this.balanceTransaction = ApiResource.setExpandableFieldId(id, this.balanceTransaction); } /** Get expanded `balanceTransaction`. */ public BalanceTransaction getBalanceTransactionObject() { return (this.balanceTransaction != null) ? this.balanceTransaction.getExpanded() : null; } public void setBalanceTransactionObject(BalanceTransaction expandableObject) { this.balanceTransaction = new ExpandableField<BalanceTransaction>(expandableObject.getId(), expandableObject); } /** Get id of expandable `customer` object. */ public String getCustomer() { return (this.customer != null) ? this.customer.getId() : null; } public void setCustomer(String id) { this.customer = ApiResource.setExpandableFieldId(id, this.customer); } /** Get expanded `customer`. */ public Customer getCustomerObject() { return (this.customer != null) ? this.customer.getExpanded() : null; } public void setCustomerObject(Customer expandableObject) { this.customer = new ExpandableField<Customer>(expandableObject.getId(), expandableObject); } /** Get id of expandable `destination` object. */ public String getDestination() { return (this.destination != null) ? this.destination.getId() : null; } public void setDestination(String id) { this.destination = ApiResource.setExpandableFieldId(id, this.destination); } /** Get expanded `destination`. */ public Account getDestinationObject() { return (this.destination != null) ? this.destination.getExpanded() : null; } public void setDestinationObject(Account expandableObject) { this.destination = new ExpandableField<Account>(expandableObject.getId(), expandableObject); } /** Get id of expandable `dispute` object. */ public String getDispute() { return (this.dispute != null) ? this.dispute.getId() : null; } public void setDispute(String id) { this.dispute = ApiResource.setExpandableFieldId(id, this.dispute); } /** Get expanded `dispute`. */ public Dispute getDisputeObject() { return (this.dispute != null) ? this.dispute.getExpanded() : null; } public void setDisputeObject(Dispute expandableObject) { this.dispute = new ExpandableField<Dispute>(expandableObject.getId(), expandableObject); } /** Get id of expandable `invoice` object. */ public String getInvoice() { return (this.invoice != null) ? this.invoice.getId() : null; } public void setInvoice(String id) { this.invoice = ApiResource.setExpandableFieldId(id, this.invoice); } /** Get expanded `invoice`. */ public Invoice getInvoiceObject() { return (this.invoice != null) ? this.invoice.getExpanded() : null; } public void setInvoiceObject(Invoice expandableObject) { this.invoice = new ExpandableField<Invoice>(expandableObject.getId(), expandableObject); } /** Get id of expandable `onBehalfOf` object. */ public String getOnBehalfOf() { return (this.onBehalfOf != null) ? this.onBehalfOf.getId() : null; } public void setOnBehalfOf(String id) { this.onBehalfOf = ApiResource.setExpandableFieldId(id, this.onBehalfOf); } /** Get expanded `onBehalfOf`. */ public Account getOnBehalfOfObject() { return (this.onBehalfOf != null) ? this.onBehalfOf.getExpanded() : null; } public void setOnBehalfOfObject(Account expandableObject) { this.onBehalfOf = new ExpandableField<Account>(expandableObject.getId(), expandableObject); } /** Get id of expandable `order` object. */ public String getOrder() { return (this.order != null) ? this.order.getId() : null; } public void setOrder(String id) { this.order = ApiResource.setExpandableFieldId(id, this.order); } /** Get expanded `order`. */ public Order getOrderObject() { return (this.order != null) ? this.order.getExpanded() : null; } public void setOrderObject(Order expandableObject) { this.order = new ExpandableField<Order>(expandableObject.getId(), expandableObject); } /** Get id of expandable `review` object. */ public String getReview() { return (this.review != null) ? this.review.getId() : null; } public void setReview(String id) { this.review = ApiResource.setExpandableFieldId(id, this.review); } /** Get expanded `review`. */ public Review getReviewObject() { return (this.review != null) ? this.review.getExpanded() : null; } public void setReviewObject(Review expandableObject) { this.review = new ExpandableField<Review>(expandableObject.getId(), expandableObject); } /** Get id of expandable `sourceTransfer` object. */ public String getSourceTransfer() { return (this.sourceTransfer != null) ? this.sourceTransfer.getId() : null; } public void setSourceTransfer(String id) { this.sourceTransfer = ApiResource.setExpandableFieldId(id, this.sourceTransfer); } /** Get expanded `sourceTransfer`. */ public Transfer getSourceTransferObject() { return (this.sourceTransfer != null) ? this.sourceTransfer.getExpanded() : null; } public void setSourceTransferObject(Transfer expandableObject) { this.sourceTransfer = new ExpandableField<Transfer>(expandableObject.getId(), expandableObject); } /** Get id of expandable `transfer` object. */ public String getTransfer() { return (this.transfer != null) ? this.transfer.getId() : null; } public void setTransfer(String id) { this.transfer = ApiResource.setExpandableFieldId(id, this.transfer); } /** Get expanded `transfer`. */ public Transfer getTransferObject() { return (this.transfer != null) ? this.transfer.getExpanded() : null; } public void setTransferObject(Transfer expandableObject) { this.transfer = new ExpandableField<Transfer>(expandableObject.getId(), expandableObject); } /** * Returns a list of charges you’ve previously created. The charges are returned in sorted order, * with the most recent charges appearing first. */ public static ChargeCollection list(Map<String, Object> params) throws StripeException { return list(params, (RequestOptions) null); } /** * Returns a list of charges you’ve previously created. The charges are returned in sorted order, * with the most recent charges appearing first. */ public static ChargeCollection list(Map<String, Object> params, RequestOptions options) throws StripeException { String url = String.format("%s%s", Stripe.getApiBase(), "/v1/charges"); return ApiResource.requestCollection(url, params, ChargeCollection.class, options); } /** * Returns a list of charges you’ve previously created. The charges are returned in sorted order, * with the most recent charges appearing first. */ public static ChargeCollection list(ChargeListParams params) throws StripeException { return list(params, (RequestOptions) null); } /** * Returns a list of charges you’ve previously created. The charges are returned in sorted order, * with the most recent charges appearing first. */ public static ChargeCollection list(ChargeListParams params, RequestOptions options) throws StripeException { String url = String.format("%s%s", Stripe.getApiBase(), "/v1/charges"); return ApiResource.requestCollection(url, params, ChargeCollection.class, options); } /** * To charge a credit card or other payment source, you create a <code>Charge</code> object. If * your API key is in test mode, the supplied payment source (e.g., card) won’t actually be * charged, although everything else will occur as if in live mode. (Stripe assumes that the * charge would have completed successfully). */ public static Charge create(Map<String, Object> params) throws StripeException { return create(params, (RequestOptions) null); } /** * To charge a credit card or other payment source, you create a <code>Charge</code> object. If * your API key is in test mode, the supplied payment source (e.g., card) won’t actually be * charged, although everything else will occur as if in live mode. (Stripe assumes that the * charge would have completed successfully). */ public static Charge create(Map<String, Object> params, RequestOptions options) throws StripeException { String url = String.format("%s%s", Stripe.getApiBase(), "/v1/charges"); return ApiResource.request(ApiResource.RequestMethod.POST, url, params, Charge.class, options); } /** * To charge a credit card or other payment source, you create a <code>Charge</code> object. If * your API key is in test mode, the supplied payment source (e.g., card) won’t actually be * charged, although everything else will occur as if in live mode. (Stripe assumes that the * charge would have completed successfully). */ public static Charge create(ChargeCreateParams params) throws StripeException { return create(params, (RequestOptions) null); } /** * To charge a credit card or other payment source, you create a <code>Charge</code> object. If * your API key is in test mode, the supplied payment source (e.g., card) won’t actually be * charged, although everything else will occur as if in live mode. (Stripe assumes that the * charge would have completed successfully). */ public static Charge create(ChargeCreateParams params, RequestOptions options) throws StripeException { String url = String.format("%s%s", Stripe.getApiBase(), "/v1/charges"); return ApiResource.request(ApiResource.RequestMethod.POST, url, params, Charge.class, options); } /** * Retrieves the details of a charge that has previously been created. Supply the unique charge ID * that was returned from your previous request, and Stripe will return the corresponding charge * information. The same information is returned when creating or refunding the charge. */ public static Charge retrieve(String charge) throws StripeException { return retrieve(charge, (Map<String, Object>) null, (RequestOptions) null); } /** * Retrieves the details of a charge that has previously been created. Supply the unique charge ID * that was returned from your previous request, and Stripe will return the corresponding charge * information. The same information is returned when creating or refunding the charge. */ public static Charge retrieve(String charge, RequestOptions options) throws StripeException { return retrieve(charge, (Map<String, Object>) null, options); } /** * Retrieves the details of a charge that has previously been created. Supply the unique charge ID * that was returned from your previous request, and Stripe will return the corresponding charge * information. The same information is returned when creating or refunding the charge. */ public static Charge retrieve(String charge, Map<String, Object> params, RequestOptions options) throws StripeException { String url = String.format( "%s%s", Stripe.getApiBase(), String.format("/v1/charges/%s", ApiResource.urlEncodeId(charge))); return ApiResource.request(ApiResource.RequestMethod.GET, url, params, Charge.class, options); } /** * Retrieves the details of a charge that has previously been created. Supply the unique charge ID * that was returned from your previous request, and Stripe will return the corresponding charge * information. The same information is returned when creating or refunding the charge. */ public static Charge retrieve(String charge, ChargeRetrieveParams params, RequestOptions options) throws StripeException { String url = String.format( "%s%s", Stripe.getApiBase(), String.format("/v1/charges/%s", ApiResource.urlEncodeId(charge))); return ApiResource.request(ApiResource.RequestMethod.GET, url, params, Charge.class, options); } /** * Updates the specified charge by setting the values of the parameters passed. Any parameters not * provided will be left unchanged. */ @Override public Charge update(Map<String, Object> params) throws StripeException { return update(params, (RequestOptions) null); } /** * Updates the specified charge by setting the values of the parameters passed. Any parameters not * provided will be left unchanged. */ @Override public Charge update(Map<String, Object> params, RequestOptions options) throws StripeException { String url = String.format( "%s%s", Stripe.getApiBase(), String.format("/v1/charges/%s", ApiResource.urlEncodeId(this.getId()))); return ApiResource.request(ApiResource.RequestMethod.POST, url, params, Charge.class, options); } /** * Updates the specified charge by setting the values of the parameters passed. Any parameters not * provided will be left unchanged. */ public Charge update(ChargeUpdateParams params) throws StripeException { return update(params, (RequestOptions) null); } /** * Updates the specified charge by setting the values of the parameters passed. Any parameters not * provided will be left unchanged. */ public Charge update(ChargeUpdateParams params, RequestOptions options) throws StripeException { String url = String.format( "%s%s", Stripe.getApiBase(), String.format("/v1/charges/%s", ApiResource.urlEncodeId(this.getId()))); return ApiResource.request(ApiResource.RequestMethod.POST, url, params, Charge.class, options); } /** * Capture the payment of an existing, uncaptured, charge. This is the second half of the two-step * payment flow, where first you <a href="#create_charge">created a charge</a> with the capture * option set to false. * * <p>Uncaptured payments expire exactly seven days after they are created. If they are not * captured by that point in time, they will be marked as refunded and will no longer be * capturable. */ public Charge capture() throws StripeException { return capture((Map<String, Object>) null, (RequestOptions) null); } /** * Capture the payment of an existing, uncaptured, charge. This is the second half of the two-step * payment flow, where first you <a href="#create_charge">created a charge</a> with the capture * option set to false. * * <p>Uncaptured payments expire exactly seven days after they are created. If they are not * captured by that point in time, they will be marked as refunded and will no longer be * capturable. */ public Charge capture(RequestOptions options) throws StripeException { return capture((Map<String, Object>) null, options); } /** * Capture the payment of an existing, uncaptured, charge. This is the second half of the two-step * payment flow, where first you <a href="#create_charge">created a charge</a> with the capture * option set to false. * * <p>Uncaptured payments expire exactly seven days after they are created. If they are not * captured by that point in time, they will be marked as refunded and will no longer be * capturable. */ public Charge capture(Map<String, Object> params) throws StripeException { return capture(params, (RequestOptions) null); } /** * Capture the payment of an existing, uncaptured, charge. This is the second half of the two-step * payment flow, where first you <a href="#create_charge">created a charge</a> with the capture * option set to false. * * <p>Uncaptured payments expire exactly seven days after they are created. If they are not * captured by that point in time, they will be marked as refunded and will no longer be * capturable. */ public Charge capture(Map<String, Object> params, RequestOptions options) throws StripeException { String url = String.format( "%s%s", Stripe.getApiBase(), String.format("/v1/charges/%s/capture", ApiResource.urlEncodeId(this.getId()))); return ApiResource.request(ApiResource.RequestMethod.POST, url, params, Charge.class, options); } /** * Capture the payment of an existing, uncaptured, charge. This is the second half of the two-step * payment flow, where first you <a href="#create_charge">created a charge</a> with the capture * option set to false. * * <p>Uncaptured payments expire exactly seven days after they are created. If they are not * captured by that point in time, they will be marked as refunded and will no longer be * capturable. */ public Charge capture(ChargeCaptureParams params) throws StripeException { return capture(params, (RequestOptions) null); } /** * Capture the payment of an existing, uncaptured, charge. This is the second half of the two-step * payment flow, where first you <a href="#create_charge">created a charge</a> with the capture * option set to false. * * <p>Uncaptured payments expire exactly seven days after they are created. If they are not * captured by that point in time, they will be marked as refunded and will no longer be * capturable. */ public Charge capture(ChargeCaptureParams params, RequestOptions options) throws StripeException { String url = String.format( "%s%s", Stripe.getApiBase(), String.format("/v1/charges/%s/capture", ApiResource.urlEncodeId(this.getId()))); return ApiResource.request(ApiResource.RequestMethod.POST, url, params, Charge.class, options); } @Getter @Setter @EqualsAndHashCode(callSuper = false) public static class AlternateStatementDescriptors extends StripeObject { /** The Kana variation of the descriptor. */ @SerializedName("kana") String kana; /** The Kanji variation of the descriptor. */ @SerializedName("kanji") String kanji; } @Getter @Setter @EqualsAndHashCode(callSuper = false) public static class FraudDetails extends StripeObject { /** Assessments from Stripe. If set, the value is `fraudulent`. */ @SerializedName("stripe_report") String stripeReport; /** Assessments reported by you. If set, possible values of are `safe` and `fraudulent`. */ @SerializedName("user_report") String userReport; } @Getter @Setter @EqualsAndHashCode(callSuper = false) public static class Level3 extends StripeObject { @SerializedName("customer_reference") String customerReference; @SerializedName("line_items") List<Charge.Level3.LineItem> lineItems; @SerializedName("merchant_reference") String merchantReference; @SerializedName("shipping_address_zip") String shippingAddressZip; @SerializedName("shipping_amount") Long shippingAmount; @SerializedName("shipping_from_zip") String shippingFromZip; @Getter @Setter @EqualsAndHashCode(callSuper = false) public static class LineItem extends StripeObject { @SerializedName("discount_amount") Long discountAmount; @SerializedName("product_code") String productCode; @SerializedName("product_description") String productDescription; @SerializedName("quantity") Long quantity; @SerializedName("tax_amount") Long taxAmount; @SerializedName("unit_cost") Long unitCost; } } @Getter @Setter @EqualsAndHashCode(callSuper = false) public static class Outcome extends StripeObject { /** * Possible values are `approved_by_network`, `declined_by_network`, `not_sent_to_network`, and * `reversed_after_approval`. The value `reversed_after_approval` indicates the payment was * [blocked by Stripe](https://stripe.com/docs/declines#blocked-payments) after bank * authorization, and may temporarily appear as "pending" on a cardholder's statement. */ @SerializedName("network_status") String networkStatus; /** * An enumerated value providing a more detailed explanation of the outcome's `type`. Charges * blocked by Radar's default block rule have the value `highest_risk_level`. Charges placed in * review by Radar's default review rule have the value `elevated_risk_level`. Charges * authorized, blocked, or placed in review by custom rules have the value `rule`. See * [understanding declines](https://stripe.com/docs/declines) for more details. */ @SerializedName("reason") String reason; /** * Stripe's evaluation of the riskiness of the payment. Possible values for evaluated payments * are `normal`, `elevated`, `highest`. For non-card payments, and card-based payments predating * the public assignment of risk levels, this field will have the value `not_assessed`. In the * event of an error in the evaluation, this field will have the value `unknown`. */ @SerializedName("risk_level") String riskLevel; /** * Stripe's evaluation of the riskiness of the payment. Possible values for evaluated payments * are between 0 and 100. For non-card payments, card-based payments predating the public * assignment of risk scores, or in the event of an error during evaluation, this field will not * be present. This field is only available with Radar for Fraud Teams. */ @SerializedName("risk_score") Long riskScore; /** The ID of the Radar rule that matched the payment, if applicable. */ @SerializedName("rule") @Getter(lombok.AccessLevel.NONE) @Setter(lombok.AccessLevel.NONE) ExpandableField<Rule> rule; /** * A human-readable description of the outcome type and reason, designed for you (the recipient * of the payment), not your customer. */ @SerializedName("seller_message") String sellerMessage; /** * Possible values are `authorized`, `manual_review`, `issuer_declined`, `blocked`, and * `invalid`. See [understanding declines](https://stripe.com/docs/declines) and [Radar * reviews](radar/review) for details. */ @SerializedName("type") String type; /** Get id of expandable `rule` object. */ public String getRule() { return (this.rule != null) ? this.rule.getId() : null; } public void setRule(String id) { this.rule = ApiResource.setExpandableFieldId(id, this.rule); } /** Get expanded `rule`. */ public Rule getRuleObject() { return (this.rule != null) ? this.rule.getExpanded() : null; } public void setRuleObject(Rule expandableObject) { this.rule = new ExpandableField<Rule>(expandableObject.getId(), expandableObject); } } @Getter @Setter @EqualsAndHashCode(callSuper = false) public static class PaymentMethodDetails extends StripeObject { @SerializedName("ach_credit_transfer") AchCreditTransfer achCreditTransfer; @SerializedName("ach_debit") AchDebit achDebit; @SerializedName("acss_debit") AcssDebit acssDebit; @SerializedName("alipay") Alipay alipay; @SerializedName("au_becs_debit") AuBecsDebit auBecsDebit; @SerializedName("bancontact") Bancontact bancontact; @SerializedName("bitcoin") Bitcoin bitcoin; @SerializedName("card") Card card; @SerializedName("card_present") CardPresent cardPresent; @SerializedName("eps") Eps eps; @SerializedName("giropay") Giropay giropay; @SerializedName("ideal") Ideal ideal; @SerializedName("klarna") Klarna klarna; @SerializedName("multibanco") Multibanco multibanco; @SerializedName("p24") P24 p24; @SerializedName("sepa_credit_transfer") SepaCreditTransfer sepaCreditTransfer; @SerializedName("sepa_debit") SepaDebit sepaDebit; @SerializedName("sofort") Sofort sofort; @SerializedName("stripe_account") StripeAccount stripeAccount; /** * The type of transaction-specific details of the payment method used in the payment, one of * `ach_credit_transfer`, `ach_debit`, `alipay`, `bancontact`, `card`, `card_present`, `eps`, * `giropay`, `ideal`, `klarna`, `multibanco`, `p24`, `sepa_debit`, `sofort`, `stripe_account`, * or `wechat`. An additional hash is included on `payment_method_details` with a name matching * this value. It contains information specific to the payment method. */ @SerializedName("type") String type; @SerializedName("wechat") Wechat wechat; @Getter @Setter @EqualsAndHashCode(callSuper = false) public static class AchCreditTransfer extends StripeObject { /** Account number to transfer funds to. */ @SerializedName("account_number") String accountNumber; /** Name of the bank associated with the routing number. */ @SerializedName("bank_name") String bankName; /** Routing transit number for the bank account to transfer funds to. */ @SerializedName("routing_number") String routingNumber; /** SWIFT code of the bank associated with the routing number. */ @SerializedName("swift_code") String swiftCode; } @Getter @Setter @EqualsAndHashCode(callSuper = false) public static class AchDebit extends StripeObject { /** Type of entity that holds the account. This can be either `individual` or `company`. */ @SerializedName("account_holder_type") String accountHolderType; /** Name of the bank associated with the bank account. */ @SerializedName("bank_name") String bankName; /** Two-letter ISO code representing the country the bank account is located in. */ @SerializedName("country") String country; /** * Uniquely identifies this particular bank account. You can use this attribute to check * whether two bank accounts are the same. */ @SerializedName("fingerprint") String fingerprint; /** Last four digits of the bank account number. */ @SerializedName("last4") String last4; /** Routing transit number of the bank account. */ @SerializedName("routing_number") String routingNumber; } @Getter @Setter @EqualsAndHashCode(callSuper = false) public static class AcssDebit extends StripeObject { /** Two-letter ISO code representing the country the bank account is located in. */ @SerializedName("country") String country; /** * Uniquely identifies this particular bank account. You can use this attribute to check * whether two bank accounts are the same. */ @SerializedName("fingerprint") String fingerprint; /** Last four digits of the bank account number. */ @SerializedName("last4") String last4; /** Routing transit number of the bank account. */ @SerializedName("routing_number") String routingNumber; } @Getter @Setter @EqualsAndHashCode(callSuper = false) public static class Alipay extends StripeObject {} @Getter @Setter @EqualsAndHashCode(callSuper = false) public static class AuBecsDebit extends StripeObject { /** Bank-State-Branch number of the bank account. */ @SerializedName("bsb_number") String bsbNumber; /** * Uniquely identifies this particular bank account. You can use this attribute to check * whether two bank accounts are the same. */ @SerializedName("fingerprint") String fingerprint; /** Last four digits of the bank account number. */ @SerializedName("last4") String last4; /** ID of the mandate used to make this payment. */ @SerializedName("mandate") String mandate; } @Getter @Setter @EqualsAndHashCode(callSuper = false) public static class Bancontact extends StripeObject { /** Bank code of bank associated with the bank account. */ @SerializedName("bank_code") String bankCode; /** Name of the bank associated with the bank account. */ @SerializedName("bank_name") String bankName; /** Bank Identifier Code of the bank associated with the bank account. */ @SerializedName("bic") String bic; /** Last four characters of the IBAN. */ @SerializedName("iban_last4") String ibanLast4; /** * Preferred language of the Bancontact authorization page that the customer is redirected to. * Can be one of `en`, `de`, `fr`, or `nl` */ @SerializedName("preferred_language") String preferredLanguage; /** * Owner's verified full name. Values are verified or provided by Bancontact directly (if * supported) at the time of authorization or settlement. They cannot be set or mutated. */ @SerializedName("verified_name") String verifiedName; } @Getter @Setter @EqualsAndHashCode(callSuper = false) public static class Bitcoin extends StripeObject { @SerializedName("address") String address; @SerializedName("amount") Long amount; @SerializedName("amount_charged") Long amountCharged; @SerializedName("amount_received") Long amountReceived; @SerializedName("amount_returned") Long amountReturned; @SerializedName("refund_address") String refundAddress; } @Getter @Setter @EqualsAndHashCode(callSuper = false) public static class Card extends StripeObject { /** * Card brand. Can be `amex`, `diners`, `discover`, `jcb`, `mastercard`, `unionpay`, `visa`, * or `unknown`. */ @SerializedName("brand") String brand; /** Check results by Card networks on Card address and CVC at time of payment. */ @SerializedName("checks") Checks checks; /** * Two-letter ISO code representing the country of the card. You could use this attribute to * get a sense of the international breakdown of cards you've collected. */ @SerializedName("country") String country; /** * Card description. (Only for internal use only and not typically available in standard API * requests.) */ @SerializedName("description") String description; /** Two-digit number representing the card's expiration month. */ @SerializedName("exp_month") Long expMonth; /** Four-digit number representing the card's expiration year. */ @SerializedName("exp_year") Long expYear; /** * Uniquely identifies this particular card number. You can use this attribute to check * whether two customers who've signed up with you are using the same card number, for * example. */ @SerializedName("fingerprint") String fingerprint; /** Card funding type. Can be `credit`, `debit`, `prepaid`, or `unknown`. */ @SerializedName("funding") String funding; /** * Issuer identification number of the card. (Only for internal use only and not typically * available in standard API requests.) */ @SerializedName("iin") String iin; /** * Installment details for this payment (Mexico only). * * <p>For more information, see the [installments integration * guide](https://stripe.com/docs/payments/installments). */ @SerializedName("installments") Installments installments; /** * Issuer bank name of the card. (Only for internal use only and not typically available in * standard API requests.) */ @SerializedName("issuer") String issuer; /** The last four digits of the card. */ @SerializedName("last4") String last4; /** True if this payment was marked as MOTO and out of scope for SCA. */ @SerializedName("moto") Boolean moto; /** Populated if this transaction used 3D Secure authentication. */ @SerializedName("three_d_secure") ThreeDSecure threeDSecure; /** If this Card is part of a card wallet, this contains the details of the card wallet. */ @SerializedName("wallet") Wallet wallet; @Getter @Setter @EqualsAndHashCode(callSuper = false) public static class Checks extends StripeObject { /** * If a address line1 was provided, results of the check, one of 'pass', 'failed', * 'unavailable' or 'unchecked'. */ @SerializedName("address_line1_check") String addressLine1Check; /** * If a address postal code was provided, results of the check, one of 'pass', 'failed', * 'unavailable' or 'unchecked'. */ @SerializedName("address_postal_code_check") String addressPostalCodeCheck; /** * If a CVC was provided, results of the check, one of 'pass', 'failed', 'unavailable' or * 'unchecked'. */ @SerializedName("cvc_check") String cvcCheck; } @Getter @Setter @EqualsAndHashCode(callSuper = false) public static class Installments extends StripeObject { /** Installment plan selected for the payment. */ @SerializedName("plan") PaymentIntent.PaymentMethodOptions.Card.Installments.Plan plan; } @Getter @Setter @EqualsAndHashCode(callSuper = false) public static class ThreeDSecure extends StripeObject { /** * Whether or not authentication was performed. 3D Secure will succeed without * authentication when the card is not enrolled. */ @SerializedName("authenticated") Boolean authenticated; /** Whether or not 3D Secure succeeded. */ @SerializedName("succeeded") Boolean succeeded; /** The version of 3D Secure that was used for this payment. */ @SerializedName("version") String version; } @Getter @Setter @EqualsAndHashCode(callSuper = false) public static class Wallet extends StripeObject { @SerializedName("amex_express_checkout") AmexExpressCheckout amexExpressCheckout; @SerializedName("apple_pay") ApplePay applePay; /** (For tokenized numbers only.) The last four digits of the device account number. */ @SerializedName("dynamic_last4") String dynamicLast4; @SerializedName("google_pay") GooglePay googlePay; @SerializedName("masterpass") Masterpass masterpass; @SerializedName("samsung_pay") SamsungPay samsungPay; /** * The type of the card wallet, one of `amex_express_checkout`, `apple_pay`, `google_pay`, * `masterpass`, `samsung_pay`, or `visa_checkout`. An additional hash is included on the * Wallet subhash with a name matching this value. It contains additional information * specific to the card wallet type. */ @SerializedName("type") String type; @SerializedName("visa_checkout") VisaCheckout visaCheckout; @Getter @Setter @EqualsAndHashCode(callSuper = false) public static class AmexExpressCheckout extends StripeObject {} @Getter @Setter @EqualsAndHashCode(callSuper = false) public static class ApplePay extends StripeObject {} @Getter @Setter @EqualsAndHashCode(callSuper = false) public static class GooglePay extends StripeObject {} @Getter @Setter @EqualsAndHashCode(callSuper = false) public static class Masterpass extends StripeObject { /** * Owner's verified billing address. Values are verified or provided by the wallet * directly (if supported) at the time of authorization or settlement. They cannot be set * or mutated. */ @SerializedName("billing_address") Address billingAddress; /** * Owner's verified email. Values are verified or provided by the wallet directly (if * supported) at the time of authorization or settlement. They cannot be set or mutated. */ @SerializedName("email") String email; /** * Owner's verified full name. Values are verified or provided by the wallet directly (if * supported) at the time of authorization or settlement. They cannot be set or mutated. */ @SerializedName("name") String name; /** * Owner's verified shipping address. Values are verified or provided by the wallet * directly (if supported) at the time of authorization or settlement. They cannot be set * or mutated. */ @SerializedName("shipping_address") Address shippingAddress; } @Getter @Setter @EqualsAndHashCode(callSuper = false) public static class SamsungPay extends StripeObject {} @Getter @Setter @EqualsAndHashCode(callSuper = false) public static class VisaCheckout extends StripeObject { /** * Owner's verified billing address. Values are verified or provided by the wallet * directly (if supported) at the time of authorization or settlement. They cannot be set * or mutated. */ @SerializedName("billing_address") Address billingAddress; /** * Owner's verified email. Values are verified or provided by the wallet directly (if * supported) at the time of authorization or settlement. They cannot be set or mutated. */ @SerializedName("email") String email; /** * Owner's verified full name. Values are verified or provided by the wallet directly (if * supported) at the time of authorization or settlement. They cannot be set or mutated. */ @SerializedName("name") String name; /** * Owner's verified shipping address. Values are verified or provided by the wallet * directly (if supported) at the time of authorization or settlement. They cannot be set * or mutated. */ @SerializedName("shipping_address") Address shippingAddress; } } } @Getter @Setter @EqualsAndHashCode(callSuper = false) public static class CardPresent extends StripeObject { /** * Card brand. Can be `amex`, `diners`, `discover`, `jcb`, `mastercard`, `unionpay`, `visa`, * or `unknown`. */ @SerializedName("brand") String brand; /** * Two-letter ISO code representing the country of the card. You could use this attribute to * get a sense of the international breakdown of cards you've collected. */ @SerializedName("country") String country; /** Authorization response cryptogram. */ @SerializedName("emv_auth_data") String emvAuthData; /** Two-digit number representing the card's expiration month. */ @SerializedName("exp_month") Long expMonth; /** Four-digit number representing the card's expiration year. */ @SerializedName("exp_year") Long expYear; /** * Uniquely identifies this particular card number. You can use this attribute to check * whether two customers who've signed up with you are using the same card number, for * example. */ @SerializedName("fingerprint") String fingerprint; /** Card funding type. Can be `credit`, `debit`, `prepaid`, or `unknown`. */ @SerializedName("funding") String funding; /** * ID of a card PaymentMethod generated from the card_present PaymentMethod that may be * attached to a Customer for future transactions. Only present if it was possible to generate * a card PaymentMethod. */ @SerializedName("generated_card") String generatedCard; /** The last four digits of the card. */ @SerializedName("last4") String last4; /** * How were card details read in this transaction. Can be contact_emv, contactless_emv, * magnetic_stripe_fallback, magnetic_stripe_track2, or contactless_magstripe_mode */ @SerializedName("read_method") String readMethod; /** * A collection of fields required to be displayed on receipts. Only required for EMV * transactions. */ @SerializedName("receipt") Receipt receipt; @Getter @Setter @EqualsAndHashCode(callSuper = false) public static class Receipt extends StripeObject { /** EMV tag 9F26, cryptogram generated by the integrated circuit chip. */ @SerializedName("application_cryptogram") String applicationCryptogram; /** Mnenomic of the Application Identifier. */ @SerializedName("application_preferred_name") String applicationPreferredName; /** Identifier for this transaction. */ @SerializedName("authorization_code") String authorizationCode; /** EMV tag 8A. A code returned by the card issuer. */ @SerializedName("authorization_response_code") String authorizationResponseCode; /** How the cardholder verified ownership of the card. */ @SerializedName("cardholder_verification_method") String cardholderVerificationMethod; /** * EMV tag 84. Similar to the application identifier stored on the integrated circuit chip. */ @SerializedName("dedicated_file_name") String dedicatedFileName; /** The outcome of a series of EMV functions performed by the card reader. */ @SerializedName("terminal_verification_results") String terminalVerificationResults; /** An indication of various EMV functions performed during the transaction. */ @SerializedName("transaction_status_information") String transactionStatusInformation; } } @Getter @Setter @EqualsAndHashCode(callSuper = false) public static class Eps extends StripeObject { /** * Owner's verified full name. Values are verified or provided by EPS directly (if supported) * at the time of authorization or settlement. They cannot be set or mutated. */ @SerializedName("verified_name") String verifiedName; } @Getter @Setter @EqualsAndHashCode(callSuper = false) public static class Giropay extends StripeObject { /** Bank code of bank associated with the bank account. */ @SerializedName("bank_code") String bankCode; /** Name of the bank associated with the bank account. */ @SerializedName("bank_name") String bankName; /** Bank Identifier Code of the bank associated with the bank account. */ @SerializedName("bic") String bic; /** * Owner's verified full name. Values are verified or provided by Giropay directly (if * supported) at the time of authorization or settlement. They cannot be set or mutated. */ @SerializedName("verified_name") String verifiedName; } @Getter @Setter @EqualsAndHashCode(callSuper = false) public static class Ideal extends StripeObject { /** * The customer's bank. Can be one of `abn_amro`, `asn_bank`, `bunq`, `handelsbanken`, `ing`, * `knab`, `moneyou`, `rabobank`, `regiobank`, `sns_bank`, `triodos_bank`, or `van_lanschot`. */ @SerializedName("bank") String bank; /** The Bank Identifier Code of the customer's bank. */ @SerializedName("bic") String bic; /** Last four characters of the IBAN. */ @SerializedName("iban_last4") String ibanLast4; /** * Owner's verified full name. Values are verified or provided by iDEAL directly (if * supported) at the time of authorization or settlement. They cannot be set or mutated. */ @SerializedName("verified_name") String verifiedName; } @Getter @Setter @EqualsAndHashCode(callSuper = false) public static class Klarna extends StripeObject {} @Getter @Setter @EqualsAndHashCode(callSuper = false) public static class Multibanco extends StripeObject { /** Entity number associated with this Multibanco payment. */ @SerializedName("entity") String entity; /** Reference number associated with this Multibanco payment. */ @SerializedName("reference") String reference; } @Getter @Setter @EqualsAndHashCode(callSuper = false) public static class P24 extends StripeObject { /** Unique reference for this Przelewy24 payment. */ @SerializedName("reference") String reference; /** * Owner's verified full name. Values are verified or provided by Przelewy24 directly (if * supported) at the time of authorization or settlement. They cannot be set or mutated. */ @SerializedName("verified_name") String verifiedName; } @Getter @Setter @EqualsAndHashCode(callSuper = false) public static class SepaCreditTransfer extends StripeObject { /** Name of the bank associated with the bank account. */ @SerializedName("bank_name") String bankName; /** Bank Identifier Code of the bank associated with the bank account. */ @SerializedName("bic") String bic; /** IBAN of the bank account to transfer funds to. */ @SerializedName("iban") String iban; } @Getter @Setter @EqualsAndHashCode(callSuper = false) public static class SepaDebit extends StripeObject { /** Bank code of bank associated with the bank account. */ @SerializedName("bank_code") String bankCode; /** Branch code of bank associated with the bank account. */ @SerializedName("branch_code") String branchCode; /** Two-letter ISO code representing the country the bank account is located in. */ @SerializedName("country") String country; /** * Uniquely identifies this particular bank account. You can use this attribute to check * whether two bank accounts are the same. */ @SerializedName("fingerprint") String fingerprint; /** Last four characters of the IBAN. */ @SerializedName("last4") String last4; /** ID of the mandate used to make this payment. */ @SerializedName("mandate") String mandate; } @Getter @Setter @EqualsAndHashCode(callSuper = false) public static class Sofort extends StripeObject { /** Bank code of bank associated with the bank account. */ @SerializedName("bank_code") String bankCode; /** Name of the bank associated with the bank account. */ @SerializedName("bank_name") String bankName; /** Bank Identifier Code of the bank associated with the bank account. */ @SerializedName("bic") String bic; /** Two-letter ISO code representing the country the bank account is located in. */ @SerializedName("country") String country; /** Last four characters of the IBAN. */ @SerializedName("iban_last4") String ibanLast4; /** * Owner's verified full name. Values are verified or provided by SOFORT directly (if * supported) at the time of authorization or settlement. They cannot be set or mutated. */ @SerializedName("verified_name") String verifiedName; } @Getter @Setter @EqualsAndHashCode(callSuper = false) public static class StripeAccount extends StripeObject {} @Getter @Setter @EqualsAndHashCode(callSuper = false) public static class Wechat extends StripeObject {} } @Getter @Setter @EqualsAndHashCode(callSuper = false) public static class TransferData extends StripeObject { /** * The amount transferred to the destination account, if specified. By default, the entire * charge amount is transferred to the destination account. */ @SerializedName("amount") Long amount; /** * ID of an existing, connected Stripe account to transfer funds to if `transfer_data` was * specified in the charge request. */ @SerializedName("destination") @Getter(lombok.AccessLevel.NONE) @Setter(lombok.AccessLevel.NONE) ExpandableField<Account> destination; /** Get id of expandable `destination` object. */ public String getDestination() { return (this.destination != null) ? this.destination.getId() : null; } public void setDestination(String id) { this.destination = ApiResource.setExpandableFieldId(id, this.destination); } /** Get expanded `destination`. */ public Account getDestinationObject() { return (this.destination != null) ? this.destination.getExpanded() : null; } public void setDestinationObject(Account expandableObject) { this.destination = new ExpandableField<Account>(expandableObject.getId(), expandableObject); } } }
34.469866
100
0.68475
3e6590e54cc4652e3602ba0b6eaba0ad7166487f
6,501
package leeon.mobile.BBSBrowser; import leeon.mobile.BBSBrowser.models.MailObject; import android.app.Activity; import android.app.NotificationManager; import android.content.Context; import android.content.Intent; import android.content.res.Configuration; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.CheckBox; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; public class MailDetailActivity extends Activity { private Button replyMailButton; private Button sendMailButton; private Button delMailButton; private CheckBox backupMailCheckBox; private EditText mailContentTextReply; private EditText mailTitleTextReply; private EditText mailReplyUser; private TextView mailContentText; private MailObject mail; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); this.setContentView(SettingActivity.displayHd(this)?R.layout.mail_detail_hd:R.layout.mail_detail); replyMailButton = (Button)this.findViewById(R.id.replyMailButton); sendMailButton = (Button)this.findViewById(R.id.sendMailButton); delMailButton = (Button)this.findViewById(R.id.delMailButton); backupMailCheckBox = (CheckBox)this.findViewById(R.id.backupMailCheckBox); mailReplyUser = (EditText)this.findViewById(R.id.mailReplyUser); mailContentTextReply = (EditText)this.findViewById(R.id.mailContentTextReply); mailTitleTextReply = (EditText)this.findViewById(R.id.mailTitleTextReply); mailContentText = (TextView)this.findViewById(R.id.mailContentText); mail = (MailObject)this.getIntent().getSerializableExtra("mail"); if (mail != null) { if (this.getIntent().getIntExtra("mailSeq", -1) != -1) { ((NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE)) .cancel(this.getIntent().getIntExtra("mailSeq", -1)); } delMailButton.setEnabled(true); replyMailButton.setEnabled(true); mailReplyUser.setEnabled(false); mailReplyUser.setText(mail.getSender()); mailTitleTextReply.setText((mail.getTitle().startsWith("Re: ")?"":"Re: ") + mail.getTitle()); fetchMail(); } else { delMailButton.setEnabled(false); replyMailButton.setEnabled(false); mailReplyUser.setEnabled(true); changeReply(); } changeReply(); replyMailButton.setOnClickListener(new OnClickListener() { public void onClick(View v) { changeReply(); } }); sendMailButton.setOnClickListener(new OnClickListener() { public void onClick(View v) { sendMail(); } }); delMailButton.setOnClickListener(new OnClickListener() { public void onClick(View v) { delMail(); } }); } @Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); if (this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) { } else if (this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) { } } static final String MAIL_ACTION_RE = "reMail"; static final String MAIL_ACTION_NEW = "newMail"; static final String MAIL_ACTION_DEL = "delMail"; private void fetchMail() { UIUtil.runActionInThread(MailDetailActivity.this, new UIUtil.ActionInThread<Object>() { @Override public void action() throws NetworkException, ContentException { ActionFactory.newInstance().newMailAction().conMail(mail); ActionFactory.newInstance().newMailAction().conReMail(mail); } @Override public void actionFinish() { mail.setContent(mail.getContent().replaceAll(UIUtil.IMG_ANSI_PATTERN, "")); mailContentText.setText(mail.getContent()); mailContentTextReply.setText("\n\n"+mail.getReContent()); } }); } private void sendMail() { UIUtil.runActionInThread(MailDetailActivity.this, new UIUtil.ActionInThread<Object>() { @Override public void action() throws NetworkException, ContentException { MailObject newMail = new MailObject(mailReplyUser.getText().toString(), mailTitleTextReply.getText().toString(), mailContentTextReply.getText().toString()); ActionFactory.newInstance().newMailAction().sendMail(newMail, backupMailCheckBox.isChecked()); } @Override public void actionFinish() { changeReply(); Toast.makeText(MailDetailActivity.this, "发送成功", Toast.LENGTH_SHORT).show(); sendMailSuccess(); } }); } private void sendMailSuccess() { setResult(RESULT_OK, (new Intent()).setAction(mail==null?MAIL_ACTION_NEW:MAIL_ACTION_RE)); finish(); } private void delMail() { UIUtil.runActionInThread(MailDetailActivity.this, new UIUtil.ActionInThread<Object>() { @Override public void action() throws NetworkException, ContentException { ActionFactory.newInstance().newMailAction().delMail(mail); } @Override public void actionFinish() { closeAll(); Toast.makeText(MailDetailActivity.this, "删除成功", Toast.LENGTH_SHORT).show(); delMailSuccess(); } }); } private void delMailSuccess() { setResult(RESULT_OK, (new Intent()).setAction(MAIL_ACTION_DEL)); finish(); } private void changeReply() { if ("回复".equals(replyMailButton.getText())) { replyMailButton.setText("取消"); mailContentTextReply.setVisibility(View.VISIBLE); mailTitleTextReply.setVisibility(View.VISIBLE); mailReplyUser.setVisibility(View.VISIBLE); sendMailButton.setEnabled(true); backupMailCheckBox.setEnabled(true); if (mail != null) { mailContentTextReply.requestFocus(); } } else { replyMailButton.setText("回复"); mailContentTextReply.setVisibility(View.GONE); mailTitleTextReply.setVisibility(View.GONE); mailReplyUser.setVisibility(View.GONE); sendMailButton.setEnabled(false); backupMailCheckBox.setEnabled(false); } } private void closeAll() { if ("取消".equals(replyMailButton.getText())) { replyMailButton.setText("回复"); mailContentTextReply.setVisibility(View.GONE); mailTitleTextReply.setVisibility(View.GONE); mailReplyUser.setVisibility(View.GONE); } mailContentText.setText(null); replyMailButton.setEnabled(false); delMailButton.setEnabled(false); sendMailButton.setEnabled(false); backupMailCheckBox.setEnabled(false); } }
33.510309
105
0.725427
cd0118092f750f6428ed36788742b7a897a15a06
1,288
package com.laegler.openbanking.soap.service; import javax.xml.ws.WebFault; /** * Too Many Requests * * This class was generated by Apache CXF 3.3.3 * 2019-10-21T07:01:27.456+13:00 * Generated source version: 3.3.3 */ @WebFault(name = "DELETE_DeleteacallbackURI_429", targetNamespace = "http://laegler.com/openbanking/soap/model") public class DELETEDeleteacallbackURI429 extends Exception { private java.lang.Object deleteDeleteacallbackURI429; public DELETEDeleteacallbackURI429() { super(); } public DELETEDeleteacallbackURI429(String message) { super(message); } public DELETEDeleteacallbackURI429(String message, java.lang.Throwable cause) { super(message, cause); } public DELETEDeleteacallbackURI429(String message, java.lang.Object deleteDeleteacallbackURI429) { super(message); this.deleteDeleteacallbackURI429 = deleteDeleteacallbackURI429; } public DELETEDeleteacallbackURI429(String message, java.lang.Object deleteDeleteacallbackURI429, java.lang.Throwable cause) { super(message, cause); this.deleteDeleteacallbackURI429 = deleteDeleteacallbackURI429; } public java.lang.Object getFaultInfo() { return this.deleteDeleteacallbackURI429; } }
28
129
0.732143
d151a360dec436d0b4ce8549ad63d04c9a0648b7
759
package main.java.JSONTypes; import java.util.ArrayList; import main.java.JSONElementVisitor; public class JSONArray implements JSONElement { private ArrayList<JSONElement> items; public JSONArray() { this.items = new ArrayList<JSONElement>(); } public JSONArray(ArrayList<JSONElement> items) { this.items = items; } public void accept(JSONElementVisitor visitor) { visitor.visit(this); } public ArrayList<JSONElement> getItems() { return items; } @Override public boolean equals(JSONElement other) { return (other instanceof JSONArray) && ((JSONArray) other).items.equals(items); } public void add(JSONElement element) { items.add(element); } }
21.685714
87
0.664032
e055e1db97792e9cf427afd5e86bdfbbc957d82b
236
package com.jenkins.android.model; import java.util.List; /** * @author RAE * @date 2021/12/31 * Copyright (c) https://github.com/raedev All rights reserved. */ public class JobChangeSet { public List<JobChangeItem> items; }
16.857143
63
0.70339
b4c0cd933457d8e070677da34d2f49480dc3a894
276
package com.opentravelsoft.service.operator; import java.util.List; import com.opentravelsoft.entity.product.FileItem; public interface PriceUploadService { List<FileItem> roGetFileList(int teamId); int txSaveFile(FileItem fileItem); int txDelFile(int fileId); }
17.25
50
0.789855
da69b6ab154050c94bed91bc939bfafc48a44a41
29,718
/*=========================================================================== * Licensed Materials - Property of IBM * "Restricted Materials of IBM" * * IBM SDK, Java(tm) Technology Edition, v8 * (C) Copyright IBM Corp. 2000, 2016. All Rights Reserved * * US Government Users Restricted Rights - Use, duplication or disclosure * restricted by GSA ADP Schedule Contract with IBM Corp. *=========================================================================== */ /* * Copyright (c) 2000, 2012, Oracle and/or its affiliates. All rights reserved. * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms. * * * * * * * * * * * * * * * * * * * * */ package java.nio; import java.util.concurrent.atomic.AtomicBoolean; import java.security.AccessController; import java.security.PrivilegedAction; //IBM-io_converter import sun.misc.Unsafe; import sun.misc.VM; /** * Access to bits, native and otherwise. */ class Bits { // package-private private Bits() { } // -- Swapping -- static short swap(short x) { return Short.reverseBytes(x); } static char swap(char x) { return Character.reverseBytes(x); } static int swap(int x) { return Integer.reverseBytes(x); } static long swap(long x) { return Long.reverseBytes(x); } // -- get/put char -- static private char makeChar(byte b1, byte b0) { return (char)((b1 << 8) | (b0 & 0xff)); } static char getCharL(ByteBuffer bb, int bi) { return makeChar(bb._get(bi + 1), bb._get(bi )); } static char getCharL(long a) { return makeChar(_get(a + 1), _get(a )); } static char getCharB(ByteBuffer bb, int bi) { return makeChar(bb._get(bi ), bb._get(bi + 1)); } static char getCharB(long a) { return makeChar(_get(a ), _get(a + 1)); } static char getChar(ByteBuffer bb, int bi, boolean bigEndian) { return bigEndian ? getCharB(bb, bi) : getCharL(bb, bi); } static char getChar(long a, boolean bigEndian) { return bigEndian ? getCharB(a) : getCharL(a); } private static byte char1(char x) { return (byte)(x >> 8); } private static byte char0(char x) { return (byte)(x ); } static void putCharL(ByteBuffer bb, int bi, char x) { bb._put(bi , char0(x)); bb._put(bi + 1, char1(x)); } static void putCharL(long a, char x) { _put(a , char0(x)); _put(a + 1, char1(x)); } static void putCharB(ByteBuffer bb, int bi, char x) { bb._put(bi , char1(x)); bb._put(bi + 1, char0(x)); } static void putCharB(long a, char x) { _put(a , char1(x)); _put(a + 1, char0(x)); } static void putChar(ByteBuffer bb, int bi, char x, boolean bigEndian) { if (bigEndian) putCharB(bb, bi, x); else putCharL(bb, bi, x); } static void putChar(long a, char x, boolean bigEndian) { if (bigEndian) putCharB(a, x); else putCharL(a, x); } // -- get/put short -- static private short makeShort(byte b1, byte b0) { return (short)((b1 << 8) | (b0 & 0xff)); } static short getShortL(ByteBuffer bb, int bi) { return makeShort(bb._get(bi + 1), bb._get(bi )); } static short getShortL(long a) { return makeShort(_get(a + 1), _get(a )); } static short getShortB(ByteBuffer bb, int bi) { return makeShort(bb._get(bi ), bb._get(bi + 1)); } static short getShortB(long a) { return makeShort(_get(a ), _get(a + 1)); } static short getShort(ByteBuffer bb, int bi, boolean bigEndian) { return bigEndian ? getShortB(bb, bi) : getShortL(bb, bi); } static short getShort(long a, boolean bigEndian) { return bigEndian ? getShortB(a) : getShortL(a); } private static byte short1(short x) { return (byte)(x >> 8); } private static byte short0(short x) { return (byte)(x ); } static void putShortL(ByteBuffer bb, int bi, short x) { bb._put(bi , short0(x)); bb._put(bi + 1, short1(x)); } static void putShortL(long a, short x) { _put(a , short0(x)); _put(a + 1, short1(x)); } static void putShortB(ByteBuffer bb, int bi, short x) { bb._put(bi , short1(x)); bb._put(bi + 1, short0(x)); } static void putShortB(long a, short x) { _put(a , short1(x)); _put(a + 1, short0(x)); } static void putShort(ByteBuffer bb, int bi, short x, boolean bigEndian) { if (bigEndian) putShortB(bb, bi, x); else putShortL(bb, bi, x); } static void putShort(long a, short x, boolean bigEndian) { if (bigEndian) putShortB(a, x); else putShortL(a, x); } // -- get/put int -- static private int makeInt(byte b3, byte b2, byte b1, byte b0) { return (((b3 ) << 24) | ((b2 & 0xff) << 16) | ((b1 & 0xff) << 8) | ((b0 & 0xff) )); } static int getIntL(ByteBuffer bb, int bi) { return makeInt(bb._get(bi + 3), bb._get(bi + 2), bb._get(bi + 1), bb._get(bi )); } static int getIntL(long a) { return makeInt(_get(a + 3), _get(a + 2), _get(a + 1), _get(a )); } static int getIntB(ByteBuffer bb, int bi) { return makeInt(bb._get(bi ), bb._get(bi + 1), bb._get(bi + 2), bb._get(bi + 3)); } static int getIntB(long a) { return makeInt(_get(a ), _get(a + 1), _get(a + 2), _get(a + 3)); } static int getInt(ByteBuffer bb, int bi, boolean bigEndian) { return bigEndian ? getIntB(bb, bi) : getIntL(bb, bi) ; } static int getInt(long a, boolean bigEndian) { return bigEndian ? getIntB(a) : getIntL(a) ; } private static byte int3(int x) { return (byte)(x >> 24); } private static byte int2(int x) { return (byte)(x >> 16); } private static byte int1(int x) { return (byte)(x >> 8); } private static byte int0(int x) { return (byte)(x ); } static void putIntL(ByteBuffer bb, int bi, int x) { bb._put(bi + 3, int3(x)); bb._put(bi + 2, int2(x)); bb._put(bi + 1, int1(x)); bb._put(bi , int0(x)); } static void putIntL(long a, int x) { _put(a + 3, int3(x)); _put(a + 2, int2(x)); _put(a + 1, int1(x)); _put(a , int0(x)); } static void putIntB(ByteBuffer bb, int bi, int x) { bb._put(bi , int3(x)); bb._put(bi + 1, int2(x)); bb._put(bi + 2, int1(x)); bb._put(bi + 3, int0(x)); } static void putIntB(long a, int x) { _put(a , int3(x)); _put(a + 1, int2(x)); _put(a + 2, int1(x)); _put(a + 3, int0(x)); } static void putInt(ByteBuffer bb, int bi, int x, boolean bigEndian) { if (bigEndian) putIntB(bb, bi, x); else putIntL(bb, bi, x); } static void putInt(long a, int x, boolean bigEndian) { if (bigEndian) putIntB(a, x); else putIntL(a, x); } // -- get/put long -- static private long makeLong(byte b7, byte b6, byte b5, byte b4, byte b3, byte b2, byte b1, byte b0) { return ((((long)b7 ) << 56) | (((long)b6 & 0xff) << 48) | (((long)b5 & 0xff) << 40) | (((long)b4 & 0xff) << 32) | (((long)b3 & 0xff) << 24) | (((long)b2 & 0xff) << 16) | (((long)b1 & 0xff) << 8) | (((long)b0 & 0xff) )); } static long getLongL(ByteBuffer bb, int bi) { return makeLong(bb._get(bi + 7), bb._get(bi + 6), bb._get(bi + 5), bb._get(bi + 4), bb._get(bi + 3), bb._get(bi + 2), bb._get(bi + 1), bb._get(bi )); } static long getLongL(long a) { return makeLong(_get(a + 7), _get(a + 6), _get(a + 5), _get(a + 4), _get(a + 3), _get(a + 2), _get(a + 1), _get(a )); } static long getLongB(ByteBuffer bb, int bi) { return makeLong(bb._get(bi ), bb._get(bi + 1), bb._get(bi + 2), bb._get(bi + 3), bb._get(bi + 4), bb._get(bi + 5), bb._get(bi + 6), bb._get(bi + 7)); } static long getLongB(long a) { return makeLong(_get(a ), _get(a + 1), _get(a + 2), _get(a + 3), _get(a + 4), _get(a + 5), _get(a + 6), _get(a + 7)); } static long getLong(ByteBuffer bb, int bi, boolean bigEndian) { return bigEndian ? getLongB(bb, bi) : getLongL(bb, bi); } static long getLong(long a, boolean bigEndian) { return bigEndian ? getLongB(a) : getLongL(a); } private static byte long7(long x) { return (byte)(x >> 56); } private static byte long6(long x) { return (byte)(x >> 48); } private static byte long5(long x) { return (byte)(x >> 40); } private static byte long4(long x) { return (byte)(x >> 32); } private static byte long3(long x) { return (byte)(x >> 24); } private static byte long2(long x) { return (byte)(x >> 16); } private static byte long1(long x) { return (byte)(x >> 8); } private static byte long0(long x) { return (byte)(x ); } static void putLongL(ByteBuffer bb, int bi, long x) { bb._put(bi + 7, long7(x)); bb._put(bi + 6, long6(x)); bb._put(bi + 5, long5(x)); bb._put(bi + 4, long4(x)); bb._put(bi + 3, long3(x)); bb._put(bi + 2, long2(x)); bb._put(bi + 1, long1(x)); bb._put(bi , long0(x)); } static void putLongL(long a, long x) { _put(a + 7, long7(x)); _put(a + 6, long6(x)); _put(a + 5, long5(x)); _put(a + 4, long4(x)); _put(a + 3, long3(x)); _put(a + 2, long2(x)); _put(a + 1, long1(x)); _put(a , long0(x)); } static void putLongB(ByteBuffer bb, int bi, long x) { bb._put(bi , long7(x)); bb._put(bi + 1, long6(x)); bb._put(bi + 2, long5(x)); bb._put(bi + 3, long4(x)); bb._put(bi + 4, long3(x)); bb._put(bi + 5, long2(x)); bb._put(bi + 6, long1(x)); bb._put(bi + 7, long0(x)); } static void putLongB(long a, long x) { _put(a , long7(x)); _put(a + 1, long6(x)); _put(a + 2, long5(x)); _put(a + 3, long4(x)); _put(a + 4, long3(x)); _put(a + 5, long2(x)); _put(a + 6, long1(x)); _put(a + 7, long0(x)); } static void putLong(ByteBuffer bb, int bi, long x, boolean bigEndian) { if (bigEndian) putLongB(bb, bi, x); else putLongL(bb, bi, x); } static void putLong(long a, long x, boolean bigEndian) { if (bigEndian) putLongB(a, x); else putLongL(a, x); } // -- get/put float -- static float getFloatL(ByteBuffer bb, int bi) { return Float.intBitsToFloat(getIntL(bb, bi)); } static float getFloatL(long a) { return Float.intBitsToFloat(getIntL(a)); } static float getFloatB(ByteBuffer bb, int bi) { return Float.intBitsToFloat(getIntB(bb, bi)); } static float getFloatB(long a) { return Float.intBitsToFloat(getIntB(a)); } static float getFloat(ByteBuffer bb, int bi, boolean bigEndian) { return bigEndian ? getFloatB(bb, bi) : getFloatL(bb, bi); } static float getFloat(long a, boolean bigEndian) { return bigEndian ? getFloatB(a) : getFloatL(a); } static void putFloatL(ByteBuffer bb, int bi, float x) { putIntL(bb, bi, Float.floatToRawIntBits(x)); } static void putFloatL(long a, float x) { putIntL(a, Float.floatToRawIntBits(x)); } static void putFloatB(ByteBuffer bb, int bi, float x) { putIntB(bb, bi, Float.floatToRawIntBits(x)); } static void putFloatB(long a, float x) { putIntB(a, Float.floatToRawIntBits(x)); } static void putFloat(ByteBuffer bb, int bi, float x, boolean bigEndian) { if (bigEndian) putFloatB(bb, bi, x); else putFloatL(bb, bi, x); } static void putFloat(long a, float x, boolean bigEndian) { if (bigEndian) putFloatB(a, x); else putFloatL(a, x); } // -- get/put double -- static double getDoubleL(ByteBuffer bb, int bi) { return Double.longBitsToDouble(getLongL(bb, bi)); } static double getDoubleL(long a) { return Double.longBitsToDouble(getLongL(a)); } static double getDoubleB(ByteBuffer bb, int bi) { return Double.longBitsToDouble(getLongB(bb, bi)); } static double getDoubleB(long a) { return Double.longBitsToDouble(getLongB(a)); } static double getDouble(ByteBuffer bb, int bi, boolean bigEndian) { return bigEndian ? getDoubleB(bb, bi) : getDoubleL(bb, bi); } static double getDouble(long a, boolean bigEndian) { return bigEndian ? getDoubleB(a) : getDoubleL(a); } static void putDoubleL(ByteBuffer bb, int bi, double x) { putLongL(bb, bi, Double.doubleToRawLongBits(x)); } static void putDoubleL(long a, double x) { putLongL(a, Double.doubleToRawLongBits(x)); } static void putDoubleB(ByteBuffer bb, int bi, double x) { putLongB(bb, bi, Double.doubleToRawLongBits(x)); } static void putDoubleB(long a, double x) { putLongB(a, Double.doubleToRawLongBits(x)); } static void putDouble(ByteBuffer bb, int bi, double x, boolean bigEndian) { if (bigEndian) putDoubleB(bb, bi, x); else putDoubleL(bb, bi, x); } static void putDouble(long a, double x, boolean bigEndian) { if (bigEndian) putDoubleB(a, x); else putDoubleL(a, x); } // -- Unsafe access -- private static final Unsafe unsafe = Unsafe.getUnsafe(); private static byte _get(long a) { return unsafe.getByte(a); } private static void _put(long a, byte b) { unsafe.putByte(a, b); } static Unsafe unsafe() { return unsafe; } // -- Processor and memory-system properties -- private static final ByteOrder byteOrder; static ByteOrder byteOrder() { if (byteOrder == null) throw new Error("Unknown byte order"); return byteOrder; } static { long a = unsafe.allocateMemory(8); try { unsafe.putLong(a, 0x0102030405060708L); byte b = unsafe.getByte(a); switch (b) { case 0x01: byteOrder = ByteOrder.BIG_ENDIAN; break; case 0x08: byteOrder = ByteOrder.LITTLE_ENDIAN; break; default: assert false; byteOrder = null; } } finally { unsafe.freeMemory(a); } } private static int pageSize = -1; static int pageSize() { if (pageSize == -1) pageSize = unsafe().pageSize(); return pageSize; } static int pageCount(long size) { return (int)(size + (long)pageSize() - 1L) / pageSize(); } static void keepAlive(Object o) { //IBM-nio_vad // Do nothing. This is just to ptovide a chance for JIT to optimize. //IBM-nio_vad } //IBM-nio_vad //IBM-nio_vad private static boolean unaligned; private static boolean unalignedKnown = false; static boolean unaligned() { if (unalignedKnown) return unaligned; if (VM.isBooted()) { //IBM-io_converter PrivilegedAction pa //IBM-io_converter = new sun.security.action.GetPropertyAction("os.arch"); //IBM-io_converter String arch = (String)AccessController.doPrivileged(pa); //IBM-io_converter unaligned = arch.equals("i386") || arch.equals("x86") //IBM-io_converter || arch.equals("amd64") || arch.equals("x86_64") || arch.equals("ppc") || arch.equals("ppc64") || arch.equals("ppc64le") || arch.equals("s390") || arch.equals("s390x"); //IBM-io_converter unalignedKnown = true; //IBM-io_converter } //IBM-io_converter else { //IBM-io_converter unaligned = false; //IBM-io_converter } //IBM-io_converter return unaligned; } // -- Direct memory management -- // A user-settable upper limit on the maximum amount of allocatable // direct buffer memory. This value may be changed during VM // initialization if it is launched with "-XX:MaxDirectMemorySize=<size>". private static volatile long maxMemory = VM.maxDirectMemory(); private static volatile long reservedMemory = 0; private static volatile long totalCapacity = 0; private static volatile long count = 0; private static boolean memoryLimitSet = false; private static boolean xxOptionUsed = false; //IBM-nio_vad private static final long MB96 = 96*1024*1024; private static final long MB64 = 64*1024*1024; private static final long MB32 = 32*1024*1024; private static final int GC_WAIT_TIME = 100; // Sleep time in milli seconds between each retry private static final int GC_WAIT_RETRY_LIMIT = 10; // Maximum number for retry for GC to release the required DBB space private static AtomicBoolean gcInProgress = new AtomicBoolean(); // These methods should be called whenever direct memory is allocated or // freed. They allow the user to control the amount of direct memory // which a process may access. All sizes are specified in bytes. static void reserveMemory(long size, int cap) { synchronized (Bits.class) { if (!memoryLimitSet && VM.isBooted()) { maxMemory = VM.maxDirectMemory(); /*JSE-2677:: * check if -XX:maxDirectMemorySize is used as a VM arg. * If the above arg is used then assume that the Application is aware of its memory usage. * Just initialise maxMemory to User specified value.If it succeeds ,well and good * else just throw an OOM exception [ Application programmer has to set appropriate value based on its usage] * If no option is provided,go with progressively incrementing maxMemory. * if maxMemory = 64*1024*1024[ie the default value] set xxOptionUsed flag to false * */ if(maxMemory == MB64) xxOptionUsed = false; else xxOptionUsed = true; memoryLimitSet = true; } if (cap <= maxMemory - totalCapacity) { reservedMemory += size; totalCapacity += cap; count++; //shrinkage if(!xxOptionUsed && totalCapacity <= 0.2 * maxMemory) { if(maxMemory >= MB96) maxMemory = maxMemory - MB32; else maxMemory = MB64; } return; } } if(!gcInProgress.getAndSet(true)) // Set a flag to indicate GC in progress to ensure only one thread do gc at a time. System.gc(); int retryCount = 0; // Number of retries allowing System.gc() to do the required cleanup /* Check whether sufficient DBB space is already available as the previous gc might have * cleaned up more DBB space or another thread might have expnaded the maxMemory size. * if not, wait for 100 ms and retry (multiple times), a maximum of one second in total. * Instead of waiting for one second and retry once, wait for shorter time (100 ms) interval and retry * multiple times (10 times) as finalizer can release the DBB space any time. * */ while ((reservedMemory + size >= maxMemory) && (retryCount++ < GC_WAIT_RETRY_LIMIT)) { try { Thread.sleep(GC_WAIT_TIME); } catch (InterruptedException x) { // Restore interrupt status Thread.currentThread().interrupt(); } } /* If the memory freed by gc is just enough for the allocation to succeed, then every such allocation request * can result in a System.gc call. To avoid such situation of frequent gc, pro-actively expand the DBB space * if the memory left after the current allocation is not good enough. Here we used an arbitrary number 10 MB * which is around 20% of the default memory size of 64 MB. */ synchronized (Bits.class) { if ((totalCapacity + cap) > 0.8 * maxMemory) { /* * If -XX:maxDirectMemorySize is not used as a VM argument,then progressively increase maxMemory. * - If allocation request is less then 32 MB, add 32 MB to maxMemory. Otherwise, add allocation * size to maxMemory. However the actual memory allocated depends on the System state and fails * only in case of genuine Out of Memory condition. * * If -XX:maxDirectMemorySize is specified as a VM argument, then throw Out of Memory error when enough * DBB space is not freed for the allocation to succeed even after 1 second wait. */ if(xxOptionUsed == false) maxMemory += (size > MB32 ? size : MB32 ); else if ((totalCapacity + cap) > maxMemory) throw new OutOfMemoryError("Direct buffer memory::Please use appropriate '<size>' via -XX:MaxDirectMemorySize=<size>"); } reservedMemory += size; totalCapacity += cap; count++; gcInProgress.set(false); // Resetting gcInProgress flag } } static synchronized void unreserveMemory(long size, int cap) { if (reservedMemory > 0) { reservedMemory -= size; totalCapacity -= cap; count--; assert (reservedMemory > -1); } } // -- Monitoring of direct buffer usage -- static { // setup access to this package in SharedSecrets sun.misc.SharedSecrets.setJavaNioAccess( new sun.misc.JavaNioAccess() { @Override public sun.misc.JavaNioAccess.BufferPool getDirectBufferPool() { return new sun.misc.JavaNioAccess.BufferPool() { @Override public String getName() { return "direct"; } @Override public long getCount() { return Bits.count; } @Override public long getTotalCapacity() { return Bits.totalCapacity; } @Override public long getMemoryUsed() { return Bits.reservedMemory; } }; } @Override public ByteBuffer newDirectByteBuffer(long addr, int cap, Object ob) { return new DirectByteBuffer(addr, cap, ob); } @Override public void truncate(Buffer buf) { buf.truncate(); } }); } // -- Bulk get/put acceleration -- // These numbers represent the point at which we have empirically // determined that the average cost of a JNI call exceeds the expense // of an element by element copy. These numbers may change over time. static final int JNI_COPY_TO_ARRAY_THRESHOLD = 6; static final int JNI_COPY_FROM_ARRAY_THRESHOLD = 6; // This number limits the number of bytes to copy per call to Unsafe's // copyMemory method. A limit is imposed to allow for safepoint polling // during a large copy static final long UNSAFE_COPY_THRESHOLD = 1024L * 1024L; // These methods do no bounds checking. Verification that the copy will not // result in memory corruption should be done prior to invocation. // All positions and lengths are specified in bytes. /** * Copy from given source array to destination address. * * @param src * source array * @param srcBaseOffset * offset of first element of storage in source array * @param srcPos * offset within source array of the first element to read * @param dstAddr * destination address * @param length * number of bytes to copy */ static void copyFromArray(Object src, long srcBaseOffset, long srcPos, long dstAddr, long length) { long offset = srcBaseOffset + srcPos; while (length > 0) { long size = (length > UNSAFE_COPY_THRESHOLD) ? UNSAFE_COPY_THRESHOLD : length; unsafe.copyMemory(src, offset, null, dstAddr, size); length -= size; offset += size; dstAddr += size; } } /** * Copy from source address into given destination array. * * @param srcAddr * source address * @param dst * destination array * @param dstBaseOffset * offset of first element of storage in destination array * @param dstPos * offset within destination array of the first element to write * @param length * number of bytes to copy */ static void copyToArray(long srcAddr, Object dst, long dstBaseOffset, long dstPos, long length) { long offset = dstBaseOffset + dstPos; while (length > 0) { long size = (length > UNSAFE_COPY_THRESHOLD) ? UNSAFE_COPY_THRESHOLD : length; unsafe.copyMemory(null, srcAddr, dst, offset, size); length -= size; srcAddr += size; offset += size; } } static void copyFromCharArray(Object src, long srcPos, long dstAddr, long length) { copyFromShortArray(src, srcPos, dstAddr, length); } static void copyToCharArray(long srcAddr, Object dst, long dstPos, long length) { copyToShortArray(srcAddr, dst, dstPos, length); } static native void copyFromShortArray(Object src, long srcPos, long dstAddr, long length); static native void copyToShortArray(long srcAddr, Object dst, long dstPos, long length); static native void copyFromIntArray(Object src, long srcPos, long dstAddr, long length); static native void copyToIntArray(long srcAddr, Object dst, long dstPos, long length); static native void copyFromLongArray(Object src, long srcPos, long dstAddr, long length); static native void copyToLongArray(long srcAddr, Object dst, long dstPos, long length); } //IBM-nio_vad
33.278835
139
0.513393
4313bb4058e20d2b7d64437d62dc6fae0f111819
2,024
package com.linda.framework.rpc.aio; import java.io.IOException; import java.net.InetSocketAddress; import java.nio.ByteBuffer; import java.nio.CharBuffer; import java.nio.channels.AsynchronousChannelGroup; import java.nio.channels.AsynchronousServerSocketChannel; import java.nio.channels.AsynchronousSocketChannel; import java.nio.channels.CompletionHandler; import java.nio.charset.Charset; import java.nio.charset.CharsetEncoder; import java.util.Date; import java.util.concurrent.ExecutionException; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; public class ServerTest { private static Charset charset = Charset.forName("utf-8"); private static CharsetEncoder encoder = charset.newEncoder(); public static void main(String[] args) throws Exception { AsynchronousChannelGroup group = AsynchronousChannelGroup .withThreadPool(Executors.newFixedThreadPool(4)); final AsynchronousServerSocketChannel server = AsynchronousServerSocketChannel .open(group).bind(new InetSocketAddress("0.0.0.0", 8013)); server.accept(null, new CompletionHandler<AsynchronousSocketChannel, Void>() { @Override public void completed(AsynchronousSocketChannel result, Void attachment) { server.accept(null, this); // 接受下一个连接 try { String now = new Date().toString(); ByteBuffer buffer = encoder.encode(CharBuffer .wrap(now + "\r\n")); // result.write(buffer, null, new // CompletionHandler<Integer,Void>(){...}); // //callback or Future<Integer> f = result.write(buffer); f.get(); System.out.println("sent to client: " + now); result.close(); } catch (IOException | InterruptedException | ExecutionException e) { e.printStackTrace(); } } @Override public void failed(Throwable exc, Void attachment) { exc.printStackTrace(); } }); group.awaitTermination(Long.MAX_VALUE, TimeUnit.SECONDS); } }
34.305085
80
0.722826
bb55374e4a7204ab8b10183c969fd5d7d6abb627
338
/** * Represents an arithmetic expression */ public interface Node { /** * @return value that results from evaluating the expression */ public double evaluate(); /** * @return expression in postfix notation */ public String toPostfixString(); /** * @return expression in infix notation */ public String toString(); }
17.789474
61
0.683432
ebf3a75455dbbf52157f601aba8a3323a21c3395
397
package hse.project.mongo.repository; import hse.project.entities.mongo.MongoCustomer; import hse.project.entities.mongo.MongoTariffCustomer; import hse.project.entities.prototypes.Customer; import org.springframework.data.mongodb.repository.MongoRepository; public interface VMCustomerRepositoryInterface extends MongoRepository<MongoCustomer, String> { Customer findByLogin(String login); }
36.090909
95
0.853904
83b39a810f62a93594efe192db503445dca6041e
12,968
package seedu.address.logic.commands; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; import static seedu.address.logic.parser.CliSyntax.PREFIX_ACAD_LEVEL; import static seedu.address.logic.parser.CliSyntax.PREFIX_ACAD_STREAM; import static seedu.address.logic.parser.CliSyntax.PREFIX_ADDRESS; import static seedu.address.logic.parser.CliSyntax.PREFIX_DATE; import static seedu.address.logic.parser.CliSyntax.PREFIX_EMAIL; import static seedu.address.logic.parser.CliSyntax.PREFIX_FEE; import static seedu.address.logic.parser.CliSyntax.PREFIX_FIND_CONDITION; import static seedu.address.logic.parser.CliSyntax.PREFIX_HOMEWORK; import static seedu.address.logic.parser.CliSyntax.PREFIX_NAME; import static seedu.address.logic.parser.CliSyntax.PREFIX_PARENT_EMAIL; import static seedu.address.logic.parser.CliSyntax.PREFIX_PARENT_PHONE; import static seedu.address.logic.parser.CliSyntax.PREFIX_PHONE; import static seedu.address.logic.parser.CliSyntax.PREFIX_REMARK; import static seedu.address.logic.parser.CliSyntax.PREFIX_SCHOOL; import static seedu.address.logic.parser.CliSyntax.PREFIX_SUBJECT; import static seedu.address.logic.parser.CliSyntax.PREFIX_TAG; import static seedu.address.logic.parser.CliSyntax.PREFIX_TIME; import static seedu.address.testutil.Assert.assertThrows; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import seedu.address.commons.core.index.Index; import seedu.address.logic.commands.exceptions.CommandException; import seedu.address.model.AddressBook; import seedu.address.model.Model; import seedu.address.model.person.NameContainsKeywordsPredicate; import seedu.address.model.person.Person; import seedu.address.testutil.EditPersonDescriptorBuilder; /** * Contains helper methods for testing commands. */ public class CommandTestUtil { public static final String EMPTY_FIELD = ""; public static final String VALID_NAME_AMY = "Amy Bee"; public static final String VALID_NAME_BOB = "Bob Choo"; public static final String VALID_PHONE_AMY = "11111111"; public static final String VALID_PHONE_BOB = "22222222"; public static final String VALID_EMAIL_AMY = "amy@example.com"; public static final String VALID_EMAIL_BOB = "bob@example.com"; public static final String VALID_PARENT_PHONE_AMY = "33333333"; public static final String VALID_PARENT_PHONE_BOB = "44444444"; public static final String VALID_PARENT_EMAIL_AMY = "amyparent@example.com"; public static final String VALID_PARENT_EMAIL_BOB = "bobparent@example.com"; public static final String VALID_ADDRESS_AMY = "Block 312, Amy Street 1"; public static final String VALID_ADDRESS_BOB = "Block 123, Bobby Street 3"; public static final String VALID_SCHOOL_AMY = "Amys School"; public static final String VALID_SCHOOL_BOB = "Bob's School"; public static final String VALID_ACAD_STREAM_AMY = "Amy stream"; public static final String VALID_ACAD_STREAM_BOB = "Bob stream"; public static final String VALID_ACAD_LEVEL_AMY = "S1"; public static final String VALID_ACAD_LEVEL_BOB = "P6"; public static final String VALID_FEE_AMY = "12345.67"; public static final String VALID_FEE_BOB = "0.50"; public static final String VALID_REMARK_AMY = "Amy loves sushi!"; public static final String VALID_REMARK_BOB = "Bob loves sashimi!"; public static final String VALID_TAG_HUSBAND = "husband"; public static final String VALID_TAG_FRIEND = "friend"; public static final String NAME_DESC_AMY = " " + PREFIX_NAME + VALID_NAME_AMY; public static final String NAME_DESC_BOB = " " + PREFIX_NAME + VALID_NAME_BOB; public static final String PHONE_DESC_AMY = " " + PREFIX_PHONE + VALID_PHONE_AMY; public static final String PHONE_DESC_BOB = " " + PREFIX_PHONE + VALID_PHONE_BOB; public static final String EMAIL_DESC_AMY = " " + PREFIX_EMAIL + VALID_EMAIL_AMY; public static final String EMAIL_DESC_BOB = " " + PREFIX_EMAIL + VALID_EMAIL_BOB; public static final String PARENT_PHONE_DESC_AMY = " " + PREFIX_PARENT_PHONE + VALID_PARENT_PHONE_AMY; public static final String PARENT_PHONE_DESC_BOB = " " + PREFIX_PARENT_PHONE + VALID_PARENT_PHONE_BOB; public static final String PARENT_EMAIL_DESC_AMY = " " + PREFIX_PARENT_EMAIL + VALID_PARENT_EMAIL_AMY; public static final String PARENT_EMAIL_DESC_BOB = " " + PREFIX_PARENT_EMAIL + VALID_PARENT_EMAIL_BOB; public static final String ADDRESS_DESC_AMY = " " + PREFIX_ADDRESS + VALID_ADDRESS_AMY; public static final String ADDRESS_DESC_BOB = " " + PREFIX_ADDRESS + VALID_ADDRESS_BOB; public static final String SCHOOL_DESC_AMY = " " + PREFIX_SCHOOL + VALID_SCHOOL_AMY; public static final String SCHOOL_DESC_BOB = " " + PREFIX_SCHOOL + VALID_SCHOOL_BOB; public static final String ACAD_STREAM_DESC_AMY = " " + PREFIX_ACAD_STREAM + VALID_ACAD_STREAM_AMY; public static final String ACAD_STREAM_DESC_BOB = " " + PREFIX_ACAD_STREAM + VALID_ACAD_STREAM_BOB; public static final String ACAD_LEVEL_DESC_AMY = " " + PREFIX_ACAD_LEVEL + VALID_ACAD_LEVEL_AMY; public static final String ACAD_LEVEL_DESC_BOB = " " + PREFIX_ACAD_LEVEL + VALID_ACAD_LEVEL_BOB; public static final String FEE_DESC_AMY = " " + PREFIX_FEE + VALID_FEE_AMY; public static final String FEE_DESC_BOB = " " + PREFIX_FEE + VALID_FEE_BOB; public static final String REMARK_DESC_AMY = " " + PREFIX_REMARK + VALID_REMARK_AMY; public static final String REMARK_DESC_BOB = " " + PREFIX_REMARK + VALID_REMARK_BOB; public static final String TAG_DESC_FRIEND = " " + PREFIX_TAG + VALID_TAG_FRIEND; public static final String TAG_DESC_HUSBAND = " " + PREFIX_TAG + VALID_TAG_HUSBAND; public static final String FIND_COND_DESC_ALL = " " + PREFIX_FIND_CONDITION + FindCommand.FindCondition.ALL; public static final String FIND_COND_DESC_ANY = " " + PREFIX_FIND_CONDITION + FindCommand.FindCondition.ANY; public static final String FIND_COND_DESC_NONE = " " + PREFIX_FIND_CONDITION + FindCommand.FindCondition.NONE; public static final String INVALID_NAME_DESC = " " + PREFIX_NAME + "James&"; // '&' not allowed in names public static final String INVALID_PHONE_DESC = " " + PREFIX_PHONE + "8765432a"; // 'a' not allowed in phones public static final String INVALID_EMAIL_DESC = " " + PREFIX_EMAIL + "bob!yahoo"; // missing '@' symbol public static final String INVALID_PARENT_PHONE_DESC = " " + PREFIX_PARENT_PHONE + "8765 4321"; // ' ' spaces not allowed in phones public static final String INVALID_PARENT_EMAIL_DESC = " " + PREFIX_PARENT_EMAIL + "bobparent.yahoo"; // missing '@' symbol public static final String INVALID_ADDRESS_DESC = " " + PREFIX_ADDRESS; // empty string not allowed for addresses public static final String INVALID_ACAD_LEVEL_DESC = " " + PREFIX_ACAD_LEVEL + "abcdefghijklmnopq"; // max 15 characters allowed for acad level public static final String INVALID_FEE_DESC = " " + PREFIX_FEE + "$999.99"; // '$' not allowed in fees public static final String INVALID_TAG_DESC = " " + PREFIX_TAG + "hubby*"; // '*' not allowed in tags public static final String VALID_DATE_PAST = "15 May 1988"; public static final String VALID_DATE_FUTURE = "07 Apr 2103"; public static final String VALID_TIME_RANGE = "1234-1345"; public static final String VALID_SUBJECT = "Language Arts"; public static final String VALID_HOMEWORK_TEXTBOOK = "Textbook pg 21-26"; public static final String VALID_HOMEWORK_POETRY = "Poetry draft"; public static final String PAST_DATE_DESC = " " + PREFIX_DATE + VALID_DATE_PAST; public static final String FUTURE_DATE_DESC = " " + PREFIX_DATE + VALID_DATE_FUTURE; public static final String TIME_RANGE_DESC = " " + PREFIX_TIME + VALID_TIME_RANGE; public static final String SUBJECT_DESC = " " + PREFIX_SUBJECT + VALID_SUBJECT; public static final String HOMEWORK_DESC_TEXTBOOK = " " + PREFIX_HOMEWORK + VALID_HOMEWORK_TEXTBOOK; public static final String HOMEWORK_DESC_POETRY = " " + PREFIX_HOMEWORK + VALID_HOMEWORK_POETRY; public static final String INVALID_DATE_DESC = " " + PREFIX_DATE + "32 Dec 2001"; // No such date public static final String INVALID_TIME_RANGE_DESC = " " + PREFIX_TIME + "0100-0300"; // Not between 0000h - 0800h public static final String INVALID_SUBJECT_DESC = " " + PREFIX_SUBJECT + "-An+"; // Not alphanumeric public static final String INVALID_HOMEWORK_DESC = " " + PREFIX_HOMEWORK + "Homework cannot be more than fifty characters long," + " including whitespaces"; public static final String PREAMBLE_WHITESPACE = "\t \r \n"; public static final String PREAMBLE_NON_EMPTY = "NonEmptyPreamble"; public static final EditCommand.EditPersonDescriptor DESC_AMY; public static final EditCommand.EditPersonDescriptor DESC_BOB; static { DESC_AMY = new EditPersonDescriptorBuilder().withName(VALID_NAME_AMY) .withPhone(VALID_PHONE_AMY).withEmail(VALID_EMAIL_AMY) .withParentPhone(VALID_PARENT_PHONE_AMY).withParentEmail(VALID_PARENT_EMAIL_AMY) .withAddress(VALID_ADDRESS_AMY) .withSchool(VALID_SCHOOL_AMY) .withAcadStream(VALID_ACAD_STREAM_AMY) .withAcadLevel(VALID_ACAD_LEVEL_AMY) .withFee(VALID_FEE_AMY).withRemark(VALID_REMARK_AMY) .withTags(VALID_TAG_FRIEND).build(); DESC_BOB = new EditPersonDescriptorBuilder().withName(VALID_NAME_BOB) .withPhone(VALID_PHONE_BOB).withEmail(VALID_EMAIL_BOB) .withParentPhone(VALID_PARENT_PHONE_BOB).withParentEmail(VALID_PARENT_EMAIL_BOB) .withAddress(VALID_ADDRESS_BOB) .withSchool(VALID_SCHOOL_BOB) .withAcadStream(VALID_ACAD_STREAM_BOB) .withAcadLevel(VALID_ACAD_LEVEL_BOB) .withFee(VALID_FEE_BOB).withRemark(VALID_REMARK_BOB) .withTags(VALID_TAG_HUSBAND, VALID_TAG_FRIEND).build(); } /** * Executes the given {@code command}, confirms that <br> * - the returned {@link CommandResult} matches {@code expectedCommandResult} <br> * - the {@code actualModel} matches {@code expectedModel} */ public static void assertCommandSuccess(Command command, Model actualModel, CommandResult expectedCommandResult, Model expectedModel) { try { CommandResult result = command.execute(); assertEquals(expectedCommandResult, result); assertEquals(expectedModel, actualModel); } catch (CommandException ce) { throw new AssertionError("Execution of command should not fail.", ce); } } /** * Convenience wrapper to {@link #assertCommandSuccess(Command, Model, CommandResult, Model)} * that takes a string {@code expectedMessage}. */ public static void assertCommandSuccess(Command command, Model actualModel, String expectedMessage, Model expectedModel) { CommandResult expectedCommandResult = new CommandResult(expectedMessage); assertCommandSuccess(command, actualModel, expectedCommandResult, expectedModel); } /** * Executes the given {@code command}, confirms that <br> * - a {@code CommandException} is thrown <br> * - the CommandException message matches {@code expectedMessage} <br> * - the address book, filtered person list and selected person in {@code actualModel} remain unchanged */ public static void assertCommandFailure(Command command, Model actualModel, String expectedMessage) { // we are unable to defensively copy the model for comparison later, so we can // only do so by copying its components. AddressBook expectedAddressBook = new AddressBook(actualModel.getAddressBook()); List<Person> expectedFilteredList = new ArrayList<>(actualModel.getFilteredPersonList()); assertThrows(CommandException.class, expectedMessage, () -> command.execute()); assertEquals(expectedAddressBook, actualModel.getAddressBook()); assertEquals(expectedFilteredList, actualModel.getFilteredPersonList()); } /** * Updates {@code model}'s filtered list to show only the person at the given {@code targetIndex} in the * {@code model}'s address book. */ public static void showPersonAtIndex(Model model, Index targetIndex) { assertTrue(targetIndex.getZeroBased() < model.getFilteredPersonList().size()); Person person = model.getFilteredPersonList().get(targetIndex.getZeroBased()); final String[] splitName = person.getName().fullName.split("\\s+"); model.updateFilteredPersonList(new NameContainsKeywordsPredicate(Arrays.asList(splitName[0]))); assertEquals(1, model.getFilteredPersonList().size()); } }
60.316279
118
0.741209
8045c6b19743fb622827606b48a0f3acc4f81912
1,431
package io.github.zeroone3010.geogpxparser.tabular; import org.junit.Test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotSame; public class TableRowTest { static final TableRow hr1 = new TableRow(true); static final TableRow r1 = new TableRow(false); static final TableRow r2 = new TableRow(false); static final TableRow r3 = new TableRow(false); static { hr1.addCell(new CellData("Hello")); hr1.addCell(new CellData(null)); hr1.addCell(new CellData("World", "http://example.net/")); r1.addCell(new CellData("Hello")); r1.addCell(new CellData(null)); r1.addCell(new CellData("World", "http://example.net/")); r2.addCell(new CellData("Hello")); r2.addCell(new CellData(null)); r2.addCell(new CellData("World", "http://example.net/")); r3.addCell(new CellData("Foo")); r3.addCell(new CellData(null)); r3.addCell(new CellData("Bar", "http://example.net/")); } @Test public void equal_rows_should_be_equal() { assertEquals(r1, r2); assertEquals(r2, r1); } @Test public void unequal_rows_should_be_unequal() { assertNotSame(r1, r3); assertNotSame(r3, r1); } @Test public void header_row_and_non_header_row_should_not_be_equal() { assertNotSame(hr1, r1); assertNotSame(r1, hr1); } }
28.058824
69
0.640811
25a6b7d543508ecc35ad963715d9452ec467ab08
875
package info.itsthesky.disky3.core.skript.properties.guild; import info.itsthesky.disky3.api.skript.properties.MultipleGuildProperty; import net.dv8tion.jda.api.entities.Guild; import net.dv8tion.jda.api.entities.NewsChannel; import net.dv8tion.jda.api.entities.StageChannel; import org.jetbrains.annotations.NotNull; public class GuildStageChannels extends MultipleGuildProperty<StageChannel> { static { register( GuildStageChannels.class, StageChannel.class, "[discord] stage( |-)channels", "guild" ); } @Override public @NotNull StageChannel[] converting(Guild guild) { return guild.getStageChannels().toArray(new StageChannel[0]); } @Override public @NotNull Class<? extends StageChannel> getReturnType() { return StageChannel.class; } }
29.166667
77
0.688
7ddb0beee718883eaab82dcfa2095c1520b7678f
8,935
package com.bnd.core.reflection; import static org.junit.Assert.*; import com.bnd.core.reflection.ReflectionProvider; import org.apache.commons.lang.StringUtils; import org.junit.Test; import com.bnd.core.domain.um.User; /** * @author © Peter Banda * @since 2012 */ public class ReflectionProviderTest { private static double[] MATRIX = new double[] { 0,50.1035714285714,27.6469479765413, 1,50.1464285714286,27.7134875819707, 2,50.1828571428571,27.8341321812934, 3,49.8735714285714,27.7420121856705, 4,50.215,27.8115265948934, 5,50.0535714285714,27.712650986964, 6,49.795,27.7610794929769, 7,49.8728571428571,27.7495473084549, 8,49.7592857142857,27.7739599858699, 9,50.0428571428571,27.8703692748497, 10,50.1485714285714,27.7852614104736, 11,49.8078571428571,27.7227751909096, 12,50.2114285714286,27.8066048759153, 13,50.3764285714286,27.7416506100742, 14,50.0935714285714,27.66123964271, 15,50.0414285714286,27.435387832041, 16,50.2592857142857,27.3177816038975, 17,50.6528571428571,27.1019807475314, 18,50.9785714285714,26.4998327591654, 19,51.3392857142857,25.98009399648, 20,52.3542857142857,25.094984394461, 21,53.1578571428571,23.8683263499403, 22,54.4785714285714,22.6423289292568, 23,55.7671428571429,21.5257636078514, 24,57.1564285714286,20.2070009220502, 25,58.98,18.7552437795612, 26,60.5828571428572,17.4414428781087, 27,62.4457142857143,16.1597447210824, 28,64.235,14.8856935705705, 29,66.0478571428571,13.9930148390443, 30,67.925,13.037524393369, 31,69.5657142857143,12.1204713758841, 32,71.1921428571429,11.4291053412373, 33,72.7557142857143,11.0769002289142, 34,74.3371428571429,10.3017820927116, 35,76.0692857142857,10.0023623857918, 36,77.1842857142857,9.6977576427081, 37,78.3985714285714,9.29069415071866, 38,79.6414285714286,9.06001091622951, 39,80.7635714285714,8.71464603380456, 40,81.7807142857143,8.47421107222987, 41,82.7321428571429,8.24854782424102, 42,83.7135714285714,8.04848060877891, 43,84.5378571428571,7.78004170304368, 44,85.4707142857143,7.72746198187469, 45,86.365,7.34696038665494, 46,87.0221428571429,7.20697757899772, 47,87.87,6.95664485886032, 48,88.5407142857143,6.8209219592095, 49,89.0514285714286,6.66266158082934, 50,89.655,6.6010509070089, 51,90.3535714285714,6.34661946010855, 52,90.79,6.21464647178186, 53,91.3907142857143,6.14548923293239, 54,91.93,5.8919554022021, 55,92.41,5.80300982912515, 56,92.9178571428571,5.71232025951388, 57,93.3057142857143,5.43648743256118, 58,93.7692857142857,5.44586570681864, 59,94.1892857142857,5.24747186643349, 60,94.5828571428572,5.13953369416006, 61,94.7742857142857,5.02496339716591, 62,95.0978571428572,4.94387916607912, 63,95.3957142857143,4.87142328638816, 64,95.77,4.59149213219407, 65,95.9957142857143,4.41351719900739, 66,96.1064285714286,4.64528148876794, 67,96.5135714285714,4.32552994911136, 68,96.69,4.07006331457084, 69,96.9214285714286,4.0665026688844, 70,97.0642857142857,3.99482302349065, 71,97.2885714285714,3.66942430433913, 72,97.4928571428571,3.57175119421924, 73,97.545,3.56864281463717, 74,97.7607142857143,3.28542109298667, 75,97.8671428571429,3.23525870698139, 76,97.9978571428571,3.04099472230698, 77,98.1028571428571,2.8229047466734, 78,98.1335714285714,2.895852756411, 79,98.2564285714286,2.69969402010632, 80,98.3235714285714,2.78023963312201, 81,98.4192857142857,2.46408811120468, 82,98.5135714285714,2.41250462619838, 83,98.5535714285714,2.43991048745916, 84,98.6507142857143,2.19229231727788, 85,98.6842857142857,2.21001814919702, 86,98.735,2.06694404672882, 87,98.79,1.93136062043158, 88,98.8,1.92578854977943, 89,98.8535714285714,1.86727941604421, 90,98.8864285714286,1.87217523482448, 91,98.98,1.68291871004377, 92,98.9907142857143,1.66037745609343, 93,99.04,1.55342301931028, 94,99.035,1.56794696731353, 95,99.1057142857143,1.46974992266196, 96,99.0785714285714,1.54312797785665, 97,99.1485714285714,1.40186061604326, 98,99.1271428571429,1.41503154937065, 99,99.1564285714286,1.33394502909953, 100,99.1857142857143,1.32489601499493, 101,99.2085714285714,1.30069127858912, 102,99.195,1.32797561377054, 103,99.1928571428572,1.31139637011868, 104,99.2392857142857,1.19639499706869, 105,99.2064285714286,1.3182132846153, 106,99.2292857142857,1.25990515079945, 107,99.265,1.19965860528351, 108,99.2464285714286,1.22938763457421, 109,99.2592857142857,1.21932808915853, 110,99.2657142857143,1.23775052964092, 111,99.2642857142857,1.18427332010111, 112,99.2757142857143,1.2387010211428, 113,99.2607142857143,1.21859606663832, 114,99.3078571428571,1.13916419138992, 115,99.2714285714286,1.20643694816186, 116,99.285,1.15038956612365, 117,99.3185714285714,1.14308527942755, 118,99.2792857142857,1.18866741344256, 119,99.2878571428571,1.1977169215536, 120,99.2864285714286,1.16293135681318, 121,99.3171428571429,1.11640514131763, 122,99.2928571428571,1.15065485416201, 123,99.2892857142857,1.18638730403053, 124,99.285,1.17488952017429, 125,99.3078571428571,1.16607282112903, 126,99.2921428571428,1.18839373539651, 127,99.2628571428571,1.18739163762379, 128,99.2435714285714,1.22425869025273, 129,99.285,1.19640969314284, 130,99.3035714285714,1.11779733365261, 131,99.2885714285714,1.19813224609009, 132,99.2778571428571,1.1851853381283, 133,99.2864285714286,1.24680272415769, 134,99.295,1.21631695009028, 135,99.2535714285714,1.31387042531046, 136,99.2721428571429,1.23225982881626, 137,99.2828571428571,1.1985210666704, 138,99.2807142857143,1.18979936437726, 139,99.2757142857143,1.19812490863987, 140,99.29,1.1829233670478, 141,99.3,1.16502228436924, 142,99.2878571428571,1.20123768589816, 143,99.2628571428571,1.24436841299221, 144,99.2757142857143,1.18695288148146, 145,99.2864285714286,1.18155443341425, 146,99.2814285714286,1.18367652248835, 147,99.2535714285714,1.24621029922325, 148,99.3207142857143,1.14924365954787, 149,99.2878571428571,1.18013153485552, 150,99.2514285714286,1.25544878364338, 151,99.2864285714286,1.17738045052342, 152,99.2785714285714,1.19399688920389, 153,99.2907142857143,1.14997969403955, 154,99.3,1.15699212150765, 155,99.3085714285714,1.13603803527101, 156,99.2842857142857,1.15327436381884, 157,99.2892857142857,1.16775566652588, 158,99.2757142857143,1.19502632275942, 159,99.3057142857143,1.1568638925708, 160,99.2957142857143,1.21124039591788, 161,99.2892857142857,1.2045903503216, 162,99.2621428571428,1.24791012109433, 163,99.2757142857143,1.21150709884402, 164,99.2685714285714,1.19432541077095, 165,99.295,1.18154234274202, 166,99.29,1.21899706568714, 167,99.2878571428571,1.22224999690941, 168,99.2971428571429,1.19811665395466, 169,99.2971428571429,1.16320134226082, 170,99.3071428571429,1.12888936959793, 171,99.2778571428571,1.19604591223574, 172,99.2964285714286,1.1554793021004, 173,99.2828571428571,1.21817283459493, 174,99.2635714285714,1.19900989373513, 175,99.2914285714286,1.17626434197327, 176,99.2821428571429,1.17557958583729, 177,99.3092857142857,1.15881547137726, 178,99.2964285714286,1.15467349459528, 179,99.2721428571429,1.18686515708352, 180,99.3028571428571,1.15471893730718, 181,99.2914285714286,1.15627290592102, 182,99.2935714285714,1.17737391709658, 183,99.25,1.2499292287658, 184,99.3007142857143,1.18388190864899, 185,99.3192857142857,1.12637242294227, 186,99.2478571428571,1.2513572850889, 187,99.29,1.17616063790362, 188,99.2792857142857,1.19096253435688, 189,99.2692857142857,1.21193084523267, 190,99.255,1.25939393238299, 191,99.2721428571429,1.22435652532214, 192,99.2564285714286,1.20242451957482, 193,99.2821428571429,1.22192898302661, 194,99.2957142857143,1.16316355279447, 195,99.2907142857143,1.17693516118195, 196,99.2585714285714,1.22622533468713, 197,99.2742857142857,1.19627443652054, 198,99.2878571428571,1.19637387114582, 199,99.2857142857143,1.2095753500599}; @Test // remove public void testMatrix() { Integer[] steps = new Integer[MATRIX.length / 3]; Double[] avgs = new Double[MATRIX.length / 3]; Double[] stds = new Double[MATRIX.length / 3]; int order = 0; int index = 0; for (double value : MATRIX) { switch (order) { case 0: steps[index] = (int) value; break; case 1: avgs[index] = value; break; case 2: stds[index] = value; break; } order++; if (order > 2) { order = 0; index++; } } System.out.println(StringUtils.join(steps, ',')); System.out.println(StringUtils.join(avgs, ',')); System.out.println(StringUtils.join(stds, ',')); } @Test public void testCreateRandomInstance() { ReflectionProvider<User> reflectionProvider = new SpringReflectionProviderImpl(User.class); User user = reflectionProvider.createRandomInstance(); assertNotNull(user); } }
35.59761
93
0.776609
b839f7698c2e5aa15d8075d2fe04e3fadf30d403
1,059
package com.arematics.minecraft.core.proxy; import com.arematics.minecraft.core.Boots; import com.arematics.minecraft.core.CoreBoot; import com.arematics.minecraft.core.server.entities.player.CorePlayer; import com.google.common.io.ByteArrayDataOutput; import com.google.common.io.ByteStreams; public class MessagingUtils { public static void sendToServer(CorePlayer player, String server) { ByteArrayDataOutput out = ByteStreams.newDataOutput(); out.writeUTF("ConnectOther"); out.writeUTF(player.getPlayer().getName()); out.writeUTF(server); player.getPlayer().sendPluginMessage(Boots.getBoot(CoreBoot.class), "BungeeCord", out.toByteArray()); } public static void kickPlayer(CorePlayer player, String message){ ByteArrayDataOutput out = ByteStreams.newDataOutput(); out.writeUTF("KickPlayer"); out.writeUTF(player.getName()); out.writeUTF(message); player.getPlayer().sendPluginMessage(Boots.getBoot(CoreBoot.class), "BungeeCord", out.toByteArray()); } }
36.517241
109
0.731822
205a6e16c955bdff18d0692e5ba31cd6e3720c77
4,800
import javax.swing.JOptionPane; class exercicio02 { public static void main(String[] args) { Teste teste = new Teste(); int opcao = 0; String aux = ""; while (opcao != 9) { opcao = Integer.parseInt(JOptionPane.showInputDialog ("\n1 - Adicionar elemento na Fila \n2 - Adicionar elemento na Pilha \n3 - Remover elemento da Fila\n4 - Remover elemento da Pilha\n" + "5 - Mostrar Fila \n6 - Mostrar Pilha\n9 - Sair")); switch (opcao) { case 1: aux = (JOptionPane.showInputDialog("Informe o valor que deseja adicionar na Fila:")); JOptionPane.showMessageDialog(null,"O elemento inserido na lista foi: "+ teste.AdicionaFinalFila(aux)); break; case 2: aux = (JOptionPane.showInputDialog("Informe o valor que deseja adicionar na Pilha:")); JOptionPane.showMessageDialog(null,"O elemento inserido na pilha foi: "+ teste.AdicionaFinalPilha(aux)); break; case 3: JOptionPane.showMessageDialog(null,"O elemento removido foi: "+ teste.RemoveInicioFila()); break; case 4: JOptionPane.showMessageDialog(null,"O elemento removido foi: "+ teste.RemoveFinalPilha()); break; case 5: JOptionPane.showMessageDialog(null,"Fila:"+ teste.ConcatenaFila()); break; case 6: JOptionPane.showMessageDialog(null,"Pilha:"+ teste.ConcatenaPilha()); break; case 9: JOptionPane.showMessageDialog(null,"Saindo"); break; default: JOptionPane.showMessageDialog(null,"Opção inválida"); break; } } } public static class Teste { private String fila[]; private String pilha[]; private int tamanho; public Teste () { fila = new String [5]; pilha = new String [5]; tamanho = 0; } public String AdicionaFinalFila(String x) { if (tamanho < fila.length) { fila[tamanho] = x ; tamanho++; } else{ System.out.println("Lista Cheia"); JOptionPane.showMessageDialog(null," A lista está cheia"); } System.out.println("O valor digitado é: " +fila[tamanho-1]); return x; } public String AdicionaFinalPilha(String x) { if (tamanho < pilha.length) { pilha[tamanho] = x ; tamanho++; } else{ System.out.println("Pilha Cheia"); JOptionPane.showMessageDialog(null,"A Pilha está cheia"); } System.out.println("O valor digitado é: " + pilha[tamanho-1]); return x; } public String RemoveInicioFila(){ String retornoFilha = ""; int i; if (tamanho >= 1){ retornoFilha = fila[0]; for (i=1;i<tamanho;i++){ fila[i-1]=fila[i]; } tamanho --; } AdicionaFinalPilha(retornoFilha); return retornoFilha; } public String RemoveFinalPilha(){ String retornoPilha = ""; int i; if (tamanho >= 1){ retornoPilha=pilha[tamanho-1]; for (i=0;i<tamanho;i++){ if (i==tamanho-1) tamanho --; } } AdicionaFinalFila(retornoPilha); return retornoPilha; } public String ConcatenaFila(){ String aux=" "; for (int i=0;i<tamanho;i++){ aux=aux+"\n"+fila[i]; } return aux; } public String ConcatenaPilha(){ String aux=" "; for (int i=0;i<tamanho;i++){ aux=aux+"\n"+pilha[i]; } return aux; } } }
34.532374
189
0.422083
80f5f91a918e6aef95f66f365b8142589aa8aa4f
8,603
package org.zstack.core.gc; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.transaction.annotation.Transactional; import org.zstack.core.Platform; import org.zstack.core.cloudbus.ResourceDestinationMaker; import org.zstack.core.db.DatabaseFacade; import org.zstack.core.db.SimpleQuery; import org.zstack.core.db.SimpleQuery.Op; import org.zstack.core.thread.AsyncThread; import org.zstack.core.thread.ThreadFacade; import org.zstack.header.errorcode.ErrorCode; import org.zstack.header.exception.CloudRuntimeException; import org.zstack.header.managementnode.ManagementNodeChangeListener; import org.zstack.header.managementnode.ManagementNodeReadyExtensionPoint; import org.zstack.utils.DebugUtils; import org.zstack.utils.Utils; import org.zstack.utils.logging.CLogger; import javax.persistence.Query; import java.util.ArrayList; import java.util.List; import static org.zstack.utils.CollectionDSL.list; /** * Created by frank on 8/5/2015. */ public class GCFacadeImpl implements GCFacade, ManagementNodeChangeListener, ManagementNodeReadyExtensionPoint { private static final CLogger logger = Utils.getLogger(GCFacadeImpl.class); @Autowired private DatabaseFacade dbf; @Autowired private ThreadFacade thdf; @Autowired private ResourceDestinationMaker destinationMaker; private GarbageCollectorVO save(GCPersistentContext context) { DebugUtils.Assert(context.getTimeUnit() != null, "timeUnit cannot be null"); DebugUtils.Assert(context.getInterval() > 0, "interval must be greater than 0"); DebugUtils.Assert(context.getRunnerClass() != null, "runnerClass cannot be null"); DebugUtils.Assert(GCRunner.class.isAssignableFrom(context.getRunnerClass()), "runnerClass must be a implementation of GCRunner"); GarbageCollectorVO vo = new GarbageCollectorVO(); vo.setContext(context.toInternal().toJson()); vo.setRunnerClass(context.getRunnerClass().getName()); vo.setManagementNodeUuid(Platform.getManagementServerId()); vo.setStatus(GCStatus.Idle); vo = dbf.persistAndRefresh(vo); return vo; } private GCRunner getGCRunner(GCContext context) { if (context instanceof GCPersistentContext) { try { return (GCRunner)((GCPersistentContext)context).getRunnerClass().newInstance(); } catch (Exception e) { throw new CloudRuntimeException(e); } } else { return ((GCEphemeralContext)context).getRunner(); } } private void scheduleTask(final GCPersistentContext context, final GarbageCollectorVO vo, boolean instant, final boolean updateDb) { final GCCompletion completion = new GCCompletion() { @Override public void success() { vo.setStatus(GCStatus.Done); dbf.update(vo); logger.debug(String.format("GC job[id:%s, name: %s, runner class:%s] is done", vo.getId(), context.getName(), vo.getRunnerClass())); } @Override public void fail(ErrorCode errorCode) { logger.debug(String.format("GC job[id:%s, name:%s, runner class:%s] failed, %s. Reschedule it", vo.getId(), context.getName(), vo.getRunnerClass(), errorCode)); scheduleTask(context, vo, false, false); } @Override public void cancel() { vo.setStatus(GCStatus.Idle); dbf.update(vo); logger.debug(String.format("GC job[id:%s, name: %s, runner class:%s] is cancelled by the runner, set it to idle", vo.getId(), context.getName(), vo.getRunnerClass())); } }; final GCRunner runner = getGCRunner(context); Runnable r = new Runnable() { @Override public void run() { context.increaseExecutedTime(); if (updateDb) { vo.setStatus(GCStatus.Processing); dbf.update(vo); } logger.debug(String.format("start running GC job[id:%s, name: %s, runner class:%s], already executed %s times", vo.getId(), context.getName(), vo.getRunnerClass(), context.getExecutedTimes())); runner.run(context, completion); } }; if (instant) { thdf.submitTimeoutTask(r, context.getTimeUnit(), 0); } else { thdf.submitTimeoutTask(r, context.getTimeUnit(), context.getInterval()); } } @Override public void schedule(final GCContext context) { if (context instanceof GCPersistentContext) { scheduleTask((GCPersistentContext) context, save((GCPersistentContext) context), false, true); } else { scheduleTask((GCEphemeralContext) context, false); } } private void scheduleTask(final GCEphemeralContext context, boolean instant) { final GCCompletion completion = new GCCompletion() { @Override public void success() { logger.debug(String.format("GC ephemeral job[name:%s] is done", context.getName())); } @Override public void fail(ErrorCode errorCode) { logger.debug(String.format("GC ephemeral job[name:%s] failed, %s. Reschedule it", context.getName(), errorCode)); scheduleTask(context, false); } @Override public void cancel() { logger.debug(String.format("GC ephemeral job[name:%s] is cancelled by the runner", context.getName())); } }; final GCRunner runner = getGCRunner(context); Runnable r = new Runnable() { @Override public void run() { context.increaseExecutedTime(); logger.debug(String.format("start running GC ephemeral job[name:%s], already executed %s times", context.getName(), context.getExecutedTimes())); runner.run(context, completion); } }; if (instant) { thdf.submitTimeoutTask(r, context.getTimeUnit(), 0); } else { thdf.submitTimeoutTask(r, context.getTimeUnit(), context.getInterval()); } } @Override public void scheduleImmediately(GCContext context) { if (context instanceof GCPersistentContext) { scheduleTask((GCPersistentContext) context, save((GCPersistentContext) context), true, true); } else { scheduleTask((GCEphemeralContext)context, true); } } @Override public void nodeJoin(String nodeId) { } @Override public void nodeLeft(String nodeId) { setJobsToIdle(nodeId); } @Transactional private void setJobsToIdle(String mgmtUuid) { String sql = "update GarbageCollectorVO vo set vo.managementNodeUuid = null, vo.status = :status where vo.managementNodeUuid = :uuid"; Query q = dbf.getEntityManager().createQuery(sql); q.setParameter("uuid", mgmtUuid); q.setParameter("status", GCStatus.Idle); q.executeUpdate(); } @Override public void iAmDead(String nodeId) { setJobsToIdle(nodeId); } @Override public void iJoin(String nodeId) { } @Override @AsyncThread public void managementNodeReady() { SimpleQuery<GarbageCollectorVO> q = dbf.createQuery(GarbageCollectorVO.class); q.select(GarbageCollectorVO_.id); q.add(GarbageCollectorVO_.status, Op.IN, list(GCStatus.Idle, GCStatus.Processing)); q.add(GarbageCollectorVO_.managementNodeUuid, Op.NULL); List<Long> ids = q.listValue(); List<Long> ours = new ArrayList<Long>(); for (long id : ids) { if (destinationMaker.isManagedByUs(String.valueOf(id))) { ours.add(id); } } if (ours.isEmpty()) { return; } q = dbf.createQuery(GarbageCollectorVO.class); q.add(GarbageCollectorVO_.id, Op.IN, ours); List<GarbageCollectorVO> vos = q.list(); for (GarbageCollectorVO vo : vos) { scheduleTask(new GCPersistentContextInternal(vo).toGCContext(), vo, true, true); } } }
38.578475
184
0.613739
7f889252ac42b35f2f12aa9acd0126df3b8df505
7,417
package uk.gov.hmcts.reform.pcqbackend.controllers; import lombok.extern.slf4j.Slf4j; import net.serenitybdd.junit.spring.integration.SpringIntegrationSerenityRunner; import net.thucydides.core.annotations.WithTag; import net.thucydides.core.annotations.WithTags; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.system.OutputCaptureRule; import uk.gov.hmcts.reform.pcq.commons.model.PcqAnswerRequest; import uk.gov.hmcts.reform.pcqbackend.domain.ProtectedCharacteristics; import uk.gov.hmcts.reform.pcqbackend.util.PcqIntegrationTest; import java.util.Map; import java.util.Optional; import static org.junit.Assert.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertTrue; import static uk.gov.hmcts.reform.pcq.commons.tests.utils.TestUtils.jsonObjectFromString; import static uk.gov.hmcts.reform.pcq.commons.tests.utils.TestUtils.jsonStringFromFile; @Slf4j @RunWith(SpringIntegrationSerenityRunner.class) @WithTags({@WithTag("testType:Integration")}) public class AddCaseForPcqTest extends PcqIntegrationTest { public static final String RESPONSE_KEY_1 = "pcqId"; public static final String RESPONSE_KEY_2 = "responseStatusCode"; public static final String RESPONSE_KEY_3 = "responseStatus"; public static final String HTTP_OK = "200"; public static final String HTTP_BAD_REQUEST = "400"; public static final String RESPONSE_SUCCESS_MSG = "Successfully updated"; public static final String EXCEPTION_MSG = "Exception while executing test"; private static final String ASSERT_MESSAGE_PCQ = "PCQId not valid"; private static final String ASSERT_MESSAGE_STATUS = "Response Status not valid"; private static final String ASSERT_MESSAGE_STATUS_CODE = "Response Status Code not valid"; private static final String ASSERT_MESSAGE_CASE_ID = "Case Id Not Matching"; private static final String TEST_CASE_ID = "CCD-121212"; private static final String JSON_FILE = "JsonTestFiles/FirstSubmitAnswer.json"; @Rule public OutputCaptureRule capture = new OutputCaptureRule(); @Test public void addCaseForPcqSuccess() { try { //Create the Test Data in the database. String jsonStringRequest = jsonStringFromFile(JSON_FILE); PcqAnswerRequest answerRequest = jsonObjectFromString(jsonStringRequest); pcqBackEndClient.createPcqAnswer(answerRequest); //Now call the actual method. Map<String, Object> responseMap = pcqBackEndClient.addCaseForPcq(answerRequest.getPcqId(), TEST_CASE_ID); //Test the assertions assertResponse(responseMap, answerRequest.getPcqId(), HTTP_OK, RESPONSE_SUCCESS_MSG); checkLogsForKeywords(); //Fetch the record from database and verify the answers. Optional<ProtectedCharacteristics> protectedCharacteristicsOptional = protectedCharacteristicsRepository.findById(answerRequest.getPcqId()); assertEquals(ASSERT_MESSAGE_CASE_ID, TEST_CASE_ID, protectedCharacteristicsOptional.get().getCaseId()); } catch (Exception e) { log.error(EXCEPTION_MSG, e); } } @Test public void addCaseForInvalidPcq() { try { //Create the Test Data in the database. String jsonStringRequest = jsonStringFromFile(JSON_FILE); PcqAnswerRequest answerRequest = jsonObjectFromString(jsonStringRequest); pcqBackEndClient.createPcqAnswer(answerRequest); //Now call the actual method. Map<String, Object> responseMap = pcqBackEndClient.addCaseForPcq("JunkPCQ", TEST_CASE_ID); //Test the assertions assertEquals(ASSERT_MESSAGE_STATUS_CODE, HTTP_BAD_REQUEST, responseMap.get("http_status")); checkLogsForKeywords(); //Fetch the record from database and verify the answers. Optional<ProtectedCharacteristics> protectedCharacteristicsOptional = protectedCharacteristicsRepository.findById(answerRequest.getPcqId()); assertEquals(ASSERT_MESSAGE_CASE_ID, null, protectedCharacteristicsOptional.get().getCaseId()); } catch (Exception e) { log.error(EXCEPTION_MSG, e); } } @Test public void addCaseForNullParams() { try { //Create the Test Data in the database. String jsonStringRequest = jsonStringFromFile(JSON_FILE); PcqAnswerRequest answerRequest = jsonObjectFromString(jsonStringRequest); pcqBackEndClient.createPcqAnswer(answerRequest); //Now call the actual method. Map<String, Object> responseMap = pcqBackEndClient.addCaseForPcq(null, null); //Test the assertions assertEquals(ASSERT_MESSAGE_STATUS_CODE, HTTP_BAD_REQUEST, responseMap.get("http_status")); checkLogsForKeywords(); //Fetch the record from database and verify the answers. Optional<ProtectedCharacteristics> protectedCharacteristicsOptional = protectedCharacteristicsRepository.findById(answerRequest.getPcqId()); assertEquals(ASSERT_MESSAGE_CASE_ID, null, protectedCharacteristicsOptional.get().getCaseId()); } catch (Exception e) { log.error(EXCEPTION_MSG, e); } } @Test public void addCaseForPcqInjectionTest() { try { //Create the Test Data in the database. String jsonStringRequest = jsonStringFromFile(JSON_FILE); PcqAnswerRequest answerRequest = jsonObjectFromString(jsonStringRequest); pcqBackEndClient.createPcqAnswer(answerRequest); //Now call the actual method. Map<String, Object> responseMap = pcqBackEndClient.addCaseForPcq(answerRequest.getPcqId(), "CCD-CASE-121';--"); //Test the assertions assertResponse(responseMap, answerRequest.getPcqId(), HTTP_OK, RESPONSE_SUCCESS_MSG); checkLogsForKeywords(); //Fetch the record from database and verify the answers. Optional<ProtectedCharacteristics> protectedCharacteristicsOptional = protectedCharacteristicsRepository.findById(answerRequest.getPcqId()); assertEquals(ASSERT_MESSAGE_CASE_ID, "CCD-CASE-121&#39;;--", protectedCharacteristicsOptional.get().getCaseId()); } catch (Exception e) { log.error(EXCEPTION_MSG, e); } } private void checkLogsForKeywords() { assertTrue(capture.getAll().contains("Co-Relation Id : " + CO_RELATION_ID_FOR_TEST), "Co-Relation Id was not logged in log files."); } @SuppressWarnings("unchecked") private void assertResponse(Map<String, Object> responseMap, String pcqId, String httpStatus, String response) { assertNotNull(responseMap.get(RESPONSE_KEY_1), ASSERT_MESSAGE_PCQ); assertEquals(ASSERT_MESSAGE_STATUS_CODE, httpStatus, responseMap.get(RESPONSE_KEY_2)); assertEquals(ASSERT_MESSAGE_STATUS, response, responseMap.get(RESPONSE_KEY_3)); assertEquals(ASSERT_MESSAGE_PCQ, pcqId, responseMap.get(RESPONSE_KEY_1)); } }
41.668539
117
0.703384
12c8e3b8771e2ae8f2f475220336239762e52ab5
211
package com.darwinsys.soundrec; import org.junit.Test; public class DummyTestToPlacateMaven { @Test public void test() { System.out.println( "Dummy test to placate M2E 'Maven->Update Project'"); } }
15.071429
56
0.720379
f864bc63d7c6315860e1b3423cbcc15c048c5640
15,379
/* * 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.ignite.internal.processors.cache.mvcc; import java.io.Serializable; import java.util.UUID; import java.util.concurrent.Callable; import javax.cache.Cache; import javax.cache.CacheException; import javax.cache.configuration.Factory; import javax.cache.expiry.ExpiryPolicy; import org.apache.ignite.Ignite; import org.apache.ignite.IgniteCache; import org.apache.ignite.IgniteCheckedException; import org.apache.ignite.cache.CacheAtomicityMode; import org.apache.ignite.cache.CacheInterceptor; import org.apache.ignite.cache.CacheMode; import org.apache.ignite.cache.CacheRebalanceMode; import org.apache.ignite.configuration.CacheConfiguration; import org.apache.ignite.configuration.DataRegionConfiguration; import org.apache.ignite.configuration.DataStorageConfiguration; import org.apache.ignite.configuration.IgniteConfiguration; import org.apache.ignite.configuration.NearCacheConfiguration; import org.apache.ignite.internal.util.typedef.X; import org.apache.ignite.lang.IgniteBiTuple; import org.apache.ignite.testframework.GridTestUtils; import org.apache.ignite.testframework.junits.common.GridCommonAbstractTest; import org.jetbrains.annotations.Nullable; import org.junit.Test; import static org.apache.ignite.cache.CacheAtomicityMode.ATOMIC; import static org.apache.ignite.cache.CacheAtomicityMode.TRANSACTIONAL; import static org.apache.ignite.cache.CacheAtomicityMode.TRANSACTIONAL_SNAPSHOT; import static org.apache.ignite.cache.CacheMode.LOCAL; import static org.apache.ignite.configuration.DataPageEvictionMode.RANDOM_2_LRU; import static org.apache.ignite.configuration.DataPageEvictionMode.RANDOM_LRU; /** * */ @SuppressWarnings("unchecked") public class CacheMvccConfigurationValidationTest extends GridCommonAbstractTest { /** {@inheritDoc} */ @Override protected void afterTest() throws Exception { stopAllGrids(); super.afterTest(); } /** * @throws Exception If failed. */ @SuppressWarnings("ThrowableNotThrown") @Test public void testMvccModeMismatchForGroup1() throws Exception { final Ignite node = startGrid(0); node.createCache(new CacheConfiguration("cache1").setGroupName("grp1").setAtomicityMode(ATOMIC)); GridTestUtils.assertThrows(log, new Callable<Void>() { @Override public Void call() { node.createCache( new CacheConfiguration("cache2").setGroupName("grp1").setAtomicityMode(TRANSACTIONAL_SNAPSHOT)); return null; } }, CacheException.class, null); node.createCache(new CacheConfiguration("cache2").setGroupName("grp1").setAtomicityMode(ATOMIC)); } /** * @throws Exception If failed. */ @SuppressWarnings("ThrowableNotThrown") @Test public void testMvccModeMismatchForGroup2() throws Exception { final Ignite node = startGrid(0); node.createCache( new CacheConfiguration("cache1").setGroupName("grp1").setAtomicityMode(TRANSACTIONAL_SNAPSHOT)); GridTestUtils.assertThrows(log, new Callable<Void>() { @Override public Void call() { node.createCache(new CacheConfiguration("cache2").setGroupName("grp1").setAtomicityMode(ATOMIC)); return null; } }, CacheException.class, null); node.createCache( new CacheConfiguration("cache2").setGroupName("grp1").setAtomicityMode(TRANSACTIONAL_SNAPSHOT)); } /** * @throws Exception If failed. */ @SuppressWarnings("ThrowableNotThrown") @Test public void testMvccLocalCacheDisabled() throws Exception { final Ignite node1 = startGrid(1); final Ignite node2 = startGrid(2); IgniteCache cache1 = node1.createCache(new CacheConfiguration("cache1") .setAtomicityMode(TRANSACTIONAL_SNAPSHOT)); cache1.put(1, 1); cache1.put(2, 2); cache1.put(2, 2); GridTestUtils.assertThrows(log, new Callable<Void>() { @Override public Void call() { node1.createCache(new CacheConfiguration("cache2").setCacheMode(CacheMode.LOCAL) .setAtomicityMode(TRANSACTIONAL_SNAPSHOT)); return null; } }, CacheException.class, null); IgniteCache cache3 = node2.createCache(new CacheConfiguration("cache3") .setAtomicityMode(TRANSACTIONAL)); cache3.put(1, 1); cache3.put(2, 2); cache3.put(3, 3); } /** * @throws Exception If failed. */ @SuppressWarnings("ThrowableNotThrown") @Test public void testNodeRestartWithCacheModeChangedTxToMvcc() throws Exception { cleanPersistenceDir(); //Enable persistence. DataStorageConfiguration storageCfg = new DataStorageConfiguration(); DataRegionConfiguration regionCfg = new DataRegionConfiguration(); regionCfg.setPersistenceEnabled(true); storageCfg.setDefaultDataRegionConfiguration(regionCfg); IgniteConfiguration cfg = getConfiguration("testGrid"); cfg.setDataStorageConfiguration(storageCfg); cfg.setConsistentId(cfg.getIgniteInstanceName()); Ignite node = startGrid(cfg); node.cluster().active(true); CacheConfiguration ccfg1 = new CacheConfiguration("test1").setAtomicityMode(TRANSACTIONAL); IgniteCache cache = node.createCache(ccfg1); cache.put(1, 1); cache.put(1, 2); cache.put(2, 2); stopGrid(cfg.getIgniteInstanceName()); CacheConfiguration ccfg2 = new CacheConfiguration().setName(ccfg1.getName()) .setAtomicityMode(TRANSACTIONAL_SNAPSHOT); IgniteConfiguration cfg2 = getConfiguration("testGrid") .setConsistentId(cfg.getIgniteInstanceName()) .setCacheConfiguration(ccfg2) .setDataStorageConfiguration(storageCfg); GridTestUtils.assertThrows(log, new Callable<Void>() { @Override public Void call() throws Exception { startGrid(cfg2); return null; } }, IgniteCheckedException.class, "Cannot start cache. Statically configured atomicity mode differs from"); } /** * @throws Exception If failed. */ @SuppressWarnings("ThrowableNotThrown") @Test public void testNodeRestartWithCacheModeChangedMvccToTx() throws Exception { cleanPersistenceDir(); //Enable persistence. DataStorageConfiguration storageCfg = new DataStorageConfiguration(); DataRegionConfiguration regionCfg = new DataRegionConfiguration(); regionCfg.setPersistenceEnabled(true); regionCfg.setPageEvictionMode(RANDOM_LRU); storageCfg.setDefaultDataRegionConfiguration(regionCfg); IgniteConfiguration cfg = getConfiguration("testGrid"); cfg.setDataStorageConfiguration(storageCfg); cfg.setConsistentId(cfg.getIgniteInstanceName()); Ignite node = startGrid(cfg); node.cluster().active(true); CacheConfiguration ccfg1 = new CacheConfiguration("test1").setAtomicityMode(TRANSACTIONAL_SNAPSHOT); IgniteCache cache = node.createCache(ccfg1); cache.put(1, 1); cache.put(1, 2); cache.put(2, 2); stopGrid(cfg.getIgniteInstanceName()); CacheConfiguration ccfg2 = new CacheConfiguration().setName(ccfg1.getName()) .setAtomicityMode(TRANSACTIONAL); IgniteConfiguration cfg2 = getConfiguration("testGrid") .setConsistentId(cfg.getIgniteInstanceName()) .setCacheConfiguration(ccfg2) .setDataStorageConfiguration(storageCfg); GridTestUtils.assertThrows(log, new Callable<Void>() { @Override public Void call() throws Exception { startGrid(cfg2); return null; } }, IgniteCheckedException.class, "Cannot start cache. Statically configured atomicity mode"); } /** * @throws Exception If failed. */ @Test public void testMvccInMemoryEvictionDisabled() throws Exception { final String memRegName = "in-memory-evictions"; // Enable in-memory eviction. DataRegionConfiguration regionCfg = new DataRegionConfiguration(); regionCfg.setPersistenceEnabled(false); regionCfg.setPageEvictionMode(RANDOM_2_LRU); regionCfg.setName(memRegName); DataStorageConfiguration storageCfg = new DataStorageConfiguration(); storageCfg.setDefaultDataRegionConfiguration(regionCfg); IgniteConfiguration cfg = getConfiguration("testGrid"); cfg.setDataStorageConfiguration(storageCfg); Ignite node = startGrid(cfg); CacheConfiguration ccfg1 = new CacheConfiguration("test1") .setAtomicityMode(TRANSACTIONAL_SNAPSHOT) .setDataRegionName(memRegName); try { node.createCache(ccfg1); fail("In memory evictions should be disabled for MVCC caches."); } catch (Exception e) { assertTrue(X.getFullStackTrace(e).contains("Data pages evictions cannot be used with TRANSACTIONAL_SNAPSHOT")); } } /** * Test TRANSACTIONAL_SNAPSHOT and near cache. * * @throws Exception If failed. */ @SuppressWarnings("unchecked") @Test public void testTransactionalSnapshotLimitations() throws Exception { assertCannotStart( mvccCacheConfig().setCacheMode(LOCAL), "LOCAL cache mode cannot be used with TRANSACTIONAL_SNAPSHOT atomicity mode" ); assertCannotStart( mvccCacheConfig().setRebalanceMode(CacheRebalanceMode.NONE), "Rebalance mode NONE cannot be used with TRANSACTIONAL_SNAPSHOT atomicity mode" ); assertCannotStart( mvccCacheConfig().setNearConfiguration(new NearCacheConfiguration<>()), "near cache cannot be used with TRANSACTIONAL_SNAPSHOT atomicity mode" ); assertCannotStart( mvccCacheConfig().setReadThrough(true), "readThrough cannot be used with TRANSACTIONAL_SNAPSHOT atomicity mode" ); assertCannotStart( mvccCacheConfig().setWriteThrough(true), "writeThrough cannot be used with TRANSACTIONAL_SNAPSHOT atomicity mode" ); assertCannotStart( mvccCacheConfig().setWriteBehindEnabled(true), "writeBehindEnabled cannot be used with TRANSACTIONAL_SNAPSHOT atomicity mode" ); assertCannotStart( mvccCacheConfig().setExpiryPolicyFactory(new TestExpiryPolicyFactory()), "expiry policy cannot be used with TRANSACTIONAL_SNAPSHOT atomicity mode" ); assertCannotStart( mvccCacheConfig().setInterceptor(new TestCacheInterceptor()), "interceptor cannot be used with TRANSACTIONAL_SNAPSHOT atomicity mode" ); } /** * Checks if passed in {@code 'Throwable'} has given class in {@code 'cause'} hierarchy * <b>including</b> that throwable itself and it contains passed message. * <p> * Note that this method follows includes {@link Throwable#getSuppressed()} * into check. * * @param t Throwable to check (if {@code null}, {@code false} is returned). * @param cls Cause class to check (if {@code null}, {@code false} is returned). * @param msg Message to check. * @return {@code True} if one of the causing exception is an instance of passed in classes * and it contains the passed message, {@code false} otherwise. */ private boolean hasCauseWithMessage(@Nullable Throwable t, Class<?> cls, String msg) { if (t == null) return false; assert cls != null; for (Throwable th = t; th != null; th = th.getCause()) { if (cls.isAssignableFrom(th.getClass()) && th.getMessage() != null && th.getMessage().contains(msg)) return true; for (Throwable n : th.getSuppressed()) { if (hasCauseWithMessage(n, cls, msg)) return true; } if (th.getCause() == th) break; } return false; } /** * Make sure cache cannot be started with the given configuration. * * @param ccfg Cache configuration. * @param msg Message. * @throws Exception If failed. */ @SuppressWarnings("unchecked") private void assertCannotStart(CacheConfiguration ccfg, String msg) throws Exception { Ignite node = startGrid(0); try { try { node.getOrCreateCache(ccfg); fail("Cache should not start."); } catch (Exception e) { if (msg != null) { assert e.getMessage() != null : "Error message is null"; assertTrue(hasCauseWithMessage(e, IgniteCheckedException.class, msg)); } } } finally { stopAllGrids(); } } /** * @return MVCC-enabled cache configuration. */ private static CacheConfiguration mvccCacheConfig() { return new CacheConfiguration().setName(DEFAULT_CACHE_NAME + UUID.randomUUID()) .setAtomicityMode(CacheAtomicityMode.TRANSACTIONAL_SNAPSHOT); } /** * Test expiry policy. */ private static class TestExpiryPolicyFactory implements Factory<ExpiryPolicy>, Serializable { /** {@inheritDoc} */ @Override public ExpiryPolicy create() { return null; } } /** * Test cache interceptor. */ private static class TestCacheInterceptor implements CacheInterceptor, Serializable { /** {@inheritDoc} */ @Nullable @Override public Object onGet(Object key, @Nullable Object val) { return null; } /** {@inheritDoc} */ @Nullable @Override public Object onBeforePut(Cache.Entry entry, Object newVal) { return null; } /** {@inheritDoc} */ @Override public void onAfterPut(Cache.Entry entry) { // No-op. } /** {@inheritDoc} */ @Nullable @Override public IgniteBiTuple onBeforeRemove(Cache.Entry entry) { return null; } /** {@inheritDoc} */ @Override public void onAfterRemove(Cache.Entry entry) { // No-op. } } }
35.111872
123
0.659406
df28b9677e025a858e25db8d04e4bc11623a0d7c
6,952
package com.ramusthastudio.myalarmmanager; import android.app.DatePickerDialog; import android.app.TimePickerDialog; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.DatePicker; import android.widget.EditText; import android.widget.TextView; import android.widget.TimePicker; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.Locale; public class MainActivity extends AppCompatActivity implements View.OnClickListener { private static final SimpleDateFormat DATE_FORMAT_1 = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault()); private static final SimpleDateFormat DATE_FORMAT_2 = new SimpleDateFormat("HH:mm", Locale.getDefault()); private static final SimpleDateFormat DATE_FORMAT_3 = new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.getDefault()); private TextView fOneTimeDateTv; private TextView fOneTimeTimeTv; private TextView fRepeatingTimeTv; private EditText fOneTimeMessageEt; private EditText fRepeatingMessageEt; private Button fOneTimeDateBtn; private Button fOneTimeTimeBtn; private Button fOneTimeBtn; private Button fRepeatingTimeBtn; private Button fRepeatingBtn; private Button fCancelRepeatingAlarmBtn; private AlarmReceiver fAlarmReceiver; private SimpleDateFormat fDateFormat = DATE_FORMAT_1; private SimpleDateFormat fTimeFormat = DATE_FORMAT_2; private SimpleDateFormat fDateTimeFormat = DATE_FORMAT_3; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); AlarmPreference.create(this); fOneTimeDateTv = findViewById(R.id.tv_one_time_alarm_date); fOneTimeTimeTv = findViewById(R.id.tv_one_time_alarm_time); fOneTimeMessageEt = findViewById(R.id.edt_one_time_alarm_message); fOneTimeDateBtn = findViewById(R.id.btn_one_time_alarm_date); fOneTimeTimeBtn = findViewById(R.id.btn_one_time_alarm_time); fOneTimeBtn = findViewById(R.id.btn_set_one_time_alarm); fRepeatingTimeTv = findViewById(R.id.tv_repeating_alarm_time); fRepeatingMessageEt = findViewById(R.id.edt_repeating_alarm_message); fRepeatingTimeBtn = findViewById(R.id.btn_repeating_time_alarm_time); fRepeatingBtn = findViewById(R.id.btn_repeating_time_alarm); fCancelRepeatingAlarmBtn = findViewById(R.id.btn_cancel_repeating_alarm); fOneTimeDateBtn.setOnClickListener(this); fOneTimeTimeBtn.setOnClickListener(this); fOneTimeBtn.setOnClickListener(this); fRepeatingTimeBtn.setOnClickListener(this); fRepeatingBtn.setOnClickListener(this); fCancelRepeatingAlarmBtn.setOnClickListener(this); fAlarmReceiver = new AlarmReceiver(); if (AlarmPreference.getOneTimeDate() != 0) { setOneTimeText(); } if (AlarmPreference.getRepeatingTime() != 0) { setRepeatingTimeText(); } } @Override public void onClick(View v) { if (v.getId() == R.id.btn_one_time_alarm_date) { datePickerDialog().show(); } else if (v.getId() == R.id.btn_one_time_alarm_time) { timePickerDialog().show(); } else if (v.getId() == R.id.btn_repeating_time_alarm_time) { repeatingTimePickerDialog().show(); } else if (v.getId() == R.id.btn_set_one_time_alarm) { String oneTimeDate = fDateFormat.format(new Date(AlarmPreference.getOneTimeDate())); String oneTimeTime = fTimeFormat.format(new Date(AlarmPreference.getOneTimeTime())); String oneTimeMessage = fOneTimeMessageEt.getText().toString(); AlarmPreference.setOneTimeMessage(oneTimeMessage); try { Date dateTime = fDateTimeFormat.parse(oneTimeDate + " " + oneTimeTime); Log.d("Debug", "############# " + dateTime); fAlarmReceiver.setOneTimeAlarm(this, dateTime.getTime(), oneTimeMessage); } catch (ParseException aE) { aE.printStackTrace(); } } else if (v.getId() == R.id.btn_repeating_time_alarm) { String repeatTimeMessage = fRepeatingMessageEt.getText().toString(); AlarmPreference.setRepeatingMessage(repeatTimeMessage); fAlarmReceiver.setRepeatingAlarm(this, AlarmPreference.getRepeatingTime(), repeatTimeMessage); } else if (v.getId() == R.id.btn_cancel_repeating_alarm) { fAlarmReceiver.cancelAlarm(this); } } private DatePickerDialog datePickerDialog() { final Calendar currentDate = Calendar.getInstance(); return new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener() { @Override public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) { Calendar calendar = Calendar.getInstance(); calendar.set(year, monthOfYear, dayOfMonth); fOneTimeDateTv.setText(fDateFormat.format(calendar.getTime())); AlarmPreference.setOneTimeDate(calendar.getTimeInMillis()); } }, currentDate.get(Calendar.YEAR), currentDate.get(Calendar.MONTH), currentDate.get(Calendar.DATE)); } private TimePickerDialog timePickerDialog() { final Calendar currentDate = Calendar.getInstance(); return new TimePickerDialog(this, new TimePickerDialog.OnTimeSetListener() { @Override public void onTimeSet(TimePicker view, int hourOfDay, int minute) { Calendar calendar = Calendar.getInstance(); calendar.set(Calendar.HOUR_OF_DAY, hourOfDay); calendar.set(Calendar.MINUTE, minute); fOneTimeTimeTv.setText(fTimeFormat.format(calendar.getTime())); AlarmPreference.setOneTimeTime(calendar.getTimeInMillis()); } }, currentDate.get(Calendar.HOUR_OF_DAY), currentDate.get(Calendar.MINUTE), true); } private TimePickerDialog repeatingTimePickerDialog() { final Calendar currentDate = Calendar.getInstance(); return new TimePickerDialog(this, new TimePickerDialog.OnTimeSetListener() { @Override public void onTimeSet(TimePicker view, int hourOfDay, int minute) { Calendar calendar = Calendar.getInstance(); calendar.set(Calendar.HOUR_OF_DAY, hourOfDay); calendar.set(Calendar.MINUTE, minute); fRepeatingTimeTv.setText(fTimeFormat.format(calendar.getTime())); AlarmPreference.setRepeatingTime(calendar.getTimeInMillis()); } }, currentDate.get(Calendar.HOUR_OF_DAY), currentDate.get(Calendar.MINUTE), true); } private void setOneTimeText() { fOneTimeDateTv.setText(fDateFormat.format(new Date(AlarmPreference.getOneTimeDate()))); fOneTimeTimeTv.setText(fTimeFormat.format(new Date(AlarmPreference.getOneTimeTime()))); fOneTimeMessageEt.setText(AlarmPreference.getOneTimeMessage()); } private void setRepeatingTimeText() { fRepeatingTimeTv.setText(fTimeFormat.format(new Date(AlarmPreference.getRepeatingTime()))); fRepeatingMessageEt.setText(AlarmPreference.getRepeatingMessage()); } }
41.879518
118
0.753884
31dc0ca27c778c15c2816d7860f6ea745495b43a
613
package com.huifer.design.singleton; import java.io.Serializable; /** * <p>Title : SerializableSign </p> * <p>Description : 序列化与反序列化的单例模式</p> * * @author huifer * @date 2019-05-16 */ public class SerializableSign implements Serializable { public final static SerializableSign Instance = new SerializableSign(); private static final long serialVersionUID = 2263605502238537664L; private SerializableSign() { } public static SerializableSign getInstance() { return Instance; } private Object readResolve() { // 反序列化时替换实例 return Instance; } }
18.029412
75
0.681892
db620903852be1abc728aad8613772dfb4bdba83
1,731
/* * @copyright defined in LICENSE.txt */ package hera.api.transaction; import static org.slf4j.LoggerFactory.getLogger; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.module.SimpleModule; import hera.annotation.ApiAudience; import hera.annotation.ApiStability; import hera.api.model.BigNumber; import hera.api.model.BytesValue; import hera.api.model.NodeStatus; import hera.exception.HerajException; import java.util.List; import org.slf4j.Logger; @ApiAudience.Private @ApiStability.Unstable public class AergoJsonMapper implements JsonMapper { protected static final ObjectMapper objectMapper = new ObjectMapper(); static { final SimpleModule module = new SimpleModule(); module.addSerializer(BigNumber.class, new BigNumberSerializer()); module.addDeserializer(BigNumber.class, new BigNumberDeserializer()); module.addDeserializer(NodeStatus.class, new NodeStatusDeserializer()); module.addDeserializer(List.class, new ListDeserializer()); objectMapper.registerModule(module); } protected final Logger logger = getLogger(getClass()); @Override public BytesValue marshal(final Object value) { try { logger.debug("Marshal: {}", value); final byte[] rawBytes = objectMapper.writer().writeValueAsBytes(value); return BytesValue.of(rawBytes); } catch (Exception e) { throw new HerajException(e); } } @Override public <T> T unmarshal(final BytesValue bytesValue, final Class<T> clazz) { try { logger.debug("Unmarshal {} as '{}'", bytesValue, clazz); return objectMapper.readValue(bytesValue.getValue(), clazz); } catch (Exception e) { throw new HerajException(e); } } }
29.338983
77
0.740612
ff5d3442182036d9c1bad4f8de6b00bdd4688bb9
159
package com.ruoyi.javamail.entity; import lombok.Data; @Data public class OnlinePdfEntity { private String remark;//提示语 private String info;//内容 }
13.25
34
0.72956
5154fcdfa3a9c7cca650a1294d7571c958496999
242
package org.firstinspires.ftc.teamcode; /** * 用于机器人的传送带运输 * * @author wfrfred * @version 1.0 * @Time 2021-07-06 19:06 */ public interface TransportModule { void startTransporting(boolean isForward); void stopTransporting(); }
16.133333
46
0.702479
7b43205e5f38fd2dd0c3b984ce4066d6c35c5db2
2,468
package org.fugerit.java.core.util.result; import java.io.Serializable; import java.util.HashMap; import java.util.logging.Level; import org.fugerit.java.core.log.BasicLogObject; public class VirtualPageCache<T> extends BasicLogObject implements Serializable { /** * */ private static final long serialVersionUID = -6408904239036858385L; public VirtualPageCache() { this.cache = new HashMap<String, CacheWrapper<T>>(); } private HashMap<String, CacheWrapper<T>> cache; // 12 hours private final static long DEFAULT_TTL = 12*60*60*1000; // <code>true</code> it the wrapper is still valid private boolean checkTtl( CacheWrapper<T> wrapper ) { return wrapper.getCacheTime()>(System.currentTimeMillis()-DEFAULT_TTL); } private String buildPageKey( String virtualKey, int currentPage ) { return virtualKey+";"+currentPage; } /** * Returns a virtual page contained in the real page. * * @param virtualKey * @param currentPage * @return */ public PagedResult<T> getCachedPage( VirtualFinder finder ) { int currentPage = finder.getRealCurrentPage(); String virtualKey = finder.getSearchVirtualKey(); String key = this.buildPageKey(virtualKey, currentPage); CacheWrapper<T> wrapper = this.cache.get( key ); this.getLogger().debug( "WRAPPER : "+wrapper ); PagedResult<T> page = null; if ( wrapper != null ) { if ( this.checkTtl( wrapper ) ) { page = wrapper.getPage(); System.out.println( "PAGE > "+page ); } else { this.cache.remove( wrapper ); } } return page; } public void addPageToCache( PagedResult<T> bufferPage ) { int currentPage = bufferPage.getRealCurrentPage(); String virtualKey = bufferPage.getVirtualSearchKey(); String key = this.buildPageKey(virtualKey, currentPage); this.getLogger().debug( "ADD TO CACHE : "+key ); this.cache.put( key , new CacheWrapper<T>( bufferPage ) ); } } class CacheWrapper<T> { public CacheWrapper(PagedResult<T> page) { super(); this.page = page; this.cacheTime = System.currentTimeMillis(); } private PagedResult<T> page; private long cacheTime; public PagedResult<T> getPage() { return page; } public void setPage(PagedResult<T> page) { this.page = page; } public long getCacheTime() { return cacheTime; } public void setCacheTime(long cacheTime) { this.cacheTime = cacheTime; } }
24.68
82
0.675851
aa94640daad7954872c75c785f3e349b9d8b49d9
940
package io.github.maseev.alpaca.util; import io.github.maseev.alpaca.http.exception.APIException; import io.github.maseev.alpaca.http.transformer.Transformer; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletionException; import java.util.function.Function; import org.asynchttpclient.ListenableFuture; import org.asynchttpclient.Response; public final class FutureTransformerUtil { private FutureTransformerUtil() { } public static <T> CompletableFuture<T> transform(ListenableFuture<Response> future, Transformer<T> transformer) { return future.toCompletableFuture().thenApply(new Function<Response, T>() { @Override public T apply(Response response) { try { return transformer.transform(response); } catch (APIException e) { throw new CompletionException(e); } } }); } }
31.333333
85
0.698936
4f7bd18aad6bf1736a361c9dc08a0545dfdc2e44
4,306
package frc.robot.controllers; import frc.robot.RobotContainer; import frc.robot.subsystems.Drive; public class InterpolatedPS4Gamepad extends PS4Gamepad { static double deadZoneThreshold; static double fullThrottleThreshold; static RampComponent rComponent; public InterpolatedPS4Gamepad(int port) { super(port); deadZoneThreshold = 0.05; fullThrottleThreshold = 0.9; rComponent = new RampComponent(1, 0.5); } public static boolean inDeadZone(double axis) { return (axis > -deadZoneThreshold) && (axis < deadZoneThreshold); } public static boolean isCeiling(double axis) { return axis <= -fullThrottleThreshold || axis >= fullThrottleThreshold; } public double interpolatedLeftYAxis() { if (RobotContainer.inDeadZone(RobotContainer.getDriver().getLeftYAxis())) return rComponent.applyAsDouble(0.0); if (RobotContainer.isCeiling(RobotContainer.getDriver().getLeftYAxis())) return rComponent.applyAsDouble(1.0); if (Drive.getInstance().isHighGear()) { if (RobotContainer.getDriver().getLeftYAxis() < 0) { return rComponent.applyAsDouble(Math.tanh(RobotContainer.getDriver().getLeftYAxis() * 2)); } return rComponent.applyAsDouble(-(Math.tanh(RobotContainer.getDriver().getLeftYAxis() * 2))); } else { if (RobotContainer.getDriver().getLeftYAxis() < 0) { return rComponent.applyAsDouble(RobotContainer.getDriver().getLeftYAxis() * RobotContainer.getDriver().getLeftYAxis() * RobotContainer.getDriver().getLeftYAxis() * RobotContainer.getDriver().getLeftYAxis()); } return rComponent.applyAsDouble(-(RobotContainer.getDriver().getLeftYAxis() * RobotContainer.getDriver().getLeftYAxis() * RobotContainer.getDriver().getLeftYAxis() * RobotContainer.getDriver().getLeftYAxis())); } } public double interpolatedLeftXAxis() { if (RobotContainer.inDeadZone(RobotContainer.getDriver().getLeftXAxis())) return rComponent.applyAsDouble(0.0); if (RobotContainer.isCeiling(RobotContainer.getDriver().getLeftXAxis())) return rComponent.applyAsDouble(1.0); if (Drive.getInstance().isHighGear()) { if (RobotContainer.getDriver().getLeftXAxis() > 0) { return rComponent.applyAsDouble(Math.tanh(RobotContainer.getDriver().getLeftXAxis() * 2)); } return rComponent.applyAsDouble(-(Math.tanh(RobotContainer.getDriver().getLeftXAxis() * 2))); } else { if (RobotContainer.getDriver().getLeftXAxis() > 0) { return rComponent.applyAsDouble(RobotContainer.getDriver().getLeftXAxis() * RobotContainer.getDriver().getLeftXAxis() * RobotContainer.getDriver().getLeftXAxis() * RobotContainer.getDriver().getLeftXAxis()); } return rComponent.applyAsDouble(-(RobotContainer.getDriver().getLeftXAxis() * RobotContainer.getDriver().getLeftXAxis() * RobotContainer.getDriver().getLeftXAxis() * RobotContainer.getDriver().getLeftXAxis())); } } public double interpolatedRightXAxis() { if (RobotContainer.inDeadZone(RobotContainer.getDriver().getRightXAxis())) return rComponent.applyAsDouble(0.0); if (RobotContainer.isCeiling(RobotContainer.getDriver().getRightXAxis())) return rComponent.applyAsDouble(1.0); if (Drive.getInstance().isHighGear()) { if (RobotContainer.getDriver().getRightXAxis() > 0) { return rComponent.applyAsDouble(Math.tanh(RobotContainer.getDriver().getRightXAxis() * 2)); } return rComponent.applyAsDouble(-(Math.tanh(RobotContainer.getDriver().getRightXAxis() * 2))); } else { if (RobotContainer.getDriver().getRightXAxis() > 0) { return rComponent.applyAsDouble(RobotContainer.getDriver().getRightXAxis() * RobotContainer.getDriver().getRightXAxis() * RobotContainer.getDriver().getRightXAxis() * RobotContainer.getDriver().getRightXAxis()); } return rComponent.applyAsDouble(-(RobotContainer.getDriver().getRightXAxis() * RobotContainer.getDriver().getRightXAxis() * RobotContainer.getDriver().getRightXAxis() * RobotContainer.getDriver().getRightXAxis())); } } }
55.922078
227
0.687413
ac10d288123721a7e353d1bf51b6b25297064241
1,044
package WayofTime.bloodmagic.client; import net.minecraft.client.renderer.ItemMeshDefinition; import net.minecraft.util.ResourceLocation; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; import javax.annotation.Nullable; import java.util.List; /** * Provides a custom {@link ItemMeshDefinition} for automatic registration of * renders. */ public interface IMeshProvider { /** * Gets the custom ItemMeshDefinition to use for the item. * * @return - the custom ItemMeshDefinition to use for the item. */ @SideOnly(Side.CLIENT) ItemMeshDefinition getMeshDefinition(); /** * Gets all possible variants for this item * * @return - All possible variants for this item */ List<String> getVariants(); /** * If a custom ResourceLocation is required, return it here. * * Can be null if unneeded. * * @return - The custom ResourceLocation */ @Nullable ResourceLocation getCustomLocation(); }
24.857143
77
0.694444
3f040ebcc77b947017d4ae3071ca13786fbb6b0a
2,085
package sword.collections; abstract class AbstractImmutableIntTransformable extends AbstractIntTraversable implements ImmutableIntTransformable { abstract ImmutableIntTransformableBuilder newIntBuilder(); abstract <U> ImmutableTransformableBuilder<U> newBuilder(); @Override public ImmutableIntTransformable filter(IntPredicate predicate) { boolean somethingRemoved = false; ImmutableIntTransformableBuilder builder = newIntBuilder(); for (int item : this) { if (predicate.apply(item)) { builder.add(item); } else { somethingRemoved = true; } } return somethingRemoved? builder.build() : this; } @Override public ImmutableIntTransformable filterNot(IntPredicate predicate) { boolean somethingRemoved = false; ImmutableIntTransformableBuilder builder = newIntBuilder(); for (int item : this) { if (predicate.apply(item)) { somethingRemoved = true; } else { builder.add(item); } } return somethingRemoved? builder.build() : this; } @Override public ImmutableIntTransformable mapToInt(IntToIntFunction func) { final ImmutableIntTransformableBuilder builder = newIntBuilder(); for (int item : this) { builder.add(func.apply(item)); } return builder.build(); } @Override public <U> ImmutableTransformable<U> map(IntFunction<? extends U> func) { final ImmutableTransformableBuilder<U> builder = newBuilder(); for (int item : this) { builder.add(func.apply(item)); } return builder.build(); } @Override public ImmutableIntPairMap count() { MutableIntPairMap result = MutableIntPairMap.empty(); for (int value : this) { final int amount = result.get(value, 0); result.put(value, amount + 1); } return result.toImmutable(); } }
28.561644
118
0.609592
5e2688ea3fce504a66dd5e0479fed90b9cff2af6
1,219
package org.animeaholic.millipede.test; import java.util.ArrayList; import java.util.List; import org.animeaholic.millipede.entity.CrawlResTask; import org.animeaholic.millipede.entity.CrawlTask; import org.animeaholic.millipede.entity.base.AbsBaseTask; import org.animeaholic.millipede.processor.AbsCrawlResProcessor; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; public class VOA_HomeProcessor extends AbsCrawlResProcessor { private static String voa_base_url = "http://www.51voa.com/"; @Override public List<AbsBaseTask<?>> process(CrawlResTask crawlResTask) throws Exception { List<AbsBaseTask<?>> nextTaskList = new ArrayList<AbsBaseTask<?>>(); String html = crawlResTask.getContent(); Document doc = Jsoup.parse(html); Elements eles = doc.select("#list > ul > li > a"); for (Element ele : eles) { String href = ele.attr("href"); if (!href.contains("VOA")) continue; String detailUrl = voa_base_url + href; CrawlTask task = new CrawlTask(crawlResTask.getPlanName()); task.setCallBack(VOA_DetailProcessor.class); task.setUrl(detailUrl); nextTaskList.add(task); } return nextTaskList; } }
31.25641
82
0.757998
6efd8a43b38a51729dd232d70a67de3a9c77156f
884
package org.thingsboard.server.dao.rule; import org.thingsboard.server.common.data.id.EntityId; import org.thingsboard.server.common.data.id.RuleNodeId; import org.thingsboard.server.common.data.id.TenantId; import org.thingsboard.server.common.data.page.PageData; import org.thingsboard.server.common.data.page.PageLink; import org.thingsboard.server.common.data.rule.RuleNodeState; public interface RuleNodeStateService { PageData<RuleNodeState> findByRuleNodeId(TenantId tenantId, RuleNodeId ruleNodeId, PageLink pageLink); RuleNodeState findByRuleNodeIdAndEntityId(TenantId tenantId, RuleNodeId ruleNodeId, EntityId entityId); RuleNodeState save(TenantId tenantId, RuleNodeState ruleNodeState); void removeByRuleNodeId(TenantId tenantId, RuleNodeId selfId); void removeByRuleNodeIdAndEntityId(TenantId tenantId, RuleNodeId selfId, EntityId entityId); }
40.181818
107
0.829186
113e6b90921beb3ce2266b8363194fca8fa8b942
729
package com.fionapet.business.service; import com.fionapet.business.entity.WarehouseOutrecordDetail; import org.dubbo.x.repository.DaoBase; import org.dubbo.x.service.CURDServiceBase; import com.fionapet.business.repository.WarehouseOutrecordDetailDao; import org.springframework.beans.factory.annotation.Autowired; /** * 出库记录明细 * Created by tom on 2016-07-18 11:56:11. */ public class WarehouseOutrecordDetailServiceImpl extends CURDServiceBase<WarehouseOutrecordDetail> implements WarehouseOutrecordDetailService { @Autowired private WarehouseOutrecordDetailDao warehouseOutrecordDetailDao; @Override public DaoBase<WarehouseOutrecordDetail> getDao() { return warehouseOutrecordDetailDao; } }
33.136364
143
0.816187
28e91162faa1346f47a18b1b8d7fe59545a0ed56
429
package tbdb4java.integration.factories; import tbdb4java.integration.DAOGenres; import tbdb4java.integration.factories.imp.DAOGenresFactoryImp; public abstract class DAOGenresFactory { private static DAOGenresFactory instance; public static DAOGenresFactory getInstance(){ if(instance == null) instance = new DAOGenresFactoryImp(); return instance; } public abstract DAOGenres getDaoGenres(DAOType daoType); }
23.833333
63
0.806527
867e6eae6c95057470fa18c03fce12c3ae41abbd
2,433
package de.hsmainz.cs.semgis.arqextension.geometry.relation; import org.apache.jena.sparql.expr.NodeValue; import org.apache.jena.sparql.function.FunctionBase3; import org.apache.sis.coverage.grid.GridCoverage; import org.locationtech.jts.geom.Geometry; import org.locationtech.jts.operation.distance3d.Distance3DOp; import org.opengis.geometry.Envelope; import de.hsmainz.cs.semgis.arqextension.util.LiteralUtils; import de.hsmainz.cs.semgis.arqextension.util.Wrapper; import io.github.galbiston.geosparql_jena.implementation.GeometryWrapper; import io.github.galbiston.geosparql_jena.implementation.datatype.raster.CoverageWrapper; public class DWithin3D extends FunctionBase3 { @Override public NodeValue exec(NodeValue v1, NodeValue v2, NodeValue v3) { Wrapper wrapper1=LiteralUtils.rasterOrVector(v1); Wrapper wrapper2=LiteralUtils.rasterOrVector(v2); Double withinDistance = v3.getDouble(); if(wrapper1 instanceof GeometryWrapper && wrapper2 instanceof GeometryWrapper) { return NodeValue.makeBoolean(Distance3DOp.isWithinDistance(((GeometryWrapper)wrapper1).getXYGeometry(), ((GeometryWrapper)wrapper2).getXYGeometry(), withinDistance)); }else if(wrapper1 instanceof CoverageWrapper && wrapper2 instanceof CoverageWrapper) { GridCoverage raster=((CoverageWrapper)wrapper1).getXYGeometry(); GridCoverage raster2=((CoverageWrapper)wrapper2).getXYGeometry(); Envelope bbox1 = raster.getGridGeometry().getEnvelope(); Envelope bbox2 = raster2.getGridGeometry().getEnvelope(); return NodeValue.makeBoolean(Distance3DOp.isWithinDistance(LiteralUtils.toGeometry(bbox1), LiteralUtils.toGeometry(bbox2), withinDistance)); }else { if(wrapper1 instanceof CoverageWrapper) { GridCoverage raster=((CoverageWrapper)wrapper1).getXYGeometry(); Envelope bbox1 = raster.getGridGeometry().getEnvelope(); Geometry geom=((GeometryWrapper)wrapper2).getXYGeometry(); return NodeValue.makeBoolean(Distance3DOp.isWithinDistance(LiteralUtils.toGeometry(bbox1), geom, withinDistance)); }else { GridCoverage raster=((CoverageWrapper)wrapper2).getXYGeometry(); Envelope bbox1 = raster.getGridGeometry().getEnvelope(); Geometry geom=((GeometryWrapper)wrapper1).getXYGeometry(); return NodeValue.makeBoolean(Distance3DOp.isWithinDistance(LiteralUtils.toGeometry(bbox1), geom, withinDistance)); } } } }
52.891304
170
0.780107
639ff25286054a2eddb81f5ec68cb6fdb7446d9d
235
package com.its.scc.Activities.Internal.CreateAbsensi.presenter; public interface IInternalCreateAbsensiPresenter { void onSubmit(String id_internal, String judul_absensi, String tgl_absensi, String jam_mulai, String jam_selesai); }
39.166667
115
0.846809
71614f6e3fb5401c34ad05418e4d3051591a66b0
4,183
package org.anddev.andengine.opengl.texture; import android.graphics.Bitmap; import java.util.ArrayList; import org.anddev.andengine.opengl.texture.builder.ITextureBuilder; import org.anddev.andengine.opengl.texture.builder.ITextureBuilder.TextureSourcePackingException; import org.anddev.andengine.opengl.texture.source.ITextureSource; import org.anddev.andengine.util.Callback; public class BuildableTexture extends Texture { private final ArrayList<TextureSourceWithWithLocationCallback> mTextureSourcesToPlace = new ArrayList(); public BuildableTexture(int paramInt1, int paramInt2) { super(paramInt1, paramInt2, TextureOptions.DEFAULT, null); } public BuildableTexture(int paramInt1, int paramInt2, Texture.ITextureStateListener paramITextureStateListener) { super(paramInt1, paramInt2, TextureOptions.DEFAULT, paramITextureStateListener); } public BuildableTexture(int paramInt1, int paramInt2, TextureOptions paramTextureOptions) throws IllegalArgumentException { super(paramInt1, paramInt2, paramTextureOptions, null); } public BuildableTexture(int paramInt1, int paramInt2, TextureOptions paramTextureOptions, Texture.ITextureStateListener paramITextureStateListener) throws IllegalArgumentException { super(paramInt1, paramInt2, paramTextureOptions, paramITextureStateListener); } @Deprecated public Texture.TextureSourceWithLocation addTextureSource(ITextureSource paramITextureSource, int paramInt1, int paramInt2) { return super.addTextureSource(paramITextureSource, paramInt1, paramInt2); } public void addTextureSource(ITextureSource paramITextureSource, Callback<Texture.TextureSourceWithLocation> paramCallback) { this.mTextureSourcesToPlace.add(new TextureSourceWithWithLocationCallback(paramITextureSource, paramCallback)); } public void build(ITextureBuilder paramITextureBuilder) throws ITextureBuilder.TextureSourcePackingException { paramITextureBuilder.pack(this, this.mTextureSourcesToPlace); this.mTextureSourcesToPlace.clear(); this.mUpdateOnHardwareNeeded = true; } public void clearTextureSources() { super.clearTextureSources(); this.mTextureSourcesToPlace.clear(); } public void removeTextureSource(ITextureSource paramITextureSource) { ArrayList localArrayList = this.mTextureSourcesToPlace; for (int i = -1 + localArrayList.size();; i--) { if (i < 0) { return; } if (((TextureSourceWithWithLocationCallback)localArrayList.get(i)).mTextureSource == paramITextureSource) { localArrayList.remove(i); this.mUpdateOnHardwareNeeded = true; return; } } } public static class TextureSourceWithWithLocationCallback implements ITextureSource { private final Callback<Texture.TextureSourceWithLocation> mCallback; private final ITextureSource mTextureSource; public TextureSourceWithWithLocationCallback(ITextureSource paramITextureSource, Callback<Texture.TextureSourceWithLocation> paramCallback) { this.mTextureSource = paramITextureSource; this.mCallback = paramCallback; } public TextureSourceWithWithLocationCallback clone() { return null; } public Callback<Texture.TextureSourceWithLocation> getCallback() { return this.mCallback; } public int getHeight() { return this.mTextureSource.getHeight(); } public ITextureSource getTextureSource() { return this.mTextureSource; } public int getWidth() { return this.mTextureSource.getWidth(); } public Bitmap onLoadBitmap() { return this.mTextureSource.onLoadBitmap(); } public String toString() { return this.mTextureSource.toString(); } } } /* Location: C:\Users\Rodelle\Desktop\Attacknid\Tools\Attacknids-dex2jar.jar * Qualified Name: org.anddev.andengine.opengl.texture.BuildableTexture * JD-Core Version: 0.7.0.1 */
31.689394
150
0.722209
d6caf6b5b7740af68bc1e13d18103821e42df785
717
package com.asaon.html; import com.asaon.html.dsl.Document; import java.util.List; import java.util.function.Function; import java.util.function.UnaryOperator; public interface HtmlInterpreter<T> { void onTagStart(String name, List<Attribute> attrs, boolean empty); void onContent(String content); void onTagEnd(String name); T onSuccess(); default <U> HtmlInterpreter<U> map(Function<T, U> fn) { return new HtmlInterpreterWrapper<>(this) { @Override public U onSuccess() { return fn.apply(wrapped.onSuccess()); } }; } default T interpret(UnaryOperator<Document<T>> expr) { return expr.apply(document()).end(); } default Document<T> document() { return new Document<>(this); } }
21.727273
68
0.718271
2532fb8ad4469890bfdb8ddac49d48891dd6632b
397
package redstone.multimeter.block; import net.minecraft.block.BlockState; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; import redstone.multimeter.interfaces.mixin.IBlock; public interface Meterable extends IBlock { @Override default boolean isMeterableRSMM() { return true; } public boolean isActiveRSMM(World world, BlockPos pos, BlockState state); }
20.894737
74
0.793451
b4aebf0f519762111fd8b2465716c916f6399974
20,436
/* Licensed to Diennea S.r.l. under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. Diennea S.r.l. 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.carapaceproxy.server; import com.google.common.annotations.VisibleForTesting; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import io.netty.bootstrap.ServerBootstrap; import io.netty.channel.Channel; import io.netty.channel.ChannelInitializer; import io.netty.channel.ChannelOption; import io.netty.channel.EventLoopGroup; import io.netty.channel.epoll.Epoll; import io.netty.channel.epoll.EpollEventLoopGroup; import io.netty.channel.epoll.EpollServerSocketChannel; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.SocketChannel; import io.netty.channel.socket.nio.NioServerSocketChannel; import io.netty.handler.codec.http.HttpRequestDecoder; import io.netty.handler.codec.http.HttpResponseEncoder; import io.netty.handler.ssl.OpenSsl; import io.netty.handler.ssl.SniHandler; import io.netty.handler.ssl.SslContext; import io.netty.handler.ssl.SslContextBuilder; import io.netty.handler.ssl.SslProvider; import io.netty.util.AsyncMapping; import io.netty.util.concurrent.Promise; import io.prometheus.client.Gauge; import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.net.InetSocketAddress; import java.security.GeneralSecurityException; import java.security.KeyStore; import java.security.KeyStoreException; import java.security.NoSuchAlgorithmException; import java.security.UnrecoverableKeyException; import java.security.cert.CertificateException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.logging.Level; import java.util.logging.Logger; import javax.net.ssl.KeyManagerFactory; import javax.net.ssl.TrustManagerFactory; import org.carapaceproxy.server.config.ConfigurationNotValidException; import org.carapaceproxy.server.config.NetworkListenerConfiguration; import org.carapaceproxy.server.config.NetworkListenerConfiguration.HostPort; import org.carapaceproxy.server.config.SSLCertificateConfiguration; import org.carapaceproxy.utils.PrometheusUtils; /** * * @author enrico.olivelli */ @SuppressFBWarnings(value = "OBL_UNSATISFIED_OBLIGATION", justification = "https://github.com/spotbugs/spotbugs/issues/432") public class Listeners { private static final Logger LOG = Logger.getLogger(Listeners.class.getName()); private static final Gauge CURRENT_CONNECTED_CLIENTS_GAUGE = PrometheusUtils.createGauge("clients", "current_connected", "currently connected clients").register(); private final EventLoopGroup bossGroup; private final EventLoopGroup workerGroup; private final HttpProxyServer parent; private final Map<String, SslContext> sslContexts = new ConcurrentHashMap<>(); private final Map<HostPort, Channel> listeningChannels = new ConcurrentHashMap<>(); private final Map<HostPort, ClientConnectionHandler> listenersHandlers = new ConcurrentHashMap<>(); private final File basePath; private boolean started; private RuntimeServerConfiguration currentConfiguration; public Listeners(HttpProxyServer parent) { this.parent = parent; this.currentConfiguration = parent.getCurrentConfiguration(); this.basePath = parent.getBasePath(); if (Epoll.isAvailable()) { this.bossGroup = new EpollEventLoopGroup(); this.workerGroup = new EpollEventLoopGroup(); } else { // For windows devs this.bossGroup = new NioEventLoopGroup(); this.workerGroup = new NioEventLoopGroup(); } } public void start() throws InterruptedException, ConfigurationNotValidException { started = true; reloadConfiguration(currentConfiguration); } private SslContext bootSslContext(NetworkListenerConfiguration listener, SSLCertificateConfiguration certificate) throws ConfigurationNotValidException { int port = listener.getPort() + parent.getListenersOffsetPort(); String sslCiphers = listener.getSslCiphers(); String trustStrorePassword = listener.getSslTrustorePassword(); String trustStoreFile = listener.getSslTrustoreFile(); File trustStoreCertFile = null; boolean caFileConfigured = trustStoreFile != null && !trustStoreFile.isEmpty(); if (caFileConfigured) { trustStoreCertFile = trustStoreFile.startsWith("/") ? new File(trustStoreFile) : new File(basePath, trustStoreFile); trustStoreCertFile = trustStoreCertFile.getAbsoluteFile(); } try { KeyManagerFactory keyFactory; String domain = certificate.getHostname(); // Try to find certificate data on db byte[] keystoreContent = parent.getDynamicCertificateManager().getCertificateForDomain(domain); if (keystoreContent != null) { LOG.log(Level.SEVERE, "start SSL with dynamic certificate id " + certificate.getId() + ", on listener " + listener.getHost() + ":" + port + " OCPS " + listener.isOcps()); keyFactory = initKeyManagerFactory("PKCS12", keystoreContent, certificate.getPassword()); } else { if (certificate.isDynamic()) { // fallback to default certificate certificate = currentConfiguration.getCertificates().get(listener.getDefaultCertificate()); if (certificate == null) { throw new ConfigurationNotValidException("Unable to boot SSL context for listener " + listener.getHost() + ": no default certificate setup."); } } String certificateFile = certificate.getFile(); File sslCertFile = certificateFile.startsWith("/") ? new File(certificateFile) : new File(basePath, certificateFile); sslCertFile = sslCertFile.getAbsoluteFile(); LOG.log(Level.SEVERE, "start SSL with certificate id " + certificate.getId() + ", on listener " + listener.getHost() + ":" + port + " file=" + sslCertFile + " OCPS " + listener.isOcps()); keyFactory = initKeyManagerFactory("PKCS12", sslCertFile, certificate.getPassword()); } TrustManagerFactory trustManagerFactory = null; if (caFileConfigured) { LOG.log(Level.SEVERE, "loading trustore from " + trustStoreCertFile); trustManagerFactory = initTrustManagerFactory("PKCS12", trustStoreCertFile, trustStrorePassword); } List<String> ciphers = null; if (sslCiphers != null && !sslCiphers.isEmpty()) { LOG.log(Level.SEVERE, "required sslCiphers " + sslCiphers); ciphers = Arrays.asList(sslCiphers.split(",")); } return SslContextBuilder .forServer(keyFactory) .enableOcsp(listener.isOcps() && OpenSsl.isOcspSupported()) .trustManager(trustManagerFactory) .sslProvider(SslProvider.OPENSSL) .ciphers(ciphers).build(); } catch (IOException | GeneralSecurityException err) { throw new ConfigurationNotValidException(err); } } private void bootListener(NetworkListenerConfiguration listener) throws InterruptedException { int port = listener.getPort() + parent.getListenersOffsetPort(); LOG.log(Level.INFO, "Starting listener at {0}:{1} ssl:{2}", new Object[]{listener.getHost(), port, listener.isSsl()}); AsyncMapping<String, SslContext> sniMappings = (String sniHostname, Promise<SslContext> promise) -> { try { SslContext sslContext = resolveSslContext(listener, sniHostname); return promise.setSuccess(sslContext); } catch (ConfigurationNotValidException err) { LOG.log(Level.SEVERE, "Error booting certificate for SNI hostname {0}, on listener {1}", new Object[]{sniHostname, listener}); return promise.setFailure(err); } }; HostPort key = new HostPort(listener.getHost(), port); ServerBootstrap b = new ServerBootstrap(); b.group(bossGroup, workerGroup) .channel(Epoll.isAvailable() ? EpollServerSocketChannel.class : NioServerSocketChannel.class) .childHandler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel channel) throws Exception { CURRENT_CONNECTED_CLIENTS_GAUGE.inc(); if (listener.isSsl()) { SniHandler sni = new SniHandler(sniMappings); channel.pipeline().addLast(sni); } channel.pipeline().addLast(new HttpRequestDecoder()); channel.pipeline().addLast(new HttpResponseEncoder()); ClientConnectionHandler connHandler = new ClientConnectionHandler(parent.getMapper(), parent.getConnectionsManager(), parent.getFilters(), parent.getCache(), channel.remoteAddress(), parent.getStaticContentsManager(), () -> CURRENT_CONNECTED_CLIENTS_GAUGE.dec(), parent.getBackendHealthManager(), parent.getRequestsLogger(), listener.getHost(), port, listener.isSsl() ); channel.pipeline().addLast(connHandler); listenersHandlers.put(key, connHandler); } }) .option(ChannelOption.SO_BACKLOG, 128) .childOption(ChannelOption.SO_KEEPALIVE, true); Channel channel = b.bind(listener.getHost(), port).sync().channel(); listeningChannels.put(key, channel); LOG.log(Level.INFO, "started listener at {0}: {1}", new Object[]{key, channel}); } private KeyManagerFactory initKeyManagerFactory(String keyStoreType, File keyStoreLocation, String keyStorePassword) throws SecurityException, KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException, UnrecoverableKeyException { KeyStore ks = loadKeyStore(keyStoreType, keyStoreLocation, keyStorePassword); KeyManagerFactory kmf = KeyManagerFactory .getInstance(KeyManagerFactory.getDefaultAlgorithm()); kmf.init(ks, keyStorePassword.toCharArray()); return kmf; } private KeyManagerFactory initKeyManagerFactory(String keyStoreType, byte[] keyStoreData, String keyStorePassword) throws SecurityException, KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException, UnrecoverableKeyException { KeyStore ks = loadKeyStore(keyStoreType, keyStoreData, keyStorePassword); KeyManagerFactory kmf = KeyManagerFactory .getInstance(KeyManagerFactory.getDefaultAlgorithm()); kmf.init(ks, keyStorePassword.toCharArray()); return kmf; } private TrustManagerFactory initTrustManagerFactory(String trustStoreType, File trustStoreLocation, String trustStorePassword) throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException, SecurityException { TrustManagerFactory tmf; // Initialize trust store KeyStore ts = loadKeyStore(trustStoreType, trustStoreLocation, trustStorePassword); tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); tmf.init(ts); return tmf; } private static KeyStore loadKeyStore(String keyStoreType, File keyStoreLocation, String keyStorePassword) throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException { KeyStore ks = KeyStore.getInstance(keyStoreType); try (FileInputStream in = new FileInputStream(keyStoreLocation)) { ks.load(in, keyStorePassword.trim().toCharArray()); } return ks; } private static KeyStore loadKeyStore(String keyStoreType, byte[] keyStoreData, String keyStorePassword) throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException { KeyStore ks = KeyStore.getInstance(keyStoreType); try (ByteArrayInputStream is = new ByteArrayInputStream(keyStoreData)) { ks.load(is, keyStorePassword.trim().toCharArray()); } return ks; } public int getLocalPort() { for (Channel c : listeningChannels.values()) { InetSocketAddress addr = (InetSocketAddress) c.localAddress(); return addr.getPort(); } return -1; } public ClientConnectionHandler getListenerHandler(HostPort key) { return listenersHandlers.get(key); } public void stop() { for (HostPort key : listeningChannels.keySet()) { try { stopListener(key); } catch (InterruptedException ex) { LOG.log(Level.SEVERE, "Interrupted while stopping a listener", ex); Thread.currentThread().interrupt(); } } if (bossGroup != null) { bossGroup.shutdownGracefully(); } if (workerGroup != null) { workerGroup.shutdownGracefully(); } } private SslContext resolveSslContext(NetworkListenerConfiguration listener, String sniHostname) throws ConfigurationNotValidException { int port = listener.getPort() + parent.getListenersOffsetPort(); String key = listener.getHost() + ":" + port + "+" + sniHostname; if (LOG.isLoggable(Level.FINER)) { LOG.log(Level.FINER, "resolve SNI mapping " + sniHostname + ", key: " + key); } try { return sslContexts.computeIfAbsent(key, (k) -> { try { SSLCertificateConfiguration choosen = chooseCertificate(sniHostname, listener.getDefaultCertificate()); if (choosen == null) { throw new ConfigurationNotValidException("cannot find a certificate for snihostname " + sniHostname + ", with default cert for listener as '" + listener .getDefaultCertificate() + "', available " + currentConfiguration.getCertificates() .keySet()); } return bootSslContext(listener, choosen); } catch (ConfigurationNotValidException err) { throw new RuntimeException(err); } }); } catch (RuntimeException err) { if (err.getCause() instanceof ConfigurationNotValidException) { throw (ConfigurationNotValidException) err.getCause(); } else { throw new ConfigurationNotValidException(err); } } } @VisibleForTesting public SSLCertificateConfiguration chooseCertificate(String sniHostname, String defaultCertificate) { if (sniHostname == null) { sniHostname = ""; } SSLCertificateConfiguration certificateMatchExact = null; SSLCertificateConfiguration certificateMatchNoExact = null; Map<String, SSLCertificateConfiguration> certificates = currentConfiguration.getCertificates(); for (SSLCertificateConfiguration c : certificates.values()) { if (certificateMatches(sniHostname, c, true)) { certificateMatchExact = c; } else if (certificateMatches(sniHostname, c, false)) { certificateMatchNoExact = c; } } SSLCertificateConfiguration choosen = null; if (certificateMatchExact != null) { choosen = certificateMatchExact; } else if (certificateMatchNoExact != null) { choosen = certificateMatchNoExact; } if (choosen == null) { choosen = certificates.get(defaultCertificate); } return choosen; } private boolean certificateMatches(String hostname, SSLCertificateConfiguration c, boolean exact) { if (exact) { return !c.isWildcard() && hostname.equals(c.getHostname()); } else { return c.isWildcard() && hostname.endsWith(c.getHostname()); } } void reloadConfiguration(RuntimeServerConfiguration newConfiguration) throws InterruptedException { if (!started) { this.currentConfiguration = newConfiguration; return; } // Clear cached ssl contexts sslContexts.clear(); // stop dropped listeners, start new one List<HostPort> listenersToStop = new ArrayList<>(); List<HostPort> listenersToStart = new ArrayList<>(); List<HostPort> listenersToRestart = new ArrayList<>(); for (HostPort key : listeningChannels.keySet()) { NetworkListenerConfiguration actualListenerConfig = currentConfiguration.getListener(key); NetworkListenerConfiguration newConfigurationForListener = newConfiguration.getListener(key); if (newConfigurationForListener == null) { LOG.log(Level.INFO, "listener: {0} is to be shut down", key); listenersToStop.add(key); } else if (!newConfigurationForListener.equals(actualListenerConfig)) { LOG.log(Level.INFO, "listener: {0} is to be restarted", key); listenersToRestart.add(key); } } for (NetworkListenerConfiguration config : newConfiguration.getListeners()) { HostPort key = config.getKey(); if (!listeningChannels.containsKey(key)) { LOG.log(Level.INFO, "listener: {0} is to be started", key); listenersToStart.add(key); } } try { for (HostPort hostport : listenersToStop) { LOG.log(Level.INFO, "Stopping {0}", hostport); stopListener(hostport); } for (HostPort hostport : listenersToRestart) { LOG.log(Level.INFO, "Restart {0}", hostport); stopListener(hostport); NetworkListenerConfiguration newConfigurationForListener = newConfiguration.getListener(hostport); bootListener(newConfigurationForListener); } for (HostPort hostport : listenersToStart) { LOG.log(Level.INFO, "Starting {0}", hostport); NetworkListenerConfiguration newConfigurationForListener = newConfiguration.getListener(hostport); bootListener(newConfigurationForListener); } // apply new configuration, this will affect SSL certificates this.currentConfiguration = newConfiguration; } catch (InterruptedException stopMe) { Thread.currentThread().interrupt(); throw stopMe; } } private void stopListener(HostPort hostport) throws InterruptedException { Channel channel = listeningChannels.remove(hostport); if (channel != null) { channel.close().sync(); } listenersHandlers.remove(hostport); } }
45.923596
203
0.649589
d6693cb5552eff052cdee65abcc9e0f310a54a94
620
package frc.robot.commands.autos; import edu.wpi.first.wpilibj2.command.InstantCommand; import edu.wpi.first.wpilibj2.command.SequentialCommandGroup; import frc.robot.subsystems.*; import frc.robot.RobotConstants.AutoConstants; import frc.robot.utils.pathplanner.AutoFromPathPlanner; public class BasicAuto extends SequentialCommandGroup { public BasicAuto(Drivetrain drive) { final AutoFromPathPlanner testCircle = new AutoFromPathPlanner(drive, "TestCircle", AutoConstants.maxSpeed); addCommands(new InstantCommand(() -> drive.resetOdometry(testCircle.getInitialPose())), testCircle); } }
34.444444
116
0.795161
bf1951ff944999b506d78e1921029b3bf9213ecd
2,767
/* * 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 org.cirdles.squidParametersManager.parameterModels.referenceMaterials; import com.thoughtworks.xstream.XStream; import java.io.File; import java.math.BigDecimal; import java.util.ArrayList; import java.util.Arrays; import org.cirdles.squidParametersManager.ValueModel; import org.cirdles.squidParametersManager.parameterModels.ParametersManager; import org.cirdles.squidParametersManager.util.ReferenceMaterialEnum; import org.cirdles.squidParametersManager.util.XStreamETReduxConverters.ETReduxRefMatConverter; /** * * @author ryanb */ public class ReferenceMaterial extends ParametersManager { ValueModel[] concentrations; boolean[] dataMeasured; public ReferenceMaterial() { super(); concentrations = new ValueModel[0]; dataMeasured = new boolean[0]; } @Override public final void initializeNewRatiosAndRhos() { ArrayList<ValueModel> holdRatios = new ArrayList<>(); for (ReferenceMaterialEnum value : ReferenceMaterialEnum.values()) { holdRatios.add( // new ValueModel(value.getName(), "ABS", BigDecimal.ZERO, BigDecimal.ZERO)); } values = holdRatios.toArray(new ValueModel[holdRatios.size()]); Arrays.sort(values, new DataValueModelNameComparator()); buildRhosMap(); } public ValueModel[] getConcentrations() { return concentrations; } public void setConcentrations(ValueModel[] concentrations) { this.concentrations = concentrations; } public boolean[] getDataMeasured() { return dataMeasured; } public void setDataMeasured(boolean[] dataMeasured) { this.dataMeasured = dataMeasured; } public static XStream getETReduxXStream() { XStream xstream = new XStream(); xstream.registerConverter(new ETReduxRefMatConverter()); xstream.alias("ReferenceMaterial", ReferenceMaterial.class); xstream.alias("MineralStandardUPbModel", ReferenceMaterial.class); return xstream; } public static ReferenceMaterial getReferenceMaterialFromETReduxXML(String input) { XStream xstream = getETReduxXStream(); ReferenceMaterial model = (ReferenceMaterial) xstream.fromXML(input); return model; } public static ReferenceMaterial getReferenceMaterialFromETReduxXML(File input) { XStream xstream = getETReduxXStream(); ReferenceMaterial model = (ReferenceMaterial) xstream.fromXML(input); return model; } }
31.804598
95
0.699313
92a2087bd7c232503551c3bd30c03b19b5fb3fc4
2,818
package com.stitch.converter; import java.io.File; import com.stitch.converter.model.StitchImage; import com.stitch.converter.view.OverviewController; import javafx.application.Application; import javafx.application.Platform; import javafx.fxml.FXMLLoader; import javafx.scene.Scene; import javafx.scene.image.Image; import javafx.scene.input.KeyEvent; import javafx.scene.layout.BorderPane; import javafx.stage.Stage; public class Main extends Application { public static void main(final String[] args) { System.setProperty("prism.lcdtext", "false"); launch(args); } private OverviewController controller; private final Listener listener = new Listener() { @Override public void onFinished(final StitchImage image) { Platform.runLater(new Runnable() { @Override public void run() { controller.setImage(image); } }); } }; private Stage primaryStage; public void initRootLayout() { try { final FXMLLoader loader = new FXMLLoader(); loader.setLocation(new File("resources/Overview.fxml").toURI().toURL()); loader.setResources(Resources.getBundle()); final BorderPane rootLayout = (BorderPane) loader.load(); final int fontSize = Preferences.getInteger("fontSize", 11); final String fontType = Preferences.getString("fontType", "Dotum"); final String style = new StringBuilder("-fx-font: ").append(fontSize).append("px ").append(fontType).append(";").toString(); rootLayout.setStyle(style); final Scene scene = new Scene(rootLayout); controller = loader.getController(); controller.setStage(primaryStage); controller.setApp(this); scene.addEventHandler(KeyEvent.KEY_PRESSED, Shortcut.get(controller)); primaryStage.setScene(scene); try { final Image icon = new Image("file:resources/icon/icons8-needle-50.png"); primaryStage.getIcons().add(icon); } catch (final Exception iconException) { LogPrinter.print(iconException); LogPrinter.error(Resources.getString("error_icon_load")); } primaryStage.show(); } catch (final Exception e) { LogPrinter.print(e); LogPrinter.error(Resources.getString("error_has_occurred")); } } public void load(final GraphicsEngine.Builder builder) { Platform.runLater(new Thread(builder.setMode(GraphicsEngine.Mode.LOAD).setListener(listener).build())); } @Override public void start(final Stage primaryStage) { this.primaryStage = primaryStage; this.primaryStage.setTitle(Resources.getString("title")); this.primaryStage.setMaximized(true); initRootLayout(); } public void startConversion(final GraphicsEngine.Builder builder) { Platform.runLater(new Thread(builder.setMode(GraphicsEngine.Mode.NEW_FILE).setListener(listener).build())); } }
30.967033
128
0.719659
7c31ff477f393533e35ea31b00d3613539ad8d24
3,697
package com.codemotionapps.reactnativehelpscout; import android.app.Application; import com.facebook.react.bridge.Callback; import com.facebook.react.bridge.ReactApplicationContext; import com.facebook.react.bridge.ReactContextBaseJavaModule; import com.facebook.react.bridge.ReactMethod; import com.facebook.react.bridge.ReadableMap; import com.facebook.react.modules.core.DeviceEventManagerModule; import com.helpscout.beacon.Beacon; import com.helpscout.beacon.model.BeaconScreens; import com.helpscout.beacon.ui.BeaconActivity; import com.helpscout.beacon.ui.BeaconEventLifecycleHandler; import com.helpscout.beacon.ui.BeaconOnClosedListener; import com.helpscout.beacon.ui.BeaconOnOpenedListener; import java.util.ArrayList; import java.util.Iterator; import java.util.Map; public class HelpScoutModule extends ReactContextBaseJavaModule { private final ReactApplicationContext reactContext; public HelpScoutModule(final ReactApplicationContext reactContext) { super(reactContext); this.reactContext = reactContext; BeaconEventLifecycleHandler eventLifecycleHandler = new BeaconEventLifecycleHandler( new BeaconOnOpenedListener() { @Override public void onOpened() { reactContext .getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class) .emit("open", null); } }, new BeaconOnClosedListener() { @Override public void onClosed() { reactContext .getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class) .emit("close", null); } } ); Application application = (Application) reactContext.getApplicationContext(); application.registerActivityLifecycleCallbacks(eventLifecycleHandler); } @Override public String getName() { return "RNHelpScoutBeacon"; } @ReactMethod public void init(String beaconId) { new Beacon.Builder() .withBeaconId(beaconId) .build(); } @ReactMethod public void open() { BeaconActivity.open(reactContext); } @ReactMethod public void identify(ReadableMap identity) { String email = identity.hasKey("email") ? identity.getString("email") : ""; if (identity.hasKey("name")) { Beacon.login(email, identity.getString("name")); } else { Beacon.login(email); } Iterator<Map.Entry<String, Object>> i = identity.getEntryIterator(); while (i.hasNext()) { Map.Entry<String, Object> entry = i.next(); String key = entry.getKey(); if (key == "email" || key == "name") continue; Beacon.addAttributeWithKey(key, (String) entry.getValue()); } } @ReactMethod public void logout() { Beacon.logout(); } @ReactMethod public void navigate(String route) { if (route.equals("/ask/chat")) { BeaconActivity.open(this.reactContext, BeaconScreens.CHAT, new ArrayList<String>()); } } @ReactMethod public void search(String query) { ArrayList<String> list = new ArrayList<String>(); list.add(query); BeaconActivity.open(this.reactContext, BeaconScreens.SEARCH_SCREEN, list); } @ReactMethod public void openArticle(String query) { ArrayList<String> list = new ArrayList<String>(); list.add(query); BeaconActivity.open(this.reactContext, BeaconScreens.ARTICLE_SCREEN, list); } @ReactMethod public void previousMessages() { BeaconActivity.open(this.reactContext, BeaconScreens.PREVIOUS_MESSAGES, new ArrayList<String>()); } @ReactMethod public void contactForm() { BeaconActivity.open(this.reactContext, BeaconScreens.CONTACT_FORM_SCREEN, new ArrayList<String>()); } // @ReactMethod // public void chat() { // BeaconActivity.open(this.reactContext, BeaconScreens.CHAT, new ArrayList<String>()); // } @ReactMethod public void dismiss(Callback callback) { } }
27.589552
101
0.747633
b629ba9617100999aed8add0fd0985cdba4b6d0a
1,017
import cells.*; import notes.Note; import java.math.BigInteger; import java.util.ArrayList; import java.util.List; public class ATM { private BigInteger balance = BigInteger.valueOf(0); private static final List<Cell> cells; static { cells = new ArrayList<>(); cells.add(new CellOne()); cells.add(new CellTwo()); cells.add(new CellFive()); cells.add(new CellTen()); } public void putMoney(Note note) { for (Cell cell : cells) { balance = cell.retain(balance, note); } } public void takeMoney(int sum){ if (getBalance().compareTo(BigInteger.valueOf(sum)) < 0) { System.out.println("Sorry. Not enough money..."); } else { for (int i = cells.size() - 1; i > 0; i--) { cells.get(i).setNext(cells.get(i - 1)); } balance = cells.get(3).produce(balance,sum); } } public BigInteger getBalance() { return balance; } }
26.076923
66
0.558505
b0043490ca1ca74fb9dd58f6aab4040b61b4b608
2,509
package uk.gov.ons.ctp.response.casesvc.client; import com.fasterxml.jackson.databind.ObjectMapper; import com.godaddy.logging.Logger; import com.godaddy.logging.LoggerFactory; import java.io.IOException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.http.HttpEntity; import org.springframework.http.HttpMethod; import org.springframework.http.ResponseEntity; import org.springframework.retry.annotation.Backoff; import org.springframework.retry.annotation.Retryable; import org.springframework.stereotype.Component; import org.springframework.web.client.RestClientException; import org.springframework.web.client.RestTemplate; import org.springframework.web.util.UriComponents; import uk.gov.ons.ctp.response.casesvc.config.AppConfig; import uk.gov.ons.ctp.response.lib.common.rest.RestUtility; import uk.gov.ons.ctp.response.lib.survey.representation.SurveyDTO; /** Impl of the service that centralizes all REST calls to the Survey service */ @Component public class SurveySvcClientService { private static final Logger log = LoggerFactory.getLogger(SurveySvcClientService.class); @Autowired private AppConfig appConfig; @Autowired private RestTemplate restTemplate; @Autowired @Qualifier("surveySvcClient") private RestUtility restUtility; @Autowired private ObjectMapper objectMapper; @Retryable( value = {RestClientException.class}, maxAttemptsExpression = "#{${retries.maxAttempts}}", backoff = @Backoff(delayExpression = "#{${retries.backoff}}")) public SurveyDTO requestDetailsForSurvey(final String surveyId) throws RestClientException { final UriComponents uriComponents = restUtility.createUriComponents( appConfig.getSurveySvc().getRequestSurveyPath(), null, surveyId); final HttpEntity<?> httpEntity = restUtility.createHttpEntity(null); final ResponseEntity<String> responseEntity = restTemplate.exchange(uriComponents.toUri(), HttpMethod.GET, httpEntity, String.class); SurveyDTO result = null; if (responseEntity != null && responseEntity.getStatusCode().is2xxSuccessful()) { final String responseBody = responseEntity.getBody(); try { result = objectMapper.readValue(responseBody, SurveyDTO.class); } catch (final IOException e) { log.error("Unable to read survey response", e); throw new RuntimeException(e); } } return result; } }
39.203125
95
0.774811
ee56deb606fe9ca35225fb29e3480cc8ad35fe4e
1,255
import java.time.LocalDate; import java.util.Objects; public class BankStatement { private LocalDate date; private double amount; private String description; public BankStatement(LocalDate date, double amount, String description) { this.date = date; this.amount = amount; this.description = description; } public LocalDate getDate() { return date; } public double getAmount() { return amount; } public String getDescription() { return description; } @Override public String toString() { return "BankStatement{" + "date=" + date + ", amount=" + amount + ", description='" + description + '\'' + '}'; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; BankStatement that = (BankStatement) o; return amount == that.amount && Objects.equals(date, that.date) && Objects.equals(description, that.description); } @Override public int hashCode() { return Objects.hash(date, amount, description); } }
24.134615
77
0.56494
61fae0b616dbc25919e71669de97cb8216656c04
1,704
/* * Copyright 2008-2021 the original author or authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.kaleidofoundry.core.lang.annotation; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * The task annotation is like a "to do"<br/> * The advantage : it can be processing by an annotation processor to build listing / report * * @author jraduget */ @Documented @Target({ ElementType.TYPE, ElementType.METHOD, ElementType.CONSTRUCTOR, ElementType.ANNOTATION_TYPE, ElementType.PACKAGE, ElementType.PARAMETER, ElementType.FIELD, ElementType.LOCAL_VARIABLE }) @Retention(RetentionPolicy.SOURCE) public @interface Task { /** @return a bug tracker code */ String code() default ""; /** @return a description of the task */ String comment() default ""; /** @return labels of the task */ TaskLabel[] labels() default TaskLabel.ImplementIt; /** @return the author of the task */ String author() default ""; /** @return the assignee for the task */ String assignee() default ""; }
32.769231
145
0.734155
cf467f6b6be76c53dde93a312d61e12abd530653
4,222
package bootstrap.casterio.com.myapplication.service; import android.app.IntentService; import android.content.Context; import android.content.Intent; import android.util.Log; /** * An {@link IntentService} subclass for handling asynchronous task requests in * a service on a separate handler thread. * <p> * TODO: Customize class - update intent actions, extra parameters and static * helper methods. */ public class MyIntentService extends IntentService { // TODO: Rename actions, choose action names that describe tasks that this // IntentService can perform, e.g. ACTION_FETCH_NEW_ITEMS private static final String ACTION_FOO = "bootstrap.casterio.com.myapplication.service.action.FOO"; private static final String ACTION_BAZ = "bootstrap.casterio.com.myapplication.service.action.BAZ"; // TODO: Rename parameters private static final String EXTRA_PARAM1 = "bootstrap.casterio.com.myapplication.service.extra.PARAM1"; private static final String EXTRA_PARAM2 = "bootstrap.casterio.com.myapplication.service.extra.PARAM2"; public MyIntentService() { super("MyIntentService"); } /** * Starts this service to perform action Foo with the given parameters. If * the service is already performing a task this action will be queued. * * @see IntentService */ // TODO: Customize helper method public static void startActionFoo(Context context, String param1, String param2) { Intent intent = new Intent(context, MyIntentService.class); intent.setAction(ACTION_FOO); intent.putExtra(EXTRA_PARAM1, param1); intent.putExtra(EXTRA_PARAM2, param2); context.startService(intent); } /** * Starts this service to perform action Baz with the given parameters. If * the service is already performing a task this action will be queued. * * @see IntentService */ // TODO: Customize helper method public static void startActionBaz(Context context, String param1, String param2) { Intent intent = new Intent(context, MyIntentService.class); intent.setAction(ACTION_BAZ); intent.putExtra(EXTRA_PARAM1, param1); intent.putExtra(EXTRA_PARAM2, param2); context.startService(intent); } @Override protected void onHandleIntent(Intent intent) { if (intent != null) { final String action = intent.getAction(); if (ACTION_FOO.equals(action)) { final String param1 = intent.getStringExtra(EXTRA_PARAM1); final String param2 = intent.getStringExtra(EXTRA_PARAM2); handleActionFoo(param1, param2); } else if (ACTION_BAZ.equals(action)) { final String param1 = intent.getStringExtra(EXTRA_PARAM1); final String param2 = intent.getStringExtra(EXTRA_PARAM2); handleActionBaz(param1, param2); } } } /** * Handle action Foo in the provided background thread with the provided * parameters. */ private void handleActionFoo(String param1, String param2) { // Normally we would do some work here, like download a file. // For our sample, we just sleep for 5 seconds. for (int x = 0; x < 5; x++) { try { Log.d("Caster.IO", "--- sleep Foo"); Thread.sleep(1000); } catch (InterruptedException e) { // Restore interrupt status. Thread.currentThread().interrupt(); } } Log.d("Caster.IO", "FOO Complete: " + param1 + " | " + param2); } /** * Handle action Baz in the provided background thread with the provided * parameters. */ private void handleActionBaz(String param1, String param2) { for (int x = 0; x < 5; x++) { try { Log.d("Caster.IO", "--- sleep Baz"); Thread.sleep(1000); } catch (InterruptedException e) { // Restore interrupt status. Thread.currentThread().interrupt(); } } Log.d("Caster.IO", "BAZ Complete: " + param1 + " | " + param2); } }
38.036036
107
0.633823
39f308df89ebc792681e1e197d8c091f62f8fe9e
244
package academy.springboot.domain; import lombok.*; @Getter @Setter @EqualsAndHashCode @AllArgsConstructor @NoArgsConstructor public class TemplateClass { private String name; private String middleName; private String lastName; }
16.266667
34
0.782787
c85145eb4dc5086085ec7069796d253390ec2497
7,553
/* * Copyright (c) 2017, ZoltanTheHun * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * 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 skyhussars.persistence.base; import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.util.function.BiFunction; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.junit.rules.TemporaryFolder; import skyhussars.persistence.terrain.TerrainDescriptor; public class RegistryLoaderTest { @Rule public ExpectedException expected = ExpectedException.none(); @Rule public TemporaryFolder folder = new TemporaryFolder(); private BiFunction<TerrainDescriptor,File,String> nameOf = (t,f) -> t.name; @Test public void testNameNullCheck(){ expected.expect(NullPointerException.class); RegistryLoader<TerrainDescriptor> rl = new RegistryLoader<>(null,new File(""), "test.json",TerrainDescriptor.class,nameOf); } @Test public void testFileNullCheck(){ expected.expect(NullPointerException.class); RegistryLoader<TerrainDescriptor> rl = new RegistryLoader<>("Test",null, "test.json",TerrainDescriptor.class,nameOf); } @Test public void testDescriptorClassNullCheck(){ expected.expect(NullPointerException.class); RegistryLoader rl = new RegistryLoader("Test",new File(""),"test.json", null,nameOf); } @Test public void testDirectoryCheck(){ expected.expect(IllegalArgumentException.class); RegistryLoader<TerrainDescriptor> rl = new RegistryLoader("Test",new File(""), "test.json",TerrainDescriptor.class,nameOf); } @Test public void testJsonNameCheck(){ expected.expect(NullPointerException.class); RegistryLoader<TerrainDescriptor> rl = new RegistryLoader("Test",new File(""), null,TerrainDescriptor.class,nameOf); } @Test public void testJsonNameLengthCheck(){ expected.expect(IllegalArgumentException.class); RegistryLoader<TerrainDescriptor> rl = new RegistryLoader("Test",new File(""), "",TerrainDescriptor.class,nameOf); } @Test public void testNamingFunctionNullCheck(){ expected.expect(NullPointerException.class); RegistryLoader<TerrainDescriptor> rl = new RegistryLoader("Test",new File(""), "",TerrainDescriptor.class,null); } @Test public void testFailOnDirectoryWithoutDescriptor(){ expected.expect(IllegalStateException.class); try { File root = folder.newFolder("root"); File child1 = new File(root, "child1"); child1.mkdir(); RegistryLoader<TerrainDescriptor> rl = new RegistryLoader<>("Terrain Registry",root, "test.json",TerrainDescriptor.class,nameOf); } catch (IOException ex) { throw new RuntimeException(ex); } } @Test public void testFailOnEmptyRootDirectory(){ expected.expect(IllegalStateException.class); try { File root = folder.newFolder("root"); RegistryLoader<TerrainDescriptor> rl = new RegistryLoader<>("Terrain Registry",root, "test.json",TerrainDescriptor.class,nameOf); } catch (IOException ex) { throw new RuntimeException(ex); } } @Test public void testTerrainRegistryIsAvailable(){ try { File root = folder.newFolder("root"); File child1 = new File(root, "child1"); child1.mkdir(); File child2 = new File(root, "child2"); child2.mkdir(); File target1 = new File(child1,"test.json"); File target2 = new File(child2,"test.json"); target1.createNewFile(); target2.createNewFile(); try (PrintWriter test1 = new PrintWriter(target1)) { test1.print("{ \"name\" : \"Test Terrain 1\", \"size\" : 10, \"heightMapLocation\" : \"Test\"}"); test1.flush(); } try (PrintWriter test2 = new PrintWriter(target2)) { test2.print("{ \"name\" : \"Test Terrain 2\", \"size\" : 10, \"heightMapLocation\" : \"Test\"}"); test2.flush(); } RegistryLoader<TerrainDescriptor> rl = new RegistryLoader<>("Terrain Registry",root, "test.json",TerrainDescriptor.class,nameOf); Registry<TerrainDescriptor> tr = rl.registry(); /* Test that that item can be retrieved */ assert(tr.item("Test Terrain 1").isPresent()); /* Test that empty folders are skipped */ assert(tr.availableItems().size() == 2); } catch (IOException ex) { throw new RuntimeException(ex); } } @Test public void testThatEmptyRootReturnsEmptyRegistry(){ try { File root = folder.newFolder("root"); File child1 = new File(root, "child1"); child1.mkdir(); File child2 = new File(root, "child2"); child2.mkdir(); File target1 = new File(child1,"test.json"); File target2 = new File(child2,"test.json"); target1.createNewFile(); target2.createNewFile(); try (PrintWriter test1 = new PrintWriter(target1)) { test1.print("{ \"name\" : \"Test Terrain 1\", \"size\" : 10, \"heightMapLocation\" : \"Test\"}"); test1.flush(); } try (PrintWriter test2 = new PrintWriter(target2)) { test2.print("{ \"name\" : \"Test Terrain 2\", \"size\" : 10, \"heightMapLocation\" : \"Test\"}"); test2.flush(); } RegistryLoader<TerrainDescriptor> rl = new RegistryLoader<>("Terrain Registry",root, "test.json",TerrainDescriptor.class,nameOf); Registry<TerrainDescriptor> tr = rl.registry(); assert(tr.item("Test Terrain 1").isPresent()); } catch (IOException ex) { throw new RuntimeException(ex); } } }
40.390374
116
0.62121
191a798c759a6af39f018dd7c6e97dfd6637bd5a
2,238
package com.cf.carpark.api.swagger; import com.cf.carpark.domain.CfCarPark; import com.cf.carpark.request.CfCarParkForm; import com.cf.framework.domain.response.ResponseResult; import io.swagger.annotations.Api; import io.swagger.annotations.ApiImplicitParam; import io.swagger.annotations.ApiImplicitParams; import io.swagger.annotations.ApiOperation; import javax.validation.constraints.Max; import javax.validation.constraints.Min; import javax.validation.constraints.Pattern; import java.util.List; import java.util.Map; @Api(tags = {"停车库管理"}) public interface CfCarParkSwagger { @ApiOperation(value = "添加车库") @ApiImplicitParams({ @ApiImplicitParam(name="authorization",value = "jwt串(请加\"Bearer \"前缀,注意有空格)",required=true,paramType="header",dataType="string") }) public ResponseResult add(CfCarParkForm cfCarParkForm); @ApiOperation(value = "根据条件查询停车场数据列表") @ApiImplicitParams({ @ApiImplicitParam(name="authorization",value = "jwt串(请加\"Bearer \"前缀,注意有空格)",required=true,paramType="header",dataType="string"), @ApiImplicitParam(name="conditions", value = "条件,例子{\"id\":{\"operator\":\"=\",\"value\":200},\"province_id\":{\"operator\":\"between\",\"min\":200,\"max\":300},\"order\":" + "{\"operator\":\"order\",\"list\":{\"id\":{\"type\":\"DESC\",\"alias\":\"cp\"},\"country_id\":{\"type\":\"ASC\",\"alias\":\"cp\"}}}," + "\"limit\":{\"operator\":\"limit\",\"page\":1,\"limit\":10},\"like\":{\"operator\":\"like\",\"list\":{\"name\":{\"0\":{\"value\":\"绿地国博\"," + "\"alias\":\"cp\"},\"1\":{\"value\":\"财富中心\",\"alias\":\"cp\"}},\"country_id\":{\"0\":{\"value\":\"1111\",\"alias\":\"cp\"},\"1\":{\"value\":\"2222\"," + "\"alias\":\"cp\"}}}}}解析出的sql为:SELECT cp.* FROM cf_car_park cp WHERE cp.id=200 AND cp.province_id>=200 AND cp.province_id<=300 AND (cp.name LIKE '%绿地国博%'" + " OR cp.name LIKE '%财富中心%') AND (cp.country_id LIKE '%1111%' OR cp.country_id LIKE '%2222%') ORDER BY cp.id DESC,cp.country_id ASC LIMIT 0,10", required=true,paramType="query",dataType="string") }) public ResponseResult selectListByCondition(String conditions); }
57.384615
176
0.626899
c1105d1e1ca176766aaf7bde562503ba772f49dc
1,493
package com.ditamex.model; // Generated 30-nov-2015 23:14:44 by Hibernate Tools 4.3.1 import java.util.Date; import java.util.HashSet; import java.util.Set; /** * Category generated by hbm2java */ public class Category implements java.io.Serializable { private Byte categoryId; private String name; private Date lastUpdate; private Set<FilmCategory> filmCategories = new HashSet<FilmCategory>(0); public Category() { } public Category(String name, Date lastUpdate) { this.name = name; this.lastUpdate = lastUpdate; } public Category(String name, Date lastUpdate, Set<FilmCategory> filmCategories) { this.name = name; this.lastUpdate = lastUpdate; this.filmCategories = filmCategories; } public Byte getCategoryId() { return this.categoryId; } public void setCategoryId(Byte categoryId) { this.categoryId = categoryId; } public String getName() { return this.name; } public void setName(String name) { this.name = name; } public Date getLastUpdate() { return this.lastUpdate; } public void setLastUpdate(Date lastUpdate) { this.lastUpdate = lastUpdate; } public Set<FilmCategory> getFilmCategories() { return this.filmCategories; } public void setFilmCategories(Set<FilmCategory> filmCategories) { this.filmCategories = filmCategories; } }
21.637681
85
0.647019
825eda87c141aeb5de067bd5320c1ca4169702fc
2,499
/** * Copyright 2014 Tampere University of Technology, Pori Department * * 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 service.tut.pori.fileservice; import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import core.tut.pori.http.ResponseData; /** * A container for file objects, which can be directly used with XML Response. * * <h3>XML Example</h3> * * {@doc.restlet service="[service.tut.pori.fileservice.reference.Definitions#SERVICE_FS_REFERENCE_EXAMPLE]" method="[service.tut.pori.fileservice.Definitions#ELEMENT_FILELIST]" type="GET" query="" body_uri=""} * * @see service.tut.pori.fileservice.File */ @XmlRootElement(name=Definitions.ELEMENT_FILELIST) @XmlAccessorType(value=XmlAccessType.NONE) public class FileList extends ResponseData { @XmlElement(name = Definitions.ELEMENT_FILE) private List<File> _files = null; /** * @return the files */ public List<File> getFiles() { return _files; } /** * @param files the files to set */ public void setFiles(List<File> files) { _files = files; } /** * */ public FileList(){ // nothing needed } /** * * @param files * @return new file list or null if null or empty list was passed */ public static FileList getFileList(List<File> files){ if(files == null || files.isEmpty()){ return null; }else{ FileList fileList = new FileList(); fileList._files = files; return fileList; } } /** * for sub-classing, use the static * * @return true if this list is empty * @see #isEmpty(FileList) */ protected boolean isEmpty(){ return (_files == null || _files.isEmpty()); } /** * * @param fileList * @return true if the given list is null or empty */ public static boolean isEmpty(FileList fileList){ return (fileList == null ? true : fileList.isEmpty()); } }
25.762887
210
0.707483
6931e12142c6307da11a99d553c7e0c329c13880
1,400
/* * Decompiled with CFR 0.150. * * Could not load the following classes: * android.content.DialogInterface$OnClickListener * androidx.appcompat.app.AlertDialog$Builder * net.runelite.mapping.Implements */ package com.jagex.mobilesdk.payments; import android.content.DialogInterface; import androidx.appcompat.app.AlertDialog; import com.jagex.mobilesdk.R$string; import com.jagex.mobilesdk.payments.CategoryListFragment; import com.jagex.mobilesdk.payments.CategoryListFragment$3$1; import com.jagex.mobilesdk.payments.CategoryListFragment$3$2; import net.runelite.mapping.Implements; @Implements(value="CategoryListFragment$3") class CategoryListFragment$3 implements Runnable { final /* synthetic */ CategoryListFragment this$0; CategoryListFragment$3(CategoryListFragment categoryListFragment) { this.this$0 = categoryListFragment; } @Override public void run() { AlertDialog.Builder builder = new AlertDialog.Builder(this.this$0.getContext()); builder.setTitle(R$string.PENDING_TRANSACTIONS); builder.setMessage(R$string.PENDING_TRANSACTION_MESSAGE).setCancelable(false).setPositiveButton(R$string.field2235, (DialogInterface.OnClickListener)new CategoryListFragment$3$2(this)).setNegativeButton(R$string.field2233, (DialogInterface.OnClickListener)new CategoryListFragment$3$1(this)); builder.create().show(); } }
37.837838
300
0.781429
7791acf9eb768f240f8c3bd6cc4bce7633b908a2
3,866
package ibis.deploy.gui.editor; import ibis.deploy.gui.misc.Utils; import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.io.File; import javax.swing.JButton; import javax.swing.JFileChooser; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JTextField; public class FileEditor extends ChangeableField implements KeyListener { /** * */ private static final long serialVersionUID = 2216106418941074147L; private final JTextField textField = new JTextField(); private final JButton openButton = Utils.createImageButton( "images/document-open.png", "Select a file", null); private String initialFile; private final JLabel label = new JLabel("", JLabel.TRAILING); /** * @param form * - parent JPanel * @param text * - text to be displayed in the label * @param value * - initial text for the textField */ public FileEditor(final JPanel tabPanel, JPanel form, final String text, File value) { if (value != null) { textField.setText(value.getPath()); initialFile = value.getPath(); } else { initialFile = ""; } this.tabPanel = tabPanel; textField.addKeyListener(this); JPanel container = new JPanel(new BorderLayout()); JPanel labelPanel = new JPanel(new BorderLayout()); labelPanel.add(label, BorderLayout.EAST); container.add(labelPanel, BorderLayout.WEST); label.setText(text); label.setPreferredSize(new Dimension(Utils.defaultLabelWidth, label .getPreferredSize().height)); final JPanel filePanel = new JPanel(new BorderLayout()); filePanel.add(textField, BorderLayout.CENTER); final JFileChooser fileChooser = new JFileChooser(value); fileChooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES); openButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { int returnVal = fileChooser.showOpenDialog(filePanel); if (returnVal == JFileChooser.APPROVE_OPTION) { textField.setText(fileChooser.getSelectedFile().getPath()); informParent(); } } }); label.setLabelFor(filePanel); filePanel.add(openButton, BorderLayout.EAST); container.add(filePanel, BorderLayout.CENTER); form.add(container); } /** * @return - new File created using the path in the textField */ public File getFile() { if (textField.getText().trim().length() > 0) { return new File(textField.getText()); } else { return null; } } /** * Sets the text of the textField to the given value * * @param fileName * - new filename to be displayed in the textField */ public void setFile(String fileName) { textField.setText(fileName); } @Override public void refreshInitialValue() { initialFile = textField.getText(); if (initialFile == null) { initialFile = ""; } } @Override public void keyPressed(KeyEvent arg0) { } @Override public void keyReleased(KeyEvent arg0) { informParent(); } @Override public void keyTyped(KeyEvent arg0) { } /** * @return - true if the text field contains a different value than the * initial value */ @Override public boolean hasChanged() { return !textField.getText().equals(initialFile); } }
27.614286
79
0.61821
d233d80de6fe94d67d5edeb962a5dc9c1dbfa1eb
1,841
package nz.rafikn.movierates.services.impl; import nz.rafikn.movierates.model.Movie; import nz.rafikn.movierates.model.RawSearch; import nz.rafikn.movierates.model.SearchResponse; import nz.rafikn.movierates.model.SearchResult; import nz.rafikn.movierates.services.VimeoAPIService; import java.util.*; /** * Created by rafik on 26/06/16. */ public class MockVimeoAPIServiceImpl implements VimeoAPIService { private final Random rand = new Random(Calendar.getInstance().getTimeInMillis()); @Override public SearchResponse search(String query) { return null; } @Override public SearchResponse search(String query, int page) { return null; } @Override public RawSearch rawSearch(Movie movie) { return mockSearch(movie); } private RawSearch mockSearch(Movie movie) { RawSearch raw = new RawSearch(movie); for (int page = 1; page < 4; page++) { raw.getPages().add(mockSearchResponse(page)); } return raw; } private SearchResponse mockSearchResponse(int page) { SearchResponse response = new SearchResponse(); response.setTotal(150); response.setPage(page); response.setPerPage(50); response.setData(mockSearchData()); return response; } private Collection<SearchResult> mockSearchData() { List<SearchResult> results = new ArrayList<>(); Map<String, Object> stats = new HashMap<>(); for (int i =0; i<50; i++) { SearchResult result = new SearchResult(); result.setName("Test Movie" + i); result.setUri("/video/test/" + i); stats.put("plays", 100 + rand.nextInt(10000)); result.setStats(stats); results.add(result); } return results; } }
25.929577
85
0.637697
6d982019ad1d68bcd6d18e03ff41d2c9f8b62249
1,888
/* * Copyright 2014 Ahmed El-mawaziny. * * 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.qfast.vaadin.addon.ui; import com.vaadin.event.ShortcutAction; import com.vaadin.server.Resource; import com.vaadin.ui.Button.ClickListener; import com.vaadin.ui.themes.ValoTheme; /** * A primary button, commonly used for e.g. saving an entity. Automatically sets * "primary" class name and hooks click shortcut for ENTER. */ public class DeleteButton extends Button { public DeleteButton() { setupPrimaryButton(); } public DeleteButton(String caption) { super(caption); setupPrimaryButton(); } public DeleteButton(String caption, ClickListener listener) { super(caption, listener); setupPrimaryButton(); } public DeleteButton(String caption, Resource icon) { super(caption, icon); setupPrimaryButton(); } public DeleteButton(Resource icon) { super(icon); setupPrimaryButton(); } public DeleteButton(Resource icon, ClickListener listener) { super(icon, listener); setupPrimaryButton(); } private void setupPrimaryButton() { setStyleName(ValoTheme.BUTTON_DANGER); setClickShortcut(ShortcutAction.KeyCode.DELETE, null); } private static final long serialVersionUID = -2021035436509034505L; }
28.606061
81
0.699682
1d825de77fa26909a682ebc1cd83524271a12c0a
645
package cursedflames.lib; public class Potions { // private static Map<String, Potion> potions = new HashMap<>(); // // public static void init() { // for (ResourceLocation potionLoc : Potion.REGISTRY.getKeys()) { // System.out.println(potionLoc.toString()); // Potion potion = Potion.getPotionFromResourceLocation(potionLoc.toString()); // System.out.println(potion.getName()); // potions.put(potion.getName(), potion); // Potion potion2 = get(potion.getName()); // System.out.println((potion2==null ? "null" : potion2.getName())); // } // } // // public static Potion get(String potion) { // return potions.get(potion); // } }
30.714286
80
0.67907
b439aa421be4f10bf6fe209377af2decbdb7573b
1,907
// // LogColors.java // // Lunar Unity Mobile Console // https://github.com/SpaceMadness/lunar-unity-console // // Copyright 2019 Alex Lementuev, SpaceMadness. // // 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 spacemadness.com.lunarconsole.settings; import spacemadness.com.lunarconsole.json.Required; public class LogColors { public @Required LogEntryColors exception; public @Required LogEntryColors error; public @Required LogEntryColors warning; public @Required LogEntryColors debug; //region Equality @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; LogColors that = (LogColors) o; if (exception != null ? !exception.equals(that.exception) : that.exception != null) return false; if (error != null ? !error.equals(that.error) : that.error != null) return false; if (warning != null ? !warning.equals(that.warning) : that.warning != null) return false; return debug != null ? debug.equals(that.debug) : that.debug == null; } @Override public int hashCode() { int result = exception != null ? exception.hashCode() : 0; result = 31 * result + (error != null ? error.hashCode() : 0); result = 31 * result + (warning != null ? warning.hashCode() : 0); result = 31 * result + (debug != null ? debug.hashCode() : 0); return result; } //endregion }
33.45614
91
0.70215
d813e7a2d449f8fdc71cd675648750a38085567f
4,176
package net.thevpc.nuts.toolbox.njob; import net.thevpc.nuts.*; import net.thevpc.nuts.toolbox.njob.model.Id; import net.thevpc.nuts.toolbox.njob.model.NJob; import net.thevpc.nuts.toolbox.njob.model.NProject; import net.thevpc.nuts.toolbox.njob.model.NTask; import java.lang.reflect.Field; import java.util.UUID; import java.util.stream.Stream; public class NJobConfigStore { private NutsApplicationContext context; private NutsElements json; private NutsPath dbPath; public NJobConfigStore(NutsApplicationContext applicationContext) { this.context = applicationContext; NutsSession session = applicationContext.getSession(); json = NutsElements.of(session).json().setNtf(false); json.setCompact(false); //ensure we always consider the latest config version dbPath = applicationContext.getVersionFolder(NutsStoreLocation.CONFIG, NJobConfigVersions.CURRENT) .resolve("db"); } private Field getKeyField(Class o) { for (Field declaredField : o.getDeclaredFields()) { Id a = declaredField.getAnnotation(Id.class); if (a != null) { declaredField.setAccessible(true); return declaredField; } } throw new RuntimeException("missing @Id field"); } private Object getKey(Object o) { try { return getKeyField(o.getClass()).get(o); } catch (IllegalAccessException e) { throw new IllegalArgumentException(e); } } private String getEntityName(Class o) { return o.getSimpleName().toLowerCase(); } private NutsPath getObjectFile(Object o) { return getFile(getEntityName(o.getClass()), getKey(o)); } private NutsPath getFile(String entityName, Object id) { return dbPath.resolve(entityName).resolve(id + ".json"); } public <T> Stream<T> search(Class<T> type) { NutsPath f = getFile(getEntityName(type), "any").getParent(); NutsFunction<NutsPath, T> parse = NutsFunction.of(x -> json.parse(x, type), "parse"); return f.list().filter( x -> x.isRegularFile() && x.getName().endsWith(".json"), "isRegularFile() && matches(*.json"+")" ) .map(parse,elem->elem.ofString("parse")) .filterNonNull().stream(); } public <T> T load(Class<T> type, Object id) { NutsPath f = getFile(getEntityName(type), id); if (f.exists()) { return json.parse(f, type); } return null; } public void store(Object o) { if(o instanceof NJob) { NJob j = (NJob) o; String ii=j.getId(); if (ii==null){ j.setId(generateId(NJob.class)); } }else if(o instanceof NTask){ NTask j = (NTask) o; String ii=j.getId(); if (ii==null){ j.setId(generateId(NTask.class)); } }else if(o instanceof NProject){ NProject j = (NProject) o; String ii=j.getId(); if (ii==null){ j.setId(generateId(NProject.class)); } } NutsPath objectFile = getObjectFile(o); objectFile.mkParentDirs(); json.setValue(o).println(objectFile); } public String generateId(Class clz) { // SimpleDateFormat yyyyMMddHHmmssSSS = new SimpleDateFormat("yyyyMMddHHmmssSSS"); while(true){ //test until we reach next millisecond String nid= UUID.randomUUID().toString(); // yyyyMMddHHmmssSSS.format(new Date()); NutsPath f = getFile(getEntityName(clz), nid); if(!f.exists()){ return nid; } } } public boolean delete(Class entityName, Object id) { return delete(getEntityName(entityName), id); } public boolean delete(String entityName, Object id) { NutsPath f = getFile(entityName, id); if (f.exists()) { f.delete(); return true; } return false; } }
32.372093
106
0.580939
2f848d89a8ec8b137e3c8250589cc4fe0318434c
26,503
package com.luulsolutions.luulpos.web.rest; import com.luulsolutions.luulpos.LuulposApp; import com.luulsolutions.luulpos.domain.ShopChange; import com.luulsolutions.luulpos.domain.Shop; import com.luulsolutions.luulpos.domain.Profile; import com.luulsolutions.luulpos.repository.ShopChangeRepository; import com.luulsolutions.luulpos.repository.search.ShopChangeSearchRepository; import com.luulsolutions.luulpos.service.ShopChangeService; import com.luulsolutions.luulpos.service.dto.ShopChangeDTO; import com.luulsolutions.luulpos.service.mapper.ShopChangeMapper; import com.luulsolutions.luulpos.web.rest.errors.ExceptionTranslator; import com.luulsolutions.luulpos.service.dto.ShopChangeCriteria; import com.luulsolutions.luulpos.service.ShopChangeQueryService; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.MockitoAnnotations; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.data.domain.PageImpl; import org.springframework.data.domain.PageRequest; import org.springframework.data.web.PageableHandlerMethodArgumentResolver; import org.springframework.http.MediaType; import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.transaction.annotation.Transactional; import javax.persistence.EntityManager; import java.time.Instant; import java.time.ZonedDateTime; import java.time.ZoneOffset; import java.time.ZoneId; import java.util.Collections; import java.util.List; import static com.luulsolutions.luulpos.web.rest.TestUtil.sameInstant; import static com.luulsolutions.luulpos.web.rest.TestUtil.createFormattingConversionService; import static org.assertj.core.api.Assertions.assertThat; import static org.elasticsearch.index.query.QueryBuilders.queryStringQuery; import static org.hamcrest.Matchers.hasItem; import static org.mockito.Mockito.*; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; /** * Test class for the ShopChangeResource REST controller. * * @see ShopChangeResource */ @RunWith(SpringRunner.class) @SpringBootTest(classes = LuulposApp.class) public class ShopChangeResourceIntTest { private static final String DEFAULT_CHANGE = "AAAAAAAAAA"; private static final String UPDATED_CHANGE = "BBBBBBBBBB"; private static final String DEFAULT_CHANGED_ENTITY = "AAAAAAAAAA"; private static final String UPDATED_CHANGED_ENTITY = "BBBBBBBBBB"; private static final String DEFAULT_NOTE = "AAAAAAAAAA"; private static final String UPDATED_NOTE = "BBBBBBBBBB"; private static final ZonedDateTime DEFAULT_CHANGE_DATE = ZonedDateTime.ofInstant(Instant.ofEpochMilli(0L), ZoneOffset.UTC); private static final ZonedDateTime UPDATED_CHANGE_DATE = ZonedDateTime.now(ZoneId.systemDefault()).withNano(0); @Autowired private ShopChangeRepository shopChangeRepository; @Autowired private ShopChangeMapper shopChangeMapper; @Autowired private ShopChangeService shopChangeService; /** * This repository is mocked in the com.luulsolutions.luulpos.repository.search test package. * * @see com.luulsolutions.luulpos.repository.search.ShopChangeSearchRepositoryMockConfiguration */ @Autowired private ShopChangeSearchRepository mockShopChangeSearchRepository; @Autowired private ShopChangeQueryService shopChangeQueryService; @Autowired private MappingJackson2HttpMessageConverter jacksonMessageConverter; @Autowired private PageableHandlerMethodArgumentResolver pageableArgumentResolver; @Autowired private ExceptionTranslator exceptionTranslator; @Autowired private EntityManager em; private MockMvc restShopChangeMockMvc; private ShopChange shopChange; @Before public void setup() { MockitoAnnotations.initMocks(this); final ShopChangeResource shopChangeResource = new ShopChangeResource(shopChangeService, shopChangeQueryService); this.restShopChangeMockMvc = MockMvcBuilders.standaloneSetup(shopChangeResource) .setCustomArgumentResolvers(pageableArgumentResolver) .setControllerAdvice(exceptionTranslator) .setConversionService(createFormattingConversionService()) .setMessageConverters(jacksonMessageConverter).build(); } /** * Create an entity for this test. * * This is a static method, as tests for other entities might also need it, * if they test an entity which requires the current entity. */ public static ShopChange createEntity(EntityManager em) { ShopChange shopChange = new ShopChange() .change(DEFAULT_CHANGE) .changedEntity(DEFAULT_CHANGED_ENTITY) .note(DEFAULT_NOTE) .changeDate(DEFAULT_CHANGE_DATE); return shopChange; } @Before public void initTest() { shopChange = createEntity(em); } @Test @Transactional public void createShopChange() throws Exception { int databaseSizeBeforeCreate = shopChangeRepository.findAll().size(); // Create the ShopChange ShopChangeDTO shopChangeDTO = shopChangeMapper.toDto(shopChange); restShopChangeMockMvc.perform(post("/api/shop-changes") .contentType(TestUtil.APPLICATION_JSON_UTF8) .content(TestUtil.convertObjectToJsonBytes(shopChangeDTO))) .andExpect(status().isCreated()); // Validate the ShopChange in the database List<ShopChange> shopChangeList = shopChangeRepository.findAll(); assertThat(shopChangeList).hasSize(databaseSizeBeforeCreate + 1); ShopChange testShopChange = shopChangeList.get(shopChangeList.size() - 1); assertThat(testShopChange.getChange()).isEqualTo(DEFAULT_CHANGE); assertThat(testShopChange.getChangedEntity()).isEqualTo(DEFAULT_CHANGED_ENTITY); assertThat(testShopChange.getNote()).isEqualTo(DEFAULT_NOTE); assertThat(testShopChange.getChangeDate()).isEqualTo(DEFAULT_CHANGE_DATE); // Validate the ShopChange in Elasticsearch verify(mockShopChangeSearchRepository, times(1)).save(testShopChange); } @Test @Transactional public void createShopChangeWithExistingId() throws Exception { int databaseSizeBeforeCreate = shopChangeRepository.findAll().size(); // Create the ShopChange with an existing ID shopChange.setId(1L); ShopChangeDTO shopChangeDTO = shopChangeMapper.toDto(shopChange); // An entity with an existing ID cannot be created, so this API call must fail restShopChangeMockMvc.perform(post("/api/shop-changes") .contentType(TestUtil.APPLICATION_JSON_UTF8) .content(TestUtil.convertObjectToJsonBytes(shopChangeDTO))) .andExpect(status().isBadRequest()); // Validate the ShopChange in the database List<ShopChange> shopChangeList = shopChangeRepository.findAll(); assertThat(shopChangeList).hasSize(databaseSizeBeforeCreate); // Validate the ShopChange in Elasticsearch verify(mockShopChangeSearchRepository, times(0)).save(shopChange); } @Test @Transactional public void getAllShopChanges() throws Exception { // Initialize the database shopChangeRepository.saveAndFlush(shopChange); // Get all the shopChangeList restShopChangeMockMvc.perform(get("/api/shop-changes?sort=id,desc")) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) .andExpect(jsonPath("$.[*].id").value(hasItem(shopChange.getId().intValue()))) .andExpect(jsonPath("$.[*].change").value(hasItem(DEFAULT_CHANGE.toString()))) .andExpect(jsonPath("$.[*].changedEntity").value(hasItem(DEFAULT_CHANGED_ENTITY.toString()))) .andExpect(jsonPath("$.[*].note").value(hasItem(DEFAULT_NOTE.toString()))) .andExpect(jsonPath("$.[*].changeDate").value(hasItem(sameInstant(DEFAULT_CHANGE_DATE)))); } @Test @Transactional public void getShopChange() throws Exception { // Initialize the database shopChangeRepository.saveAndFlush(shopChange); // Get the shopChange restShopChangeMockMvc.perform(get("/api/shop-changes/{id}", shopChange.getId())) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) .andExpect(jsonPath("$.id").value(shopChange.getId().intValue())) .andExpect(jsonPath("$.change").value(DEFAULT_CHANGE.toString())) .andExpect(jsonPath("$.changedEntity").value(DEFAULT_CHANGED_ENTITY.toString())) .andExpect(jsonPath("$.note").value(DEFAULT_NOTE.toString())) .andExpect(jsonPath("$.changeDate").value(sameInstant(DEFAULT_CHANGE_DATE))); } @Test @Transactional public void getAllShopChangesByChangeIsEqualToSomething() throws Exception { // Initialize the database shopChangeRepository.saveAndFlush(shopChange); // Get all the shopChangeList where change equals to DEFAULT_CHANGE defaultShopChangeShouldBeFound("change.equals=" + DEFAULT_CHANGE); // Get all the shopChangeList where change equals to UPDATED_CHANGE defaultShopChangeShouldNotBeFound("change.equals=" + UPDATED_CHANGE); } @Test @Transactional public void getAllShopChangesByChangeIsInShouldWork() throws Exception { // Initialize the database shopChangeRepository.saveAndFlush(shopChange); // Get all the shopChangeList where change in DEFAULT_CHANGE or UPDATED_CHANGE defaultShopChangeShouldBeFound("change.in=" + DEFAULT_CHANGE + "," + UPDATED_CHANGE); // Get all the shopChangeList where change equals to UPDATED_CHANGE defaultShopChangeShouldNotBeFound("change.in=" + UPDATED_CHANGE); } @Test @Transactional public void getAllShopChangesByChangeIsNullOrNotNull() throws Exception { // Initialize the database shopChangeRepository.saveAndFlush(shopChange); // Get all the shopChangeList where change is not null defaultShopChangeShouldBeFound("change.specified=true"); // Get all the shopChangeList where change is null defaultShopChangeShouldNotBeFound("change.specified=false"); } @Test @Transactional public void getAllShopChangesByChangedEntityIsEqualToSomething() throws Exception { // Initialize the database shopChangeRepository.saveAndFlush(shopChange); // Get all the shopChangeList where changedEntity equals to DEFAULT_CHANGED_ENTITY defaultShopChangeShouldBeFound("changedEntity.equals=" + DEFAULT_CHANGED_ENTITY); // Get all the shopChangeList where changedEntity equals to UPDATED_CHANGED_ENTITY defaultShopChangeShouldNotBeFound("changedEntity.equals=" + UPDATED_CHANGED_ENTITY); } @Test @Transactional public void getAllShopChangesByChangedEntityIsInShouldWork() throws Exception { // Initialize the database shopChangeRepository.saveAndFlush(shopChange); // Get all the shopChangeList where changedEntity in DEFAULT_CHANGED_ENTITY or UPDATED_CHANGED_ENTITY defaultShopChangeShouldBeFound("changedEntity.in=" + DEFAULT_CHANGED_ENTITY + "," + UPDATED_CHANGED_ENTITY); // Get all the shopChangeList where changedEntity equals to UPDATED_CHANGED_ENTITY defaultShopChangeShouldNotBeFound("changedEntity.in=" + UPDATED_CHANGED_ENTITY); } @Test @Transactional public void getAllShopChangesByChangedEntityIsNullOrNotNull() throws Exception { // Initialize the database shopChangeRepository.saveAndFlush(shopChange); // Get all the shopChangeList where changedEntity is not null defaultShopChangeShouldBeFound("changedEntity.specified=true"); // Get all the shopChangeList where changedEntity is null defaultShopChangeShouldNotBeFound("changedEntity.specified=false"); } @Test @Transactional public void getAllShopChangesByNoteIsEqualToSomething() throws Exception { // Initialize the database shopChangeRepository.saveAndFlush(shopChange); // Get all the shopChangeList where note equals to DEFAULT_NOTE defaultShopChangeShouldBeFound("note.equals=" + DEFAULT_NOTE); // Get all the shopChangeList where note equals to UPDATED_NOTE defaultShopChangeShouldNotBeFound("note.equals=" + UPDATED_NOTE); } @Test @Transactional public void getAllShopChangesByNoteIsInShouldWork() throws Exception { // Initialize the database shopChangeRepository.saveAndFlush(shopChange); // Get all the shopChangeList where note in DEFAULT_NOTE or UPDATED_NOTE defaultShopChangeShouldBeFound("note.in=" + DEFAULT_NOTE + "," + UPDATED_NOTE); // Get all the shopChangeList where note equals to UPDATED_NOTE defaultShopChangeShouldNotBeFound("note.in=" + UPDATED_NOTE); } @Test @Transactional public void getAllShopChangesByNoteIsNullOrNotNull() throws Exception { // Initialize the database shopChangeRepository.saveAndFlush(shopChange); // Get all the shopChangeList where note is not null defaultShopChangeShouldBeFound("note.specified=true"); // Get all the shopChangeList where note is null defaultShopChangeShouldNotBeFound("note.specified=false"); } @Test @Transactional public void getAllShopChangesByChangeDateIsEqualToSomething() throws Exception { // Initialize the database shopChangeRepository.saveAndFlush(shopChange); // Get all the shopChangeList where changeDate equals to DEFAULT_CHANGE_DATE defaultShopChangeShouldBeFound("changeDate.equals=" + DEFAULT_CHANGE_DATE); // Get all the shopChangeList where changeDate equals to UPDATED_CHANGE_DATE defaultShopChangeShouldNotBeFound("changeDate.equals=" + UPDATED_CHANGE_DATE); } @Test @Transactional public void getAllShopChangesByChangeDateIsInShouldWork() throws Exception { // Initialize the database shopChangeRepository.saveAndFlush(shopChange); // Get all the shopChangeList where changeDate in DEFAULT_CHANGE_DATE or UPDATED_CHANGE_DATE defaultShopChangeShouldBeFound("changeDate.in=" + DEFAULT_CHANGE_DATE + "," + UPDATED_CHANGE_DATE); // Get all the shopChangeList where changeDate equals to UPDATED_CHANGE_DATE defaultShopChangeShouldNotBeFound("changeDate.in=" + UPDATED_CHANGE_DATE); } @Test @Transactional public void getAllShopChangesByChangeDateIsNullOrNotNull() throws Exception { // Initialize the database shopChangeRepository.saveAndFlush(shopChange); // Get all the shopChangeList where changeDate is not null defaultShopChangeShouldBeFound("changeDate.specified=true"); // Get all the shopChangeList where changeDate is null defaultShopChangeShouldNotBeFound("changeDate.specified=false"); } @Test @Transactional public void getAllShopChangesByChangeDateIsGreaterThanOrEqualToSomething() throws Exception { // Initialize the database shopChangeRepository.saveAndFlush(shopChange); // Get all the shopChangeList where changeDate greater than or equals to DEFAULT_CHANGE_DATE defaultShopChangeShouldBeFound("changeDate.greaterOrEqualThan=" + DEFAULT_CHANGE_DATE); // Get all the shopChangeList where changeDate greater than or equals to UPDATED_CHANGE_DATE defaultShopChangeShouldNotBeFound("changeDate.greaterOrEqualThan=" + UPDATED_CHANGE_DATE); } @Test @Transactional public void getAllShopChangesByChangeDateIsLessThanSomething() throws Exception { // Initialize the database shopChangeRepository.saveAndFlush(shopChange); // Get all the shopChangeList where changeDate less than or equals to DEFAULT_CHANGE_DATE defaultShopChangeShouldNotBeFound("changeDate.lessThan=" + DEFAULT_CHANGE_DATE); // Get all the shopChangeList where changeDate less than or equals to UPDATED_CHANGE_DATE defaultShopChangeShouldBeFound("changeDate.lessThan=" + UPDATED_CHANGE_DATE); } @Test @Transactional public void getAllShopChangesByShopIsEqualToSomething() throws Exception { // Initialize the database Shop shop = ShopResourceIntTest.createEntity(em); em.persist(shop); em.flush(); shopChange.setShop(shop); shopChangeRepository.saveAndFlush(shopChange); Long shopId = shop.getId(); // Get all the shopChangeList where shop equals to shopId defaultShopChangeShouldBeFound("shopId.equals=" + shopId); // Get all the shopChangeList where shop equals to shopId + 1 defaultShopChangeShouldNotBeFound("shopId.equals=" + (shopId + 1)); } @Test @Transactional public void getAllShopChangesByChangedByIsEqualToSomething() throws Exception { // Initialize the database Profile changedBy = ProfileResourceIntTest.createEntity(em); em.persist(changedBy); em.flush(); shopChange.setChangedBy(changedBy); shopChangeRepository.saveAndFlush(shopChange); Long changedById = changedBy.getId(); // Get all the shopChangeList where changedBy equals to changedById defaultShopChangeShouldBeFound("changedById.equals=" + changedById); // Get all the shopChangeList where changedBy equals to changedById + 1 defaultShopChangeShouldNotBeFound("changedById.equals=" + (changedById + 1)); } /** * Executes the search, and checks that the default entity is returned */ private void defaultShopChangeShouldBeFound(String filter) throws Exception { restShopChangeMockMvc.perform(get("/api/shop-changes?sort=id,desc&" + filter)) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) .andExpect(jsonPath("$.[*].id").value(hasItem(shopChange.getId().intValue()))) .andExpect(jsonPath("$.[*].change").value(hasItem(DEFAULT_CHANGE.toString()))) .andExpect(jsonPath("$.[*].changedEntity").value(hasItem(DEFAULT_CHANGED_ENTITY.toString()))) .andExpect(jsonPath("$.[*].note").value(hasItem(DEFAULT_NOTE.toString()))) .andExpect(jsonPath("$.[*].changeDate").value(hasItem(sameInstant(DEFAULT_CHANGE_DATE)))); // Check, that the count call also returns 1 restShopChangeMockMvc.perform(get("/api/shop-changes/count?sort=id,desc&" + filter)) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) .andExpect(content().string("1")); } /** * Executes the search, and checks that the default entity is not returned */ private void defaultShopChangeShouldNotBeFound(String filter) throws Exception { restShopChangeMockMvc.perform(get("/api/shop-changes?sort=id,desc&" + filter)) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) .andExpect(jsonPath("$").isArray()) .andExpect(jsonPath("$").isEmpty()); // Check, that the count call also returns 0 restShopChangeMockMvc.perform(get("/api/shop-changes/count?sort=id,desc&" + filter)) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) .andExpect(content().string("0")); } @Test @Transactional public void getNonExistingShopChange() throws Exception { // Get the shopChange restShopChangeMockMvc.perform(get("/api/shop-changes/{id}", Long.MAX_VALUE)) .andExpect(status().isNotFound()); } @Test @Transactional public void updateShopChange() throws Exception { // Initialize the database shopChangeRepository.saveAndFlush(shopChange); int databaseSizeBeforeUpdate = shopChangeRepository.findAll().size(); // Update the shopChange ShopChange updatedShopChange = shopChangeRepository.findById(shopChange.getId()).get(); // Disconnect from session so that the updates on updatedShopChange are not directly saved in db em.detach(updatedShopChange); updatedShopChange .change(UPDATED_CHANGE) .changedEntity(UPDATED_CHANGED_ENTITY) .note(UPDATED_NOTE) .changeDate(UPDATED_CHANGE_DATE); ShopChangeDTO shopChangeDTO = shopChangeMapper.toDto(updatedShopChange); restShopChangeMockMvc.perform(put("/api/shop-changes") .contentType(TestUtil.APPLICATION_JSON_UTF8) .content(TestUtil.convertObjectToJsonBytes(shopChangeDTO))) .andExpect(status().isOk()); // Validate the ShopChange in the database List<ShopChange> shopChangeList = shopChangeRepository.findAll(); assertThat(shopChangeList).hasSize(databaseSizeBeforeUpdate); ShopChange testShopChange = shopChangeList.get(shopChangeList.size() - 1); assertThat(testShopChange.getChange()).isEqualTo(UPDATED_CHANGE); assertThat(testShopChange.getChangedEntity()).isEqualTo(UPDATED_CHANGED_ENTITY); assertThat(testShopChange.getNote()).isEqualTo(UPDATED_NOTE); assertThat(testShopChange.getChangeDate()).isEqualTo(UPDATED_CHANGE_DATE); // Validate the ShopChange in Elasticsearch verify(mockShopChangeSearchRepository, times(1)).save(testShopChange); } @Test @Transactional public void updateNonExistingShopChange() throws Exception { int databaseSizeBeforeUpdate = shopChangeRepository.findAll().size(); // Create the ShopChange ShopChangeDTO shopChangeDTO = shopChangeMapper.toDto(shopChange); // If the entity doesn't have an ID, it will throw BadRequestAlertException restShopChangeMockMvc.perform(put("/api/shop-changes") .contentType(TestUtil.APPLICATION_JSON_UTF8) .content(TestUtil.convertObjectToJsonBytes(shopChangeDTO))) .andExpect(status().isBadRequest()); // Validate the ShopChange in the database List<ShopChange> shopChangeList = shopChangeRepository.findAll(); assertThat(shopChangeList).hasSize(databaseSizeBeforeUpdate); // Validate the ShopChange in Elasticsearch verify(mockShopChangeSearchRepository, times(0)).save(shopChange); } @Test @Transactional public void deleteShopChange() throws Exception { // Initialize the database shopChangeRepository.saveAndFlush(shopChange); int databaseSizeBeforeDelete = shopChangeRepository.findAll().size(); // Get the shopChange restShopChangeMockMvc.perform(delete("/api/shop-changes/{id}", shopChange.getId()) .accept(TestUtil.APPLICATION_JSON_UTF8)) .andExpect(status().isOk()); // Validate the database is empty List<ShopChange> shopChangeList = shopChangeRepository.findAll(); assertThat(shopChangeList).hasSize(databaseSizeBeforeDelete - 1); // Validate the ShopChange in Elasticsearch verify(mockShopChangeSearchRepository, times(1)).deleteById(shopChange.getId()); } @Test @Transactional public void searchShopChange() throws Exception { // Initialize the database shopChangeRepository.saveAndFlush(shopChange); when(mockShopChangeSearchRepository.search(queryStringQuery("id:" + shopChange.getId()), PageRequest.of(0, 20))) .thenReturn(new PageImpl<>(Collections.singletonList(shopChange), PageRequest.of(0, 1), 1)); // Search the shopChange restShopChangeMockMvc.perform(get("/api/_search/shop-changes?query=id:" + shopChange.getId())) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) .andExpect(jsonPath("$.[*].id").value(hasItem(shopChange.getId().intValue()))) .andExpect(jsonPath("$.[*].change").value(hasItem(DEFAULT_CHANGE))) .andExpect(jsonPath("$.[*].changedEntity").value(hasItem(DEFAULT_CHANGED_ENTITY))) .andExpect(jsonPath("$.[*].note").value(hasItem(DEFAULT_NOTE))) .andExpect(jsonPath("$.[*].changeDate").value(hasItem(sameInstant(DEFAULT_CHANGE_DATE)))); } @Test @Transactional public void equalsVerifier() throws Exception { TestUtil.equalsVerifier(ShopChange.class); ShopChange shopChange1 = new ShopChange(); shopChange1.setId(1L); ShopChange shopChange2 = new ShopChange(); shopChange2.setId(shopChange1.getId()); assertThat(shopChange1).isEqualTo(shopChange2); shopChange2.setId(2L); assertThat(shopChange1).isNotEqualTo(shopChange2); shopChange1.setId(null); assertThat(shopChange1).isNotEqualTo(shopChange2); } @Test @Transactional public void dtoEqualsVerifier() throws Exception { TestUtil.equalsVerifier(ShopChangeDTO.class); ShopChangeDTO shopChangeDTO1 = new ShopChangeDTO(); shopChangeDTO1.setId(1L); ShopChangeDTO shopChangeDTO2 = new ShopChangeDTO(); assertThat(shopChangeDTO1).isNotEqualTo(shopChangeDTO2); shopChangeDTO2.setId(shopChangeDTO1.getId()); assertThat(shopChangeDTO1).isEqualTo(shopChangeDTO2); shopChangeDTO2.setId(2L); assertThat(shopChangeDTO1).isNotEqualTo(shopChangeDTO2); shopChangeDTO1.setId(null); assertThat(shopChangeDTO1).isNotEqualTo(shopChangeDTO2); } @Test @Transactional public void testEntityFromId() { assertThat(shopChangeMapper.fromId(42L).getId()).isEqualTo(42); assertThat(shopChangeMapper.fromId(null)).isNull(); } }
42.540931
127
0.720824
887282bfdcbe5c78cdb428c8720a0586304b530b
803
package io.cucumber.config.builders; import io.cucumber.config.MapBuilder; import io.cucumber.config.FieldSetterContract; import java.io.StringReader; public class JsonTest extends FieldSetterContract { @Override protected MapBuilder makeMapBuilder() { StringReader jsonReader = new StringReader("" + "{\n" + " \"testing\": {\n" + " \"somebool\": true,\n" + " \"meaning\": 42,\n" + " \"message\": \"hello\",\n" + " \"stringlist\": [\n" + " \"one\",\n" + " \"two\"\n" + " ]\n" + " }\n" + "}\n" ); return new JsonBuilder(new String[]{"testing"}, jsonReader); } }
29.740741
68
0.4533
d7f6f05e609cb942f4b72ce5699a8cbe1d8014cd
6,372
/* * 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. * * Contributions from 2013-2017 where performed either by US government * employees, or under US Veterans Health Administration contracts. * * US Veterans Health Administration contributions by government employees * are work of the U.S. Government and are not subject to copyright * protection in the United States. Portions contributed by government * employees are USGovWork (17USC §105). Not subject to copyright. * * Contribution by contractors to the US Veterans Health Administration * during this period are contractually contributed under the * Apache License, Version 2.0. * * See: https://www.usa.gov/government-works * * Contributions prior to 2013: * * Copyright (C) International Health Terminology Standards Development Organisation. * Licensed under the Apache License, Version 2.0. * */ package sh.isaac.converters.sharedUtils.propertyTypes; //~--- non-JDK imports -------------------------------------------------------- import sh.isaac.api.chronicle.VersionType; import sh.isaac.api.component.semantic.version.dynamic.DynamicColumnInfo; import sh.isaac.api.component.semantic.version.dynamic.DynamicDataType; import sh.isaac.api.constants.DynamicConstants; import sh.isaac.api.externalizable.IsaacObjectType; //~--- classes ---------------------------------------------------------------- /** * The Class PropertyAssociation. */ public class PropertyAssociation extends Property { /** The association inverse name. */ private final String associationInverseName; /** The association component type restriction. */ private final IsaacObjectType associationComponentTypeRestriction; /** The association component type sub restriction. */ private final VersionType associationComponentTypeSubRestriction; //~--- constructors -------------------------------------------------------- /** * Instantiates a new property association. * * @param owner the owner * @param sourcePropertyNameFQN the source property name fully qualified name * @param sourcePropertyAltName the source property alt name * @param associationInverseName the association inverse name * @param associationDescription the association description * @param disabled the disabled */ public PropertyAssociation(PropertyType owner, String sourcePropertyNameFQN, String sourcePropertyAltName, String associationInverseName, String associationDescription, boolean disabled) { this(owner, sourcePropertyNameFQN, sourcePropertyAltName, associationInverseName, associationDescription, disabled, null, null); } /** * Instantiates a new property association. * * @param owner the owner * @param sourcePropertyNameFQN the source property name FQN * @param sourcePropertyAltName the source property alt name * @param associationInverseName the association inverse name * @param associationDescription the association description * @param disabled the disabled * @param associationComponentTypeRestriction the association component type restriction * @param associationComponentTypeSubRestriction the association component type sub restriction */ public PropertyAssociation(PropertyType owner, String sourcePropertyNameFQN, String sourcePropertyAltName, String associationInverseName, String associationDescription, boolean disabled, IsaacObjectType associationComponentTypeRestriction, VersionType associationComponentTypeSubRestriction) { super(owner, sourcePropertyNameFQN, sourcePropertyAltName, associationDescription, disabled, Integer.MAX_VALUE, null); if (associationDescription == null) { throw new RuntimeException("association description is required"); } this.associationInverseName = associationInverseName; this.associationComponentTypeRestriction = associationComponentTypeRestriction; this.associationComponentTypeSubRestriction = associationComponentTypeSubRestriction; } //~--- get methods --------------------------------------------------------- /** * Gets the association component type restriction. * * @return the association component type restriction */ public IsaacObjectType getAssociationComponentTypeRestriction() { return this.associationComponentTypeRestriction; } /** * Gets the association component type sub restriction. * * @return the association component type sub restriction */ public VersionType getAssociationComponentTypeSubRestriction() { return this.associationComponentTypeSubRestriction; } /** * Gets the association inverse name. * * @return the association inverse name */ public String getAssociationInverseName() { return this.associationInverseName; } /** * Gets the data columns for dynamic refex. * * @return the data columns for dynamic refex */ @Override public DynamicColumnInfo[] getDataColumnsForDynamicRefex() { final DynamicColumnInfo[] columns = new DynamicColumnInfo[] { new DynamicColumnInfo(0, DynamicConstants.get().DYNAMIC_COLUMN_ASSOCIATION_TARGET_COMPONENT.getPrimordialUuid(), DynamicDataType.UUID, null, false, true) }; return columns; } }
36.411429
125
0.665254
71611481171b114bcf8d24ef4c657c6a532942a8
424
package com.redhat.ceylon.compiler.typechecker.analyzer; import com.redhat.ceylon.compiler.typechecker.tree.Node; /** * Represents situations that the typechecker accepts, * because they are in principle well-typed, but that * the backends don't yet support. */ public class UnsupportedError extends AnalysisError { public UnsupportedError(Node treeNode, String message) { super(treeNode, message); } }
24.941176
57
0.759434
6e5314b321bffa25fbf7996ba6b666f43e001a77
2,222
package com.igitras.codegen.common.next; import com.igitras.codegen.common.next.annotations.NonNls; import com.igitras.codegen.common.next.annotations.NotNull; import com.igitras.codegen.common.next.annotations.Nullable; /** * Represents a Java annotation. * <p> * Created by mason on 1/5/15. */ public interface CgAnnotation extends CgAnnotationMemberValue, CgMetaOwner { /** * Kinds of element to which an annotation type is applicable (see {@link java.lang.annotation.ElementType}). */ enum TargetType { // see java.lang.annotation.ElementType TYPE, FIELD, METHOD, PARAMETER, CONSTRUCTOR, LOCAL_VARIABLE, ANNOTATION_TYPE, PACKAGE, TYPE_USE, TYPE_PARAMETER, // auxiliary value, used when it's impossible to determine annotation's targets UNKNOWN; public static final TargetType[] EMPTY_ARRAY = {}; } /** * Returns the list of parameters for the annotation. * * @return the parameter list instance. */ @NotNull CgAnnotationParameterList getParameterList(); /** * Returns the fully qualified name of the annotation class. * * @return the class name, or null if the annotation is unresolved. */ @Nullable @NonNls String getQualifiedName(); /** * Returns the element representing the name of the annotation. * * @return the annotation name element. */ @Nullable CgNamedElement getNameReferenceElement(); /** * Set annotation attribute value. Adds new name-value pair or uses an existing one, expands unnamed 'value' attribute name if needed. * * @param attributeName attribute name * @param value new value template element * @return new declared attribute value */ <T extends CgAnnotationMemberValue> T setDeclaredAttributeValue( @Nullable @NonNls String attributeName, @Nullable T value); /** * Returns an owner of the annotation - usually a parent, but for type annotations the owner might be a type element. * * @return annotation owner */ @Nullable CgAnnotationOwner getOwner(); }
28.126582
138
0.659316
30b7a5005f0a253757561a40be344a97ab60d92c
5,563
// 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 edu.iu.dsc.tws.comms.dfw; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.logging.Level; import java.util.logging.Logger; import edu.iu.dsc.tws.common.config.Config; import edu.iu.dsc.tws.comms.api.BulkReceiver; import edu.iu.dsc.tws.comms.api.DataFlowOperation; import edu.iu.dsc.tws.comms.api.MessageReceiver; import edu.iu.dsc.tws.comms.api.MessageType; import edu.iu.dsc.tws.comms.api.TWSChannel; import edu.iu.dsc.tws.comms.core.TaskPlan; import edu.iu.dsc.tws.comms.dfw.io.allgather.AllGatherBatchFinalReceiver; import edu.iu.dsc.tws.comms.dfw.io.allgather.AllGatherStreamingFinalReceiver; import edu.iu.dsc.tws.comms.dfw.io.gather.GatherBatchPartialReceiver; import edu.iu.dsc.tws.comms.dfw.io.gather.GatherStreamingPartialReceiver; public class DataFlowAllGather implements DataFlowOperation { private static final Logger LOG = Logger.getLogger(DataFlowAllGather.class.getName()); private DataFlowGather gather; private DataFlowBroadcast broadcast; // the source tasks protected Set<Integer> sources; // the destination task private Set<Integer> destinations; // the final receiver private BulkReceiver finalReceiver; private TWSChannel channel; private int executor; private int middleTask; private int gatherEdge; private int broadCastEdge; private boolean streaming; public DataFlowAllGather(TWSChannel chnl, Set<Integer> sources, Set<Integer> destination, int middleTask, BulkReceiver finalRecv, int redEdge, int broadEdge, boolean stream) { this.channel = chnl; this.sources = sources; this.destinations = destination; this.finalReceiver = finalRecv; this.gatherEdge = redEdge; this.broadCastEdge = broadEdge; this.middleTask = middleTask; this.streaming = stream; } /** * Initialize */ public void init(Config config, MessageType type, TaskPlan instancePlan, int edge) { this.executor = instancePlan.getThisExecutor(); broadcast = new DataFlowBroadcast(channel, middleTask, destinations, new BCastReceiver(finalReceiver)); broadcast.init(config, MessageType.OBJECT, instancePlan, broadCastEdge); MessageReceiver partialReceiver; MessageReceiver finalRecvr; if (streaming) { finalRecvr = new AllGatherStreamingFinalReceiver(broadcast); partialReceiver = new GatherStreamingPartialReceiver(); } else { finalRecvr = new AllGatherBatchFinalReceiver(broadcast); partialReceiver = new GatherBatchPartialReceiver(0); } gather = new DataFlowGather(channel, sources, middleTask, finalRecvr, partialReceiver, 0, 0, config, type, instancePlan, gatherEdge); gather.init(config, type, instancePlan, gatherEdge); } @Override public boolean sendPartial(int source, Object message, int flags) { return gather.sendPartial(source, message, flags); } @Override public boolean send(int source, Object message, int flags) { return gather.send(source, message, flags); } @Override public boolean send(int source, Object message, int flags, int target) { throw new RuntimeException("Not-implemented"); } @Override public boolean sendPartial(int source, Object message, int flags, int target) { throw new RuntimeException("Not-implemented"); } @Override public synchronized boolean progress() { try { boolean bCastProgress = broadcast.progress(); boolean reduceProgress = gather.progress(); return bCastProgress || reduceProgress; } catch (Throwable t) { LOG.log(Level.SEVERE, "un-expected error", t); throw new RuntimeException(t); } } public boolean isComplete() { return gather.isComplete() && broadcast.isComplete(); } @Override public void close() { } @Override public void finish(int source) { gather.finish(source); } @Override public TaskPlan getTaskPlan() { return null; } @Override public String getUniqueId() { return String.valueOf(gatherEdge); } @SuppressWarnings("unchecked") private static class BCastReceiver implements MessageReceiver { private BulkReceiver bulkReceiver; private boolean received = false; BCastReceiver(BulkReceiver reduceRcvr) { this.bulkReceiver = reduceRcvr; } @Override public void init(Config cfg, DataFlowOperation op, Map<Integer, List<Integer>> expectedIds) { this.bulkReceiver.init(cfg, expectedIds.keySet()); } @Override public boolean onMessage(int source, int path, int target, int flags, Object object) { if (object instanceof List) { boolean rcvd = bulkReceiver.receive(target, (Iterator<Object>) ((List) object).iterator()); if (rcvd) { received = true; return true; } } return false; } @Override public boolean progress() { return !received; } } }
29.590426
99
0.712206
bf6cff5e43471c6221a6b61b07cfbc647f0a61c9
5,502
/* * Copyright 2020 Centre for Computational Geography. * * 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.ac.leeds.ccg.v3d.geometrics; import uk.ac.leeds.ccg.v3d.geometry.V3D_Line; import uk.ac.leeds.ccg.v3d.geometry.V3D_Plane; import uk.ac.leeds.ccg.v3d.geometry.V3D_Point; /** * A class for geometrics. * * @author Andy Turner * @version 1.0 */ public class V3D_Geometrics { /** * @param points The points to test if they are coincident. * @return {@code true} iff all the points are coincident. */ public static boolean isCoincident(V3D_Point... points) { V3D_Point p0 = points[0]; for (V3D_Point p1 : points) { if (!p1.equals(p0)) { return false; } } return true; } /** * @param l The line to test points are collinear with. * @param points The points to test if they are collinear with l. * @return {@code true} iff all points are collinear with l. */ public static boolean isCollinear(int oom, V3D_Line l, V3D_Point... points) { for (V3D_Point p : points) { if (!l.isIntersectedBy(p, oom)) { return false; } } return true; } /** * @param points The points to test if they are collinear. * @return {@code false} if all points are coincident. {@code true} iff all * the points are collinear. */ public static boolean isCollinear(int oom, V3D_Point... points) { // For the points to be in a line at least two must be different. if (isCoincident(points)) { return false; } return isCollinear0(oom, points); } /** * @param points The points to test if they are collinear. * @return {@code true} iff all the points are collinear or coincident. */ private static boolean isCollinear0(int oom, V3D_Point... points) { // Get a line V3D_Line l = getLine(points); return isCollinear(oom, l, points); } /** * There should be at least two different points. * * @param points Any number of points, but with two being different. * @return A line defined by any two different points or null if the points are coincident. */ public static V3D_Line getLine(V3D_Point... points) { V3D_Point p0 = points[0]; for (V3D_Point p1 : points) { if (!p1.equals(p0)) { return new V3D_Line(p0, p1, -1); } } return null; } /** * @param p The plane to test points are coplanar with. * @param points The points to test if they are coplanar with p. * @return {@code true} iff all points are coplanar with p. */ public static boolean isCoplanar(int oom, V3D_Plane p, V3D_Point... points) { for (V3D_Point pt : points) { if (!p.isIntersectedBy(pt, oom)) { return false; } } return true; } /** * @param points The points to test if they are coplanar. * @return {@code false} if points are coincident or collinear. {@code true} * iff all points are coplanar. */ public static boolean isCoplanar(int oom, V3D_Point... points) { // For the points to be in a plane at least one must not be collinear. if (isCoincident(points)) { return false; } if (!isCollinear0(oom, points)) { V3D_Plane p = getPlane0(oom, points); return isCoplanar(oom, p, points); } return false; } /** * @param oom The Order of Magnitude used to initialise any vectors for the * resulting plane. * @param points The points from which a plane is to be derived. * @return A plane that may or may not contain all the points or * {@code null} if there is no such plane. This does not test if the points are coincident or * collinear. */ private static V3D_Plane getPlane0(int oom, V3D_Point... points) { V3D_Line l = getLine(points); for (V3D_Point p : points) { if (!isCollinear(oom, l, p)) { return new V3D_Plane(l.p, l.q, p, oom); } } return null; } /** * @param oom The Order of Magnitude used to initialise any vectors for the * resulting plane. * @param points The points from which a plane is to be derived. * @return A plane that may or may not contain all the points or * {@code null} if there is no such plane (if the points are coincident or * collinear). */ public static V3D_Plane getPlane(int oom, V3D_Point... points) { V3D_Line l = getLine(points); if (l == null) { return null; } for (V3D_Point p : points) { if (!isCollinear(oom, l, p)) { return new V3D_Plane(l.p, l.q, p, oom); } } return null; } }
32.946108
97
0.597056
fab1c972f5800c32f9048fb7967fb91fe8fe8c0c
4,093
/* * Copyright 2006-2010 The Virtual Laboratory for e-Science (VL-e) * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * For details, see the LICENCE.txt file location in the root directory of this * distribution or obtain the Apache Licence at the following location: * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * See: http://www.vl-e.nl/ * See: LICENCE.txt (located in the root folder of this distribution). * --- * $Id: TestReplicaRegistration.java,v 1.4 2011-06-07 15:15:10 ptdeboer Exp $ * $Date: 2011-06-07 15:15:10 $ */ // source: package test; import nl.uva.vlet.Global; import nl.uva.vlet.exception.VlException; import nl.uva.vlet.exception.VRLSyntaxException; import nl.uva.vlet.vfs.VFSClient; import nl.uva.vlet.vfs.VFile; import nl.uva.vlet.vfs.VReplicatable; import nl.uva.vlet.vfs.lfc.LFCFSFactory; import nl.uva.vlet.vrl.VRL; import nl.uva.vlet.vrs.VRS; public class TestReplicaRegistration { public static void main(String args[]) { try { Global.init(); // VRS.getRegistry().addVRSDriverClass(LFCFSFactory.class); // VRS.getRegistry().addVRSDriverClass(SRMFSFactory.class); } catch (Exception e) { e.printStackTrace(); } VRS.exit(); //testVReplicatable(); // VRS.exit(); } public static void testVReplicatable() { VFSClient vfs=new VFSClient(); try { VRL rep1=new VRL("srm://hello.world/bogus/1"); VRL rep2=new VRL("srm://hello.world/bogus/2"); VFile file=vfs.newFile(new VRL("lfn://lfc.grid.sara.nl/grid/pvier/piter/testRegistration")); if (file.exists()==false) file.create(); if (file instanceof VReplicatable) { VReplicatable repFile=((VReplicatable)file); VRL reps[]=repFile.getReplicas(); println("current replicas (should empty)"); println(reps); if (reps!=null) { try { repFile.unregisterReplicas(repFile.getReplicas()); } catch (Exception e) { e.printStackTrace(); } } VRL newReps[]=new VRL[1]; newReps[0]=rep1; repFile.registerReplicas(newReps); reps=repFile.getReplicas(); println("-- Added on replica ---"); println(reps); newReps[0]=rep2; repFile.registerReplicas(newReps); reps=repFile.getReplicas(); println("-- Added another replica ---"); println(reps); VRL delReps[]=new VRL[2]; delReps[0]=rep1; delReps[1]=rep2; repFile.unregisterReplicas(delReps); reps=repFile.getReplicas(); println("-- Deleted replicas ---"); println(reps); } } catch (VlException e) { e.printStackTrace(); } } private static void println(VRL[] reps) { for (VRL rep:reps) { System.out.println("Replica : "+rep); } } public static void println(String str) { System.out.println(str); } }
29.65942
104
0.524065
37aaeb49fd5db7456a6c9093749cd259211aa2a5
2,764
/** * <copyright> * Copyright (c) 2005 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation * </copyright> * * $Id: Target.java,v 1.4 2011/03/30 18:54:25 rbrodt Exp $ */ package org.eclipse.bpel.model; /** * <!-- begin-user-doc --> * A representation of the model object '<em><b>Target</b></em>'. * <!-- end-user-doc --> * * <p> * The following features are supported: * <ul> * <li>{@link org.eclipse.bpel.model.Target#getLink <em>Link</em>}</li> * <li>{@link org.eclipse.bpel.model.Target#getActivity <em>Activity</em>}</li> * </ul> * </p> * * @see org.eclipse.bpel.model.BPELPackage#getTarget() * @model * @generated */ public interface Target extends BPELExtensibleElement { /** * Returns the value of the '<em><b>Link</b></em>' reference. * It is bidirectional and its opposite is '{@link org.eclipse.bpel.model.Link#getTargets <em>Targets</em>}'. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Link</em>' reference isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>Link</em>' reference. * @see #setLink(Link) * @see org.eclipse.bpel.model.BPELPackage#getTarget_Link() * @see org.eclipse.bpel.model.Link#getTargets * @model opposite="targets" required="true" * @generated */ Link getLink(); /** * Sets the value of the '{@link org.eclipse.bpel.model.Target#getLink <em>Link</em>}' reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Link</em>' reference. * @see #getLink() * @generated */ void setLink(Link value); /** * Returns the value of the '<em><b>Activity</b></em>' reference. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Activity</em>' reference isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>Activity</em>' reference. * @see #setActivity(Activity) * @see org.eclipse.bpel.model.BPELPackage#getTarget_Activity() * @model required="true" * @generated */ Activity getActivity(); /** * Sets the value of the '{@link org.eclipse.bpel.model.Target#getActivity <em>Activity</em>}' reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Activity</em>' reference. * @see #getActivity() * @generated */ void setActivity(Activity value); } // Target
30.711111
110
0.643994
99be362c349d75b5dc0013e66f222cba576ecc5a
8,282
package duke.ui.window; import duke.DukeCore; import duke.command.Executor; import duke.command.Parser; import duke.data.Impression; import duke.data.Investigation; import duke.data.Medicine; import duke.data.Observation; import duke.data.Patient; import duke.data.Plan; import duke.data.Result; import duke.data.SearchResults; import duke.data.storage.GsonStorage; import duke.exception.DukeException; import duke.exception.DukeFatalException; import duke.ui.commons.UiElement; import duke.ui.commons.UiStrings; import duke.ui.context.Context; import duke.ui.context.UiContext; import javafx.fxml.FXML; import javafx.scene.control.Tab; import javafx.scene.control.TabPane; import javafx.scene.layout.AnchorPane; import javafx.scene.layout.VBox; import javafx.stage.Stage; import java.util.ArrayList; import static duke.DukeCore.logger; //@@author gowgos5 /** * Main UI window of the application. * This window is the main interface between the user and Dr. Duke. * It also acts as a container for other child UI elements. */ public class MainWindow extends UiElement<Stage> { private static final String FXML = "MainWindow.fxml"; @FXML private TabPane contextWindowHolder; @FXML private AnchorPane commandWindowHolder; @FXML private VBox helpWindowHolder; private Tab currentTab; private ContextWindow currentContextWindow; private CommandWindow commandWindow; private HelpWindow helpWindow; private Stage primaryStage; private DukeCore core; private UiContext uiContext; private ArrayList<Patient> patientList; private Parser parser; private Executor executor; private GsonStorage storage; /** * Constructs the main UI window to house other child UI elements. * * @param primaryStage Main stage of the application. * @param core Core of Dr. Duke. * @throws DukeFatalException If {@code currentContextWindow} fails to initialise / load. */ public MainWindow(Stage primaryStage, DukeCore core) throws DukeFatalException { super(FXML, primaryStage); this.primaryStage = primaryStage; this.core = core; this.uiContext = core.uiContext; this.patientList = core.patientData.getPatientList(); this.parser = new Parser(core.uiContext); this.executor = new Executor(core); this.storage = core.storage; fillWithChildUiElements(); attachListenerToUiContext(); } /** * Shows the main UI window. */ public void show() { primaryStage.show(); } /** * Shows message on the {@code commandWindow}. * * @param message Output message. */ public void showMessage(String message) { commandWindow.print(message); } /** * Updates {@code currentContextWindow} and shows message on the {@code commandWindow}. * * @param message Output message. * @throws DukeFatalException If the {@code currentContextWindow} to be updated cannot be initialised / loaded. */ public void updateUi(String message) throws DukeFatalException { if (currentContextWindow != null) { currentContextWindow.updateUi(); } showMessage(message); } /** * Initialises and places child UI elements in the main UI window. * * @throws DukeFatalException If the {@code currentContextWindow} to be updated cannot be initialised / loaded. */ private void fillWithChildUiElements() throws DukeFatalException { initialiseHelpWindow(); initialiseContextWindow(); initialiseCommandWindow(); } /** * Initialises the help window, {@code helpWindow}. * The help window provides users with real-time visual feedback on the available commands in each context. */ private void initialiseHelpWindow() { logger.info(UiStrings.LOG_INFO_LAUNCH_HELP); try { helpWindow = new HelpWindow(storage, uiContext); helpWindowHolder.getChildren().add(helpWindow.getRoot()); } catch (DukeException e) { showMessage(e.getMessage()); } } /** * Initialises the context window, {@code currentContextWindow}. * The application starts out at the HOME context. * The context window changes according to the current {@code uiContext}. * * @throws DukeFatalException If the {@code currentContextWindow} to be updated cannot be initialised / loaded. * @see #attachListenerToUiContext() */ private void initialiseContextWindow() throws DukeFatalException { logger.info(UiStrings.LOG_INFO_LAUNCH_HOME); currentContextWindow = new HomeContextWindow(patientList); currentTab = new Tab(Context.HOME.toString(), currentContextWindow.getRoot()); contextWindowHolder.getTabs().add(currentTab); } /** * Initialises the command window, {@code commandWindow}. * The command window allows users to interact with the application through the sending of commands. */ private void initialiseCommandWindow() { logger.info(UiStrings.LOG_INFO_LAUNCH_COMMAND); commandWindow = new CommandWindow(parser, executor); commandWindow.attachTextListenerToTextField(helpWindow); commandWindowHolder.getChildren().add(commandWindow.getRoot()); } /** * Attaches a listener to the {@code uiContext}. * This listener listens to changes in the current context and displays the corresponding {@link ContextWindow} * in the {@code contextWindowHolder}. */ private void attachListenerToUiContext() { uiContext.addListener(event -> { logger.info(UiStrings.LOG_INFO_SWITCH_CONTEXT); contextWindowHolder.getTabs().remove(currentTab); Context context = (Context) event.getNewValue(); try { switch (context) { case HOME: currentContextWindow = new HomeContextWindow(patientList); break; case PATIENT: Patient patient = (Patient) uiContext.getObject(); currentContextWindow = new PatientContextWindow(patient); break; case IMPRESSION: Impression impression = (Impression) uiContext.getObject(); currentContextWindow = new ImpressionContextWindow(impression, impression.getParent()); break; case PLAN: Plan plan = (Plan) uiContext.getObject(); currentContextWindow = new PlanContextWindow(plan); break; case INVESTIGATION: Investigation investigation = (Investigation) uiContext.getObject(); currentContextWindow = new InvestigationContextWindow(investigation); break; case OBSERVATION: Observation observation = (Observation) uiContext.getObject(); currentContextWindow = new ObservationContextWindow(observation); break; case RESULT: Result result = (Result) uiContext.getObject(); currentContextWindow = new ResultContextWindow(result); break; case MEDICINE: Medicine medicine = (Medicine) uiContext.getObject(); currentContextWindow = new MedicineContextWindow(medicine); break; case SEARCH: SearchResults searchResults = (SearchResults) uiContext.getObject(); currentContextWindow = new SearchContextWindow(searchResults); break; default: return; } } catch (DukeFatalException e) { core.ui.showErrorDialogAndShutdown(UiStrings.MESSAGE_ERROR_OPEN_CONTEXT, e); } currentTab = new Tab(context.toString(), currentContextWindow.getRoot()); contextWindowHolder.getTabs().add(currentTab); contextWindowHolder.getSelectionModel().select(currentTab); }); } }
36.165939
115
0.648032
d6bfeac60c7c0006b0de8543b970082f074498dd
2,235
/* * 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.servicecomb.swagger.generator.springmvc; import java.lang.reflect.Method; import org.apache.servicecomb.swagger.generator.OperationGenerator; import org.apache.servicecomb.swagger.generator.rest.RestSwaggerGenerator; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PatchMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestMapping; public class SpringmvcSwaggerGenerator extends RestSwaggerGenerator { public SpringmvcSwaggerGenerator(Class<?> cls) { super(cls); } @Override protected boolean isSkipMethod(Method method) { if (super.isSkipMethod(method)) { return true; } return method.getAnnotation(RequestMapping.class) == null && method.getAnnotation(GetMapping.class) == null && method.getAnnotation(PutMapping.class) == null && method.getAnnotation(PostMapping.class) == null && method.getAnnotation(PatchMapping.class) == null && method.getAnnotation(DeleteMapping.class) == null; } @SuppressWarnings("unchecked") @Override public <T extends OperationGenerator> T createOperationGenerator(Method method) { return (T) new SpringmvcOperationGenerator(this, method); } }
39.910714
83
0.76689
8b467e5bdebf667cd477aa64c7f4345d71dac223
3,043
/* * Copyright (c) 2012, Isaiah van der Elst (isaiah.v@comcast.net) * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - 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 org.gearman.impl.util; import java.net.InetSocketAddress; import java.nio.charset.Charset; import java.util.UUID; import org.gearman.context.GearmanContext; import org.gearman.impl.core.GearmanConnection; public class GearmanUtils { public boolean testJDBCConnection(String jdbcDriver, String jdbcConnectionString) { return false; } public boolean testGearmanConnection(InetSocketAddress address) { return false; } public static final String toString(GearmanConnection<?> conn) { if(conn==null) System.out.println("error"); return "["+conn.getHostAddress() + ":" + conn.getPort() +"]"; } public static final byte[] createUID() { return UUID.randomUUID().toString().getBytes(); } public static final String getProjectName() { return GearmanContext.getProperty(GearmanContext.PROPERTY_PROJECT_NAME); } public static final String getVersion() { return GearmanContext.getProperty(GearmanContext.PROPERTY_VERSION); } public static final int getPort() { return (Integer) GearmanContext.getAttribute(GearmanContext.ATTRIBUTE_PORT); } public static final long getThreadTimeout() { return (Long) GearmanContext.getAttribute(GearmanContext.ATTRIBUTE_THREAD_TIMEOUT); } public static final int getWorkerThreads() { return (Integer) GearmanContext.getAttribute(GearmanContext.ATTRIBUTE_WORKER_THREADS); } public static final Charset getCharset() { return (Charset) GearmanContext.getAttribute(GearmanContext.ATTRIBUTE_CHARSET); } public static final String getJobHandlePrefix() { return GearmanContext.getProperty(GearmanContext.PROPERTY_JOB_HANDLE_PREFIX); } }
35.8
88
0.769964
72e0e589d4cd223261fc1f562d599489c3f2fc31
1,481
package com.asche.wetalk.other; import com.asche.wetalk.entity.Logger; import com.asche.wetalk.mapper.LoggerMapper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.servlet.HandlerInterceptor; import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.text.SimpleDateFormat; import java.util.Date; public class LoggerInterceptor implements HandlerInterceptor { @Autowired private LoggerMapper loggerMapper; @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String time = format.format(new Date()); Logger logger = new Logger(); logger.setIp(request.getRemoteAddr()); logger.setTime(time); logger.setType(request.getMethod()); logger.setUri(request.getRequestURI()); logger.setArgs(request.getQueryString()); loggerMapper.add(logger); return true; } @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { } @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { } }
32.911111
146
0.755571
cacdef60978568c8f2d34f0f5b66685eba6e20c0
995
/* $Id: //depot/External Projects/i9500/Implementation/Source/bgxop/main/modules/gui/src/java/net/bgx/bgxnetwork/bgxop/gui/lv/timetable/timedia/model/test/TestDataTDPair.java#1 $ $DateTime: 2007/07/04 14:49:50 $ $Change: 19371 $ $Author: O.Lukashevich $ */ package net.bgx.bgxnetwork.transfer.tt; import java.util.List; import java.io.Serializable; public class TestDataTDPair implements TDPair, Serializable { private TDObject objectOne = null; private TDObject objectTwo = null; private List<TDLink> links = null; public TestDataTDPair(TDObject objectOne, TDObject objectTwo) { this.objectOne = objectOne; this.objectTwo = objectTwo; } public TDObject getObjectOne() { return objectOne; } public TDObject getObjectTwo() { return objectTwo; } public List<TDLink> getLinks() { return links; } public void setLinks(List<TDLink> links) { this.links = links; } }
30.151515
176
0.670352
ab7e2c4ab78ddd37123553608aa50e705d7eff36
747
package com.stylefeng.guns.modular.system.dao; import com.baomidou.mybatisplus.plugins.Page; import com.stylefeng.guns.modular.system.model.Order; import com.baomidou.mybatisplus.mapper.BaseMapper; import java.util.List; import java.util.Map; /** * <p> * 订单 Mapper 接口 * </p> * * @author simple.song * @since 2018-10-18 */ public interface OrderMapper extends BaseMapper<Order> { /** * 订单查询 * * @param queryParams * @return */ List<Map<String,Object>> queryForList(Map<String, Object> queryParams); /** * 分页查询 * * @param page * @param arguments * @return */ List<Map<String, Object>> selectPageList(Page<Map<String, Object>> page, Map<String, Object> arguments); }
20.189189
108
0.651941
f531e0f07e13f4e77c1595ddb21c786dde3a25c3
3,020
/* * The MIT License * * Copyright 2015 Neil McAlister. * * 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 sonicScream.utilities; public class Constants { //Navigation enum public enum navigationSource {UNSET, STARTUP, MAIN} //-------Category names------- public static final String CATEGORY_HEROES = "Heroes"; public static final String CATEGORY_ITEMS = "Items"; public static final String CATEGORY_MUSIC = "Music"; public static final String CATEGORY_VOICES = "Voices"; //-------Settings file & folder names------- public static final String SETTINGS_FILE_NAME = "settings.xml"; public static final String CRC_CACHE_FILE_NAME = "crcs.xml"; public static final String PROFILE_FILE_SUFFIX = "profile.xml"; public static final String PROFILES_DIRECTORY = "profiles"; //-------Settings keys------- public static final String SETTING_MAIN_VPK_PATH = "mainVPKPathSetting"; public static final String SETTING_MAIN_VPK_DIR = "mainVPKDirSetting"; public static final String SETTING_ADDON_PATH = "addonPath"; public static final String SETTING_ACTIVE_PROFILE ="activeProfile"; public static final String SETTING_PREVIOUS_SOUND_DIRECTORY = "previousSoundDirectory"; //-------Standard VPK paths------ public static final String HERO_SPELLS_SCRIPTS_VPK_PATH = "soundevents/game_sounds_heroes/"; public static final String ITEMS_SCRIPTS_VPK_PATH = "soundevents/game_sounds_items.vsndevts_c"; public static final String VOICE_SCRIPTS_VPK_PATH = "soundevents/voscripts/"; //Music public static final String MUSIC_DEFAULT_SCRIPTS_VPK_PATH = "soundevents/music/valve_dota_001/"; public static final String MUSIC_TI4_SCRIPTS_VPK_PATH = "soundevents/music/valve_ti4/"; public static final String MUSIC_TI5_SCRIPTS_VPK_PATH = "soundevents/music/valve_ti5/"; //TODO add custom music packs? }
48.709677
101
0.728477
8ef4295e2d268bf7c861d18ebafcf633501a7f66
425
/* * 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 ed.biodare2.backend.util.concurrent.id.db; import org.springframework.data.jpa.repository.JpaRepository; /** * * @author Zielu */ public interface LongRecordRep extends JpaRepository<LongRecord,String> { }
25
80
0.724706
3dfd1886a7122cd2a915654dbe19cf28b6012735
3,503
/******************************************************************************* * Copyright (c) 2004 Actuate Corporation . * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Actuate Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.birt.report.designer.core.util.mediator.request; import java.util.ArrayList; import java.util.List; import java.util.Map; import org.eclipse.birt.report.designer.core.mediator.IMediatorRequest; import org.eclipse.gef.Request; /** * An Object used to communicate with Views. Request encapsulates the * information views need to perform various functions. Requests are used for * obtaining selection, and performing generic operations. */ public class ReportRequest extends Request implements IMediatorRequest, ReportRequestConstants { private Object source; private IRequestConverter converter; private List selectionObject = new ArrayList( ); /** * Create a report request. */ public ReportRequest( ) { this( null, SELECTION ); } public ReportRequest( String type ) { this( null, type ); } /** * Create a report request with give source object. * * @param source */ public ReportRequest( Object source ) { this( source, SELECTION ); } public ReportRequest( Object source, String type ) { super( ); setSource( source ); setType( type ); } /** * Get the source of request. * * @return Returns the source. */ public Object getSource( ) { return source; } /** * Set the source of request. * * @param source * The source to set. */ public void setSource( Object source ) { this.source = source; } /** * Get the selection objcect of request source. * * @return Returns the selectionObject. */ public List getSelectionObject( ) { return selectionObject; } /** * Get the selection objcect of request source. * * @return Returns the selectionObject. */ public List getSelectionModelList( ) { if ( converter != null ) { return converter.convertSelectionToModelLisr( getSelectionObject( ) ); } return getSelectionObject( ); } /** * Set the selection object of reqeust source * * @param selectionObject * The selectionObject to set. */ public void setSelectionObject( List selectionObject ) { assert selectionObject != null; this.selectionObject = selectionObject; } /** * @return Returns the request converter. */ public IRequestConverter getRequestConverter( ) { return converter; } /** * @param convert * The converter to set. * * @deprecated use {@link #setRequestConverter(IRequestConverter)} instead. */ public void setRequestConvert( IRequestConvert converter ) { this.converter = converter; } /** * @param convert * The converter to set. */ public void setRequestConverter( IRequestConverter converter ) { this.converter = converter; } public String getType( ) { return String.valueOf( super.getType( ) ); } public Object getData( ) { return getSelectionModelList( ); } public boolean isSticky( ) { return SELECTION.equals( getType( ) ); } public Map<?, ?> getExtras( ) { return null; } }
20.248555
81
0.655724