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
81d90e707ebd82439e722f132b02502e81506917
212
/** * @author Aleksey Terzi * */ package com.aleksey.castlegates.database; public class LinkInfo { public int link_id; public Integer gearblock1_id; public Integer gearblock2_id; public byte[] blocks; }
15.142857
41
0.740566
6180d90c2dae33ae1babce23627cb6e88f54c2f0
2,179
package it.unibz.inf.ontop.answering.resultset.impl; import com.google.common.collect.ImmutableList; import it.unibz.inf.ontop.answering.resultset.OntopBinding; import it.unibz.inf.ontop.answering.resultset.OntopBindingSet; import it.unibz.inf.ontop.model.term.RDFConstant; import it.unibz.inf.ontop.utils.ImmutableCollectors; import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.util.Iterator; import java.util.LinkedHashMap; import static java.util.stream.Collectors.joining; public abstract class AbstractOntopBindingSet implements OntopBindingSet { //LinkedHashMap to preserve variable ordering private final LinkedHashMap<String, OntopBinding> bindingMap; AbstractOntopBindingSet(LinkedHashMap<String, OntopBinding> bindingMap) { this.bindingMap = bindingMap; } @Override @Nonnull public Iterator<OntopBinding> iterator() { return getBindings().iterator(); } @Override public ImmutableList<OntopBinding> getBindings() { return bindingMap.values().stream() .collect(ImmutableCollectors.toList()); } @Override public ImmutableList<RDFConstant> getValues() { return bindingMap.values().stream() .map(OntopBinding::getValue) .collect(ImmutableCollectors.toList()); } @Override public ImmutableList<String> getBindingNames() { return bindingMap.keySet().stream() .collect(ImmutableCollectors.toList()); } @Nullable @Override public RDFConstant getConstant(String name) { OntopBinding binding = bindingMap.get(name); return (binding == null) ? null : binding.getValue(); } @Override public String toString() { return getBindings().stream() .map(OntopBinding::toString) .collect(joining(",", "[", "]")); } @Override public boolean hasBinding(String bindingName) { return bindingMap.containsKey(bindingName); } @Override @Nullable public OntopBinding getBinding(String name) { return bindingMap.get(name); } }
28.298701
77
0.67508
d1865b1c5748a39b8f2b086fbb14e50400d1d7aa
4,615
package edu.umich.mlib; import java.awt.*; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import javax.imageio.ImageIO; /** * This program demonstrates how to resize an image. * * @author www.codejava.net * */ public class ImageResizer { /** * Resizes an image to a absolute width and height (the image may not be * proportional) * @param inputImagePath Path of the original image * @param outputImagePath Path to save the resized image * @param scaledWidth absolute width in pixels * @param scaledHeight absolute height in pixels * @throws IOException */ public static void resize(String inputImagePath, String outputImagePath, int scaledWidth, int scaledHeight) throws IOException { // reads input image File inputFile = new File(inputImagePath); BufferedImage inputImage = ImageIO.read(inputFile); // creates output image BufferedImage outputImage = new BufferedImage(scaledWidth, scaledHeight, inputImage.getType()); // scales the input image to the output image Graphics2D g2d = outputImage.createGraphics(); g2d.setComposite(AlphaComposite.Src); g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION,RenderingHints.VALUE_INTERPOLATION_BILINEAR); g2d.setRenderingHint(RenderingHints.KEY_RENDERING,RenderingHints.VALUE_RENDER_QUALITY); g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON); g2d.drawImage(inputImage, 0, 0, scaledWidth, scaledHeight, null); g2d.dispose(); // extracts extension of output file String formatName = outputImagePath.substring(outputImagePath .lastIndexOf(".") + 1); // writes to output file ImageIO.write(outputImage, formatName, new File(outputImagePath)); } /** * Resizes an image by a percentage of original size (proportional). * @param inputImagePath Path of the original image * @param outputImagePath Path to save the resized image * @param percent a double number specifies percentage of the output image * over the input image. * @throws IOException */ public static void resize(String inputImagePath, String outputImagePath, double percent) throws IOException { File inputFile = new File(inputImagePath); BufferedImage inputImage = ImageIO.read(inputFile); int scaledWidth = (int) (inputImage.getWidth() * percent); int scaledHeight = (int) (inputImage.getHeight() * percent); resize(inputImagePath, outputImagePath, scaledWidth, scaledHeight); } /** * Resizes an image to a absolute width and height (the image may not be * proportional) * @param inputImage Loaded original image * @param outputImagePath Path to save the resized image * @param scaledWidth absolute width in pixels * @param scaledHeight absolute height in pixels * @throws IOException */ public static void resize(BufferedImage inputImage, String outputImagePath, int scaledWidth, int scaledHeight) throws IOException { // creates output image BufferedImage outputImage = new BufferedImage(scaledWidth, scaledHeight, inputImage.getType()); // scales the input image to the output image Graphics2D g2d = outputImage.createGraphics(); g2d.drawImage(inputImage, 0, 0, scaledWidth, scaledHeight, null); g2d.dispose(); // extracts extension of output file String formatName = outputImagePath.substring(outputImagePath .lastIndexOf(".") + 1); // writes to output file ImageIO.write(outputImage, formatName, new File(outputImagePath)); } /** * Resizes an image by a percentage of original size (proportional). * @param inputImage Loaded original image * @param outputImagePath Path to save the resized image * @param percent a double number specifies percentage of the output image * over the input image. * @throws IOException */ public static void resize(BufferedImage inputImage, String outputImagePath, double percent) throws IOException { int scaledWidth = (int) (inputImage.getWidth() * percent); int scaledHeight = (int) (inputImage.getHeight() * percent); resize(inputImage, outputImagePath, scaledWidth, scaledHeight); } }
39.444444
107
0.672806
b924e4f954cc805c4ead432d6342667ddfb7c63d
503
class Logging{ //Final Static private obj private static final Logging SingleInstance = new Logging(); /*Private constructor*/ private Logging(){ System.out.println("Private Constructor"); } //Accesor Method for private obj public static Logging getSingleInstance(){ return SingleInstance; } public void log(String msg){ System.out.println(msg); } } class runner{ public static void main(String[] args){ //Using directly class name Logging.getSingleInstance().log("LOL"); } }
19.346154
61
0.723658
f0898ee8ff3756651b0f9e574c74ba53675c9ffb
379
package com.linln.modules.system.service; import java.lang.annotation.*; import static java.lang.annotation.RetentionPolicy.RUNTIME; @Documented//说明该注解将被包含在javadoc中 @Target({ElementType.METHOD, ElementType.TYPE})//目标下的方法和类型 @Retention(RUNTIME)// 注解会在class字节码文件中存在,在运行时可以通过反射获取到 @Inherited//说明子类可以继承父类中的该注解 // public @interface DoneTime { String param() default ""; }
27.071429
59
0.783641
4e18024da7acaad96e1e9219a4e8c1b5a02c79e2
11,781
/** * This package provides classes to facilitate the handling of opengl textures and glsl shaders in Processing. * @author Andres Colubri * @version 0.6.5 * * Copyright (c) 2008 Andres Colubri * * This source is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This code is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * A copy of the GNU General Public License is available on the World * Wide Web at <http://www.gnu.org/copyleft/gpl.html>. You can also * obtain it by writing to the Free Software Foundation, * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ package codeanticode.gltexture; import processing.core.*; import processing.opengl.*; import javax.media.opengl.*; import com.sun.opengl.util.*; import java.nio.*; // Changes: // Renamed to GLTexture. // Fixed bug in putImage where height was compared to img.width. // Added putPixelsIntoTexture and putPixels methods. // Added comments.// // ToDo: // Color texture using tint color in renderTexture method. // Add support for rectangular textures, mipmapping, etc. // Test compatiliby of texture usage with normal processing operation. /** * This class adds an opengl texture to a PImage object. The texture is handled in a similar way to the * pixels property: image data can be copied to and from the texture using loadTexture and updateTexture methods. * However, bringing the texture down to image or pixels data can slow down the application considerably (since * involves copying texture data from GPU to CPU), especially when handling large textures. So it is recommended * to do all the texture handling without calling updateTexture, and doing so only at the end if the texture * is needed as a regular image. */ public class GLTexture extends PImage implements PConstants { /** * Creates an instance of GLTexture with size 1x1. The texture is not initialized. * @param parent PApplet */ public GLTexture(PApplet parent) { super(1, 1, ARGB); this.parent = parent; pgl = (PGraphicsOpenGL)parent.g; gl = pgl.gl; glstate = new GLState(gl); } /** * Creates an instance of GLTexture with size width x height. The texture is initialized (empty) to that size. * @param parent PApplet * @param width int * @param height int */ public GLTexture(PApplet parent, int width, int height) { super(width, height, ARGB); this.parent = parent; pgl = (PGraphicsOpenGL)parent.g; gl = pgl.gl; glstate = new GLState(gl); initTexture(width, height); } /** * Creates an instance of GLTexture using image file filename as source. * @param filename String */ public GLTexture(PApplet parent, String filename) { super(1, 1, ARGB); this.parent = parent; pgl = (PGraphicsOpenGL)parent.g; gl = pgl.gl; glstate = new GLState(gl); loadTexture(filename); } /** * Sets the size of the image and texture to width x height. If the texture is already initialized, * it first destroys the current opengl texture object and then creates a new one with the specified * size. * @param width int * @param height int */ public void init(int width, int height) { init(width, height, ARGB); initTexture(width, height); } /** * Returns true if the texture has been initialized. * @return boolean */ public boolean available() { return 0 < tex[0]; } /** * Provides the ID of the opegl texture object. * @return int */ public int getTextureID() { return tex[0]; } /** * Returns the texture target. * @return int */ public int getTextureTarget() { // Only 2D textures for now... return GL.GL_TEXTURE_2D; } /** * Puts img into texture, pixels and image. * @param img PImage */ public void putImage(PImage img) { img.loadPixels(); if ((img.width != width) || (img.height != height)) { init(img.width, img.height); } // Putting img into pixels... parent.arraycopy(img.pixels, pixels); // ...into texture... loadTexture(); // ...and into image. updatePixels(); } /** * Puts pixels of img into texture only. * @param img PImage */ public void putPixelsIntoTexture(PImage img) { if ((img.width != width) || (img.height != height)) { init(img.width, img.height); } // Putting into texture. putPixels(img.pixels); } /** * Copies texture to img. * @param img PImage */ public void getImage(PImage img) { int w = width; int h = height; if ((img.width != w) || (img.height != h)) { img.init(w, h, ARGB); } IntBuffer buffer = BufferUtil.newIntBuffer(w * h * 4); gl.glBindTexture(GL.GL_TEXTURE_2D, tex[0]); gl.glGetTexImage(GL.GL_TEXTURE_2D, 0, GL.GL_BGRA, GL.GL_UNSIGNED_BYTE, buffer); gl.glBindTexture(GL.GL_TEXTURE_2D, 0); buffer.get(img.pixels); img.updatePixels(); } /** * Load texture, pixels and image from file. * @param filename String */ public void loadTexture(String filename) { PImage img = parent.loadImage(filename); putImage(img); } /** * Copy pixels to texture (loadPixels should have been called beforehand). */ public void loadTexture() { putPixels(pixels); } /** * Copy texture to pixels (doesn't call updatePixels). */ public void updateTexture() { IntBuffer buffer = BufferUtil.newIntBuffer(width * height * 4); gl.glBindTexture(GL.GL_TEXTURE_2D, tex[0]); gl.glGetTexImage(GL.GL_TEXTURE_2D, 0, GL.GL_BGRA, GL.GL_UNSIGNED_BYTE, buffer); gl.glBindTexture(GL.GL_TEXTURE_2D, 0); buffer.get(pixels); } /** * Applies filter texFilter using this texture as source and destTex as destination. */ public void filter(GLTextureFilter texFilter, GLTexture destTex) { texFilter.apply(new GLTexture[] { this }, new GLTexture[] { destTex }); } /** * Applies filter texFilter using this texture as source and destTex as multiple destinations. */ public void filter(GLTextureFilter texFilter, GLTexture[] destTexArray) { texFilter.apply(new GLTexture[] { this }, destTexArray); } /** * Applies filter texFilter using this texture as source, destTex as destination and params as the * parameters for the filter. */ public void filter(GLTextureFilter texFilter, GLTexture destTex, GLTextureFilterParams params) { texFilter.apply(new GLTexture[] { this }, new GLTexture[] { destTex }, params); } /** * Applies filter texFilter using this texture as source, destTex as multiple destinations and params as the * parameters for the filter. */ public void filter(GLTextureFilter texFilter, GLTexture[] destTexArray, GLTextureFilterParams params) { texFilter.apply(new GLTexture[] { this }, destTexArray, params); } /** * Draws the texture using the opengl commands, inside a rectangle located at the origin with the original * size of the texture. */ public void renderTexture() { renderTexture(0, 0, width, height); } /** * Draws the texture using the opengl commands, inside a rectangle located at (x,y) with the original * size of the texture. * @param x float * @param y float */ public void renderTexture(float x, float y) { renderTexture(x, y, width, height); } /** * Draws the texture using the opengl commands, inside a rectangle of width w and height h * located at (x,y). * @param x float * @param y float * @param w float * @param h float */ public void renderTexture(float x, float y, float w, float h) { pgl.beginGL(); int pw = parent.width; int ph = parent.height; glstate.saveGLState(); glstate.setOrthographicView(pw, ph); gl.glEnable(GL.GL_TEXTURE_2D); gl.glActiveTexture(GL.GL_TEXTURE0); gl.glBindTexture(GL.GL_TEXTURE_2D, tex[0]); // set tint color?? gl.glColor4f(1.0f, 1.0f, 1.0f, 1.0f); gl.glBegin(GL.GL_QUADS); gl.glTexCoord2f(0.0f, 0.0f); gl.glVertex2f(x, ph - y); gl.glTexCoord2f(1.0f, 0.0f); gl.glVertex2f(x + w, ph - y); gl.glTexCoord2f(1.0f, 1.0f); gl.glVertex2f(x + w, ph - (y + h)); gl.glTexCoord2f(0.0f, 1.0f); gl.glVertex2f(x, ph - (y + h)); gl.glEnd(); gl.glBindTexture(GL.GL_TEXTURE_2D, 0); glstate.restoreGLState(); pgl.endGL(); } /** * @invisible * Creates the opengl texture object. * @param w int * @param h int */ protected void initTexture(int w, int h) { if (tex[0] != 0) { releaseTexture(); } gl.glGenTextures(1, tex, 0); gl.glBindTexture(GL.GL_TEXTURE_2D, tex[0]); gl.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MIN_FILTER, GL.GL_NEAREST); gl.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MAG_FILTER, GL.GL_NEAREST); gl.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_WRAP_S, GL.GL_CLAMP); gl.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_WRAP_T, GL.GL_CLAMP); gl.glTexImage2D(GL.GL_TEXTURE_2D, 0, GL.GL_RGBA, w, h, 0, GL.GL_BGRA, GL.GL_UNSIGNED_BYTE, null); gl.glBindTexture(GL.GL_TEXTURE_2D, 0); } /** * @invisible * Deletes the opengl texture object. */ protected void releaseTexture() { gl.glDeleteTextures(1, tex, 0); tex[0] = 0; } /** * @invisible * Copies pix into the texture. * @param pix int[] */ public void putPixels(int[] pix) { if (tex[0] == 0) { initTexture(width, height); } gl.glBindTexture(GL.GL_TEXTURE_2D, tex[0]); gl.glTexSubImage2D(GL.GL_TEXTURE_2D, 0, 0, 0, width, height, GL.GL_BGRA, GL.GL_UNSIGNED_BYTE, IntBuffer.wrap(pix)); gl.glBindTexture(GL.GL_TEXTURE_2D, 0); } /** * @invisible */ protected GL gl; /** * @invisible */ protected PGraphicsOpenGL pgl; /** * @invisible */ protected int[] tex = { 0 }; /** * @invisible */ protected GLState glstate; }
29.233251
124
0.579577
84b2ad6ef0043964aed0eb0f1771151e4ecba9f2
999
package seedu.moolah.testutil; import seedu.moolah.model.MooLah; import seedu.moolah.model.event.Event; import seedu.moolah.model.expense.Expense; /** * A utility class to help with building MooLah objects. * Example usage: <br> * {@code MooLah ab = new MooLahBuilder().withExpense("John", "Doe").build();} */ public class MooLahBuilder { private MooLah mooLah; public MooLahBuilder() { mooLah = new MooLah(); } public MooLahBuilder(MooLah mooLah) { this.mooLah = mooLah; } /** * Adds a new {@code Expense} to the {@code MooLah} that we are building. */ public MooLahBuilder withExpense(Expense expense) { mooLah.addExpense(expense); return this; } /** * Adds a new {@code Event} to the {@code MooLah} that we are building. */ public MooLahBuilder withEvent(Event event) { mooLah.addEvent(event); return this; } public MooLah build() { return mooLah; } }
22.704545
82
0.628629
84f96cba65c977e41233a94464b703abfa99a6fa
1,517
package com.hbm.items.machine; import java.util.List; import com.hbm.items.ModItems; import com.hbm.main.MainRegistry; import net.minecraft.client.util.ITooltipFlag; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.world.World; public class ItemStamp extends Item { public ItemStamp(String s, int dura) { this.setUnlocalizedName(s); this.setRegistryName(s); this.setMaxDamage(dura); this.setCreativeTab(MainRegistry.controlTab); this.setMaxStackSize(1); ModItems.ALL_ITEMS.add(this); } @Override public void addInformation(ItemStack stack, World worldIn, List<String> tooltip, ITooltipFlag flagIn) { if(this == ModItems.stamp_iron_circuit || this == ModItems.stamp_iron_plate || this == ModItems.stamp_iron_wire || this == ModItems.stamp_obsidian_circuit || this == ModItems.stamp_obsidian_plate || this == ModItems.stamp_obsidian_wire || this == ModItems.stamp_schrabidium_circuit || this == ModItems.stamp_schrabidium_plate || this == ModItems.stamp_schrabidium_wire || this == ModItems.stamp_steel_circuit || this == ModItems.stamp_steel_plate || this == ModItems.stamp_steel_wire || this == ModItems.stamp_titanium_circuit || this == ModItems.stamp_titanium_plate || this == ModItems.stamp_titanium_wire || this == ModItems.stamp_stone_circuit || this == ModItems.stamp_stone_plate || this == ModItems.stamp_stone_wire) tooltip.add("[CREATED USING TEMPLATE FOLDER]"); } }
31.604167
104
0.738299
fd1379060c3f0e08d5419e4c52d6ec9cba537485
7,961
package iudx.gis.server.cache; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.Mockito.mock; import io.vertx.core.Vertx; import io.vertx.core.cli.annotations.Description; import io.vertx.core.json.JsonObject; import io.vertx.junit5.VertxExtension; import io.vertx.junit5.VertxTestContext; import iudx.gis.server.cache.cacheImpl.CacheType; import iudx.gis.server.database.postgres.PostgresService; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.MethodOrderer.OrderAnnotation; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.TestMethodOrder; import org.junit.jupiter.api.extension.ExtendWith; @ExtendWith({VertxExtension.class}) @TestMethodOrder(OrderAnnotation.class) public class CacheServiceTest { private static final Logger LOGGER = LogManager.getLogger(CacheServiceTest.class); static CacheService cacheService; static PostgresService pgService; static JsonObject testJson_0 = new JsonObject() .put("type", CacheType.REVOKED_CLIENT) .put("key", "revoked_client_id_0") .put("value", "2020-10-18T14:20:00Z"); static JsonObject testJson_1 = new JsonObject() .put("type", CacheType.REVOKED_CLIENT) .put("key", "revoked_client_id_1") .put("value", "2020-10-19T14:20:00Z"); @BeforeAll public static void setup(Vertx vertx, VertxTestContext testContext) { pgService = mock(PostgresService.class); cacheService = new CacheServiceImpl(vertx, pgService); testContext.completeNow(); } @Test public void cachePutTest(Vertx vertx, VertxTestContext testContext) { cacheService.put( testJson_0, handler -> { if (handler.succeeded()) { testContext.completeNow(); } else { testContext.failNow("failed to insert in cache"); } }); } @Test public void cachePutTest2(Vertx vertx, VertxTestContext testContext) { cacheService.put( testJson_1, handler -> { if (handler.succeeded()) { testContext.completeNow(); } else { testContext.failNow("failed to insert in cache"); } }); } @Description("fail for no type present in json request") @Test public void failCachePutTestNoType(Vertx vertx, VertxTestContext testContext) { JsonObject json = testJson_0.copy(); json.remove("type"); cacheService.put( json, handler -> { if (handler.succeeded()) { testContext.failNow("failed - inserted in cache for no type"); } else { testContext.completeNow(); } }); } @Description("fail for invalid type present in json request") @Test public void failCachePutTestInvalidType(Vertx vertx, VertxTestContext testContext) { JsonObject json = testJson_0.copy(); json.put("type", "invalid_cache_type"); cacheService.put( json, handler -> { if (handler.succeeded()) { testContext.failNow("failed - inserted in cache for no type"); } else { testContext.completeNow(); } }); } @Description("fail for no key present in json request") @Test public void failCachePutTestNoKey(Vertx vertx, VertxTestContext testContext) { JsonObject json = testJson_0.copy(); json.remove("key"); cacheService.put( json, handler -> { if (handler.succeeded()) { testContext.failNow("failed - inserted in cache for no key"); } else { testContext.completeNow(); } }); } @Description("fail for no value present in json request") @Test public void failCachePutTestNoValue(Vertx vertx, VertxTestContext testContext) { JsonObject json = testJson_0.copy(); json.remove("value"); cacheService.put( json, handler -> { if (handler.succeeded()) { testContext.failNow("failed - inserted in cache for no value"); } else { testContext.completeNow(); } }); } @Test public void getValueFromCache(Vertx vertx, VertxTestContext testContext) { JsonObject json = testJson_0.copy(); json.remove("value"); cacheService.put(testJson_0, handler -> {}); cacheService.get( json, handler -> { if (handler.succeeded()) { JsonObject resultJson = handler.result(); assertTrue(resultJson.containsKey("value")); assertEquals(testJson_0.getString("value"), resultJson.getString("value")); testContext.completeNow(); } else { testContext.failNow("no value returned for known key value."); } }); } @Test public void getValueFromCache2(Vertx vertx, VertxTestContext testContext) { JsonObject json = testJson_1.copy(); json.remove("value"); cacheService.put(testJson_1, handler -> {}); cacheService.get( json, handler -> { if (handler.succeeded()) { JsonObject resultJson = handler.result(); assertTrue(resultJson.containsKey("value")); assertEquals(testJson_1.getString("value"), resultJson.getString("value")); testContext.completeNow(); } else { testContext.failNow("no value returned for known key value."); } }); } @Description("fail - get cahce for no type") @Test public void failGetValueFromCacheNoType(Vertx vertx, VertxTestContext testContext) { JsonObject json = testJson_1.copy(); json.remove("type"); cacheService.get( json, handler -> { if (handler.succeeded()) { testContext.failNow("get operation succeeded for no type in request"); } else { testContext.completeNow(); } }); } @Description("fail - get cache for invalid(null)") @Test public void failGetValueFromCacheInvalidKey(Vertx vertx, VertxTestContext testContext) { JsonObject json = testJson_1.copy(); json.remove("key"); cacheService.get( json, handler -> { if (handler.succeeded()) { testContext.failNow("get operation succeeded for invalid(null) in request"); } else { testContext.completeNow(); } }); } @Description("fail - get cache for key not in cache") @Test public void failGetValueFromCacheNoKey(Vertx vertx, VertxTestContext testContext) { JsonObject json = testJson_1.copy(); json.put("key", "123"); cacheService.get( json, handler -> { if (handler.succeeded()) { testContext.failNow("get operation succeeded for key not in cache"); } else { testContext.completeNow(); } }); } @Description("refresh cache passing key and value") @Test public void refreshCacheTest(Vertx vertx, VertxTestContext testContext) { cacheService.refresh( testJson_0, handler -> { if (handler.succeeded()) { testContext.completeNow(); JsonObject json = testJson_0.copy(); json.remove("value"); cacheService.get( json, getHandler -> { if (getHandler.succeeded()) { assertEquals( testJson_0.getString("value"), getHandler.result().getString("value")); testContext.completeNow(); } else { testContext.failNow("fail to fetch value for key"); } }); } else { testContext.failNow("fail to refresh cache"); } }); } }
30.619231
95
0.612863
2d7f1338f7249e8bbb7db450eb4f50c312791e98
8,574
package xyz.redtorch.utils; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.text.ParseException; import java.util.Date; import org.bson.Document; import org.joda.time.DateTime; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * @author sun0x00@gmail.com */ public class MongoDBUtil { private static Logger log = LoggerFactory.getLogger(MongoDBUtil.class); /** * 将实体Bean对象转换成Mongo Document * * @param bean * @return * @throws IllegalArgumentException * @throws IllegalAccessException */ public static <T> Document beanToDocument(T bean) throws IllegalArgumentException, IllegalAccessException { if (bean == null) { return null; } Document document = new Document(); // 获取对象类的属性域 Field[] fields = bean.getClass().getDeclaredFields(); for (Field field : fields) { // 获取变量的属性名 String varName = field.getName(); // 修改访问控制权限 boolean accessFlag = field.isAccessible(); if (!accessFlag) { field.setAccessible(true); } Object param = field.get(bean); if (param == null || "serialVersionUID".equals(field.getName())) { continue; } else if (param instanceof Integer) { // 判断变量的类型 int value = ((Integer) param).intValue(); document.put(varName, value); } else if (param instanceof String) { String value = (String) param; document.put(varName, value); } else if (param instanceof Double) { double value = ((Double) param).doubleValue(); document.put(varName, value); } else if (param instanceof Float) { float value = ((Float) param).floatValue(); document.put(varName, value); } else if (param instanceof Long) { long value = ((Long) param).longValue(); document.put(varName, value); } else if (param instanceof Boolean) { boolean value = ((Boolean) param).booleanValue(); document.put(varName, value); } else if (param instanceof Date) { Date value = (Date) param; document.put(varName, value); } else if (param instanceof DateTime) { DateTime dataTimeValue = (DateTime) param; Date value = dataTimeValue.toDate(); document.put(varName, value); } // 恢复访问控制权限 field.setAccessible(accessFlag); } return document; } /** * 将Mongo Document转换成Bean对象 * * @param document * @param bean * @return * @throws IllegalAccessException * @throws InvocationTargetException * @throws NoSuchMethodException */ public static <T> T documentToBean(Document document, T bean) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { if (bean == null) { return null; } Field[] fields = bean.getClass().getDeclaredFields(); for (Field field : fields) { String varName = field.getName(); Object object = document.get(varName); if (object != null) { // BeanUtils.setProperty(bean, varName, object); setProperty(bean, varName, object); } } return bean; } /** * 针对MongoDB设计的通过反射对成员变量赋值 * * @param bean * 需要赋值的Class * @param varName * 属性名称 * @param object * 值 */ public static <T> void setProperty(T bean, String varName, T object) { String upperCaseVarName = varName.substring(0, 1).toUpperCase() + varName.substring(1); try { // 获取变量类型 //String type = object.getClass().getName(); if(bean.getClass().getDeclaredField(varName) == null) { log.error("Class-{}中无法找到对应成员变量{}",bean.getClass().getName(),varName); return; } String type = bean.getClass().getDeclaredField(varName).getType().getName(); String objectType = object.getClass().getName(); // 类型为String if (type.equals("java.lang.String")) { Method m = bean.getClass().getMethod("set" + upperCaseVarName, String.class); if(objectType.equals("java.lang.String")) { m.invoke(bean, object); }else{ log.debug("Class-{}中成员变量{}的类型{}与当前值的类型{}不匹配,将尝试转换,可能丢失精度、溢出或出错",bean.getClass().getName(),varName,type,objectType); try { String castingObject = object.toString(); m.invoke(bean, castingObject); } catch (Exception e) { log.error("Class-{}中成员变量{}的类型{}与当前值的类型{}不匹配,强制转换出错",bean.getClass().getName(),varName,type,objectType); } } } else if (type.equals("java.lang.Integer")) { // 类型为Integer Method m = bean.getClass().getMethod("set" + upperCaseVarName, Integer.class); if(objectType.equals("java.lang.Integer")) { m.invoke(bean, object); }else{ log.debug("Class-{}中成员变量{}的类型{}与当前值的类型{}不匹配,将尝试转换,可能丢失精度、溢出或出错",bean.getClass().getName(),varName,type,objectType); try { Integer castingObject = Integer.valueOf(object.toString()); m.invoke(bean, castingObject); } catch (Exception e) { log.error("Class-{}中成员变量{}的类型{}与当前值的类型{}不匹配,强制转换出错",bean.getClass().getName(),varName,type,objectType); } } } else if (type.equals("java.lang.Boolean")) {// 类型为Boolean Method m = bean.getClass().getMethod("set" + upperCaseVarName, Boolean.class); if(objectType.equals("java.lang.Boolean")) { m.invoke(bean, object); }else{ log.debug("Class-{}中成员变量{}的类型{}与当前值的类型{}不匹配,将尝试转换,可能丢失精度、溢出或出错",bean.getClass().getName(),varName,type,objectType); try { Boolean castingObject = Boolean.valueOf(object.toString()); m.invoke(bean, castingObject); } catch (Exception e) { log.error("Class-{}中成员变量{}的类型{}与当前值的类型{}不匹配,强制转换出错",bean.getClass().getName(),varName,type,objectType); } } } else if (type.equals("java.lang.Long")) { // 类型为Long Method m = bean.getClass().getMethod("set" + upperCaseVarName, Long.class); if(objectType.equals("java.lang.Long")) { m.invoke(bean, object); }else{ log.debug("Class-{}中成员变量{}的类型{}与当前值的类型{}不匹配,将尝试转换,可能丢失精度、溢出或出错",bean.getClass().getName(),varName,type,objectType); try { Long castingObject = Long.valueOf(object.toString()); m.invoke(bean, castingObject); } catch (Exception e) { log.error("Class-{}中成员变量{}的类型{}与当前值的类型{}不匹配,强制转换出错",bean.getClass().getName(),varName,type,objectType); } } } else if (type.equals("java.lang.Float")) {// 类型为Float Method m = bean.getClass().getMethod("set" + upperCaseVarName, Float.class); if(objectType.equals("java.lang.Float")) { m.invoke(bean, object); }else{ log.debug("Class-{}中成员变量{}的类型{}与当前值的类型{}不匹配,将尝试转换,可能丢失精度、溢出或出错",bean.getClass().getName(),varName,type,objectType); try { Float castingObject = Float.valueOf(object.toString()); m.invoke(bean, castingObject); } catch (Exception e) { log.error("Class-{}中成员变量{}的类型{}与当前值的类型{}不匹配,强制转换出错",bean.getClass().getName(),varName,type,objectType); } } }else if (type.equals("java.lang.Double")) {// 类型为Double Method m = bean.getClass().getMethod("set" + upperCaseVarName, Double.class); if(objectType.equals("java.lang.Double")) { m.invoke(bean, object); }else{ log.debug("Class-{}中成员变量{}的类型{}与当前值的类型{}不匹配,将尝试转换,可能丢失精度、溢出或出错",bean.getClass().getName(),varName,type,objectType); try { Double castingObject = Double.valueOf(object.toString()); m.invoke(bean, castingObject); } catch (Exception e) { log.error("Class-{}中成员变量{}的类型{}与当前值的类型{}不匹配,强制转换出错",bean.getClass().getName(),varName,type,objectType); } } } else if (type.equals("java.util.Date")) {// 类型为Date或者DateTime Method m = bean.getClass().getMethod("set" + upperCaseVarName, Date.class); m.invoke(bean, object); } else if(type.equals("org.joda.time.DateTime")) { Method m = bean.getClass().getMethod("set" + upperCaseVarName, DateTime.class); if(objectType.equals("java.util.Date")) { Date date = (Date) object; DateTime newObject = new DateTime(CommonUtil.changeDateTimeZoneFromLondonToShanghai(date).getTime()); m.invoke(bean, newObject); } else if(objectType.equals("java.lang.Long")) { DateTime newObject = new DateTime((Long)object); m.invoke(bean, newObject); }else { log.error("Class-{}中成员变量{}的类型{}与当前值的类型{}不匹配,不可赋值",bean.getClass().getName(),varName,type,objectType); } } } catch (NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException | InvocationTargetException | NoSuchFieldException | ParseException e) { throw new RuntimeException(e); } } }
37.605263
121
0.649988
c6b71ad0f2f3fa79e3e9e7381612024fe9dd0b0d
393
package shuaicj.hello.configuration.case12.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import shuaicj.hello.configuration.case12.bean.B; /** * Override B. * * @author shuaicj 2019/10/12 */ @Configuration public class OverrideB { @Bean public B overrideB() { return new B("override-B"); } }
20.684211
60
0.73028
40594f57da921b3a3d3ad6edc02718b94b3caef6
40,401
/* * Copyright 2004 Outerthought bvba and Schaubroeck nv * * 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.outerj.daisy.replication.serverimpl; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Set; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import javax.annotation.PreDestroy; import javax.jms.Message; import javax.jms.MessageListener; import javax.jms.TextMessage; import javax.management.MBeanServer; import javax.management.ObjectName; import javax.sql.DataSource; import org.apache.avalon.framework.configuration.Configuration; import org.apache.avalon.framework.configuration.ConfigurationException; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.outerj.daisy.credentialsprovider.CredentialsProvider; import org.outerj.daisy.jdbcutil.JdbcHelper; import org.outerj.daisy.jdbcutil.SqlCounter; import org.outerj.daisy.jms.JmsClient; import org.outerj.daisy.repository.AvailableVariant; import org.outerj.daisy.repository.AvailableVariants; import org.outerj.daisy.repository.CollectionNotFoundException; import org.outerj.daisy.repository.Credentials; import org.outerj.daisy.repository.Document; import org.outerj.daisy.repository.DocumentCollection; import org.outerj.daisy.repository.DocumentNotFoundException; import org.outerj.daisy.repository.DocumentVariantNotFoundException; import org.outerj.daisy.repository.LiveHistoryEntry; import org.outerj.daisy.repository.Repository; import org.outerj.daisy.repository.RepositoryEventType; import org.outerj.daisy.repository.RepositoryException; import org.outerj.daisy.repository.RepositoryManager; import org.outerj.daisy.repository.Timeline; import org.outerj.daisy.repository.VariantKey; import org.outerj.daisy.repository.Version; import org.outerj.daisy.repository.clientimpl.RemoteRepositoryManager; import org.outerj.daisy.repository.namespace.Namespace; import org.outerj.daisy.repository.namespace.NamespaceNotFoundException; import org.outerj.daisy.repository.schema.DocumentType; import org.outerj.daisy.repository.schema.DocumentTypeNotFoundException; import org.outerj.daisy.repository.schema.FieldType; import org.outerj.daisy.repository.schema.FieldTypeNotFoundException; import org.outerj.daisy.repository.schema.PartType; import org.outerj.daisy.repository.schema.PartTypeNotFoundException; import org.outerj.daisy.repository.user.Role; import org.outerj.daisy.repository.variant.Branch; import org.outerj.daisy.repository.variant.BranchNotFoundException; import org.outerj.daisy.repository.variant.Language; import org.outerj.daisy.repository.variant.LanguageNotFoundException; import org.outerj.daisy.util.ObjectUtils; import org.outerx.daisy.x10.DocumentDocument; import org.outerx.daisy.x10.DocumentVariantCreatedDocument; import org.outerx.daisy.x10.DocumentVariantDeletedDocument; import org.outerx.daisy.x10.DocumentVariantUpdatedDocument; import org.outerx.daisy.x10.TimelineUpdatedDocument; public class ReplicationService implements ReplicationServiceMBean { private final Log log = LogFactory.getLog(getClass().getName()); private static final int DEFAULT_REPLICATION_INTERVAL = 300; // in seconds private ObjectName mbeanName = new ObjectName("Daisy:name=ReplicationService"); private final Runnable replicationTask = new ReplicationRunner(); /** * Construction phase */ private JmsClient jmsClient; private RepositoryManager sourceRepositoryManager; private CredentialsProvider credentialsProvider; private DataSource dataSource; private JdbcHelper jdbcHelper; private MBeanServer mbeanServer; /** * Configuration */ private String repositoryKey; private String jmsTopic; private String jmsSubscriptionName; private Map<String, ReplicationTarget> targets = new HashMap<String, ReplicationTarget>(); private int replicationInterval; private List<ReplicationCondition> conditions = new ArrayList<ReplicationCondition>(); /** * Initialization */ private Repository sourceRepository; private ScheduledExecutorService executorService = Executors.newScheduledThreadPool(1); private SqlCounter replicationCounter; public ReplicationService(Configuration configuration, JmsClient jmsClient, RepositoryManager sourceRepositoryManager, CredentialsProvider credentialsProvider, DataSource dataSource, MBeanServer mbeanServer) throws Exception { this.jmsClient = jmsClient; this.sourceRepositoryManager = sourceRepositoryManager; this.credentialsProvider = credentialsProvider; this.dataSource = dataSource; this.jdbcHelper = JdbcHelper.getInstance(dataSource, log); this.mbeanServer = mbeanServer; configure(configuration); initialize(); } public void configure(Configuration configuration) throws ConfigurationException { for (Configuration target: configuration.getChild("targets").getChildren("target")) { String name = target.getAttribute("name"); String url = target.getAttribute("url"); String username = target.getAttribute("username"); String password = target.getAttribute("password"); String role = target.getChild("role").getValue(null); targets.put(name, new ReplicationTarget(name, url, new Credentials(username, password), role)); } for (Configuration cond: configuration.getChild("conditions").getChildren("condition")) { conditions.add(new ReplicationCondition(cond.getAttribute("namespace", null), cond.getAttribute("branch", null), cond.getAttribute("language", null))); } repositoryKey = configuration.getChild("repositoryKey").getValue("internal"); replicationInterval = configuration.getChild("replicationInterval").getValueAsInteger(DEFAULT_REPLICATION_INTERVAL); jmsTopic = configuration.getChild("jmsTopic").getValue("daisy"); jmsSubscriptionName = configuration.getChild("jmsSubscriptionName").getValue("daisy-replication-service"); } @PreDestroy public void dispose() { try { log.info("Waiting for replication thread to be terminated."); executorService.shutdownNow(); // stop running threads // Wait a while for existing threads to terminate if (!executorService.awaitTermination(60, TimeUnit.SECONDS)) { System.err.println("Executor service did not terminate."); } } catch (InterruptedException ie) { // (Re-)attempt shutdown if current thread is terminated. executorService.shutdownNow(); Thread.currentThread().interrupt(); } try { mbeanServer.unregisterMBean(mbeanName); } catch (Exception e) { log.error("Error unregistering MBean", e); } } public void initialize() throws Exception { replicationCounter = new SqlCounter("replication_sequence", dataSource, log); jmsClient.registerDurableTopicListener(jmsTopic, jmsSubscriptionName, new ReplicationMessageListener()); sourceRepository = sourceRepositoryManager.getRepository(credentialsProvider.getCredentials(repositoryKey)); mbeanServer.registerMBean(this, mbeanName); if (targets.isEmpty()) { log.info("No targets defined - will not start replication thread"); return; } if (replicationInterval >= 0) { executorService.scheduleWithFixedDelay(replicationTask, replicationInterval, replicationInterval, TimeUnit.SECONDS); } } private Repository getTargetRepository(ReplicationTarget replicationTarget) throws Exception { RemoteRepositoryManager repoManager = new RemoteRepositoryManager(replicationTarget.getUrl(), replicationTarget.getCredentials()); Repository result = repoManager.getRepository(replicationTarget.getCredentials()); if (!result.getServerVersion().equals(result.getClientVersion())) { throw new ReplicationTargetException("The target repository is running another version of Daisy.", replicationTarget.getName()); } result.setActiveRoleIds(new long[] { Role.ADMINISTRATOR }); return result; } public void scheduleReplication(String query) throws RepositoryException { VariantKey[] keys = sourceRepository.getQueryManager().performQueryReturnKeys(query, Locale.getDefault()); scheduleReplication(keys); } private void scheduleReplication(VariantKey key) throws RepositoryException { scheduleReplication(new VariantKey[] { key }); } private void scheduleReplication(VariantKey[] keys) throws RepositoryException { Connection conn = null; PreparedStatement select = null; PreparedStatement insert = null; PreparedStatement update = null; ResultSet rs = null; try { conn = dataSource.getConnection(); jdbcHelper.startTransaction(conn); for (VariantKey key: keys) { if (acceptDocument(key)) { for (String targetName: targets.keySet()) { if (select == null) select = conn.prepareStatement("select id from replication where document_id = ? and branch_id = ? and lang_id = ? and target = ?" + jdbcHelper.getSharedLockClause()); select.setString(1, key.getDocumentId()); select.setLong(2, key.getBranchId()); select.setLong(3, key.getLanguageId()); select.setString(4, targetName); select.execute(); try { rs = select.getResultSet(); if (!rs.next()) { if (insert == null) insert = conn.prepareStatement("insert into replication(id, document_id, branch_id, lang_id, target, state) values (?,?,?,?,?,?)"); insert.setLong(1, replicationCounter.getNextId()); insert.setString(2, key.getDocumentId()); insert.setLong(3, key.getBranchId()); insert.setLong(4, key.getLanguageId()); insert.setString(5, targetName); insert.setString(6, ReplicationState.NEW.getCode()); insert.execute(); } else { if (update == null) update = conn.prepareStatement("update replication set state = ? where id = ?"); update.setString(1, ReplicationState.NEW.getCode()); update.setLong(2, rs.getLong(1)); update.execute(); } } finally { if (rs != null) rs.close(); } } } } conn.commit(); } catch (SQLException e) { throw new RepositoryException("Failed to schedule replication", e); } finally { jdbcHelper.closeStatement(select); jdbcHelper.closeStatement(insert); jdbcHelper.closeStatement(update); jdbcHelper.closeConnection(conn); } } private class ReplicationMessageListener implements MessageListener { public void onMessage(Message aMessage) { try { TextMessage message = (TextMessage)aMessage; String type = message.getStringProperty("type"); String documentId = null; long branchId = -1; long languageId = -1; if (type.equals(RepositoryEventType.DOCUMENT_VARIANT_CREATED.toString())) { DocumentVariantCreatedDocument eventXml = DocumentVariantCreatedDocument.Factory.parse(message.getText()); DocumentDocument.Document documentXml = eventXml.getDocumentVariantCreated().getNewDocumentVariant().getDocument(); documentId = documentXml.getId(); branchId = documentXml.getBranchId(); languageId = documentXml.getLanguageId(); } else if (type.equals(RepositoryEventType.DOCUMENT_VARIANT_UPDATED.toString())) { DocumentVariantUpdatedDocument eventXml = DocumentVariantUpdatedDocument.Factory.parse(message.getText()); DocumentDocument.Document documentXml = eventXml.getDocumentVariantUpdated().getNewDocumentVariant().getDocument(); documentId = documentXml.getId(); branchId = documentXml.getBranchId(); languageId = documentXml.getLanguageId(); } else if (type.equals(RepositoryEventType.DOCUMENT_VARIANT_DELETED.toString())) { DocumentVariantDeletedDocument eventXml = DocumentVariantDeletedDocument.Factory.parse(message.getText()); DocumentDocument.Document documentXml = eventXml.getDocumentVariantDeleted().getDeletedDocumentVariant().getDocument(); documentId = documentXml.getId(); branchId = documentXml.getBranchId(); languageId = documentXml.getLanguageId(); } else if (type.equals(RepositoryEventType.DOCUMENT_VARIANT_TIMELINE_UPDATED.toString())) { TimelineUpdatedDocument eventXml = TimelineUpdatedDocument.Factory.parse(message.getText()); documentId = eventXml.getTimelineUpdated().getDocumentId(); branchId = eventXml.getTimelineUpdated().getBranchId(); languageId = eventXml.getTimelineUpdated().getLanguageId(); } if (documentId != null) { VariantKey key = new VariantKey(documentId, branchId, languageId); scheduleReplication(key); } } catch (Throwable e) { log.error("Error processing JMS message.", e); } } } private void replicateDocument(Repository sourceRepository, DocumentType sourceDocumentType, Document sourceDocument, String targetName, Repository targetRepository) throws Exception { VariantKey variantKey = sourceDocument.getVariantKey(); String branch = sourceRepository.getVariantManager().getBranch(variantKey.getBranchId(), false).getName(); String language = sourceRepository.getVariantManager().getLanguage(variantKey.getLanguageId(), false).getName(); Document targetDocument = null; try { targetDocument = targetRepository.getDocument(variantKey, true); } catch (DocumentNotFoundException dnfe) { targetDocument = targetRepository.createDocument(sourceDocument.getName(), sourceDocumentType.getName(), branch, language); targetDocument.setRequestedId(variantKey.getDocumentId()); } catch (DocumentVariantNotFoundException dvnfe) { if (sourceDocument.getVariantCreatedFromBranchId() != -1) { String srcFromBranch = sourceRepository.getVariantManager().getBranch(sourceDocument.getVariantCreatedFromBranchId(), false).getName(); String srcFromLanguage = sourceRepository.getVariantManager().getLanguage(sourceDocument.getVariantCreatedFromLanguageId(), false).getName(); targetDocument = targetRepository.createVariant(variantKey.getDocumentId(), srcFromBranch, srcFromLanguage, 1, branch, language, false); } else { // as a last resort pick the first available variant AvailableVariants variants = targetRepository.getAvailableVariants(variantKey.getDocumentId()); AvailableVariant variant = variants.getArray()[0]; targetDocument = targetRepository.createVariant(variantKey.getDocumentId(), variant.getBranch().getName(), variant.getLanguage().getName(), 1, branch, language, false); } } if (targetDocument.hasCustomField("dsy-ReplicationError")) { log.error("Document is excluded from replication due to earlier errors. Manual intervention needed"); } // copy all missing versions from source to target long startVersion = targetDocument.getLastVersionId() == -1 ? 1 : targetDocument.getLastVersionId() + 1; for (long i = startVersion; i <= sourceDocument.getLastVersionId(); i++) { targetDocument.setDocumentTypeChecksEnabled(false); Version sourceVersion = sourceDocument.getVersion(i); ReplicationHelper.copyVersionData(sourceVersion, targetDocument); targetDocument.save(false); } if (targetDocument.getLastVersionId() != sourceDocument.getLastVersionId()) { targetDocument.setCustomField("dsy-ReplicationError", String.format("Local and source repository have diverged. (local has %d versions, origin has %d versions)", targetDocument.getLastVersionId(), sourceDocument.getLastVersionId())); throw new ReplicationException(String.format("Got %d versions, but expected %d", targetDocument.getLastVersionId(), sourceDocument.getLastVersionId()), variantKey, targetName); } // now copy the non-versioned data and then update the timeline. ReplicationHelper.copyNonVersionedData(sourceDocument, targetDocument); targetDocument.save(false); // find the first difference in the timeline, replace everything from there on with the versions from the target repository Timeline sourceTimeline = sourceDocument.getTimeline(); Timeline targetTimeline = targetDocument.getTimeline(); LiveHistoryEntry[] sourceHistory = sourceTimeline.getLiveHistory(); LiveHistoryEntry[] targetHistory = targetTimeline.getLiveHistory(); int startDiverging = 0; while (startDiverging < sourceHistory.length) { if (startDiverging >= targetHistory.length) break; LiveHistoryEntry srcEntry = sourceHistory[startDiverging]; LiveHistoryEntry targetEntry = targetHistory[startDiverging]; if (!ObjectUtils.safeEquals(srcEntry.getBeginDate(), targetEntry.getBeginDate()) || !ObjectUtils.safeEquals(srcEntry.getEndDate(), targetEntry.getEndDate()) || srcEntry.getVersionId() != targetEntry.getVersionId()) { break; } startDiverging++; } for (int i = startDiverging; i < targetHistory.length; i++) { targetTimeline.deleteLiveHistoryEntry(targetHistory[i]); } for (int i = startDiverging; i < sourceHistory.length; i++) { targetTimeline.addLiveHistoryEntry(sourceHistory[i].getBeginDate(), sourceHistory[i].getEndDate(), sourceHistory[i].getVersionId()); } targetTimeline.save(); } public boolean acceptDocument(VariantKey variantKey) throws RepositoryException { if (conditions.isEmpty()) return true; for (ReplicationCondition condition: conditions) { if (condition.matches(sourceRepository, variantKey)) return true; } return false; } private Document getSourceOrDeleteTarget(VariantKey variantKey, Repository targetRepository) throws RepositoryException { try { return sourceRepository.getDocument(variantKey, false); } catch (DocumentNotFoundException dnfe) { try { targetRepository.deleteDocument(variantKey.getDocumentId()); } catch (DocumentNotFoundException dnfe2) { log.info("No document found while trying to delete " + variantKey.getDocumentId()); } } catch (DocumentVariantNotFoundException dvnfe) { try { targetRepository.deleteVariant(variantKey); } catch (DocumentNotFoundException dnfe) { log.info("No document found while trying to delete " + variantKey); } catch (DocumentVariantNotFoundException dvnfe2) { log.info("No document found while trying to delete " + variantKey); } } return null; } private class ReplicationRunner implements Runnable { public void run() { // query for document / target combinations to replicate, // for each one obtain a repository client to the target // and synchronise the document. Connection conn = null; PreparedStatement stmt = null; try { conn = dataSource.getConnection(); jdbcHelper.startTransaction(conn); stmt = conn.prepareStatement("select id, document_id, branch_id, lang_id, target from replication where state=?"); stmt.setString(1, ReplicationState.NEW.getCode()); stmt.execute(); ResultSet rs = stmt.getResultSet(); Map<String, Repository> repositories = new HashMap<String, Repository>(); while (rs.next()) { long replicationId = rs.getLong("id"); String documentId = rs.getString("document_id"); Long branchId = rs.getLong("branch_id"); Long languageId = rs.getLong("lang_id"); String targetName = rs.getString("target"); VariantKey variantKey = new VariantKey(documentId, branchId, languageId); ReplicationTarget replicationTarget = targets.get(targetName); if (replicationTarget == null) { throw new ReplicationTargetException("Unknown replication target: ", targetName); } try { if (replicationTarget.isSuspended()) { log.info("Replication target " + targetName + " is suspended - setting error state for " + variantKey); setReplicationState(conn, replicationId, ReplicationState.ERROR); } else { Repository targetRepository = repositories.get(replicationTarget.getName()); if (targetRepository == null) { try { targetRepository = getTargetRepository(replicationTarget); repositories.put(targetName, targetRepository); checkTargetRepository(targetName, targetRepository); } catch (RepositoryException re) { log.error("There is a problem with the target repository", re); } } Document sourceDocument = getSourceOrDeleteTarget(variantKey, targetRepository); DocumentType sourceDocumentType = sourceRepository.getRepositorySchema().getDocumentTypeById(sourceDocument.getDocumentTypeId(), false); if (sourceDocument != null) { replicateDocument(sourceRepository, sourceDocumentType, sourceDocument, targetName, targetRepository); } finishedReplication(conn, replicationId); } } catch (ReplicationTargetException rte) { log.error("Problem with replication target", rte); setReplicationState(conn, replicationId, ReplicationState.ERROR); if (replicationTarget != null) { replicationTarget.setSuspended(true); } } catch (ReplicationException re) { log.error("Failed to replicate document", re); setReplicationState(conn, replicationId, ReplicationState.ERROR); } catch (Exception e) { log.error("Unhandled error during replication: " , e); setReplicationState(conn, replicationId, ReplicationState.ERROR); } conn.commit(); } } catch (SQLException e) { log.error("Replication error", e); } catch (Throwable t) { log.error("Unhandled error", t); } finally { jdbcHelper.closeStatement(stmt); jdbcHelper.closeConnection(conn); } } } ///////////////////////////////////////// repository namespace, variant-space and schema synchronization private void checkTargetRepository(String targetName, Repository targetRepository) throws RepositoryException, ReplicationTargetException { checkTargetNamespaces(targetName, targetRepository); syncBranches(targetName, targetRepository); syncLanguages(targetName, targetRepository); syncCollections(targetName, targetRepository); syncRepositorySchema(targetRepository); } private void checkTargetNamespaces(String targetName, Repository targetRepository) throws RepositoryException, ReplicationTargetException { for (Namespace srcNamespace: sourceRepository.getNamespaceManager().getAllNamespaces().getArray()) { try { Namespace targetNamespace = targetRepository.getNamespaceManager().getNamespace(srcNamespace.getName()); if (!srcNamespace.getFingerprint().equals(targetNamespace.getFingerprint())) { throw new ReplicationTargetException(String.format("Non-matching namespace fingerprint for namespace %s: expected %s, but was %s", srcNamespace.getName(), srcNamespace.getFingerprint(), targetNamespace.getFingerprint()), targetName); } } catch (NamespaceNotFoundException nnfe) { targetRepository.getNamespaceManager().registerNamespace(srcNamespace.getName(), srcNamespace.getFingerprint()); } } } private void syncCollections(String targetName, Repository targetRepository) throws RepositoryException, ReplicationTargetException { // get collections sorted by name. DocumentCollection[] srcCollections = sourceRepository.getCollectionManager().getCollections(false).getArray(); Arrays.sort(srcCollections, 0, srcCollections.length, new Comparator<DocumentCollection>() { public int compare(DocumentCollection a, DocumentCollection b) { if (a.getId() < b.getId()) return -1; if (a.getId() > b.getId()) return 1; return 0; } }); // check branches and create them if necessary. for (DocumentCollection srcCollection: srcCollections) { DocumentCollection targetCollection = null; try { targetCollection = targetRepository.getCollectionManager().getCollection(srcCollection.getId(), true); if (!targetCollection.getName().equals(srcCollection.getName())) { targetCollection.setName(srcCollection.getName()); targetCollection.save(); } } catch (CollectionNotFoundException e) { while (true) { targetCollection = targetRepository.getCollectionManager().createCollection(srcCollection.getName()); targetCollection.setName(srcCollection.getName()); targetCollection.save(); if (targetCollection.getId() > srcCollection.getId()) { throw new ReplicationTargetException("Collection id counters are out of sync. You should manually sunc them", targetName); } else if (targetCollection.getId() < srcCollection.getId()) { targetRepository.getCollectionManager().deleteCollection(targetCollection.getId()); } else break; } } } } private void syncBranches(String targetName, Repository targetRepository) throws RepositoryException, ReplicationTargetException { // get branches sorted by name. Branch[] srcBranches = sourceRepository.getVariantManager().getAllBranches(false).getArray(); Arrays.sort(srcBranches, 0, srcBranches.length, new Comparator<Branch>() { public int compare(Branch a, Branch b) { if (a.getId() < b.getId()) return -1; if (a.getId() > b.getId()) return 1; return 0; } }); // check branches and create them if necessary. for (Branch srcBranch: srcBranches) { Branch targetBranch = null; try { targetBranch = targetRepository.getVariantManager().getBranch(srcBranch.getId(), true); if (!ObjectUtils.safeEquals(targetBranch.getName(), srcBranch.getName()) || !ObjectUtils.safeEquals(targetBranch.getDescription(), srcBranch.getDescription())) { targetBranch.setName(srcBranch.getName()); targetBranch.setDescription(srcBranch.getDescription()); targetBranch.save(); } } catch (BranchNotFoundException e) { while (true) { targetBranch = targetRepository.getVariantManager().createBranch(srcBranch.getName()); targetBranch.setAllFromXml(targetBranch.getXml().getBranch()); targetBranch.save(); if (targetBranch.getId() > srcBranch.getId()) { throw new ReplicationTargetException("Branch id counters are out of sync. You should manually sunc them", targetName); } else if (targetBranch.getId() < srcBranch.getId()) { targetRepository.getVariantManager().deleteBranch(targetBranch.getId()); } else break; } } } } private void syncLanguages(String targetName, Repository targetRepository) throws RepositoryException, ReplicationTargetException { // get languaes sorted by name. Language[] srcLanguages = sourceRepository.getVariantManager().getAllLanguages(false).getArray(); Arrays.sort(srcLanguages, 0, srcLanguages.length, new Comparator<Language>() { public int compare(Language a, Language b) { if (a.getId() < b.getId()) return -1; if (a.getId() > b.getId()) return 1; return 0; } }); // check languages and create them if necessary. for (Language srcLanguage: srcLanguages) { Language targetLanguage = null; try { targetLanguage = targetRepository.getVariantManager().getLanguage(srcLanguage.getId(), true); if (!ObjectUtils.safeEquals(targetLanguage.getName(), srcLanguage.getName()) || !ObjectUtils.safeEquals(targetLanguage.getDescription(), srcLanguage.getDescription())) { targetLanguage.setName(srcLanguage.getName()); targetLanguage.setDescription(srcLanguage.getDescription()); targetLanguage.save(); } } catch (LanguageNotFoundException e) { while (true) { targetLanguage = targetRepository.getVariantManager().createLanguage(srcLanguage.getName()); targetLanguage.setAllFromXml(srcLanguage.getXml().getLanguage()); targetLanguage.save(); if (targetLanguage.getId() > srcLanguage.getId()) { throw new ReplicationTargetException("Language id counters are out of sync. You should manually sync them.", targetName); } else if (targetLanguage.getId() < srcLanguage.getId()) { targetRepository.getVariantManager().deleteLanguage(targetLanguage.getId()); } else break; } } } } private void syncRepositorySchema(Repository targetRepository) throws RepositoryException, ReplicationTargetException { for (PartType srcPartType: sourceRepository.getRepositorySchema().getAllPartTypes(false).getArray()) { PartType targetPartType = null; try { targetPartType = targetRepository.getRepositorySchema().getPartType(srcPartType.getName(), true); } catch (PartTypeNotFoundException e) { targetPartType = targetRepository.getRepositorySchema().createPartType(srcPartType.getName(), srcPartType.getMimeTypes()); targetPartType.setAllFromXml(srcPartType.getXml().getPartType()); targetPartType.save(); } } for (FieldType srcFieldType: sourceRepository.getRepositorySchema().getAllFieldTypes(false).getArray()) { FieldType targetFieldType = null; try { targetFieldType = targetRepository.getRepositorySchema().getFieldType(srcFieldType.getName(), true); } catch (FieldTypeNotFoundException e) { targetFieldType = targetRepository.getRepositorySchema().createFieldType(srcFieldType.getName(), srcFieldType.getValueType()); targetFieldType.setAllFromXml(srcFieldType.getXml().getFieldType()); targetFieldType.save(); } } for (DocumentType srcDocumentType: sourceRepository.getRepositorySchema().getAllDocumentTypes(false).getArray()) { DocumentType targetDocumentType = null; try { targetDocumentType = targetRepository.getRepositorySchema().getDocumentType(srcDocumentType.getName(), true); } catch (DocumentTypeNotFoundException e) { targetDocumentType = targetRepository.getRepositorySchema().createDocumentType(srcDocumentType.getName()); targetDocumentType.setAllFromXml(srcDocumentType.getXml().getDocumentType()); targetDocumentType.save(); } } } private void setReplicationState(Connection conn, long replicationId, ReplicationState replicationState) throws SQLException { PreparedStatement stmt = conn.prepareStatement("update replication set state = ? where id = ?"); stmt.setString(1, replicationState.getCode()); stmt.setLong(2, replicationId); stmt.execute(); conn.commit(); } private void finishedReplication(Connection conn, long replicationId) throws SQLException { PreparedStatement stmt = conn.prepareStatement("delete from replication where id = ?"); stmt.setLong(1, replicationId); stmt.execute(); conn.commit(); } public boolean isSuspended(String targetName) { ReplicationTarget target = targets.get(targetName); if (target == null) throw new IllegalArgumentException("Target '" + targetName + "' does not exist"); return target.isSuspended(); } public void resumeTarget(String targetName) { ReplicationTarget target = targets.get(targetName); if (target == null) throw new IllegalArgumentException("Target '" + targetName + "' does not exist"); target.setSuspended(false); } public void suspendTarget(String targetName) { ReplicationTarget target = targets.get(targetName); if (target == null) throw new IllegalArgumentException("Target '" + targetName + "' does not exist"); target.setSuspended(true); } public void restartFailedReplications() throws RepositoryException { Connection conn = null; PreparedStatement stmt = null; try { conn = dataSource.getConnection(); jdbcHelper.startTransaction(conn); stmt = conn.prepareStatement("update replication set state = ? where state = ?"); stmt.setString(1, ReplicationState.NEW.getCode()); stmt.setString(2, ReplicationState.ERROR.getCode()); stmt.execute(); conn.commit(); } catch (SQLException e) { throw new RepositoryException("Failed to reschedule replication", e); } finally { jdbcHelper.closeStatement(stmt); jdbcHelper.closeConnection(conn); } } public void clearFailedReplications() throws RepositoryException { Connection conn = null; PreparedStatement stmt = null; try { conn = dataSource.getConnection(); jdbcHelper.startTransaction(conn); stmt = conn.prepareStatement("delete from replication where state = ?"); stmt.setString(1, ReplicationState.ERROR.getCode()); stmt.execute(); conn.commit(); } catch (SQLException e) { throw new RepositoryException("Failed to clear failed replications", e); } finally { jdbcHelper.closeStatement(stmt); jdbcHelper.closeConnection(conn); } } public void triggerReplication() { executorService.submit(replicationTask); } public int getReplicationsByState(ReplicationState state) { Connection conn = null; PreparedStatement stmt = null; ResultSet rs = null; try { conn = dataSource.getConnection(); stmt = conn.prepareStatement("select count(*) from replication where state = ?"); stmt.setString(1, state.getCode()); stmt.execute(); rs = stmt.getResultSet(); rs.next(); return rs.getInt(1); } catch (SQLException e) { throw new RuntimeException("Error obtaining replication state", e); } finally { jdbcHelper.closeStatement(stmt); jdbcHelper.closeConnection(conn); } } public int getReplicationQueueSize() { return getReplicationsByState(ReplicationState.NEW); } public int getReplicationErrors() { return getReplicationsByState(ReplicationState.ERROR); } public String[] getTargetNames() { Set<String> names = targets.keySet(); return (String[]) names.toArray(new String[names.size()]); } public String[] getFailedTargetNames() { Set<String> names = new HashSet<String>(); for (String targetName: targets.keySet()) { names.add(targetName); } return (String[]) names.toArray(new String[names.size()]); } }
50.818868
253
0.632583
8a844175a60240c9ea2389de99d53f28f00aac03
2,328
package com.obdobion.billiardsFX.model.drills.drdave; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.obdobion.billiardsFX.model.drills.AbstractDrillCommand; /** * <p> * UpdateScoreFromInt class. * </p> * * @author Chris DeGreef fedupforone@gmail.com */ public class UpdateScoreFromInt extends AbstractDrillCommand<SingleScoreDrill> { final static Logger logger = LoggerFactory.getLogger(UpdateScoreFromInt.class); int previousScore; int score; private UpdateScoreFromInt() { super(null); } /** * <p> * Constructor for UpdateScoreFromInt. * </p> * * @param p_drill a * {@link com.obdobion.billiardsFX.model.drills.drdave.SingleScoreDrill} * object. * @param p_score a int. */ public UpdateScoreFromInt(SingleScoreDrill p_drill, int p_score) { this(p_drill, p_score, null); } /** * <p> * Constructor for UpdateScoreFromInt. * </p> * * @param p_drill a * {@link com.obdobion.billiardsFX.model.drills.drdave.SingleScoreDrill} * object. * @param p_score a int. * @param p_note a {@link java.lang.String} object. */ public UpdateScoreFromInt(SingleScoreDrill p_drill, int p_score, String p_note) { super(p_note); drill = p_drill; score = p_score; } /** {@inheritDoc} */ @Override public void privateExecute() { previousScore = drill.score; drill.score = score; logger.info("updateScore({})", this); drill.notifyScoreChangedObservers(); if (drill.isComplete()) drill.notifyDrillOverObservers(); } /** {@inheritDoc} */ @Override public void privateUndo() { drill.score = previousScore; logger.info("updateScoreUndo({})", drill); drill.notifyDrillStartObservers(); } /** {@inheritDoc} */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("int(").append(score).append(")"); sb.append(" => ").append(drill); return sb.toString(); } }
24.765957
88
0.568729
beec1ce4d235a5ca95731f41c85d8b936b2a9662
3,168
/* * Copyright 2018-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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. */ /* * Copyright 2019-2020 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 com.yofish.gary.biz.controller; import com.yofish.gary.api.dto.req.RoleAddReqDTO; import com.yofish.gary.api.dto.req.RoleDeleteReqDTO; import com.yofish.gary.api.dto.req.RoleEditReqDTO; import com.yofish.gary.api.dto.req.RoleQueryReqDTO; import com.yofish.gary.api.dto.rsp.RoleQueryRspDTO; import com.yofish.gary.api.feign.RoleApi; import com.yofish.gary.biz.service.RoleService; import com.youyu.common.api.PageData; import com.youyu.common.api.Result; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import javax.validation.Valid; import static com.youyu.common.api.Result.ok; /** * @author pqq * @version v1.0 * @date 2019年6月27日 10:00:00 * @work 用户controller */ @RestController @RequestMapping(value = "/role") public class RoleController implements RoleApi { @Autowired private RoleService roleService; @Override @PostMapping("/add") public Result add(@Valid @RequestBody RoleAddReqDTO roleAddReqDTO) { roleService.add(roleAddReqDTO); return ok(); } @Override @PostMapping("/delete") public Result delete(@Valid @RequestBody RoleDeleteReqDTO roleDeleteReqDTO) { roleService.delete(roleDeleteReqDTO); return ok(); } @Override @PostMapping("/edit") public Result edit(@Valid @RequestBody RoleEditReqDTO roleEditReqDTO) { roleService.edit(roleEditReqDTO); return ok(); } @Override @PostMapping("/getPage") public Result<PageData<RoleQueryRspDTO>> getPage(@RequestBody RoleQueryReqDTO roleQueryReqDTO) { return ok(roleService.getPage(roleQueryReqDTO)); } }
34.434783
100
0.731692
fdd9465e1aa7573f77eeaca0df54b237771a4be2
6,260
package com.donfyy.crowds.viewpager; import android.app.Fragment; import android.content.Context; import android.graphics.Color; import android.net.Uri; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.donfyy.crowds.R; import java.util.Arrays; import java.util.List; import androidx.annotation.NonNull; import androidx.viewpager.widget.PagerAdapter; import androidx.viewpager.widget.ViewPager; /** * A simple {@link Fragment} subclass. * Activities that contain this fragment must implement the * {@link ViewPagerFragment.OnFragmentInteractionListener} interface * to handle interaction events. * Use the {@link ViewPagerFragment#newInstance} factory method to * create an instance of this fragment. */ public class ViewPagerFragment extends Fragment { // TODO: Rename parameter arguments, choose names that match // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER private static final String ARG_PARAM1 = "param1"; private static final String ARG_PARAM2 = "param2"; // TODO: Rename and change types of parameters private String mParam1; private String mParam2; private OnFragmentInteractionListener mListener; public ViewPagerFragment() { // Required empty public constructor } /** * Use this factory method to create a new instance of * this fragment using the provided parameters. * * @param param1 Parameter 1. * @param param2 Parameter 2. * @return A new instance of fragment ViewPagerFragment. */ // TODO: Rename and change types and number of parameters public static ViewPagerFragment newInstance(String param1, String param2) { ViewPagerFragment fragment = new ViewPagerFragment(); Bundle args = new Bundle(); args.putString(ARG_PARAM1, param1); args.putString(ARG_PARAM2, param2); fragment.setArguments(args); return fragment; } // TODO: Rename method, update argument and hook method into UI event public void onButtonPressed(Uri uri) { if (mListener != null) { mListener.onFragmentInteraction(uri); } } @Override public void onAttach(Context context) { super.onAttach(context); if (context instanceof OnFragmentInteractionListener) { mListener = (OnFragmentInteractionListener) context; } else { // throw new RuntimeException(context.toString() // + " must implement OnFragmentInteractionListener"); } } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (getArguments() != null) { mParam1 = getArguments().getString(ARG_PARAM1); mParam2 = getArguments().getString(ARG_PARAM2); } } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment return inflater.inflate(R.layout.fragment_view_pager, container, false); } @Override public void onViewCreated(View view, Bundle savedInstanceState) { ViewPager viewPager = view.findViewById(R.id.viewPager); PagerAdapterExample underlyingPagerAdapter = new PagerAdapterExample(); // view.findViewById(R.id.jump).setOnClickListener(v -> { underlyingPagerAdapter.setOriginData(Arrays.asList(Color.YELLOW, Color.BLUE, Color.RED, Color.CYAN)); // underlyingPagerAdapter.notifyDataSetChanged(); // }); view.post(new Runnable() { @Override public void run() { } }); InfiniteLoopPagerAdapter infiniteLoopPagerAdapter = new InfiniteLoopPagerAdapter(underlyingPagerAdapter); infiniteLoopPagerAdapter.assemble(viewPager); viewPager.setPageTransformer(true, new ZoomOutSlideTransformer(infiniteLoopPagerAdapter)); super.onViewCreated(view, savedInstanceState); } @Override public void onDetach() { super.onDetach(); mListener = null; } /** * This interface must be implemented by activities that contain this * fragment to allow an interaction in this fragment to be communicated * to the activity and potentially other fragments contained in that * activity. * <p> * See the Android Training lesson <a href= * "http://developer.android.com/training/basics/fragments/communicating.html" * >Communicating with Other Fragments</a> for more information. */ public interface OnFragmentInteractionListener { // TODO: Update argument type and name void onFragmentInteraction(Uri uri); } private static class PagerAdapterExample extends PagerAdapter { private List<Integer> mOriginData; private PagerAdapterExample(List<Integer> originData) { mOriginData = originData; } public PagerAdapterExample() { } @Override public boolean isViewFromObject(@NonNull View view, @NonNull Object object) { return object == view; } public void setOriginData(List<Integer> originData) { mOriginData = originData; } @Override public int getCount() { return mOriginData != null ? mOriginData.size() : 0; } @NonNull @Override public Object instantiateItem(@NonNull ViewGroup container, int position) { LayoutInflater inflater = LayoutInflater.from(container.getContext()); View view = inflater.inflate(R.layout.fragment_view_pager_item, container, false); view.setBackgroundColor(mOriginData.get(position)); TextView textView = view.findViewById(R.id.number); textView.setText(String.valueOf(position)); container.addView(view); return view; } @Override public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) { container.removeView(((View) object)); } } }
34.20765
113
0.672843
a39636b8418a1e0456c777cc2c5ca032c07c23ea
1,039
package com.hsuforum.easportalm.exception; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Pointcut; import com.hsuforum.common.web.jsf.utils.JSFMessageUtils; /** * Exception handler in web layer action * @author Marvin * */ @Aspect public class ExceptionHandler { protected final Log logger = LogFactory.getLog(this.getClass()); @Pointcut("execution(* com.hsuforum.easportalm.web.jsf.managed..*ManagedBean.do*Action(..))") public void doActionInWebLayer() { } @Around("doActionInWebLayer()") public Object handleUnprocessedException(ProceedingJoinPoint pjp) throws Throwable { try { return pjp.proceed(); } catch (Exception e) { logger.error(e.getMessage()); e.printStackTrace(); JSFMessageUtils.showErrorMessage(e.getMessage()); return null; } } }
24.738095
95
0.72666
12e2fddda6be15c4a4b1b4697015ab0654e19e89
3,020
/* * Copyright 2016-2022 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.data.util; import static org.assertj.core.api.Assertions.*; import lombok.Getter; import java.util.Collection; import org.junit.jupiter.api.Test; import org.springframework.data.util.MethodInvocationRecorder.Recorded; /** * Unit tests for {@link MethodInvocationRecorder}. * * @author Oliver Gierke * @soundtrack The Intersphere - Don't Think Twice (The Grand Delusion) */ class MethodInvocationRecorderUnitTests { private Recorded<Foo> recorder = MethodInvocationRecorder.forProxyOf(Foo.class); @Test // DATACMNS-1449 void rejectsFinalTypes() { assertThatIllegalArgumentException() // .isThrownBy(() -> MethodInvocationRecorder.forProxyOf(FinalType.class)); } @Test // DATACMNS-1449 void createsPropertyPathForSimpleMethodReference() { var wrapper = recorder.record(Foo::getBar); assertThat(wrapper.getPropertyPath()).hasValue("bar"); } @Test // DATACMNS-1449 void createsPropertyPathForNestedMethodReference() { var wrapper = recorder.record(Foo::getBar).record(Bar::getFooBar); assertThat(wrapper.getPropertyPath()).hasValue("bar.fooBar"); } @Test // DATACMNS-1449 void createsPropertyPathForNestedCall() { var wrapper = recorder.record((Foo source) -> source.getBar().getFooBar()); assertThat(wrapper.getPropertyPath()).hasValue("bar.fooBar"); } @Test // DATACMNS-1449 void usesCustomPropertyNamingStrategy() { var recorded = MethodInvocationRecorder.forProxyOf(Foo.class).record(Foo::getBar); assertThat(recorded.getPropertyPath(method -> method.getName())).hasValue("getBar"); } @Test // DATACMNS-1449 void registersLookupToFinalType() { assertThat(recorder.record(Foo::getName).getPropertyPath()).hasValue("name"); } @Test // DATACMNS-1449 void recordsInvocationOnInterface() { var recorder = MethodInvocationRecorder.forProxyOf(Sample.class); assertThat(recorder.record(Sample::getName).getPropertyPath()).hasValue("name"); } @Test // #2612 void registersLookupForPrimitiveValue() { var recorder = MethodInvocationRecorder.forProxyOf(Foo.class); assertThat(recorder.record(Foo::getAge).getPropertyPath()).hasValue("age"); } static final class FinalType {} @Getter static class Foo { Bar bar; Collection<Bar> bars; String name; int age; } @Getter static class Bar { FooBar fooBar; } static class FooBar {} interface Sample { String getName(); } }
25.59322
86
0.744371
29a4af57f52445e223970afe5dc1e2071013868f
7,695
package com.flaurite.addon.headerbutton.impl; import com.flaurite.addon.headerbutton.ext.AttachableButton; import com.haulmont.bali.events.Subscription; import com.haulmont.bali.util.Preconditions; import com.haulmont.cuba.gui.icons.CubaIcon; import com.haulmont.cuba.gui.screen.Screen; import java.util.EventObject; import java.util.function.Consumer; /** * Describes a button that can be added to the dialog header. */ public class HeaderButton extends AttachableButton { protected Consumer<HeaderButton> markAsDirtyListener; protected String id; protected String caption; protected String icon; protected String description; protected String styleName; protected Boolean sanitizeHtml; protected boolean descriptionAsHtml = false; protected boolean enabled = true; protected Consumer<ButtonClickEvent> clickHandler; /** * @param id button's id, not null */ public HeaderButton(String id) { Preconditions.checkNotNullArgument(id); this.id = id; } public String getId() { return id; } public void setId(String id) { Preconditions.checkNotNullArgument(id); this.id = id; } public HeaderButton withId(String id) { Preconditions.checkNotNullArgument(id); this.id = id; return this; } public String getCaption() { return caption; } /** * Sets button's caption. If is used in runtime, button will be recreated with new caption. * * @param caption button's caption */ public void setCaption(String caption) { this.caption = caption; markAsDirty(); } /** * Sets button's caption. If is used in runtime, button will be recreated with new caption. * * @param caption button's caption * @return current instance */ public HeaderButton withCaption(String caption) { this.caption = caption; markAsDirty(); return this; } public String getIcon() { return icon; } /** * Sets button's icon. If is used in runtime, button will be recreated with new icon. Example: * <ul> * <li>BITCOIN</li> * <li>font-icon:BITCOIN</li> * <li>icons/chain.png</li> * </ul> * * @param icon icon source or name */ public void setIcon(String icon) { this.icon = icon; markAsDirty(); } /** * Sets button's icon. If is used in runtime, button will be recreated with new icon. * * @param icon icon */ public void setIcon(CubaIcon icon) { this.icon = icon.source(); markAsDirty(); } /** * Sets button's icon. If is used in runtime, button will be recreated with new icon. Example: * <ul> * <li>BITCOIN</li> * <li>font-icon:BITCOIN</li> * <li>icons/chain.png</li> * </ul> * * @param icon icon source or name * @return current instance */ public HeaderButton withIcon(String icon) { this.icon = icon; markAsDirty(); return this; } /** * Sets button's icon. If is used in runtime, button will be recreated with new icon. * * @param icon icon * @return current instance */ public HeaderButton withIcon(CubaIcon icon) { this.icon = icon.source(); markAsDirty(); return this; } public String getDescription() { return description; } /** * Sets button's description. If is used in runtime, button will be recreated with new description. * * @param description description */ public void setDescription(String description) { this.description = description; markAsDirty(); } /** * Sets button's description. If is used in runtime, button will be recreated with new description. * * @param description description * @return current instance */ public HeaderButton withDescription(String description) { this.description = description; markAsDirty(); return this; } public String getStyleName() { return styleName; } /** * Sets button's styleName. If is used in runtime, button will be recreated with new styleName. * * @param styleName styleName */ public void setStyleName(String styleName) { this.styleName = styleName; markAsDirty(); } /** * Sets button's styleName. If is used in runtime, button will be recreated with new styleName. * * @param styleName styleName * @return current instance */ public HeaderButton withtStyleName(String styleName) { this.styleName = styleName; markAsDirty(); return this; } public Boolean isSanitizeHtml() { return sanitizeHtml; } public void setSanitizeHtml(Boolean sanitizeHtml) { this.sanitizeHtml = sanitizeHtml; } public HeaderButton withSanitizeHtml(Boolean sanitizeHtml) { this.sanitizeHtml = sanitizeHtml; return this; } public boolean isDescriptionAsHtml() { return descriptionAsHtml; } public void setDescriptionAsHtml(boolean descriptionAsHtml) { this.descriptionAsHtml = descriptionAsHtml; } public boolean isEnabled() { return enabled; } public void setEnabled(boolean enabled) { this.enabled = enabled; markAsDirty(); } public HeaderButton withEnabled(boolean enabled) { this.enabled = enabled; markAsDirty(); return this; } public HeaderButton withDescriptionAsHtml(boolean descriptionAsHtml) { this.descriptionAsHtml = descriptionAsHtml; return this; } public Consumer<ButtonClickEvent> getClickHandler() { return clickHandler; } public void setClickHandler(Consumer<ButtonClickEvent> clickHandler) { this.clickHandler = clickHandler; getEventHub().subscribe(ButtonClickEvent.class, clickHandler); } public HeaderButton withClickHandler(Consumer<ButtonClickEvent> clickHandler) { this.clickHandler = clickHandler; getEventHub().subscribe(ButtonClickEvent.class, clickHandler); return this; } public Subscription addClickListener(Consumer<ButtonClickEvent> clickListener) { this.clickHandler = clickListener; return getEventHub().subscribe(ButtonClickEvent.class, clickHandler); } @Override protected void attache(Consumer<HeaderButton> markAsDirtyListener) { this.markAsDirtyListener = markAsDirtyListener; } protected void markAsDirty() { if (markAsDirtyListener != null) { markAsDirtyListener.accept(this); } } @Override public boolean equals(Object obj) { if (obj == null || obj.getClass() != this.getClass()) { return false; } HeaderButton hButton = (HeaderButton) obj; return id.equals(hButton.getId()); } @Override public int hashCode() { return id.hashCode(); } public static class ButtonClickEvent extends EventObject { protected HeaderButton button; public ButtonClickEvent(Screen source, HeaderButton button) { super(source); this.button = button; } public HeaderButton getButton() { return button; } public String getButtonId() { return button.getId(); } @Override public Screen getSource() { return (Screen) super.getSource(); } } }
25.229508
103
0.624821
4daa94deb11405163366174d249ad938368e8966
586
package com.rokejits.android.tool.connection2; import com.rokejits.android.tool.connection2.handler.ErrorHandler; public interface IConnection2 { public String getUrl(); public void setConnectionListener(ConnectionListener listener); public ConnectionListener getConnectionListener(); public void setErrorHandler(ErrorHandler errorHandler); public ErrorHandler getErrorHandler(); public IConnectionDescriptor getConnectionDescription(); public void connect(); public void stopConnect(); public void immediateConnect(); public IConnection2 deepCopy(); }
29.3
66
0.798635
938932c30be566d9017934797e48cf6aad50710e
6,218
/* * Licensed to Elasticsearch B.V. under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch B.V. 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. */ //---------------------------------------------------- // THIS CODE IS GENERATED. MANUAL EDITS WILL BE LOST. //---------------------------------------------------- package co.elastic.clients.elasticsearch._global.search; import co.elastic.clients.json.BuildFunctionDeserializer; import co.elastic.clients.json.JsonpDeserializer; import co.elastic.clients.json.JsonpMapper; import co.elastic.clients.json.ObjectDeserializer; import co.elastic.clients.json.ToJsonp; import co.elastic.clients.util.ObjectBuilder; import co.elastic.clients.util.StringEnum; import co.elastic.clients.util.TaggedUnion; import jakarta.json.stream.JsonGenerator; import java.lang.Object; import java.util.function.Function; import javax.annotation.Nullable; public class SmoothingModelContainer extends TaggedUnion<SmoothingModelContainer.Tag, Object> implements ToJsonp { public enum Tag implements StringEnum { laplace("laplace"), linearInterpolation("linear_interpolation"), stupidBackoff("stupid_backoff"), ; private final String jsonValue; Tag(String jsonValue) { this.jsonValue = jsonValue; } public String jsonValue() { return this.jsonValue; } public static StringEnum.Deserializer<Tag> DESERIALIZER = new StringEnum.Deserializer<>(Tag.values()); } private SmoothingModelContainer(Builder builder) { super(builder.$tag, builder.$variant); } /** * Is this {@link SmoothingModelContainer} of a {@code laplace} kind? */ public boolean isLaplace() { return is(Tag.laplace); } /** * Get the {@code laplace} variant value. * * @throws IllegalStateException * if the current variant is not of the {@code laplace} kind. */ public LaplaceSmoothingModel laplace() { return get(Tag.laplace); } /** * Is this {@link SmoothingModelContainer} of a {@code linear_interpolation} * kind? */ public boolean isLinearInterpolation() { return is(Tag.linearInterpolation); } /** * Get the {@code linear_interpolation} variant value. * * @throws IllegalStateException * if the current variant is not of the {@code linear_interpolation} * kind. */ public LinearInterpolationSmoothingModel linearInterpolation() { return get(Tag.linearInterpolation); } /** * Is this {@link SmoothingModelContainer} of a {@code stupid_backoff} kind? */ public boolean isStupidBackoff() { return is(Tag.stupidBackoff); } /** * Get the {@code stupid_backoff} variant value. * * @throws IllegalStateException * if the current variant is not of the {@code stupid_backoff} kind. */ public StupidBackoffSmoothingModel stupidBackoff() { return get(Tag.stupidBackoff); } @Override public void toJsonp(JsonGenerator generator, JsonpMapper mapper) { generator.writeStartObject(); generator.writeKey(tag.jsonValue); if (value instanceof ToJsonp) { ((ToJsonp) value).toJsonp(generator, mapper); } generator.writeEnd(); } public static class Builder { private Tag $tag; private Object $variant; public ObjectBuilder<SmoothingModelContainer> laplace(LaplaceSmoothingModel v) { this.$variant = v; this.$tag = Tag.laplace; return new ObjectBuilder.Constant<>(this.build()); } public ObjectBuilder<SmoothingModelContainer> laplace( Function<LaplaceSmoothingModel.Builder, ObjectBuilder<LaplaceSmoothingModel>> f) { return this.laplace(f.apply(new LaplaceSmoothingModel.Builder()).build()); } public ObjectBuilder<SmoothingModelContainer> linearInterpolation(LinearInterpolationSmoothingModel v) { this.$variant = v; this.$tag = Tag.linearInterpolation; return new ObjectBuilder.Constant<>(this.build()); } public ObjectBuilder<SmoothingModelContainer> linearInterpolation( Function<LinearInterpolationSmoothingModel.Builder, ObjectBuilder<LinearInterpolationSmoothingModel>> f) { return this.linearInterpolation(f.apply(new LinearInterpolationSmoothingModel.Builder()).build()); } public ObjectBuilder<SmoothingModelContainer> stupidBackoff(StupidBackoffSmoothingModel v) { this.$variant = v; this.$tag = Tag.stupidBackoff; return new ObjectBuilder.Constant<>(this.build()); } public ObjectBuilder<SmoothingModelContainer> stupidBackoff( Function<StupidBackoffSmoothingModel.Builder, ObjectBuilder<StupidBackoffSmoothingModel>> f) { return this.stupidBackoff(f.apply(new StupidBackoffSmoothingModel.Builder()).build()); } protected SmoothingModelContainer build() { return new SmoothingModelContainer(this); } } // Variants can be recursive data structures. Building the union's deserializer // lazily // avoids cyclic dependencies between static class initialization code, which // can lead to unwanted things like NPEs or stack overflows public static final JsonpDeserializer<SmoothingModelContainer> DESERIALIZER = JsonpDeserializer .lazy(SmoothingModelContainer::buildDeserializer); private static JsonpDeserializer<SmoothingModelContainer> buildDeserializer() { ObjectDeserializer<Builder> op = new ObjectDeserializer<>(Builder::new); op.add(Builder::laplace, LaplaceSmoothingModel.DESERIALIZER, "laplace"); op.add(Builder::linearInterpolation, LinearInterpolationSmoothingModel.DESERIALIZER, "linear_interpolation"); op.add(Builder::stupidBackoff, StupidBackoffSmoothingModel.DESERIALIZER, "stupid_backoff"); return new BuildFunctionDeserializer<>(op, Builder::build); } }
32.051546
114
0.74413
dc47880bde82dc29b5e7ec281d734e671e45a094
286
package io.kenxue.cicd.coreclient.dto.sys.user; import io.kenxue.cicd.coreclient.dto.common.command.CommonCommand; import lombok.Data; import lombok.experimental.Accessors; @Accessors(chain = true) @Data public class UserFullGetQry extends CommonCommand { private String userId; }
26
66
0.807692
bd70d1d992401cb7ec53bf0497912203d7e93405
4,225
/* * 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.geode.metrics.internal; import java.util.concurrent.TimeUnit; import java.util.function.ToDoubleFunction; import java.util.function.ToLongFunction; import io.micrometer.core.instrument.Clock; import io.micrometer.core.instrument.Counter; import io.micrometer.core.instrument.DistributionSummary; import io.micrometer.core.instrument.FunctionCounter; import io.micrometer.core.instrument.FunctionTimer; import io.micrometer.core.instrument.Gauge; import io.micrometer.core.instrument.LongTaskTimer; import io.micrometer.core.instrument.Measurement; import io.micrometer.core.instrument.Meter; import io.micrometer.core.instrument.MeterRegistry; import io.micrometer.core.instrument.Timer; import io.micrometer.core.instrument.distribution.DistributionStatisticConfig; import io.micrometer.core.instrument.distribution.pause.PauseDetector; import io.micrometer.core.instrument.noop.NoopCounter; import io.micrometer.core.instrument.noop.NoopDistributionSummary; import io.micrometer.core.instrument.noop.NoopFunctionCounter; import io.micrometer.core.instrument.noop.NoopFunctionTimer; import io.micrometer.core.instrument.noop.NoopGauge; import io.micrometer.core.instrument.noop.NoopLongTaskTimer; import io.micrometer.core.instrument.noop.NoopMeter; import io.micrometer.core.instrument.noop.NoopTimer; import io.micrometer.core.lang.NonNullApi; import io.micrometer.core.lang.Nullable; import org.apache.geode.annotations.Immutable; import org.apache.geode.annotations.VisibleForTesting; @NonNullApi public class NoopMeterRegistry extends MeterRegistry { @Immutable @VisibleForTesting static final Clock NOOP_CLOCK = new Clock() { @Override public long wallTime() { return 0; } @Override public long monotonicTime() { return 0; } }; public NoopMeterRegistry() { this(NOOP_CLOCK); } private NoopMeterRegistry(Clock clock) { super(clock); } @Override protected <T> Gauge newGauge(Meter.Id id, @Nullable T obj, ToDoubleFunction<T> valueFunction) { return new NoopGauge(id); } @Override protected Counter newCounter(Meter.Id id) { return new NoopCounter(id); } @Override protected LongTaskTimer newLongTaskTimer(Meter.Id id) { return new NoopLongTaskTimer(id); } @Override protected Timer newTimer(Meter.Id id, DistributionStatisticConfig distributionStatisticConfig, PauseDetector pauseDetector) { return new NoopTimer(id); } @Override protected DistributionSummary newDistributionSummary(Meter.Id id, DistributionStatisticConfig distributionStatisticConfig, double scale) { return new NoopDistributionSummary(id); } @Override protected Meter newMeter(Meter.Id id, Meter.Type type, Iterable<Measurement> measurements) { return new NoopMeter(id); } @Override protected <T> FunctionTimer newFunctionTimer(Meter.Id id, T obj, ToLongFunction<T> countFunction, ToDoubleFunction<T> totalTimeFunction, TimeUnit totalTimeFunctionUnit) { return new NoopFunctionTimer(id); } @Override protected <T> FunctionCounter newFunctionCounter(Meter.Id id, T obj, ToDoubleFunction<T> countFunction) { return new NoopFunctionCounter(id); } @Override protected TimeUnit getBaseTimeUnit() { return TimeUnit.SECONDS; } @Override protected DistributionStatisticConfig defaultHistogramConfig() { return DistributionStatisticConfig.NONE; } }
33.267717
100
0.781065
ee2174099497f02b34f86ba08edbe6b402488c6e
1,425
package io.rong.callkit.util; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.telephony.TelephonyManager; import android.text.TextUtils; import io.rong.calllib.RongCallClient; import io.rong.calllib.RongCallSession; import io.rong.common.RLog; public class RTCPhoneStateReceiver extends BroadcastReceiver { private static final String TAG = "RTCPhoneStateReceiver"; //21以上会回调两次(状态值一样) private static String twice = ""; @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if (("android.intent.action.PHONE_STATE").equals(action)) { String state = intent.getStringExtra(TelephonyManager.EXTRA_STATE); RLog.i(TAG, "state :" + state + " , twice : " + twice); if (!TextUtils.isEmpty(state) && !twice.equals(state)) { twice = state; RongCallSession session = RongCallClient.getInstance().getCallSession(); if (session != null && (twice.equals(TelephonyManager.EXTRA_STATE_RINGING) || twice.equals(TelephonyManager.EXTRA_STATE_OFFHOOK))) { RongCallClient.getInstance().hangUpCall(); } else { RLog.i(TAG, "onReceive->session = null."); } } } } }
36.538462
93
0.632281
c9042a4c6cbd371e2616ecfadb494a855a9aae21
2,677
/* * (c) Copyright 2019 Palantir Technologies Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.palantir.dialogue.core; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.verify; import com.palantir.conjure.java.api.config.service.UserAgent; import com.palantir.dialogue.Channel; import com.palantir.dialogue.Endpoint; import com.palantir.dialogue.Request; import com.palantir.dialogue.TestEndpoint; import java.util.Optional; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; @ExtendWith(MockitoExtension.class) @SuppressWarnings("FutureReturnValueIgnored") public final class UserAgentChannelTest { private static final UserAgent baseAgent = UserAgent.of(UserAgent.Agent.of("test-class", "1.2.3")); @Mock private Channel delegate; @Captor private ArgumentCaptor<Request> requestCaptor; private UserAgentChannel channel; @BeforeEach public void before() { channel = new UserAgentChannel(delegate, baseAgent); } private Request request = Request.builder() .putHeaderParams("header", "value") .putQueryParams("query", "value") .putPathParams("path", "value") .build(); @Test public void injectsDialogueVersionAndEndpointVersion() { // Special case: In IDEs, tests are run against classes (not JARs) and thus don't carry versions. String dialogueVersion = Optional.ofNullable(Channel.class.getPackage().getImplementationVersion()) .orElse("0.0.0"); channel.execute(TestEndpoint.POST, request); verify(delegate).execute(eq((Endpoint) TestEndpoint.POST), requestCaptor.capture()); assertThat(requestCaptor.getValue().headerParams().get("user-agent")) .containsExactly("test-class/1.2.3 service/1.0.0 dialogue/" + dialogueVersion); } }
36.175676
107
0.732163
815158d02cde760ef9d5d23bbfdfdbe465d79255
17,474
/* * 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 bft; import bft.util.ProxyReplyListener; import bft.util.BFTCommon; import bft.util.ECDSAKeyLoader; import bftsmart.communication.client.ReplyListener; import bftsmart.tom.AsynchServiceProxy; import bftsmart.tom.RequestContext; import bftsmart.tom.core.messages.TOMMessage; import bftsmart.tom.core.messages.TOMMessageType; import bftsmart.tom.util.KeyLoader; import com.etsy.net.JUDS; import com.etsy.net.UnixDomainSocket; import com.etsy.net.UnixDomainSocketServer; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.net.ServerSocket; import java.net.Socket; import java.nio.file.FileSystems; import java.nio.file.Files; import java.nio.file.Path; import java.security.NoSuchAlgorithmException; import java.security.NoSuchProviderException; import java.security.PrivateKey; import java.security.PublicKey; import java.security.Security; import java.security.cert.CertificateException; import java.security.spec.InvalidKeySpecException; import java.time.Duration; import java.util.Arrays; import java.util.Map; import java.util.Timer; import java.util.TimerTask; import java.util.TreeMap; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.logging.Level; import org.apache.commons.io.FileUtils; import org.bouncycastle.jce.provider.BouncyCastleProvider; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.hyperledger.fabric.protos.common.Common; import org.hyperledger.fabric.protos.common.Configtx; import org.hyperledger.fabric.protos.orderer.Configuration; import org.hyperledger.fabric.sdk.exception.CryptoException; import org.hyperledger.fabric.sdk.exception.InvalidArgumentException; import org.hyperledger.fabric.sdk.helper.Config; import org.hyperledger.fabric.sdk.security.CryptoPrimitives; /** * * @author joao */ public class BFTProxy { private static UnixDomainSocketServer recvServer = null; private static ServerSocket sendServer = null; private static DataInputStream is; private static UnixDomainSocket recvSocket = null; private static Socket sendSocket = null; private static ExecutorService executor = null; private static Map<String, DataOutputStream> outputs; private static Map<String, Timer> timers; private static Map<String, Long> BatchTimeout; private static int frontendID; private static int nextID; private static ProxyReplyListener sysProxy; private static Logger logger; private static String configDir; private static CryptoPrimitives crypto; //measurements private static final int interval = 10000; private static long envelopeMeasurementStartTime = -1; private static final long blockMeasurementStartTime = -1; private static final long sigsMeasurementStartTime = -1; private static int countEnvelopes = 0; private static final int countBlocks = 0; private static final int countSigs = 0; public static void main(String args[]) throws ClassNotFoundException, IllegalAccessException, InstantiationException, CryptoException, InvalidArgumentException, NoSuchAlgorithmException, NoSuchProviderException, IOException { if(args.length < 3) { System.out.println("Use: java bft.BFTProxy <proxy id> <pool size> <send port>"); System.exit(-1); } int pool = Integer.parseInt(args[1]); int sendPort = Integer.parseInt(args[2]); Path proxy_ready = FileSystems.getDefault().getPath(System.getProperty("java.io.tmpdir"), "hlf-proxy-"+sendPort+".ready"); Files.deleteIfExists(proxy_ready); configDir = BFTCommon.getBFTSMaRtConfigDir("FRONTEND_CONFIG_DIR"); if (System.getProperty("logback.configurationFile") == null) System.setProperty("logback.configurationFile", configDir + "logback.xml"); Security.addProvider(new BouncyCastleProvider()); BFTProxy.logger = LoggerFactory.getLogger(BFTProxy.class); frontendID = Integer.parseInt(args[0]); nextID = frontendID + 1; crypto = new CryptoPrimitives(); crypto.init(); BFTCommon.init(crypto); ECDSAKeyLoader loader = new ECDSAKeyLoader(frontendID, configDir, crypto.getProperties().getProperty(Config.SIGNATURE_ALGORITHM)); sysProxy = new ProxyReplyListener(frontendID, configDir, loader, Security.getProvider("BC")); try { logger.info("Creating UNIX socket..."); Path socket_file = FileSystems.getDefault().getPath(System.getProperty("java.io.tmpdir"), "hlf-pool-"+sendPort+".sock"); Files.deleteIfExists(socket_file); recvServer = new UnixDomainSocketServer(socket_file.toString(), JUDS.SOCK_STREAM, pool); sendServer = new ServerSocket(sendPort); FileUtils.touch(proxy_ready.toFile()); //Indicate the Go component that the java component is ready logger.info("Waiting for local connections and parameters..."); recvSocket = recvServer.accept(); is = new DataInputStream(recvSocket.getInputStream()); executor = Executors.newFixedThreadPool(pool); for (int i = 0; i < pool; i++) { UnixDomainSocket socket = recvServer.accept(); executor.execute(new ReceiverThread(socket, nextID)); nextID++; } outputs = new TreeMap<>(); timers = new TreeMap<>(); BatchTimeout = new TreeMap<>(); // request latest reply sequence from the ordering nodes sysProxy.invokeAsynchRequest(BFTCommon.assembleSignedRequest(sysProxy.getViewManager().getStaticConf().getPrivateKey(), frontendID, "SEQUENCE", "", new byte[]{}), null, TOMMessageType.ORDERED_REQUEST); new SenderThread().start(); logger.info("Java component is ready"); while (true) { // wait for the creation of new channels sendSocket = sendServer.accept(); DataOutputStream os = new DataOutputStream(sendSocket.getOutputStream()); String channel = readString(is); //byte[] bytes = readBytes(is); outputs.put(channel, os); BatchTimeout.put(channel, readLong(is)); logger.info("Read BatchTimeout: " + BatchTimeout.get(channel)); //sysProxy.invokeAsynchRequest(BFTUtil.assembleSignedRequest(sysProxy.getViewManager().getStaticConf().getRSAPrivateKey(), "NEWCHANNEL", channel, bytes), null, TOMMessageType.ORDERED_REQUEST); Timer timer = new Timer(); timer.schedule(new BatchTimeout(channel), (BatchTimeout.get(channel) / 1000000)); timers.put(channel, timer); logger.info("Setting up system for new channel '" + channel + "'"); nextID++; } } catch (IOException e) { logger.error("Failed to launch frontend", e); System.exit(1); } } private static String readString(DataInputStream is) throws IOException { byte[] bytes = readBytes(is); return new String(bytes); } private static boolean readBoolean(DataInputStream is) throws IOException { byte[] bytes = readBytes(is); return bytes[0] == 1; } private static byte[] readBytes(DataInputStream is) throws IOException { long size = readLong(is); logger.debug("Read number of bytes: " + size); byte[] bytes = new byte[(int) size]; is.read(bytes); logger.debug("Read all bytes!"); return bytes; } private static long readLong(DataInputStream is) throws IOException { byte[] buffer = new byte[8]; is.read(buffer); //This is for little endian //long value = 0; //for (int i = 0; i < by.length; i++) //{ // value += ((long) by[i] & 0xffL) << (8 * i); //} //This is for big endian long value = 0; for (int i = 0; i < buffer.length; i++) { value = (value << 8) + (buffer[i] & 0xff); } return value; } private static long readInt() throws IOException { byte[] buffer = new byte[4]; long value = 0; is.read(buffer); for (int i = 0; i < buffer.length; i++) { value = (value << 8) + (buffer[i] & 0xff); } return value; } private static synchronized void resetTimer(String channel) { if (timers.get(channel) != null) timers.get(channel).cancel(); Timer timer = new Timer(); timer.schedule(new BatchTimeout(channel), (BatchTimeout.get(channel) / 1000000)); timers.put(channel, timer); } private static class ReceiverThread extends Thread { private int id; private UnixDomainSocket recv; private DataInputStream input; private AsynchServiceProxy out; public ReceiverThread(UnixDomainSocket recv, int id) throws IOException { this.id = id; this.recv = recv; this.input = new DataInputStream(this.recv.getInputStream()); this.out = new AsynchServiceProxy(this.id, configDir, new KeyLoader() { @Override public PublicKey loadPublicKey(int i) throws IOException, NoSuchAlgorithmException, InvalidKeySpecException, CertificateException { return null; } @Override public PublicKey loadPublicKey() throws IOException, NoSuchAlgorithmException, InvalidKeySpecException, CertificateException { return null; } @Override public PrivateKey loadPrivateKey() throws IOException, NoSuchAlgorithmException, InvalidKeySpecException { return null; } @Override public String getSignatureAlgorithm() { return null; } }, Security.getProvider("BC")); } public void run() { String channelID; boolean isConfig; byte[] env; while (true) { try { channelID = readString(this.input); isConfig = readBoolean(this.input); env = readBytes(this.input); resetTimer(channelID); logger.debug("Received envelope" + Arrays.toString(env) + " for channel id " + channelID + (isConfig ? " (type config)" : " (type normal)")); this.out.invokeAsynchRequest(BFTCommon.serializeRequest(this.id, (isConfig ? "CONFIG" : "REGULAR"), channelID, env), new ReplyListener(){ private int replies = 0; @Override public void reset() { replies = 0; } @Override public void replyReceived(RequestContext rc, TOMMessage tomm) { if (Arrays.equals(tomm.getContent(), "ACK".getBytes())) replies++; double q = Math.ceil((double) (out.getViewManager().getCurrentViewN() + out.getViewManager().getCurrentViewF() + 1) / 2.0); if (replies >= q) { out.cleanAsynchRequest(rc.getOperationId()); } } }, TOMMessageType.ORDERED_REQUEST); } catch (IOException ex) { logger.error("Error while receiving envelope from Go component", ex); continue; } if (envelopeMeasurementStartTime == -1) { envelopeMeasurementStartTime = System.currentTimeMillis(); } countEnvelopes++; if (countEnvelopes % interval == 0) { float tp = (float) (interval * 1000 / (float) (System.currentTimeMillis() - envelopeMeasurementStartTime)); logger.info("Throughput = " + tp + " envelopes/sec"); envelopeMeasurementStartTime = System.currentTimeMillis(); } //byte[] reply = proxy.invokeOrdered(bytes); //by = new byte[8]; //by[0] = (byte) ((byte) value>>56); //by[1] = (byte) ((byte) value>>48); //by[2] = (byte) ((byte) value>>40); //by[3] = (byte) ((byte) value>>32); //by[4] = (byte) ((byte) value>>24); //by[5] = (byte) ((byte) value>>16); //by[6] = (byte) ((byte) value>>8); //by[7] = (byte) ((byte) value>>0); } } } private static class SenderThread extends Thread { public void run() { while (true) { Map.Entry<String,Common.Block> reply = sysProxy.getNext(); logger.info("Received block # " + reply.getValue().getHeader().getNumber()); if (reply != null) { try { String[] params = reply.getKey().split("\\:"); boolean isConfig = Boolean.parseBoolean(params[1]); if (isConfig) { //if config block, make sure to update the timeout in case it was changed Common.Envelope env = Common.Envelope.parseFrom(reply.getValue().getData().getData(0)); Common.Payload payload = Common.Payload.parseFrom(env.getPayload()); Common.ChannelHeader chanHeader = Common.ChannelHeader.parseFrom(payload.getHeader().getChannelHeader()); if (chanHeader.getType() == Common.HeaderType.CONFIG_VALUE) { Configtx.ConfigEnvelope confEnv = Configtx.ConfigEnvelope.parseFrom(payload.getData()); Map<String,Configtx.ConfigGroup> groups = confEnv.getConfig().getChannelGroup().getGroupsMap(); Configuration.BatchTimeout timeout = Configuration.BatchTimeout.parseFrom(groups.get("Orderer").getValuesMap().get("BatchTimeout").getValue()); Duration duration = BFTCommon.parseDuration(timeout.getTimeout()); BatchTimeout.put(params[0], duration.toNanos()); } } byte[] bytes = reply.getValue().toByteArray(); DataOutputStream os = outputs.get(params[0]); os.writeLong(bytes.length); os.write(bytes); os.writeLong(1); os.write(isConfig ? (byte) 1 : (byte) 0); } catch (IOException ex) { logger.error("Error while sending block to Go component", ex); } } } } } private static class BatchTimeout extends TimerTask { String channel; BatchTimeout(String channel) { this.channel = channel; } @Override public void run() { try { int reqId = sysProxy.invokeAsynchRequest(BFTCommon.assembleSignedRequest(sysProxy.getViewManager().getStaticConf().getPrivateKey(), frontendID, "TIMEOUT", this.channel,new byte[0]), null, TOMMessageType.ORDERED_REQUEST); sysProxy.cleanAsynchRequest(reqId); Timer timer = new Timer(); timer.schedule(new BatchTimeout(this.channel), (BatchTimeout.get(channel) / 1000000)); timers.put(this.channel, timer); } catch (IOException ex) { logger.error("Failed to send envelope to nodes", ex); } } } }
37.099788
236
0.554481
96322f17bc2d57b2dc4a0e02122cdb99b3598702
158
/** * Contains fun search to prevent our snake to do certain things * @author carl.lajeunesse * */ package ai.nettogrof.battlesnake.treesearch.search.fun;
26.333333
64
0.753165
c5e0b02062266adf0bbba65e1e98d180fa432ebc
1,654
package net.pugsworth.manythings.entity; import net.fabricmc.fabric.api.entity.FabricEntityTypeBuilder; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityCategory; import net.minecraft.entity.EntityDimensions; import net.minecraft.entity.EntityType; import net.minecraft.util.Identifier; import net.minecraft.util.registry.Registry; import net.pugsworth.manythings.ManyThingsMod; import net.pugsworth.manythings.entity.projectile.ArrowExplodingEntity; import net.pugsworth.manythings.entity.thrown.ThrownDynamiteStickEntity; public class ModEntities { public static EntityType<ArrowExplodingEntity> ARROW_EXPLODING_ENTITY; public static EntityType<ThrownDynamiteStickEntity> THROWN_DYNAMITE_STICK_ENTITY; public static void RegisterEntities() { if (ManyThingsMod.CONFIG.isAllowed(ManyThingsMod.CONFIG.enableExplodingArrow)) { ARROW_EXPLODING_ENTITY = registerEntity("arrow_exploding_entity", FabricEntityTypeBuilder.<ArrowExplodingEntity>create(EntityCategory.MISC, ArrowExplodingEntity::new).size(EntityDimensions.fixed(0.5f, 0.5f)).build()); THROWN_DYNAMITE_STICK_ENTITY = registerEntity("thrown_dynamite_stick_entity", FabricEntityTypeBuilder.<ThrownDynamiteStickEntity>create(EntityCategory.MISC, ThrownDynamiteStickEntity::new).size(EntityDimensions.fixed(0.25f, 0.25f)).build()); } } public static <T extends Entity> EntityType<T> registerEntity(String id, EntityType<T> entityType) { return Registry.register( Registry.ENTITY_TYPE, new Identifier(ManyThingsMod.MODID, id), entityType ); } }
45.944444
253
0.779927
6e2d657d8b07b6f6514ca80995a8a850bde4a0bb
547
package com.diancan.service.resto; import com.diancan.domain.resto.DialingTable; import java.sql.Date; import java.util.List; public interface DialingTableService { DialingTable findOneById(Long id); DialingTable findOneByNum(Integer num); List<DialingTable> findMultipleByGivenRestaurantId(Long restaurantId); List<DialingTable> findMultipleByIsBooked(Boolean isBooked); List<DialingTable> findMultipleByBookedTime(Integer bookedTime); List<DialingTable> findMultipleByGivenStartBookedTime(Date startBookTime); }
24.863636
78
0.804388
e561778995252dcb794077aec7730051e44b5105
6,258
/* Copyright (c) 2017 atacama | Software GmbH * * 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 de.atacama.apenio.nks.api; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import de.atacama.apenio.nks.api.builder.Nks; import de.atacama.apenio.nks.api.builder.query.elastic.ElasticQueryBuilder; import de.atacama.apenio.nks.api.builder.query.simple.BasicEntries; import de.atacama.apenio.nks.api.builder.query.simple.SimpleQueryBuilder; import org.elasticsearch.action.search.SearchRequest; import org.elasticsearch.action.search.SearchType; import org.elasticsearch.index.query.*; import org.elasticsearch.index.search.MatchQuery; import org.elasticsearch.search.builder.SearchSourceBuilder; import java.io.IOException; public class Debug { public static void main(String[] args) throws IOException { QueryBuilder query = new QueryBuilder(); query.setLanguage("de"); query.setSearchDepth(5); query.addTarget(new TargetBuilder("InterventionOrdner").addStructure("AkutPflege_")); query.addAttribute("MännlichGeschlecht_"); query.addAttribute("HochaltrigeAlter_"); query.addSimpleConcept("UA1732"); query.addSimpleConcept("PC1234"); query.setSearchText("unterstützen"); //NksResponse response = NksRequest.INSTANCE.access(query); //System.out.println(new GsonBuilder().setPrettyPrinting().create().toJson(response)); //System.out.println("Results: " + response.size()); //NksResponse response = Nks.newConnection("http://apenioapp02:19080").prepareRequest().get().appliances().cName("IA123").execute(); //NksResponse response = Nks.newConnection("http://apenioapp02:19080").prepareRequest().access().element().createSimpleQuery().addConcept("IA123").done().execute(); //System.out.println(new GsonBuilder().setPrettyPrinting().create().toJson(response)); //System.out.println("Results: " + response.size()); /*Nks.newConnection("").prepareRequest().search().proposal().createSimpleQuery() .addTargets() .causes() .addStructure("Test").addStructure("") .done() .bodyLocations() .done() .done();*/ Gson gson = new Gson(); SimpleQueryBuilder response = Nks.newConnection("http://192.168.1.18:8080/NksService").prepareRequest().access().element().createSimpleQuery().defineTemplate().defaultTemplate().setNoxgrade().done().addTargets().shapes().addStructure("AkutPflege_").done().done().setOrder().list(); //System.out.println(gson.toJson(response.getQuery())); //SimpleQueryBuilder response = Nks.newConnection("http://192.168.0.144/nks/NksService").prepareRequest().access().element().createSimpleQuery().defineTemplate().structureTemplate().setDeprecatedElements().done().addTargets().interventions().done().done().addConceptByCName("IA123").done().setOrder().single().getDeprecatedElements(); //NksResponse response = Nks.newConnection("http://localhost:8080").prepareRequest().get().interventions().cName("IA123").execute(); //System.out.println(gson.toJson(response.getQuery())); NksResponse res = response.execute(); System.out.println(response.getPath()); System.out.println(gson.toJson(res)); //Bool Query BoolQueryBuilder boolQuery = QueryBuilders.boolQuery(); SearchSourceBuilder source = new SearchSourceBuilder(); source.query(boolQuery); SearchRequest request = new SearchRequest(new String[]{"trunk"}); request.source(source); request.searchType(SearchType.DFS_QUERY_THEN_FETCH); source.from(0).size(10); //MUST String value = "*Ver*"; QueryStringQueryBuilder stringQuery = QueryBuilders.queryStringQuery(value); stringQuery.defaultOperator(Operator.AND); stringQuery.field("http://www.w3.org/2002/07/owl#hasLabel@de"); boolQuery.must(stringQuery); //MUST NOT MatchQueryBuilder matchQuery = QueryBuilders.matchQuery("http://www.apenio.atacama.de/core#storno", "1"); boolQuery.mustNot(matchQuery); //FILTER TermsQueryBuilder category = QueryBuilders.termsQuery("http://www.apenio.atacama.de/core#hasCategory", new String[]{"http://www.apenio.atacama.de/ta#InterventionOrdner"}); TermsQueryBuilder structure = QueryBuilders.termsQuery("http://www.apenio.atacama.de/core#hasStructure", new String[]{"http://www.apenio.atacama.de/ta#Hebamme"}); boolQuery.filter(category); //boolQuery.filter(structure); /*ElasticQueryBuilder builder = Nks.newConnection("http://ce0013:8080/NksService") .prepareV3Request().elastic().request().setSearchRequest(request); System.out.println(builder.getPath()); NksResponse response = builder.execute(); System.out.println("Done!"); */ //NksResponse response = Nks.newConnection("http://apenioapp02:19080").prepareRequest().access().element().createSimpleQuery(). //NksResponse response = Nks.newConnection("http://localhost:8080").prepareRequest().get().appliances().list().execute(); /* response = Nks.newConnection("http://localhost:8080").prepareRequest().search() .catalog() .createSimpleQuery() .addTargets() .appliances().done() .done() .setSearchText("Pfeffer").execute(); */ } }
49.666667
342
0.72643
eab5ff7c6c97eb1ed200156068ef7640e63dac84
14,194
package eu.isas.reporter.gui.tablemodels; import com.compomics.util.exceptions.ExceptionHandler; import com.compomics.util.experiment.identification.Identification; import com.compomics.util.experiment.identification.matches.SpectrumMatch; import com.compomics.util.experiment.identification.peptide_shaker.PSParameter; import com.compomics.util.experiment.mass_spectrometry.SpectrumProvider; import com.compomics.util.experiment.mass_spectrometry.spectra.Precursor; import com.compomics.util.experiment.quantification.reporterion.ReporterIonQuantification; import com.compomics.util.gui.tablemodels.SelfUpdatingTableModel; import com.compomics.util.math.BasicMathFunctions; import com.compomics.util.parameters.identification.IdentificationParameters; import com.compomics.util.parameters.identification.search.SearchParameters; import com.compomics.util.waiting.WaitingHandler; import eu.isas.peptideshaker.gui.tabpanels.SpectrumIdentificationPanel; import eu.isas.peptideshaker.scoring.PSMaps; import eu.isas.peptideshaker.scoring.maps.InputMap; import eu.isas.peptideshaker.utils.DisplayFeaturesGenerator; import eu.isas.reporter.calculation.QuantificationFeaturesGenerator; import eu.isas.reporter.preferences.DisplayPreferences; import eu.isas.reporter.quantificationdetails.PsmQuantificationDetails; import java.awt.Color; import java.util.ArrayList; import java.util.Collections; import no.uib.jsparklines.data.JSparklinesDataSeries; /** * Model for the PSM table. * * @author Marc Vaudel * @author Harald Barsnes */ public class PsmTableModel extends SelfUpdatingTableModel { /** * The identification of this project. */ private Identification identification; /** * The spectrum provider. */ private SpectrumProvider spectrumProvider; /** * The display features generator. */ private DisplayFeaturesGenerator displayFeaturesGenerator; /** * The ID input map. */ private InputMap inputMap; /** * The identification parameters. */ private IdentificationParameters identificationParameters; /** * The quantification feature generator. */ private QuantificationFeaturesGenerator quantificationFeaturesGenerator; /** * The reporter ion quantification. */ private ReporterIonQuantification reporterIonQuantification; /** * The sample indexes. */ private ArrayList<String> sampleIndexes; /** * A list of ordered PSM keys. */ private long[] psmKeys = null; /** * Indicates whether the scores should be displayed instead of the * confidence */ private boolean showScores = false; /** * The batch size. */ private int batchSize = 20; /** * The exception handler catches exceptions. */ private ExceptionHandler exceptionHandler; /** * The display preferences. */ private DisplayPreferences displayPreferences; /** * Constructor which sets a new empty table. */ public PsmTableModel() { } /** * Constructor which sets a new table. * * @param identification the identification object containing the matches * @param spectrumProvider the spectrum provider * @param displayFeaturesGenerator the display features generator * @param displayPreferences the display preferences * @param reporterIonQuantification the reporter quantification information * @param quantificationFeaturesGenerator the quantification feature * @param identificationParameters the identification parameters * @param psmKeys the PSM keys * @param displayScores boolean indicating whether the scores should be * displayed instead of the confidence * @param exceptionHandler handler for the exceptions */ public PsmTableModel( Identification identification, SpectrumProvider spectrumProvider, DisplayFeaturesGenerator displayFeaturesGenerator, DisplayPreferences displayPreferences, IdentificationParameters identificationParameters, ReporterIonQuantification reporterIonQuantification, QuantificationFeaturesGenerator quantificationFeaturesGenerator, long[] psmKeys, boolean displayScores, ExceptionHandler exceptionHandler ) { this.identification = identification; this.spectrumProvider = spectrumProvider; this.displayFeaturesGenerator = displayFeaturesGenerator; this.displayPreferences = displayPreferences; this.reporterIonQuantification = reporterIonQuantification; this.quantificationFeaturesGenerator = quantificationFeaturesGenerator; this.identificationParameters = identificationParameters; this.psmKeys = psmKeys; this.showScores = displayScores; this.exceptionHandler = exceptionHandler; PSMaps pSMaps = new PSMaps(); pSMaps = (PSMaps) identification.getUrParam(pSMaps); inputMap = pSMaps.getInputMap(); sampleIndexes = new ArrayList<String>(reporterIonQuantification.getSampleIndexes()); Collections.sort(sampleIndexes); } /** * Update the data in the table model without having to reset the whole * table model. This keeps the sorting order of the table. * * @param identification the identification object containing the matches * @param spectrumProvider the spectrum provider * @param displayFeaturesGenerator the display features generator * @param displayPreferences the display preferences * @param reporterIonQuantification the reporter quantification information * @param quantificationFeaturesGenerator the quantification feature * @param identificationParameters the identification parameters * @param psmKeys the PSM keys * @param displayScores boolean indicating whether the scores should be * displayed instead of the confidence */ public void updateDataModel( Identification identification, SpectrumProvider spectrumProvider, DisplayFeaturesGenerator displayFeaturesGenerator, DisplayPreferences displayPreferences, IdentificationParameters identificationParameters, ReporterIonQuantification reporterIonQuantification, QuantificationFeaturesGenerator quantificationFeaturesGenerator, long[] psmKeys, boolean displayScores ) { this.identification = identification; this.displayFeaturesGenerator = displayFeaturesGenerator; this.displayPreferences = displayPreferences; this.reporterIonQuantification = reporterIonQuantification; this.quantificationFeaturesGenerator = quantificationFeaturesGenerator; this.identificationParameters = identificationParameters; this.psmKeys = psmKeys; this.showScores = displayScores; PSMaps pSMaps = new PSMaps(); pSMaps = (PSMaps) identification.getUrParam(pSMaps); inputMap = pSMaps.getInputMap(); sampleIndexes = new ArrayList<String>(reporterIonQuantification.getSampleIndexes()); Collections.sort(sampleIndexes); } /** * Resets the peptide keys. */ public void reset() { psmKeys = null; } @Override public int getRowCount() { return psmKeys == null ? 0 : psmKeys.length; } @Override public int getColumnCount() { return 8; } @Override public String getColumnName(int column) { switch (column) { case 0: return " "; case 1: return "Quant"; case 2: return "ID"; case 3: return "Sequence"; case 4: return "Charge"; case 5: return "m/z Error"; case 6: if (showScores) { return "Score"; } else { return "Confidence"; } case 7: return ""; default: return ""; } } @Override public Object getValueAt(int row, int column) { int viewIndex = getViewIndex(row); if (viewIndex < psmKeys.length) { if (column == 0) { return viewIndex + 1; } // if (isScrolling) { // return null; // } // // if (!isSelfUpdating()) { // dataMissingAtRow(row); // return DisplayParameters.LOADING_MESSAGE; // } long psmKey = psmKeys[viewIndex]; SpectrumMatch spectrumMatch = identification.getSpectrumMatch(psmKey); switch (column) { case 1: ArrayList<Double> data = new ArrayList<>(); PsmQuantificationDetails quantificationDetails = quantificationFeaturesGenerator.getPSMQuantificationDetails(spectrumProvider, spectrumMatch.getKey()); ArrayList<String> reagentsOrder = displayPreferences.getReagents(); for (String tempReagent : reagentsOrder) { int sampleIndex = sampleIndexes.indexOf(tempReagent); Double ratio = quantificationDetails.getRatio( sampleIndexes.get(sampleIndex), reporterIonQuantification.getNormalizationFactors() ); if (ratio != null) { if (ratio != 0) { ratio = BasicMathFunctions.log(ratio, 2); } data.add(ratio); } } return new JSparklinesDataSeries(data, Color.BLACK, null); case 2: return SpectrumIdentificationPanel.isBestPsmEqualForAllIdSoftware(spectrumMatch, identificationParameters.getSequenceMatchingParameters(), inputMap.getInputAlgorithmsSorted().size()); case 3: return displayFeaturesGenerator.getTaggedPeptideSequence(spectrumMatch, true, true, true); case 4: if (spectrumMatch.getBestPeptideAssumption() != null) { return spectrumMatch.getBestPeptideAssumption().getIdentificationCharge(); } else if (spectrumMatch.getBestTagAssumption() != null) { return spectrumMatch.getBestTagAssumption().getIdentificationCharge(); } else { throw new IllegalArgumentException("No best assumption found for spectrum " + psmKey + "."); } case 5: Precursor precursor = spectrumProvider.getPrecursor(spectrumMatch.getSpectrumFile(), spectrumMatch.getSpectrumTitle()); SearchParameters searchParameters = identificationParameters.getSearchParameters(); if (spectrumMatch.getBestPeptideAssumption() != null) { return Math.abs( spectrumMatch.getBestPeptideAssumption().getDeltaMz( precursor.mz, searchParameters.isPrecursorAccuracyTypePpm(), searchParameters.getMinIsotopicCorrection(), searchParameters.getMaxIsotopicCorrection() ) ); } else if (spectrumMatch.getBestTagAssumption() != null) { return Math.abs( spectrumMatch.getBestTagAssumption().getDeltaMz( precursor.mz, searchParameters.isPrecursorAccuracyTypePpm(), searchParameters.getMinIsotopicCorrection(), searchParameters.getMaxIsotopicCorrection() ) ); } else { throw new IllegalArgumentException("No best assumption found for spectrum " + psmKey + "."); } case 6: PSParameter psParameter = (PSParameter) spectrumMatch.getUrParam(PSParameter.dummy); return showScores ? psParameter.getTransformedScore() : psParameter.getConfidence(); case 7: psParameter = (PSParameter) spectrumMatch.getUrParam(PSParameter.dummy); return psParameter.getMatchValidationLevel().getIndex(); default: return null; } } return null; } /** * Indicates whether the table content was instantiated. * * @return a boolean indicating whether the table content was instantiated. */ public boolean isInstantiated() { return identification != null; } @Override public Class getColumnClass(int columnIndex) { for (int i = 0; i < getRowCount(); i++) { if (getValueAt(i, columnIndex) != null) { return getValueAt(i, columnIndex).getClass(); } } return String.class; } @Override public boolean isCellEditable(int rowIndex, int columnIndex) { return false; } @Override protected void catchException(Exception e) { setSelfUpdating(false); exceptionHandler.catchException(e); } @Override protected int loadDataForRows(ArrayList<Integer> rows, WaitingHandler waitingHandler) { boolean canceled = rows.stream() .map(i -> identification.getSpectrumMatch(psmKeys[i])) .anyMatch(dummy -> waitingHandler.isRunCanceled()); return canceled ? rows.get(0) : rows.get(rows.size() - 1); } }
37.157068
203
0.620755
d97f059197681cbd74fdf51430634395f833a860
1,299
package Negocios; import java.io.Serializable; public class Lesson implements Serializable { private static final long serialVersionUID = 1L; private String lessonID; private Subject subject; private Teacher teacher; private Career career; private String hour; public Lesson() {} public Lesson(String lessonID, Subject subject, Teacher teacher, Career career, String hour) { this.lessonID = lessonID; this.subject = subject; this.teacher = teacher; this.career = career; this.hour = hour; } public String getLessonID() { return lessonID; } public void setLessonID(String lessonID) { this.lessonID = lessonID; } public Subject getSubject() { return subject; } public void setSubject(Subject subject) { this.subject = subject; } public Teacher getTeacher() { return teacher; } public void setTeacher(Teacher teacher) { this.teacher = teacher; } public Career getCareer() { return career; } public void setCareer(Career career) { this.career = career; } public String getHour() { return hour; } public void setHour(String hour) { this.hour = hour; } }
20.619048
98
0.619707
35ec0477e4389411f65916162bcc99881b95a81b
599
package base.patient.mapper; import base.core.mapper.BaseMapper; import base.patient.model.Hospital; import org.apache.ibatis.annotations.Param; import java.util.List; /** * Created by zyn on 10/24/16. */ public interface HospitalMapper extends BaseMapper<Hospital> { List<Hospital> findByUserID(int userId); List<Hospital> findByIds(@Param("ids")String ids); int addUser2Hospital(@Param("userId") int userId,@Param("hospitalId") int hospitalId); int removeHospitalByUser(int userId); int deleteHospitalByHospital(int HospitalID); int deleteById(int id); }
35.235294
91
0.736227
18957170994a5325d267b9b5e26142b8785bf664
723
package com.bolyartech.forge.server.tple.rythm; import com.bolyartech.forge.server.misc.TemplateEngine; import org.rythmengine.RythmEngine; import java.util.HashMap; import java.util.Map; public class RythmTemplateEngine implements TemplateEngine { private final RythmEngine mRythmEngine; private final Map<String, Object> mAttributes = new HashMap<>(); public RythmTemplateEngine(RythmEngine rythmEngine) { mRythmEngine = rythmEngine; } @Override public void assign(String varName, Object object) { mAttributes.put(varName, object); } @Override public String render(String templateName) { return mRythmEngine.render(templateName, mAttributes); } }
23.322581
68
0.73444
6580e1d0ea454b5ed277c2671be7adcfd6a75cba
447
package cz.metacentrum.perun.webgui.json.keyproviders; import com.google.gwt.view.client.ProvidesKey; import cz.metacentrum.perun.webgui.model.FacilityState; /** * Provides key for tables with FacilityState objects * * @author Pavel Zlamal <256627@mail.muni.cz> */ public class FacilityStateKeyProvider implements ProvidesKey<FacilityState> { public Object getKey(FacilityState o) { // returns ID return o.getFacility().getId(); } }
23.526316
77
0.769575
c7c6d019f6666e545810ac4f88bb78aebfb78b15
360
package com.algaworks.algafood.api.controller.model.input; import javax.validation.Valid; import javax.validation.constraints.NotBlank; import javax.validation.constraints.NotNull; import lombok.Getter; import lombok.Setter; @Getter @Setter public class CidadeInput { @NotBlank private String nome; @NotNull @Valid private EstadoIdInput estado; }
16.363636
58
0.8
989471a91decee3218a7004c697f671914e10d3d
3,271
/* * Copyright (C) 2008-2013, fluid Operations AG * * FedX is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.fluidops.fedx.algebra; import java.util.Collection; import java.util.Set; import org.eclipse.rdf4j.query.algebra.AbstractQueryModelNode; import org.eclipse.rdf4j.query.algebra.Filter; import org.eclipse.rdf4j.query.algebra.QueryModelNode; import org.eclipse.rdf4j.query.algebra.QueryModelVisitor; import org.eclipse.rdf4j.query.algebra.Service; import org.eclipse.rdf4j.query.algebra.StatementPattern; import org.eclipse.rdf4j.query.algebra.TupleExpr; import org.eclipse.rdf4j.query.algebra.Union; import org.eclipse.rdf4j.query.algebra.helpers.AbstractQueryModelVisitor; import com.fluidops.fedx.structures.QueryInfo; public class FedXService extends AbstractQueryModelNode implements TupleExpr, FedXExpr, BoundJoinTupleExpr { private static final long serialVersionUID = -825303693177221091L; protected Service expr; protected QueryInfo queryInfo; protected boolean simple = true; // consists of BGPs only protected int nTriples = 0; public FedXService(Service expr, QueryInfo queryInfo) { this.expr = expr; this.queryInfo = queryInfo; expr.visit(new ServiceAnalyzer()); } public Service getService() { return this.expr; } public QueryInfo getQueryInfo() { return queryInfo; } public int getNumberOfTriplePatterns() { return nTriples; } public boolean isSimple() { return simple; } public Collection<String> getFreeVars() { return expr.getServiceVars(); } public int getFreeVarCount() { return expr.getServiceVars().size(); } @Override public <X extends Exception> void visit(QueryModelVisitor<X> visitor) throws X { visitor.meetOther(this); } @Override public <X extends Exception> void visitChildren(QueryModelVisitor<X> visitor) throws X { expr.visit(visitor); } @Override public FedXService clone() { return (FedXService)super.clone(); } @Override public Set<String> getAssuredBindingNames() { return expr.getAssuredBindingNames(); } @Override public Set<String> getBindingNames() { return expr.getBindingNames(); } private class ServiceAnalyzer extends AbstractQueryModelVisitor<RuntimeException> { @Override protected void meetNode(QueryModelNode node) { if (node instanceof StatementTupleExpr) { nTriples++; } else if (node instanceof StatementPattern) { nTriples++; } else if (node instanceof Filter) { simple=false; } else if (node instanceof Union){ simple=false; } super.meetNode(node); } } @Override public void visit(FedXExprVisitor v) { v.meet(this); } }
24.969466
108
0.745644
ad063b444c0aec392fc1c5af5e72eed2eda2f7e6
3,415
package com.bugsnag.android; import static org.junit.Assert.assertEquals; import android.support.test.filters.SmallTest; import android.support.test.runner.AndroidJUnit4; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import java.util.Map; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; @RunWith(AndroidJUnit4.class) @SmallTest public class ClientNotifyTest { private Client client; private FakeClient apiClient; /** * Generates a configuration and clears sharedPrefs values to begin the test with a clean slate * * @throws Exception if initialisation failed */ @SuppressWarnings("deprecation") @Before public void setUp() throws Exception { client = BugsnagTestUtils.generateClient(); apiClient = new FakeClient(); client.setErrorReportApiClient(apiClient); } @After public void tearDown() throws Exception { Async.cancelTasks(); } @Test public void testNotifyBlockingDefaultSeverity() { client.notifyBlocking(new RuntimeException("Testing")); assertEquals(Severity.WARNING, apiClient.report.getError().getSeverity()); } @Test public void testNotifyBlockingCallback() { client.notifyBlocking(new RuntimeException("Testing"), new Callback() { @Override public void beforeNotify(Report report) { report.getError().setUserName("Foo"); } }); Error error = apiClient.report.getError(); assertEquals(Severity.WARNING, error.getSeverity()); assertEquals("Foo", error.getUser().getName()); } @Test public void testNotifyBlockingCustomSeverity() { client.notifyBlocking(new RuntimeException("Testing"), Severity.INFO); assertEquals(Severity.INFO, apiClient.report.getError().getSeverity()); } @Test public void testNotifyBlockingCustomStackTrace() { StackTraceElement[] stacktrace = { new StackTraceElement("MyClass", "MyMethod", "MyFile", 5) }; client.notifyBlocking("Name", "Message", stacktrace, new Callback() { @Override public void beforeNotify(Report report) { report.getError().setSeverity(Severity.ERROR); } }); Error error = apiClient.report.getError(); assertEquals(Severity.ERROR, error.getSeverity()); assertEquals("Name", error.getExceptionName()); assertEquals("Message", error.getExceptionMessage()); } @SuppressWarnings("deprecation") static class FakeClient implements ErrorReportApiClient { CountDownLatch latch = new CountDownLatch(1); Report report; @Override public void postReport(String urlString, Report report, Map<String, String> headers) throws NetworkException, BadResponseException { try { Thread.sleep(10); // simulate async request } catch (InterruptedException ignored) { ignored.printStackTrace(); } this.report = report; latch.countDown(); } void awaitReport() throws InterruptedException { latch.await(2000, TimeUnit.MILLISECONDS); } } }
30.765766
99
0.64041
c9c38a45f5e47285a5c622910dc06ee9788637f7
479
package pushDominoes; import PushDominoes.Solution; import org.junit.Assert; import org.junit.Test; public class SolutionTest { @Test public void test1() { Solution s = new Solution(); System.out.println(".L.R...LR..L.."); Assert.assertEquals("LL.RR.LLRRLL..", s.pushDominoes(".L.R...LR..L..")); } @Test public void test2() { Solution s = new Solution(); Assert.assertEquals("RR.L", s.pushDominoes("RR.L")); } }
22.809524
80
0.601253
26c321ae0c1193f28614fa7903b4ba126429f310
2,818
package me.arasple.mc.trchat.utils; import io.izzel.taboolib.module.inject.TSchedule; import me.arasple.mc.trchat.TrChat; import me.arasple.mc.trchat.TrChatFiles; import me.clip.placeholderapi.PlaceholderAPI; import me.clip.placeholderapi.PlaceholderAPIPlugin; import me.clip.placeholderapi.expansion.cloud.CloudExpansion; import org.bukkit.Bukkit; import org.bukkit.entity.Player; import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; /** * @author Arasple * @date 2019/11/29 21:29 */ public class Vars { @TSchedule(delay = 20 * 15) public static void downloadExpansions() { downloadExpansions(TrChatFiles.getSettings().getStringList("GENERAL.DEPEND-EXPANSIONS")); } /** * 自动下载 PlaceholderAPI 拓展变量并注册 * * @param expansions 拓展 */ public static void downloadExpansions(List<String> expansions) { if (expansions != null && expansions.size() > 0) { if (PlaceholderAPIPlugin.getInstance().getExpansionCloud().getCloudExpansions().isEmpty()) { PlaceholderAPIPlugin.getInstance().getExpansionCloud().fetch(false); } List<String> unInstalled = expansions.stream().filter(d -> PlaceholderAPI.getExpansions().stream().noneMatch(e -> e.getName().equalsIgnoreCase(d)) && PlaceholderAPIPlugin.getInstance().getExpansionCloud().getCloudExpansion(d) != null && !PlaceholderAPIPlugin.getInstance().getExpansionCloud().isDownloading(d)).collect(Collectors.toList()); if (unInstalled.size() > 0) { unInstalled.forEach(ex -> { CloudExpansion cloudExpansion = PlaceholderAPIPlugin.getInstance().getExpansionCloud().getCloudExpansion(ex); PlaceholderAPIPlugin.getInstance().getExpansionCloud().downloadExpansion(null, cloudExpansion); }); Bukkit.getScheduler().runTaskLater(TrChat.getPlugin(), () -> PlaceholderAPIPlugin.getInstance().getExpansionManager().registerAllExpansions(), 40); } } } /** * 使用 PlaceholderAPI 变量替换 * * @param player 玩家 * @param strings 内容 * @return 替换后内容 */ public static List<String> replace(Player player, List<String> strings) { List<String> results = new ArrayList<>(); strings.forEach(str -> results.add(replace(player, str))); return results; } /** * 使用 PlaceholderAPI 变量替换 * * @param player 玩家 * @param string 内容 * @return 替换后内容 */ public static String replace(Player player, String string) { if (string == null || player == null) { return string; } if (player instanceof Player) { return PlaceholderAPI.setPlaceholders(player, string); } return string; } }
35.670886
352
0.656494
1a94de4370e490ba11d230a699d4c9dd6122dd48
389
package com.duan.blogos.dto.blogger; import lombok.Data; import java.io.Serializable; /** * Created on 2018/5/4. * * @author j_jiasheng */ @Data public class BloggerBriefDTO implements Serializable { private static final long serialVersionUID = -5298929293069099257L; // 博主统计信息 private BloggerStatisticsDTO statistics; // 博主 dto private BloggerDTO blogger; }
16.913043
71
0.727506
1bea27ec6ec3bfeffc9ffb7e93f660a130df231a
12,158
/** * Copyright 2005 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.nutch.admin.scheduling; import java.io.IOException; import java.io.InputStream; import java.text.ParseException; import java.util.Map; import java.util.Properties; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.quartz.CronTrigger; import org.quartz.JobDataMap; import org.quartz.JobDetail; import org.quartz.Scheduler; import org.quartz.SchedulerException; import org.quartz.SchedulerFactory; import org.quartz.Trigger; import org.quartz.impl.StdSchedulerFactory; /** * Scheduling service which uses the quartz scheduling framework. For example * and explanation of <i>cronExpression</i>s which are used to initialize cron * jobs see below(taken from quartz documentation). <p/> * * A cron expression has 6 mandatory and 1 optional elements separate with white * space. <br/> "sec min hour dayOfMonth Month dayOfWeek Year(optional)" <p/> * * An example of a complete cron-expression is the string "0 0 12 ? * WED" which * means "every Wednesday at 12:00 pm". <br> * <br> * * Individual sub-expressions can contain ranges and/or lists. For example, the * day of week field in the previous (which reads "WED") example could be * replaces with "MON-FRI", "MON, WED, FRI", or even "MON-WED,SAT". <br> * <br> * * Wild-cards (the '*' character) can be used to say "every" possible value of * this field. Therefore the '*' character in the "Month" field of the previous * example simply means "every month". A '*' in the Day-Of-Week field would * obviously mean "every day of the week". <br> * <br> * * All of the fields have a set of valid values that can be specified. These * values should be fairly obvious - such as the numbers 0 to 59 for seconds and * minutes, and the values 0 to 23 for hours. Day-of-Month can be any value * 0-31, but you need to be careful about how many days are in a given month! * Months can be specified as values between 0 and 11, or by using the strings * JAN, FEB, MAR, APR, MAY, JUN, JUL, AUG, SEP, OCT, NOV and DEC. Days-of-Week * can be specified as values between 1 and 7 (1 = Sunday) or by using the * strings SUN, MON, TUE, WED, THU, FRI and SAT. <br> * <br> * * The '/' character can be used to specify increments to values. For example, * if you put '0/15' in the Minutes field, it means 'every 15 minutes, starting * at minute zero'. If you used '3/20' in the Minutes field, it would mean * 'every 20 minutes during the hour, starting at minute three' - or in other * words it is the same as specifying '3,23,43' in the Minutes field. <br> * <br> * * The '?' character is allowed for the day-of-month and day-of-week fields. It * is used to specify "no specific value". This is useful when you need to * specify something in one of the two fields, but not the other. See the * examples below for clarification. <br> * <br> * * The 'L' character is allowed for the day-of-month and day-of-week fields. * This character is short-hand for "last", but it has different meaning in each * of the two fields. For example, the value "L" in the day-of-month field means * "the last day of the month" - day 31 for January, day 28 for February on * non-leap years. If used in the day-of-week field by itself, it simply means * "7" or "SAT". But if used in the day-of-week field after another value, it * means "the last xxx day of the month" - for example "6L" or "FRIL" both mean * "the last Friday of the month". When using the 'L' option, it is important * not to specify lists, or ranges of values, as you'll get confusing results. * <br> * <br> * * "0 0/25 * * * ?" Fire every 25 minutes<br> * * "10 0/5 * * * ?" Fires every 5 minutes, at 10 seconds after the minute (i.e. * 10:00:10 am, 10:05:10 am, etc.).</br> * * "0 0 12 * * ?" Fire at 12pm (noon) every day<br> * * "0 15 10 ? * *" Fire at 10:15am every day<br> * * "0 15 10 * * ?" Fire at 10:15am every day<br> * * "0 15 10 * * ? *" Fire at 10:15am every day<br> * * "0 15 10 * * ? 2005" Fire at 10:15am every day during the year 2005<br> * * "0 * 14 * * ?" Fire every minute starting at 2pm and ending at 2:59pm, every * day<br> * * "0 0/5 14 * * ?" Fire every 5 minutes starting at 2pm and ending at 2:55pm, * every day<br> * * "0 0/5 14,18 * * ?" Fire every 5 minutes starting at 2pm and ending at * 2:55pm, AND fire every 5 minutes starting at 6pm and ending at 6:55pm, every * day<br> * * "0 0-5 14 * * ?" Fire every minute starting at 2pm and ending at 2:05pm, * every day<br> * * "0 10,44 14 ? 3 WED" Fire at 2:10pm and at 2:44pm every Wednesday in the * month of March.<br> * * "0 15 10 ? * MON-FRI"Fire at 10:15am every Monday, Tuesday, Wednesday, * Thursday and Friday<br> * * "0 15 10 15 * ?" Fire at 10:15am on the 15th day of every month<br> * * "0 15 10 L * ?" Fire at 10:15am on the last day of every month<br> * * "0 15 10 ? * 6L" Fire at 10:15am on the last Friday of every month<br> * * "0 15 10 ? * 6L" Fire at 10:15am on the last Friday of every month<br> * * "0 15 10 ? * 6L 2002-2005" Fire at 10:15am on every last Friday of every * month during the years 2002, 2003, 2004 and 2005<br> * * "0 15 10 ? * 6#3" Fire at 10:15am on the third Friday of every month<br> * * <br/><br/>created on 11.10.2005 * */ public class SchedulingService { /** * */ public static final String CRAWL_JOB = "crawl"; private Scheduler fScheduler; private static final Log LOG = LogFactory.getLog(SchedulingService.class); /** * @throws SchedulerException * @throws IOException */ public SchedulingService(PathSerializable fileStorePath) throws SchedulerException, IOException { InputStream resourceAsStream = SchedulingService.class.getResourceAsStream("/quartz.properties"); Properties properties = new Properties(); if (resourceAsStream != null) { // load values from config file properties.load(resourceAsStream); } else { // use some default values properties.put( StdSchedulerFactory.PROP_JOB_STORE_CLASS, FileJobStore.class.getName() ); properties.put( StdSchedulerFactory.PROP_THREAD_POOL_CLASS, "org.quartz.simpl.SimpleThreadPool" ); properties.put("org.quartz.threadPool.threadCount", "5"); } properties.setProperty( "org.quartz.jobStore.storeFilePath", fileStorePath.toString() ); SchedulerFactory schedulerFactory = new StdSchedulerFactory(properties); this.fScheduler = schedulerFactory.getScheduler(); this.fScheduler.start(); } /** * @throws SchedulerException */ public void shutdown() throws SchedulerException { this.fScheduler.shutdown(); } /** * There will be one trigger for job, with the same name and group as the job. * All optional parameters could be left blank (null). For * cron-expression-examples see class description. * * @param jobName * @param jobGroup * (optional) * @param jobClass * @param jobData * (optional), will be available in * Job#execute(org.quartz.JobExecutionContext) * @param cronExpression * @throws ParseException * @throws SchedulerException */ public void scheduleCronJob( String jobName, String jobGroup, Class jobClass, Map<String,PathSerializable> jobData, String cronExpression) throws ParseException, SchedulerException { JobDetail jobDetail = new JobDetail(jobName, jobGroup, jobClass); if (jobData != null) { jobDetail.setJobDataMap(new JobDataMap(jobData)); } CronTrigger trigger = new CronTrigger(jobName, jobGroup); trigger.setCronExpression(cronExpression); this.fScheduler.deleteJob(jobName, jobGroup); this.fScheduler.scheduleJob(jobDetail, trigger); LOG.info("Job scheduled: jobName: " + jobName + " cronExp: " + cronExpression ); } /** * Schedule job with striped cronExpression. The cron expression will be * integrated from the single parameters sec - year. If you leave those * parameter blank, the "*"-character will be inserted. For * cron-expression-examples see class description. * * There will be one trigger for job, with the same name and group as the job. * * All optional parameters could be left blank (null). * * @param jobName * @param jobGroup * (optional) * @param jobClass * @param jobData * (optional), will be available in * Job#execute(org.quartz.JobExecutionContext) * @param sec * @param min * @param hours * @param dayOfMonth * @param month * @param dayOfWeek * @param year * @throws SchedulerException * @throws ParseException */ public void scheduleCronJob( String jobName, String jobGroup, Class jobClass, Map jobData, String sec, String min, String hours, String dayOfMonth, String month, String dayOfWeek, String year) throws ParseException, SchedulerException { String cronExpression = getCronExpression(sec, min, hours, dayOfMonth, month, dayOfWeek, year); scheduleCronJob(jobName, jobGroup, jobClass, jobData, cronExpression); LOG.info("Job scheduled: jobName: " + jobName + " time: " + year + " " + month + " " + dayOfMonth + " " + hours + " " + min + " " + sec); } /** * @param jobName * @param groupName * @return true if job exists * @throws SchedulerException */ public boolean removeJob(String jobName, String groupName) throws SchedulerException { return this.fScheduler.deleteJob(jobName, groupName); } /** * The cron expression will be integrated from the single parameters sec - * year. If you leave those parameter blank, the "*"-character will be * inserted. For cron-expression-examples see class description. * * @param sec * @param min * @param hours * @param dayOfMonth * @param month * @param dayOfWeek * @param year * @return the integrated cron expression */ public static String getCronExpression( String sec, String min, String hours, String dayOfMonth, String month, String dayOfWeek, String year) { StringBuffer buffer = new StringBuffer(); appendNextExpression(buffer, sec); appendNextExpression(buffer, min); appendNextExpression(buffer, hours); appendNextExpression(buffer, dayOfMonth); appendNextExpression(buffer, month); appendNextExpression(buffer, dayOfWeek); appendNextExpression(buffer, year); return buffer.toString(); } private static void appendNextExpression( StringBuffer buffer, String expression) { if (buffer.length() > 0) { buffer.append(" "); } if (expression == null) { buffer.append("*"); } else { buffer.append(expression); } } /** * @return * @throws SchedulerException */ public String getCronExpressions(String jobName, String jobGroup) throws SchedulerException { String ret = null; Trigger trigger = this.fScheduler.getTrigger(jobName, jobGroup); if (trigger instanceof CronTrigger) { CronTrigger cronTrigger = (CronTrigger) trigger; ret = cronTrigger.getCronExpression(); } return ret; } /** * @param jobName * @param jobGroup * @throws SchedulerException */ public void deleteJob(String jobName, String jobGroup) throws SchedulerException { this.fScheduler.deleteJob(jobName, jobGroup); } }
34.936782
108
0.678154
da8e7b4b52d45379e9dcebdb2df3a33d4bbf244f
2,597
package com.operations.ship.cucumber.entity; import com.operations.ship.cucumber.client.ShipClient; import com.operations.ship.dto.ShipCreationDTO; import com.operations.ship.dto.ShipDTO; import com.operations.ship.dto.ShipResponseDTO; import com.operations.ship.dto.ShipUpdationDTO; import kong.unirest.HttpResponse; import kong.unirest.JsonNode; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.NoArgsConstructor; import lombok.extern.slf4j.Slf4j; import java.io.IOException; import java.time.ZonedDateTime; import java.util.List; @Data @NoArgsConstructor @EqualsAndHashCode @Slf4j public class ShipEntity { private Long id; private String name; private double length; private double width; private String code; private ZonedDateTime createdDate; private ZonedDateTime updatedDate; public HttpResponse<JsonNode> findShipById(long id) throws IOException { return ShipClient.findById(id); } public HttpResponse<JsonNode> searchShips(String searchParam) throws IOException { return ShipClient.searchShips(searchParam); } public List<ShipDTO> findShipLists(int pageNo, int pageSize, String direction, String sortField) throws IOException { ShipResponseDTO responseDTO = ShipClient.listShips(pageNo, pageSize, direction, sortField); List<ShipDTO> shipDTOS = responseDTO.getShips(); if (!responseDTO.getShips().isEmpty()) { shipDTOS = responseDTO.getShips(); log.info("findShipLists(): found Ships lists: " + shipDTOS.toString()); } else { log.info("findShipLists(): Ships list is empty."); } return shipDTOS; } public HttpResponse createShip(ShipCreationDTO creationDTO) { String response = ShipClient.createShip(creationDTO).getBody().toString(); if (!response.isEmpty()) { log.info("createShip(): " + response.toString()); } else { log.info("createShip(): Ship not created"); } return ShipClient.createShip(creationDTO); } public HttpResponse updateShip(ShipUpdationDTO updationDTO) { String response = ShipClient.updateShip(updationDTO).getBody().toString(); if (!response.isEmpty()) { log.info("createShip(): " + response.toString()); } else { log.info("createShip(): Ship not created"); } return ShipClient.updateShip(updationDTO); } public int deleteShip(Long id) { HttpResponse response = ShipClient.delete(id); return response.getStatus(); } }
33.294872
121
0.693492
223e4a530182040cf44947a14060cffc0d5f6581
1,475
package ru.job4j.condition; import org.junit.Test; import static org.hamcrest.core.Is.is; import static org.junit.Assert.assertThat; /** * Class MaxTest тест задачи части 001 - урок Максимум из двух чисел 3.2. * @author vmyaskovskiy * @version $Id$ * @since 0.1 */ public class MaxTest { @Test public void maxFromTwoNumberOneAndTwo() { Max max = new Max(); int res = max.maxN(1, 2); assertThat(res, is(2)); } @Test public void maxFromTwoNumberOneAndOne() { Max max = new Max(); int res = max.maxN(1, 1); assertThat(res, is(1)); } @Test public void maxFromTwoNumberZeroAndZero() { Max max = new Max(); int res = max.maxN(0, 0); assertThat(res, is(0)); } @Test public void maxFromTwoNumberMinusOneAndOne() { Max max = new Max(); int res = max.maxN(-1, 0); assertThat(res, is(0)); } @Test public void maxFromThreeNumberOneAndTwoAndThreeReturnThree() { Max max = new Max(); int res = max.max(1, 2, 3); assertThat(res, is(3)); } @Test public void maxFromThreeNumberThreeAndTwoAndOneReturnThree() { Max max = new Max(); int res = max.max(3, 2, 1); assertThat(res, is(3)); } @Test public void maxFromThreeNumberMinusThreeAndTwoAndOneReturnTwo() { Max max = new Max(); int res = max.max(-3, 2, 1); assertThat(res, is(2)); } }
26.818182
73
0.584407
2cd1513e0eb2566a8cead46741514e8bf06bd94a
2,285
/* * Copyright (C) 2008 feilong * * 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.feilong.core.bean.propertyValueobtainer; import static org.junit.Assert.assertEquals; import java.beans.IntrospectionException; import java.beans.PropertyDescriptor; import org.junit.Test; import com.feilong.core.bean.PropertyValueObtainer; import com.feilong.lib.beanutils.PropertyUtils; import com.feilong.store.member.Member; /** * * @author <a href="https://github.com/ifeilong/feilong">feilong</a> * @since 1.12.2 */ public class GetValueTest{ @Test public void testGetValue() throws IntrospectionException{ Member member = new Member(); member.setId(1L); Object value = PropertyValueObtainer.getValue(member, new PropertyDescriptor("id", Member.class)); assertEquals(1L, value); } @Test(expected = NullPointerException.class) public void testGetValueError(){ PropertyDescriptor[] propertyDescriptors = PropertyUtils.getPropertyDescriptors(StoreLocatorErrorProperty.class); //--------------------------------------------------------------- for (PropertyDescriptor propertyDescriptor : propertyDescriptors){ PropertyValueObtainer.getValue(new StoreLocatorErrorProperty(), propertyDescriptor); } } //--------------------------------------------------------------- @Test(expected = NullPointerException.class) public void testGetValueNullObj(){ PropertyValueObtainer.getValue(new Member(), null); } @Test(expected = NullPointerException.class) public void testGetValueNullPropertyDescriptor() throws IntrospectionException{ PropertyValueObtainer.getValue(null, new PropertyDescriptor("id", Member.class)); } }
33.602941
121
0.690591
3d73b0c1db43b65660a85f25052575f21734a370
1,895
package javaspringexamples.ThreadExamples; import java.util.ArrayList; import java.util.List; import java.util.concurrent.ExecutionException; import java.util.concurrent.ForkJoinPool; import java.util.concurrent.RecursiveTask; import java.util.stream.IntStream; /** * This example represents how to create a pool of threads using ForkJoinPool * and extending the RecursiveTask class. * * @author mounir.sahrani@gmail.com * */ public class ListInitializerRecursiveTask extends RecursiveTask<List<Integer>> { private int[] data; private int begin; private int end; public ListInitializerRecursiveTask(int[] data, int _begin, int _end) { this.data = data; begin = _begin; end = _end; } /** * Method compute() to override for RecursiveTask objects, we initiate the * list recursively. */ @Override protected List<Integer> compute() { List<Integer> l = new ArrayList<>(); int middle = (end - begin) / 2; if (middle > 500) { ListInitializerRecursiveTask li1 = new ListInitializerRecursiveTask(data, begin, (begin + middle)); li1.fork(); ListInitializerRecursiveTask li2 = new ListInitializerRecursiveTask(data, (begin + middle), end); l = li2.compute(); l.addAll(li1.join()); } else { for (int i = begin; i < end; i++) { l.add(data[i] % 2); } } return l; } /** * The main method. * * @param args * @throws InterruptedException * @throws ExecutionException */ public static void main(String[] args) throws InterruptedException, ExecutionException { int lenght = 10000; ListInitializerRecursiveTask li1 = new ListInitializerRecursiveTask(IntStream.range(0, lenght).toArray(), 0, lenght); // Initiating the ForkJoinPool ForkJoinPool fjp = new ForkJoinPool(); // Getting the list initiated recursively List<Integer> l = fjp.invoke(li1); System.out.println(l.size()); System.out.println(l); } }
25.608108
110
0.711346
c904d919a5bac3a307d9a89a0ad94f1c7c00658c
4,165
package com.chao.jsoup.util; import okhttp3.*; import java.io.IOException; import java.util.Map; /** * 利用okhttp进行get和post的访问 * Created by Chao on 2017/8/18. */ public class OKHttpUtils { private static final OkHttpClient client = new OkHttpClient(); /** * 同步GET * * @throws Exception */ public static String get(String utl) throws Exception { Request request = new Request.Builder() .url(utl) .build(); Response response = client.newCall(request).execute(); if (!response.isSuccessful()) throw new IOException("Unexpected code " + response); Headers responseHeaders = response.headers(); for (int i = 0; i < responseHeaders.size(); i++) { //System.out.println(responseHeaders.name(i) + ": " + responseHeaders.value(i)); } String string = response.body().string(); //System.out.println(string); return string; } /** * 异步GET * * @throws Exception */ public static void asynchronousGet(String utl, HttpResponse httpResponse) throws Exception { Request request = new Request.Builder() .url(utl) .build(); client.newCall(request).enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { e.printStackTrace(); } @Override public void onResponse(Call call, Response response) throws IOException { if (!response.isSuccessful()) throw new IOException("Unexpected code " + response); Headers responseHeaders = response.headers(); for (int i = 0, size = responseHeaders.size(); i < size; i++) { System.err.println(responseHeaders.name(i) + ": " + responseHeaders.value(i)); } String string = response.body().string(); System.out.println(string); if (httpResponse != null) { httpResponse.onResponse(string); } } }); } /** * 同步POST * * @throws Exception */ public static String post(String url, Map<String, String> parameter) throws Exception { FormBody.Builder builder = new FormBody.Builder(); for (String key : parameter.keySet()) { builder.add(key, parameter.get(key)); } RequestBody formBody = builder.build(); Request request = new Request.Builder() .url(url) .post(formBody) .build(); Response response = client.newCall(request).execute(); if (!response.isSuccessful()) throw new IOException("Unexpected code " + response); String string = response.body().string(); System.out.println(string); return string; } /** * 异步POST * * @throws Exception */ public static void asynchronousPost(String url, Map<String, String> parameter, HttpResponse httpResponse) throws Exception { FormBody.Builder builder = new FormBody.Builder(); for (String key : parameter.keySet()) { builder.add(key, parameter.get(key)); } RequestBody formBody = builder.build(); Request request = new Request.Builder() .url(url) .post(formBody) .build(); client.newCall(request).enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { } @Override public void onResponse(Call call, Response response) throws IOException { if (!response.isSuccessful()) throw new IOException("Unexpected code " + response); String string = response.body().string(); System.out.println(string); if (httpResponse != null) { httpResponse.onResponse(string); } } }); } public interface HttpResponse { public void onResponse(String content); } }
31.315789
128
0.556062
3b680c430369bc31c03ee42cc9bcc3c1dc7b7d37
4,855
package com.daxiang.core.ios; import com.daxiang.api.MasterApi; import com.daxiang.core.MobileDevice; import com.daxiang.core.MobileDeviceHolder; import com.daxiang.core.appium.AppiumServer; import com.daxiang.model.Device; import com.daxiang.websocket.MobileDeviceWebSocketSessionPool; import io.appium.java_client.AppiumDriver; import lombok.extern.slf4j.Slf4j; import org.openqa.selenium.Dimension; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import javax.websocket.Session; import java.io.IOException; import java.util.Date; /** * Created by jiangyitao. */ @Slf4j @Component public class DefaultIosDeviceChangeListener implements IosDeviceChangeListener { @Autowired private MasterApi masterApi; @Override public void onDeviceConnected(String deviceId) { new Thread(() -> iosDeviceConnected(deviceId)).start(); } @Override public void onDeviceDisconnected(String deviceId) { new Thread(() -> iosDeviceDisconnected(deviceId)).start(); } private void iosDeviceConnected(String deviceId) { log.info("[ios][{}]已连接", deviceId); MobileDevice mobileDevice = MobileDeviceHolder.get(deviceId); if (mobileDevice == null) { log.info("[ios][{}]首次在agent上线", deviceId); log.info("[ios][{}]启动appium server...", deviceId); AppiumServer appiumServer = new AppiumServer(); appiumServer.start(); log.info("[ios][{}]启动appium server完成,url: {}", deviceId, appiumServer.getUrl()); log.info("[ios][{}]检查是否已接入过master", deviceId); Device device = masterApi.getDeviceById(deviceId); if (device == null) { log.info("[ios][{}]首次接入master,开始初始化设备", deviceId); try { mobileDevice = initIosDevice(deviceId, appiumServer); log.info("[ios][{}]初始化设备完成", deviceId); } catch (Exception e) { appiumServer.stop(); throw new RuntimeException("初始化设备" + deviceId + "出错", e); } } else { log.info("[ios][{}]已接入过master", deviceId); mobileDevice = new IosDevice(device, appiumServer); } MobileDeviceHolder.add(deviceId, mobileDevice); } else { log.info("[ios][{}]非首次在agent上线", deviceId); } mobileDevice.saveOnlineDeviceToMaster(); log.info("[ios][{}]iosDeviceConnected处理完成", deviceId); } private void iosDeviceDisconnected(String deviceId) { log.info("[ios][{}]断开连接", deviceId); MobileDevice mobileDevice = MobileDeviceHolder.get(deviceId); if (mobileDevice == null) { return; } mobileDevice.saveOfflineDeviceToMaster(); // 有人正在使用,则断开连接 Session openedSession = MobileDeviceWebSocketSessionPool.getOpenedSession(deviceId); if (openedSession != null) { try { log.info("[ios][{}]sessionId: {}正在使用,关闭连接", deviceId, openedSession.getId()); openedSession.close(); } catch (IOException e) { log.error("close opened session err", e); } } log.info("[ios][{}]iosDeviceDisconnected处理完成", deviceId); } private MobileDevice initIosDevice(String deviceId, AppiumServer appiumServer) throws Exception { Device device = new Device(); device.setPlatform(MobileDevice.IOS); device.setCreateTime(new Date()); device.setId(deviceId); device.setSystemVersion(IosUtil.getSystemVersion(deviceId)); device.setName(IosUtil.getDeviceName(deviceId)); String msg = "请根据productType:" + IosUtil.getProductType(deviceId) + "查出相应的信息,补充到device表"; device.setCpuInfo(msg); device.setMemSize(msg); IosDevice iosDevice = new IosDevice(device, appiumServer); log.info("[ios][{}]开始初始化appium", deviceId); AppiumDriver appiumDriver = iosDevice.initAppiumDriver(); log.info("[ios][{}]初始化appium完成", deviceId); // 有时window获取的宽高可能为0 while (true) { Dimension window = appiumDriver.manage().window().getSize(); int width = window.getWidth(); int height = window.getHeight(); if (width > 0 && height > 0) { device.setScreenWidth(window.getWidth()); device.setScreenHeight(window.getHeight()); break; } else { log.warn("[ios][{}]未获取到正确的屏幕宽高: {}", deviceId, window); } } // 截图并上传到服务器 String imgDownloadUrl = iosDevice.screenshotAndUploadToMaster(); device.setImgUrl(imgDownloadUrl); appiumDriver.quit(); return iosDevice; } }
34.678571
101
0.61586
18780b5ebc7ed355bf240db4b12fcfccdd231a18
4,598
/* * Copyright (c) 1999-2012 weborganic systems pty. ltd. */ package org.pageseeder.psml.process.config; /** * Defines how to traverse XRefs, including the XRefs types and some patterns to include/exclude. * * <p>Used to represent the inner ANT element:<p> * <pre>{@code<xrefs * types="[xref types]" * levels="[true|false]" * xrefragment="[include,exclude,only]" * includes="[patterns]" * excludes="[patterns]"> * <include name="[name]" /> * <exclude name="[name]" /> * </xrefs> }</pre> * * <p>Details are:</p> * <ul> * <li>types: Comma separated list of xref types to process in included files * (i.e. transclude, embed ) - default none. </li> * <li>levels: Whether to modify heading levels based on XRef level attribute - default true. </li> * <li>xreffragment: Defines how to handle XRefs in an <xref-fragment> element. * Possible values are "include" (process XRefs in an xref-fragment), * "exclude" (don't process XRefs in an xref-fragment) and * "only" (process only XRefs in an xref-fragment). Default is "include". </li> * <li>includes: A comma-separated list of patterns matching documents/folders to include. * When not specified, all documents/folders are included. * The format is similar to other ant tasks file pattern selection. Here are some examples: * *.psml,archive,folder1/*.psml,** /*.psml</li> * <li>excludes: A comma-separated list of patterns matching documents/folders to exclude. * When not specified, no documents/folders are excluded. * The format is similar to other ant tasks file pattern selection. Here are some examples: * _local/**,_external/**</li> * </ul> * * @author Jean-Baptiste Reure * @version 1.7.9 * */ public final class XRefsTransclude extends IncludeExcludeConfig { public static enum XREF_IN_XREF_FRAGMENT { /** Process xrefs inside <xref-fragment> */ INCLUDE, /** Don't process xrefs inside <xref-fragment> */ EXCLUDE, /** Process only xrefs inside <xref-fragment> */ ONLY; /** * Returns the XREF_IN_XREF_FRAGMENT corresponding to the given name. * * @param name The name of XREF_IN_XREF_FRAGMENT (include, exclude or only). * * @return The corresponding XREF_IN_XREF_FRAGMENT. */ public static XREF_IN_XREF_FRAGMENT forName(String name) { for (XREF_IN_XREF_FRAGMENT n : values()) { if (n.name().equalsIgnoreCase(name)) return n; } throw new IllegalArgumentException("Invalid xreffragment attribute value: " + name); } } /** * List of XRefs types to match. */ private String types = null; /** * How to handle xrefs in an xref-fragment. */ private XREF_IN_XREF_FRAGMENT xRefFragment = XREF_IN_XREF_FRAGMENT.INCLUDE; /** * Whether to process xref levels */ private boolean levels = true; /** * @param t the types to set */ public void setTypes(String t) { this.types = t; } /** * @param s the xRefFragment to set */ public void setXRefsInXRefFragment(XREF_IN_XREF_FRAGMENT xf) { this.xRefFragment = xf; } /** * @param s the name of xRefFragment to set (include, exclude or only) */ public void setXRefFragment(String s) { this.xRefFragment = XREF_IN_XREF_FRAGMENT.forName(s); } /** * @param b the levels to set */ public void setLevels(Boolean b) { this.levels = b; } /** * @return <code>true</code> if the XRefs in an xref-fragment are included */ public boolean includeXRefsInXRefFragment() { return this.xRefFragment == XREF_IN_XREF_FRAGMENT.INCLUDE; } /** * @return <code>true</code> if the XRefs in an xref-fragment are excluded */ public boolean excludeXRefsInXRefFragment() { return this.xRefFragment == XREF_IN_XREF_FRAGMENT.EXCLUDE; } /** * @return <code>true</code> if only the XRefs in an xref-fragment are included */ public boolean onlyXRefsInXRefFragment() { return this.xRefFragment == XREF_IN_XREF_FRAGMENT.ONLY; } /** * @return the types */ public String getTypes() { return this.types; } /** * @return the levels */ public boolean getLevels() { return this.levels; } }
30.653333
112
0.608525
18e96b3f612e4b2a99f06f5bd56223e51807fee6
330
package com.netflix.ribbon.proxy.sample; import com.netflix.ribbon.http.HttpResourceGroup; /** * @author Tomasz Bak */ public class ResourceGroupClasses { public static class SampleHttpResourceGroup extends HttpResourceGroup { public SampleHttpResourceGroup() { super("myTestGroup"); } } }
22
75
0.70303
42b14c84019bf5c2ffee5f29cfe4e41a13577962
967
package mb.resource.classloader; import mb.resource.fs.FSResource; import org.checkerframework.checker.nullness.qual.Nullable; import java.io.Serializable; import java.util.Objects; public class JarFileWithPath implements Serializable { public final FSResource file; public final String path; public JarFileWithPath(FSResource file, String path) { this.file = file; this.path = path; } @Override public boolean equals(@Nullable Object o) { if(this == o) return true; if(o == null || getClass() != o.getClass()) return false; final JarFileWithPath that = (JarFileWithPath)o; return file.equals(that.file) && path.equals(that.path); } @Override public int hashCode() { return Objects.hash(file, path); } @Override public String toString() { return "JarFileWithPath{" + "file=" + file + ", path='" + path + '\'' + '}'; } }
26.861111
65
0.627715
bcf3fab7336df77ae3615ae84b1848b37406182f
7,662
package controller.out.formatter; import controller.in.reader.StringReader; import controller.in.transformer.CSVTransformer; import junit.framework.TestCase; import model.Solution; import model.SolutionTemplate; public class PlainFormatterTest extends TestCase { public void testFormatHappyPath() throws Exception { String testInput = "5\nSAME;nationality;English;color;Red\nSAME;nationality;Spaniard;pet;Dog\nSAME;drink;Coffee;color;Green\nTO_THE_LEFT_OF;color;Ivory;color;Green\nSAME;drink;Tea;nationality;Ukrainian\nSAME;smoke;Old gold;pet;Snails\nSAME;smoke;Kools;color;Yellow\nNEXT_TO;smoke;Chesterfields;pet;Fox\nSAME;nationality;Norwegian;position;1\nSAME;drink;Milk;position;3\nNEXT_TO;smoke;Kools;pet;Horse\nSAME;smoke;Parliaments;nationality;Japanese\nSAME;smoke;Lucky strike;drink;Orange juice"; Solution[] solutions = createSolution(testInput); String result = new PlainFormatter().format(solutions); assertEquals("Number of solutions: 5\n" + "Solution 1\n" + "position: 1| 2| 3| 4| 5| \n" + "nationality: english| null| null| null| null| \n" + "color: red| null| null| null| null| \n" + "pet: null| null| null| null| null| \n" + "drink: null| null| null| null| null| \n" + "smoke: null| null| null| null| null| \n" + "\n" + "Solution 2\n" + "position: 1| 2| 3| 4| 5| \n" + "nationality: null| english| null| null| null| \n" + "color: null| red| null| null| null| \n" + "pet: null| null| null| null| null| \n" + "drink: null| null| null| null| null| \n" + "smoke: null| null| null| null| null| \n" + "\n" + "Solution 3\n" + "position: 1| 2| 3| 4| 5| \n" + "nationality: null| null| english| null| null| \n" + "color: null| null| red| null| null| \n" + "pet: null| null| null| null| null| \n" + "drink: null| null| null| null| null| \n" + "smoke: null| null| null| null| null| \n" + "\n" + "Solution 4\n" + "position: 1| 2| 3| 4| 5| \n" + "nationality: null| null| null| english| null| \n" + "color: null| null| null| red| null| \n" + "pet: null| null| null| null| null| \n" + "drink: null| null| null| null| null| \n" + "smoke: null| null| null| null| null| \n" + "\n" + "Solution 5\n" + "position: 1| 2| 3| 4| 5| \n" + "nationality: null| null| null| null| english| \n" + "color: null| null| null| null| red| \n" + "pet: null| null| null| null| null| \n" + "drink: null| null| null| null| null| \n" + "smoke: null| null| null| null| null|", result); } public void testFormatHappyPath2() throws Exception { String testInput = "3\nSAME;nationality;English;color;Red\nSAME;nationality;Spaniard;pet;Dog;Size;tall;Smoke;none;Fun;no"; Solution[] solutions = createSolution(testInput); String result = new PlainFormatter().format(solutions); assertEquals("Number of solutions: 3\n" + "Solution 1\n" + "position: 1| 2| 3| \n" + "nationality: english| null| null| \n" + "color: red| null| null| \n" + "pet: null| null| null| \n" + "fun: null| null| null| \n" + "smoke: null| null| null| \n" + "size: null| null| null| \n" + "\n" + "Solution 2\n" + "position: 1| 2| 3| \n" + "nationality: null| english| null| \n" + "color: null| red| null| \n" + "pet: null| null| null| \n" + "fun: null| null| null| \n" + "smoke: null| null| null| \n" + "size: null| null| null| \n" + "\n" + "Solution 3\n" + "position: 1| 2| 3| \n" + "nationality: null| null| english| \n" + "color: null| null| red| \n" + "pet: null| null| null| \n" + "fun: null| null| null| \n" + "smoke: null| null| null| \n" + "size: null| null| null|", result); } private Solution[] createSolution(String tests) throws Exception { StringReader reader = new StringReader(tests); CSVTransformer transformer = new CSVTransformer(";", "\\r?\\n"); SolutionTemplate template = transformer.parse(reader); Solution solution = new Solution(template); return solution.invokeConstraint(); } }
72.971429
498
0.329157
ee214864d6f27f895e9dac5106a9ad1d9f30a792
3,896
/* --------------------------------------------------------------------------- Open Asset Import Library - Java Binding (jassimp) --------------------------------------------------------------------------- Copyright (c) 2006-2012, assimp team All rights reserved. Redistribution and use of this software 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 assimp team, nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission of the assimp team. 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 OWNER 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.github.dabasan.jassimp; import java.nio.ByteBuffer; /** * Wrapper for colors. * <p> * * The wrapper is writable, i.e., changes performed via the set-methods will * modify the underlying mesh. */ public final class AiColor { /** * Wrapped buffer. */ private final ByteBuffer m_buffer; /** * Offset into m_buffer. */ private final int m_offset; /** * Constructor. * * @param buffer * the buffer to wrap * @param offset * offset into buffer */ public AiColor(ByteBuffer buffer, int offset) { m_buffer = buffer; m_offset = offset; } /** * Returns the red color component. * * @return the red component */ public float getRed() { return m_buffer.getFloat(m_offset); } /** * Returns the green color component. * * @return the green component */ public float getGreen() { return m_buffer.getFloat(m_offset + 4); } /** * Returns the blue color component. * * @return the blue component */ public float getBlue() { return m_buffer.getFloat(m_offset + 8); } /** * Returns the alpha color component. * * @return the alpha component */ public float getAlpha() { return m_buffer.getFloat(m_offset + 12); } /** * Sets the red color component. * * @param red * the new value */ public void setRed(float red) { m_buffer.putFloat(m_offset, red); } /** * Sets the green color component. * * @param green * the new value */ public void setGreen(float green) { m_buffer.putFloat(m_offset + 4, green); } /** * Sets the blue color component. * * @param blue * the new value */ public void setBlue(float blue) { m_buffer.putFloat(m_offset + 8, blue); } /** * Sets the alpha color component. * * @param alpha * the new value */ public void setAlpha(float alpha) { m_buffer.putFloat(m_offset + 12, alpha); } @Override public String toString() { return "[" + getRed() + ", " + getGreen() + ", " + getBlue() + ", " + getAlpha() + "]"; } }
24.815287
89
0.649384
0a4626669dd866666e0cd26d98f375af20a06b3b
2,473
/* Copyright 2021 Adobe. All rights reserved. This file is licensed 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 REPRESENTATIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.adobe.s3fs.metastore.internal.dynamodb.configuration; import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.when; import com.adobe.s3fs.common.configuration.FileSystemConfiguration; import org.junit.Before; import org.junit.Test; import org.mockito.Mock; import org.mockito.MockitoAnnotations; public class DynamoMetaStoreConfigurationTest { @Mock private FileSystemConfiguration mockConfig; private DynamoMetaStoreConfiguration configuration; @Before public void setup() { MockitoAnnotations.initMocks(this); configuration = new DynamoMetaStoreConfiguration(mockConfig); } @Test public void testGetSuffixReturnCorrectNumberOfSuffixes() { when(mockConfig.getInt(DynamoMetaStoreConfiguration.SUFFIX_COUNT_PROP_NAME, 0)).thenReturn(10); assertEquals(10, configuration.getSuffixCount()); } @Test(expected = IllegalStateException.class) public void testGetSuffixThrowsErrorIfSuffixPropertyNegative() { when(mockConfig.getInt(DynamoMetaStoreConfiguration.SUFFIX_COUNT_PROP_NAME,0 )).thenReturn(-1); int ignored = configuration.getSuffixCount(); } @Test(expected = IllegalStateException.class) public void testGetSuffixThrowsErrorIfSuffixPropertyZero() { when(mockConfig.getInt(DynamoMetaStoreConfiguration.SUFFIX_COUNT_PROP_NAME, 0)).thenReturn(0); int ignored = configuration.getSuffixCount(); } @Test public void testGetTableReturnsTheCorrectTable() { when(mockConfig.getString("fs.s3k.metastore.dynamo.table")).thenReturn("table"); assertEquals("table", configuration.getDynamoTableForBucket()); } @Test(expected = IllegalStateException.class) public void testGetTableThrowsErrorIfTableIsNotSet() { when(mockConfig.getString("fs.s3k.metastore.dynamo.table")).thenReturn(""); String ignored = configuration.getDynamoTableForBucket(); } }
33.876712
99
0.790538
55f8f9f0074b2da9e85e1d7cd55ce0497300d441
2,638
package io.apicurio.registry.utils.streams.ext; import java.util.Objects; import java.util.concurrent.atomic.AtomicLong; @FunctionalInterface public interface LongGenerator { long getNext(); class HiLo implements LongGenerator { private final LongGenerator hiGenerator; private final AtomicLong hilo = new AtomicLong(); private final Object lock = new Object(); private final int loBits; private final long loMask; public HiLo(LongGenerator hiGenerator) { this(hiGenerator, 16); } public HiLo(LongGenerator hiGenerator, int loBits) { this.hiGenerator = Objects.requireNonNull(hiGenerator); if (loBits < 1 || loBits > 62) { throw new IllegalArgumentException("loBits must be between 1 and 62"); } this.loBits = loBits; this.loMask = (1L << loBits) - 1; } @Override public long getNext() { // retry loop while (true) { // obtain current hilo value long hl = hilo.get(); // check for overflow if ((hl & loMask) == 0L) { // initial or overflowed lo value synchronized (lock) { // re-obtain under lock hl = hilo.get(); // re-check overflow under lock if ((hl & loMask) == 0L) { // still at initial or overflowed lo value, but we now have lock // obtain new hi value and integrate it hl = (hiGenerator.getNext() << loBits) | (hl & loMask); // set back incremented value with new hi part and return this one // (we don't need or want to CAS here as only one thread is modifying // hilo at this time since it contains initial or overflowed lo value) hilo.set(hl + 1); return hl; } } } else { // not initial and not overflowed - this is fast-path // try to CAS back incremented value if (hilo.compareAndSet(hl, hl + 1)) { // if CAS was successful, return this value return hl; } } // in any other case, we lost race with a concurrent thread and must retry } } } }
38.794118
98
0.486353
4d1bac169522bf8c8439051b0a26d7ed037f8785
1,027
package messages; import io.smallrye.mutiny.Multi; import org.eclipse.microprofile.reactive.messaging.Incoming; import org.eclipse.microprofile.reactive.messaging.Message; import org.eclipse.microprofile.reactive.messaging.Metadata; import org.eclipse.microprofile.reactive.messaging.Outgoing; import java.util.Optional; import java.util.concurrent.CompletionStage; public class MetadataWithMessageChainExamples { // tag::chain[] @Outgoing("source") public Multi<Message<Integer>> generate() { return Multi.createFrom().range(0, 10) .map(i -> Message.of(i, Metadata.of(new MyMetadata("author", "me")))); } @Incoming("source") @Outgoing("sink") public Message<Integer> increment(Message<Integer> in) { return in.withPayload(in.getPayload() + 1); } @Outgoing("sink") public CompletionStage<Void> consume(Message<Integer> in) { Optional<MyMetadata> metadata = in.getMetadata(MyMetadata.class); return in.ack(); } // end::chain[] }
29.342857
82
0.703019
fec38ec44cf11d004a2a976669cc4d3486427b95
4,164
package com.kc.shiptransport.data.bean.device.repair; import android.os.Parcel; import android.os.Parcelable; /** * @author 邱永恒 * @time 2018/6/17 12:45 * @desc */ public class DeviceRepairDetailBean implements Parcelable { public static final Parcelable.Creator<DeviceRepairDetailBean> CREATOR = new Creator<DeviceRepairDetailBean>() { @Override public DeviceRepairDetailBean createFromParcel(Parcel in) { return new DeviceRepairDetailBean(in); } @Override public DeviceRepairDetailBean[] newArray(int size) { return new DeviceRepairDetailBean[size]; } }; /** * rownumber : 1 * ItemID : 1 * StartTime : 2018-06-11T15:36:28 * EndTime : 2018-06-12T18:36:02 * ShipAccount : jx1 * ShipName : 吉星1 * RepairProject : 修理项目 * RepairProcess : 修理过程 * Repairman : 修理人员 * Attachment : https://cchk3.kingwi.org/Files/20180330/bfbdbc9b-4d73-4c39-8dcc-439d297e0ef2.jpeg,https://cchk3.kingwi.org/Files/20180423/961a60d4-794e-4f3a-acee-b68feeb80410.jpg, * Creator : wd * Remark : 备注 */ private int rownumber; private int ItemID; private String StartTime; private String EndTime; private String ShipAccount; private String ShipName; private String RepairProject; private String RepairProcess; private String Repairman; private String Attachment; private String Creator; private String Remark; protected DeviceRepairDetailBean(Parcel in) { rownumber = in.readInt(); ItemID = in.readInt(); StartTime = in.readString(); EndTime = in.readString(); ShipAccount = in.readString(); ShipName = in.readString(); RepairProject = in.readString(); RepairProcess = in.readString(); Repairman = in.readString(); Attachment = in.readString(); Creator = in.readString(); Remark = in.readString(); } public int getRownumber() { return rownumber;} public void setRownumber(int rownumber) { this.rownumber = rownumber;} public int getItemID() { return ItemID;} public void setItemID(int ItemID) { this.ItemID = ItemID;} public String getStartTime() { return StartTime;} public void setStartTime(String StartTime) { this.StartTime = StartTime;} public String getEndTime() { return EndTime;} public void setEndTime(String EndTime) { this.EndTime = EndTime;} public String getShipAccount() { return ShipAccount;} public void setShipAccount(String ShipAccount) { this.ShipAccount = ShipAccount;} public String getShipName() { return ShipName;} public void setShipName(String ShipName) { this.ShipName = ShipName;} public String getRepairProject() { return RepairProject;} public void setRepairProject(String RepairProject) { this.RepairProject = RepairProject;} public String getRepairProcess() { return RepairProcess;} public void setRepairProcess(String RepairProcess) { this.RepairProcess = RepairProcess;} public String getRepairman() { return Repairman;} public void setRepairman(String Repairman) { this.Repairman = Repairman;} public String getAttachment() { return Attachment;} public void setAttachment(String Attachment) { this.Attachment = Attachment;} public String getCreator() { return Creator;} public void setCreator(String Creator) { this.Creator = Creator;} public String getRemark() { return Remark;} public void setRemark(String Remark) { this.Remark = Remark;} @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeInt(rownumber); dest.writeInt(ItemID); dest.writeString(StartTime); dest.writeString(EndTime); dest.writeString(ShipAccount); dest.writeString(ShipName); dest.writeString(RepairProject); dest.writeString(RepairProcess); dest.writeString(Repairman); dest.writeString(Attachment); dest.writeString(Creator); dest.writeString(Remark); } }
30.617647
183
0.677474
d38a769bf00331a8ef6d7d5ffc9e663efed659ee
331
package com.itscoder.ljuns.practise.dagger2; import dagger.Component; /** * Created by ljuns at 2018/11/30. * I am just a developer. */ @Component(modules = DemoModule.class) public interface DaggerComponent { void daggerActivity(DaggerActivity activity); void daggerDemoB(DemoB b); void daggerDemoC(DemoB b); }
19.470588
49
0.734139
dd49b9b47e73aca74011ef2e819aef062432283a
802
package czy.spring.boot.starter.swagger; import lombok.Data; import org.springframework.beans.factory.InitializingBean; import org.springframework.util.Assert; import springfox.documentation.spi.DocumentationType; /** * {@link springfox.documentation.spring.web.plugins.Docket}属性 */ @Data public class DocketProperties implements InitializingBean { /** 文档类型,默认为{@link DocumentationType#SWAGGER_2} */ private DocumentationType documentationType = DocumentationType.SWAGGER_2; /** 分组名称 */ private String groupName; /** 扫描的基础包 */ private String basePackage = null; @Override public void afterPropertiesSet() throws Exception { Assert.notNull(groupName,"groupName can not be nul"); Assert.notNull(basePackage,"basePackage can not be null"); } }
26.733333
78
0.741895
837662a34df3cd092ad2acfe8c293724fb741e59
321
package org.bricolages.streaming.event; import org.bricolages.streaming.exception.ApplicationException; public class MessageParseException extends ApplicationException { MessageParseException(String message) { super(message); } MessageParseException(Exception cause) { super(cause); } }
24.692308
65
0.750779
c12892b0517f7ad5a63a1e729ef100a3d722c8d7
287
package edu.thinktank.thymeleaf.example; import com.fasterxml.jackson.annotation.JsonProperty; import io.dropwizard.Configuration; import java.util.Map; public class ExampleConfig extends Configuration { @JsonProperty("views") public Map<String, Map<String, String>> views; }
23.916667
53
0.787456
1fb08702caad9e1d33a056756f2be4d7edfc3445
211
package de.hhu.stups.plues; public enum HistoryChangeType { BACK, FORWARD; public boolean isBack() { return this.equals(BACK); } public boolean isForward() { return this.equals(FORWARD); } }
16.230769
32
0.682464
1242056275b69437f085695b2135860c29dd3acd
571
package com.github.cc3002.finalreality.controller.combatphases; /** * this class was created to interact with the gui. NOT IMPLEMENTED YET */ public class SelectingWeaponPhase extends CombatPhase { public SelectingWeaponPhase() { super(); // code to show and hide some buttons } @Override public boolean equals(Object o) { if (!(o instanceof SelectingWeaponPhase)) return false; return super.equals(o); } @Override public void selectReturn() { controller.setPhase(new WaitActionState()); } }
22.84
71
0.669002
a9ad9e7672292986be89d091495d4398685d41b1
3,062
package com.redescooter.ses.tool.utils.ssl; import org.bouncycastle.jce.provider.BouncyCastleProvider; import org.bouncycastle.openssl.PEMReader; import org.bouncycastle.openssl.PasswordFinder; import javax.net.ssl.KeyManagerFactory; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLSocketFactory; import javax.net.ssl.TrustManagerFactory; import java.io.ByteArrayInputStream; import java.io.InputStreamReader; import java.nio.file.Files; import java.nio.file.Paths; import java.security.KeyPair; import java.security.KeyStore; import java.security.Security; import java.security.cert.X509Certificate; /** * ssl工具类 * @author assert * @date 2020/11/16 13:32 */ public class SslUtil { public static SSLSocketFactory getSocketFactory(final String caCrtFile, final String crtFile, final String keyFile, final String password) throws Exception { Security.addProvider(new BouncyCastleProvider()); // load CA certificate PEMReader reader = new PEMReader(new InputStreamReader(new ByteArrayInputStream(Files.readAllBytes(Paths.get(caCrtFile))))); X509Certificate caCert = (X509Certificate)reader.readObject(); reader.close(); // load client certificate reader = new PEMReader(new InputStreamReader(new ByteArrayInputStream(Files.readAllBytes(Paths.get(crtFile))))); X509Certificate cert = (X509Certificate)reader.readObject(); reader.close(); // load client private key reader = new PEMReader( new InputStreamReader(new ByteArrayInputStream(Files.readAllBytes(Paths.get(keyFile)))), new PasswordFinder() { @Override public char[] getPassword() { return password.toCharArray(); } } ); KeyPair key = (KeyPair)reader.readObject(); reader.close(); // CA certificate is used to authenticate server KeyStore caKs = KeyStore.getInstance(KeyStore.getDefaultType()); caKs.load(null, null); caKs.setCertificateEntry("ca-certificate", caCert); TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); tmf.init(caKs); // client key and certificates are sent to server so it can authenticate us KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType()); ks.load(null, null); ks.setCertificateEntry("certificate", cert); ks.setKeyEntry("private-key", key.getPrivate(), password.toCharArray(), new java.security.cert.Certificate[]{cert}); KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); kmf.init(ks, password.toCharArray()); // finally, create SSL socket factory SSLContext context = SSLContext.getInstance("TLSv1.2"); context.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null); return context.getSocketFactory(); } }
39.766234
132
0.684847
ac8b13c218313df0c56bca65c201d157ed484294
4,068
package com.gp.health.ui.faqs; import android.annotation.SuppressLint; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.LinearLayout; import androidx.annotation.NonNull; import androidx.appcompat.widget.AppCompatTextView; import androidx.recyclerview.widget.RecyclerView; import com.gp.health.R; import com.gp.health.data.models.FAQsModel; import com.gp.health.ui.base.BaseViewHolder; import com.gp.health.utils.ImageUtils; import com.gp.health.utils.LanguageHelper; import java.util.List; import butterknife.BindView; import butterknife.ButterKnife; public class FAQsAdapter extends RecyclerView.Adapter<BaseViewHolder> { public static final int VIEW_TYPE_EMPTY = 0; public static final int VIEW_TYPE_FAQ = 1; private Callback mCallback; private List<FAQsModel> mFAQsList; public FAQsAdapter(List<FAQsModel> list) { mFAQsList = list; } public void setCallback(Callback callback) { mCallback = callback; } @Override public void onBindViewHolder(BaseViewHolder holder, int position) { holder.onBind(position); } @NonNull @Override public BaseViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { switch (viewType) { case VIEW_TYPE_FAQ: return new FAQViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.item_faq, parent, false)); case VIEW_TYPE_EMPTY: default: return new EmptyViewHolder( LayoutInflater.from(parent.getContext()).inflate(R.layout.item_empty_view, parent, false)); } } @Override public int getItemViewType(int position) { if (mFAQsList != null && mFAQsList.size() > 0) { return VIEW_TYPE_FAQ; } else { return VIEW_TYPE_EMPTY; } } @Override public int getItemCount() { if (mFAQsList != null && mFAQsList.size() > 0) { return mFAQsList.size(); } else { return 1; } } public void addItems(List<FAQsModel> list) { mFAQsList.clear(); mFAQsList.addAll(list); notifyDataSetChanged(); } public void clearItems() { mFAQsList.clear(); notifyDataSetChanged(); } public interface Callback { } public static class EmptyViewHolder extends BaseViewHolder { EmptyViewHolder(View itemView) { super(itemView); } @Override public void onBind(int position) { } } @SuppressLint("NonConstantResourceId") public class FAQViewHolder extends BaseViewHolder { @BindView(R.id.tv_question) AppCompatTextView tvQuestion; @BindView(R.id.ll_expand_collapse) LinearLayout llExpandCollapse; @BindView(R.id.iv_expand_collapse) ImageView ivExpandCollapse; @BindView(R.id.tv_answer) AppCompatTextView tvAnswer; public FAQViewHolder(View itemView) { super(itemView); ButterKnife.bind(this, itemView); } protected void clear() { } @SuppressLint("SetTextI18n") public void onBind(int position) { FAQsModel faQsModel = mFAQsList.get(position); if (LanguageHelper.getLanguage(itemView.getContext()).equals("ar")) { tvQuestion.setText(faQsModel.getQuestion().getAr()); tvAnswer.setText(faQsModel.getAnswer().getAr()); } else { tvQuestion.setText(faQsModel.getQuestion().getEn()); tvAnswer.setText(faQsModel.getAnswer().getEn()); } llExpandCollapse.setOnClickListener(v -> { ImageUtils.rotate(ivExpandCollapse, tvAnswer.getVisibility() == View.VISIBLE ? 0 : 1); tvAnswer.setVisibility(tvAnswer.getVisibility() == View.VISIBLE ? View.GONE : View.VISIBLE); }); } } }
26.940397
125
0.637906
03e8c555e19b6c638eb55699799e7d10b30f702e
2,518
package org.jenkinsci.plugins.ghprb_lp.extensions; import hudson.DescriptorExtensionList; import hudson.model.Descriptor; import jenkins.model.Jenkins; import org.apache.commons.collections.Predicate; import org.apache.commons.collections.PredicateUtils; import org.apache.commons.collections.functors.InstanceofPredicate; import java.util.ArrayList; import java.util.Iterator; import java.util.List; @SuppressWarnings("unchecked") public abstract class GhprbExtensionDescriptor extends Descriptor<GhprbExtension> { public boolean isApplicable(Class<?> type) { return true; } public static List<GhprbExtensionDescriptor> getExtensions(Class<? extends GhprbExtensionType>... types) { List<GhprbExtensionDescriptor> list = getExtensions(); filterExtensions(list, types); return list; } private static void filterExtensions(List<GhprbExtensionDescriptor> descriptors, Class<? extends GhprbExtensionType>... types) { List<Predicate> predicates = new ArrayList<Predicate>(types.length); for (Class<? extends GhprbExtensionType> type : types) { predicates.add(InstanceofPredicate.getInstance(type)); } Predicate anyPredicate = PredicateUtils.anyPredicate(predicates); Iterator<GhprbExtensionDescriptor> iter = descriptors.iterator(); while (iter.hasNext()) { GhprbExtensionDescriptor descriptor = iter.next(); if (!anyPredicate.evaluate(descriptor)) { iter.remove(); } } } private static DescriptorExtensionList<GhprbExtension, GhprbExtensionDescriptor> getExtensionList() { return Jenkins.getInstance().getDescriptorList(GhprbExtension.class); } /** * Don't mutate the list from Jenkins, they will persist; * * @return list of extensions */ private static List<GhprbExtensionDescriptor> getExtensions() { List<GhprbExtensionDescriptor> list = new ArrayList<GhprbExtensionDescriptor>(); list.addAll(getExtensionList()); return list; } public static List<GhprbExtensionDescriptor> allProject() { List<GhprbExtensionDescriptor> list = getExtensions(); filterExtensions(list, GhprbProjectExtension.class); return list; } public static List<GhprbExtensionDescriptor> allGlobal() { List<GhprbExtensionDescriptor> list = getExtensions(); filterExtensions(list, GhprbGlobalExtension.class); return list; } }
35.971429
132
0.710882
59390496d0df85b2eb01ff03fe5619a7bab11605
792
package org.opentosca.yamlconverter.main; import org.junit.Test; import org.opentosca.yamlconverter.main.exceptions.ConverterException; import org.opentosca.yamlconverter.main.interfaces.IToscaYaml2XmlConverter; import java.io.IOException; import java.net.URISyntaxException; public class Yaml2XmlQuickConverterTest extends BaseTest { private final IToscaYaml2XmlConverter c = new ToscaYaml2XmlConverter(); @Test public void testYaml2xml() throws URISyntaxException, IOException, ConverterException { final String yaml = this.testUtils.readYamlTestResource("/yaml/helloworld.yaml"); final String result = this.c.convertToXml(yaml); // TODO: assertNotEquals is not a correct method! Maybe assertNotSame ? // Assert.assertNotEquals(result, ""); System.out.println(result); } }
36
88
0.808081
4681cec199deb85c8abbc3a8c22c3f8d0c686588
3,735
package io.quarkus.paths; import java.io.IOException; import java.nio.file.Path; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.List; import java.util.concurrent.atomic.AtomicBoolean; import java.util.function.Consumer; import java.util.function.Function; import java.util.jar.Manifest; public class MultiRootPathTree implements OpenPathTree { private final PathTree[] trees; private final List<Path> roots; public MultiRootPathTree(PathTree... trees) { this.trees = trees; final ArrayList<Path> tmp = new ArrayList<>(); for (PathTree t : trees) { tmp.addAll(t.getRoots()); } tmp.trimToSize(); roots = tmp; } @Override public Collection<Path> getRoots() { return roots; } @Override public Manifest getManifest() { for (PathTree tree : trees) { final Manifest m = tree.getManifest(); if (m != null) { return m; } } return null; } @Override public void walk(PathVisitor visitor) { if (trees.length == 0) { return; } for (PathTree t : trees) { t.walk(visitor); } } @Override public <T> T apply(String relativePath, Function<PathVisit, T> func) { for (PathTree tree : trees) { T result = tree.apply(relativePath, func); if (result != null) { return result; } } return null; } @Override public void accept(String relativePath, Consumer<PathVisit> func) { final AtomicBoolean consumed = new AtomicBoolean(); final Consumer<PathVisit> wrapper = new Consumer<>() { @Override public void accept(PathVisit t) { if (t != null) { func.accept(t); consumed.set(true); } } }; for (PathTree tree : trees) { tree.accept(relativePath, wrapper); if (consumed.get()) { break; } } if (!consumed.get()) { func.accept(null); } } @Override public boolean contains(String relativePath) { for (PathTree tree : trees) { if (tree.contains(relativePath)) { return true; } } return false; } @Override public Path getPath(String relativePath) { for (PathTree tree : trees) { if (tree instanceof OpenPathTree) { final Path p = ((OpenPathTree) tree).getPath(relativePath); if (p != null) { return p; } } else { throw new UnsupportedOperationException(); } } return null; } @Override public OpenPathTree open() { return this; } @Override public boolean isOpen() { return true; } @Override public void close() throws IOException { } @Override public PathTree getOriginalTree() { return this; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + Arrays.hashCode(trees); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; MultiRootPathTree other = (MultiRootPathTree) obj; return Arrays.equals(trees, other.trees); } }
24.411765
75
0.527711
f0e088092cc0272724d28a090921e33d24d360da
596
package chapter7; public class RecTest { int valumes[]; RecTest(int i) { valumes = new int[i]; } //выводим рекрсивно элементы массива void printArray (int i) { if (i == 0) return; else printArray(i-1); System.out.println("[" + (i - 1) + "]" + valumes[i-1]); } } class Recursion2 { public static void main (String[] args) { RecTest ob = new RecTest(10); int i; for (i=0; i<8; i++) ob.valumes[i] = i; //тут мы проходу устанавливаем знаечния для массива ob.printArray(8); // а тут выводим их? } }
22.074074
98
0.550336
e6154b0d2a75d802a281c4c43b74c303deefc690
5,204
package com.wardrobe.platform.rfid.rfid.bean; import com.wardrobe.platform.rfid.rfid.config.HEAD; /** * Object of describing data package; * @author Administrator * */ public class MessageTran { private byte btPacketType; //head of data, defauld value is 0xA0 private byte btDataLen; //Length of data package, which means the byte quantity after the "length", not including the "length" private byte btReadId; //Address of reader private byte btCmd; //The commend code of data package private byte[] btAryData; //The commend specification of data package, some commends without specification private byte btCheck; //Checksum private byte[] btAryTranData; //Complete data package /** * MessageTran default constructor */ public MessageTran() { } /** * MessageTran Constructor * @param btReadId address of reader * @param btCmd command code of data package * @param btAryData command parameters of data package, some commands without parameters */ public MessageTran(byte btReadId, byte btCmd, byte[] btAryData) { int nLen = btAryData.length; this.btPacketType = HEAD.HEAD; this.btDataLen = (byte)(nLen + 3); this.btReadId = btReadId; this.btCmd = btCmd; this.btAryData = new byte[nLen]; System.arraycopy(btAryData, 0, this.btAryData, 0, btAryData.length); //btAryData.CopyTo(this.btAryData, 0); this.btAryTranData = new byte[nLen + 5]; this.btAryTranData[0] = this.btPacketType; this.btAryTranData[1] = this.btDataLen; this.btAryTranData[2] = this.btReadId; this.btAryTranData[3] = this.btCmd; System.arraycopy(this.btAryData, 0, this.btAryTranData, 4, this.btAryData.length); //this.btAryData.CopyTo(this.btAryTranData, 4); this.btCheck = checkSum(this.btAryTranData, 0, nLen + 4); this.btAryTranData[nLen + 4] = this.btCheck; } /** * MessageTran Constructor * @param btReadId address of reader * @param btCmd read command */ public MessageTran(byte btReadId, byte btCmd) { this.btPacketType = HEAD.HEAD; this.btDataLen = 0x03; this.btReadId = btReadId; this.btCmd = btCmd; this.btAryTranData = new byte[5]; this.btAryTranData[0] = this.btPacketType; this.btAryTranData[1] = this.btDataLen; this.btAryTranData[2] = this.btReadId; this.btAryTranData[3] = this.btCmd; this.btCheck = checkSum(this.btAryTranData, 0, 4); this.btAryTranData[4] = this.btCheck; } /** * MessageTran constructor * @param btAryTranData complete data package */ public MessageTran(byte[] btAryTranData) { int nLen = btAryTranData.length; this.btAryTranData = new byte[nLen]; System.arraycopy(btAryTranData, 0, this.btAryTranData, 0, btAryTranData.length); //btAryTranData.CopyTo(this.btAryTranData, 0); byte btCK = checkSum(this.btAryTranData, 0, this.btAryTranData.length - 1); if (btCK != btAryTranData[nLen - 1]) { return; } this.btPacketType = btAryTranData[0]; this.btDataLen = btAryTranData[1]; this.btReadId = btAryTranData[2]; this.btCmd = btAryTranData[3]; this.btCheck = btAryTranData[nLen - 1]; if (nLen > 5) { this.btAryData = new byte[nLen - 5]; for (int nloop = 0; nloop < nLen - 5; nloop++ ) { this.btAryData[nloop] = btAryTranData[4 + nloop]; } } } /** * Obtain complete data package * @return Data package */ public byte[] getAryTranData() { return this.btAryTranData; } /** * Obtain command parameters of data package, some command without parameters * @return commends parameters */ public byte[] getAryData() { return this.btAryData; } /** * Obtain address of reader * @return Address of reader */ public byte getReadId() { return this.btReadId; } /** * Obtain command of data package * @return command */ public byte getCmd() { return this.btCmd; } /** * Obain head of data, default 0xA0 * @return head of data */ public byte getPacketType() { return this.btPacketType; } /** * Check head of data * @return Result of checking */ public boolean checkPacketType() { return this.btPacketType == HEAD.HEAD; } /** * Calculate checksum * @param btAryBuffer data * @param nStartPos start position * @param nLen Checking length * @return Checksum */ public byte checkSum(byte[] btAryBuffer, int nStartPos, int nLen) { byte btSum = 0x00; for (int nloop = nStartPos; nloop < nStartPos + nLen; nloop++ ) { btSum += btAryBuffer[nloop]; } return (byte)(((~btSum) + 1) & 0xFF); } }
30.432749
138
0.593966
bdd453a1a1ed6b9ae46468b581050417bb71672d
3,035
package io.github.mariazevedo88.financialjavaapi.test.repository.transaction; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotNull; import java.math.BigDecimal; import java.util.Date; import java.util.List; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.TestInstance; import org.junit.jupiter.api.TestInstance.Lifecycle; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.TestExecutionListeners; import org.springframework.test.context.support.DependencyInjectionTestExecutionListener; import io.github.mariazevedo88.financialjavaapi.model.enumeration.TransactionTypeEnum; import io.github.mariazevedo88.financialjavaapi.model.transaction.Transaction; import io.github.mariazevedo88.financialjavaapi.repository.transaction.TransactionRepository; /** * Class that implements tests of the TransactionRepository funcionalities * * @author Mariana Azevedo * @since 04/04/2020 */ @SpringBootTest @TestExecutionListeners({ DependencyInjectionTestExecutionListener.class }) @ActiveProfiles("test") @TestInstance(Lifecycle.PER_CLASS) public class TransactionRepositoryTest { @Autowired private TransactionRepository repository; /** * Method to setup an User to use in the tests. * * @author Mariana Azevedo * @since 24/03/2020 */ @BeforeAll private void setUp() { Transaction transaction = new Transaction(); transaction.setNsu("220788"); transaction.setAuthorizationNumber("000123"); transaction.setTransactionDate(new Date()); transaction.setAmount(new BigDecimal(100d)); transaction.setType(TransactionTypeEnum.CARD); repository.save(transaction); } /** * Method that test the repository that save an User in the API. * * @author Mariana Azevedo * @since 24/03/2020 */ @Test public void testSave() { Transaction transaction = new Transaction(); transaction.setNsu("270257"); transaction.setAuthorizationNumber("000123"); transaction.setTransactionDate(new Date()); transaction.setAmount(new BigDecimal(100d)); transaction.setType(TransactionTypeEnum.CARD); Transaction response = repository.save(transaction); assertNotNull(response); } /** * Method that test the repository that search for an User by the email. * * @author Mariana Azevedo * @since 24/03/2020 */ @Test public void testFindByNsu(){ List<Transaction> response = repository.findByNsu("220788"); assertFalse(response.isEmpty()); assertEquals("220788", response.get(0).getNsu()); } /** * Method to remove all User test data. * * @author Mariana Azevedo * @since 24/03/2020 */ @AfterAll private void tearDown() { repository.deleteAll(); } }
28.101852
93
0.771334
95a69541a9125133017d81c7e33b20a05c91eeb5
1,836
package com.dutchs.modpacktools.network; import com.dutchs.modpacktools.Constants; import net.minecraft.network.FriendlyByteBuf; import net.minecraft.network.chat.Component; import net.minecraft.server.level.ServerPlayer; import net.minecraftforge.network.NetworkEvent; import org.jetbrains.annotations.NotNull; import java.util.function.Supplier; public class PrivilegedMessagePacket implements NetworkManager.INetworkPacket { private String message; public PrivilegedMessagePacket() { } public PrivilegedMessagePacket(@NotNull String msg) { message = msg; } @Override public void encode(Object msg, FriendlyByteBuf packetBuffer) { PrivilegedMessagePacket blockPacket = (PrivilegedMessagePacket) msg; packetBuffer.writeUtf(blockPacket.message); } @Override public <MESSAGE> MESSAGE decode(FriendlyByteBuf packetBuffer) { PrivilegedMessagePacket result = new PrivilegedMessagePacket(); result.message = packetBuffer.readUtf(); return (MESSAGE) result; } @Override public void handle(Object msg, Supplier<NetworkEvent.Context> contextSupplier) { contextSupplier.get().enqueueWork(() -> { ServerPlayer p = contextSupplier.get().getSender(); if (p != null) { if (p.hasPermissions(2)) { PrivilegedMessagePacket privilegedMessagePacket = (PrivilegedMessagePacket) msg; p.sendSystemMessage(Component.literal(privilegedMessagePacket.message).withStyle(Constants.ERROR_FORMAT)); } else { p.sendSystemMessage(Component.literal("You lack permissions to run this command").withStyle(Constants.ERROR_FORMAT)); } } }); contextSupplier.get().setPacketHandled(true); } }
36
137
0.6939
8e7d4baad10cb2e5fe63e6ca04acefeb0ab6233c
1,742
package com.ruoyi.schoolJob.mapper; import java.util.List; import java.util.Map; import com.ruoyi.schoolJob.domain.MyTitle; import com.ruoyi.schoolJob.domain.MyClass; /** * MyTitleMapper接口 * */ public interface MyTitleMapper { /** * 查询MyTitle * * @param titleId MyTitle主键 * @return MyTitle */ public MyTitle selectMyTitleByTitleId(Long titleId); /** * 查询MyTitle列表 * * @param myTitle MyTitle * @return MyTitle集合 */ public List<MyTitle> selectMyTitleList(MyTitle myTitle); /** * 新增MyTitle * * @param myTitle MyTitle * @return 结果 */ public int insertMyTitle(MyTitle myTitle); /** * 修改MyTitle * * @param myTitle MyTitle * @return 结果 */ public int updateMyTitle(MyTitle myTitle); /** * 删除MyTitle * * @param titleId MyTitle主键 * @return 结果 */ public int deleteMyTitleByTitleId(Long titleId); /** * 批量删除MyTitle * * @param titleIds 需要删除的数据主键集合 * @return 结果 */ public int deleteMyTitleByTitleIds(Long[] titleIds); /** * 批量删除MyClass * * @param titleIds 需要删除的数据主键集合 * @return 结果 */ public int deleteMyClassByClassIds(Long[] titleIds); /** * 批量新增MyClass * * @param myClassList MyClass列表 * @return 结果 */ public int batchMyClass(List<MyClass> myClassList); /** * 通过MyTitle主键删除MyClass信息 * * @param titleId MyTitleID * @return 结果 */ public int deleteMyClassByClassId(Long titleId); /** * 根据教学班ID查询题目 * @param classId * @return */ public List<Map<String,Object>> selectTitleByClassId(Long classId); }
18.336842
71
0.588404
580503b200ed00e723e8805eb5f2029664cf4efb
2,237
/* 314 Binary Tree Vertical Order Traversal Given a binary tree, return the vertical order traversal of its nodes' values. (ie, from top to bottom, column by column). If two nodes are in the same row and column, the order should be from left to right. Examples: Given binary tree [3,9,20,null,null,15,7], 3 / \ 9 20 / \ 15 7 return its vertical order traversal as: [ [9], [3,15], [20], [7] ] Given binary tree [3,9,20,4,5,2,7], _3_ / \ 9 20 / \ / \ 4 5 2 7 return its vertical order traversal as: [ [4], [9], [3,5,2], [20], [7] ] */ /***** 1. column标号, 按标号输出。 2. 图想,标号只能从root开始; 如果从最做开始,下一列(右子,父-难找)。 root 表0, 左标 -1, 右边+1, 标号不是自然数,不能数组, 只能map<标号, List<>>, list是列。 3. 从root开始bfs遍历标号, 还需要一个map<node, 标号>, 这样node可以找到所在列,并添加。 4. 标号的同时记录最小标号, 循环输出map.get(min++), 直至key不含min 303 1. DFS, 错, preorder, postorder(右树越界左伸)都不行, 列里的添加顺序不对。 2. 一定bfs,入队时存入w,出对时找回。 411 1. 必须需要 weight(node -> col) 无法用Queue<int[]> *****/ public class Solution { public List<List<Integer>> verticalOrder(TreeNode root) { List<List<Integer>> res = new ArrayList<>(); if (root == null) { return res; } //map's key is column, we assume the root column is zero, the left node wi ll minus 1 ,and the right node will plus 1 HashMap<Integer, ArrayList<Integer>> map = new HashMap<Integer, ArrayList<Integer>>(); Queue<TreeNode> queue = new LinkedList<>(); //use a HashMap to store the TreeNode and the according cloumn value HashMap<TreeNode, Integer> weight = new HashMap<TreeNode, Integer>(); queue.offer(root); weight.put(root, 0); int min = 0; // when output the arraylist from map, need to start with min. while (!queue.isEmpty()) { TreeNode node = queue.poll(); int w = weight.get(node); if (!map.containsKey(w)) { map.put(w, new ArrayList<>()); } map.get(w).add(node.val); if (node.left != null) { queue.add(node.left); weight.put(node.left, w - 1); } if (node.right != null) { queue.add(node.right); weight.put(node.right, w + 1); } //update min ,min means the minimum column value, which is the left most node min = Math.min(min, w); } while (map.containsKey(min)) { res.add(map.get(min++)); } return res; } }
20.522936
122
0.637014
e91ac2bb9bd1f18303ab8811f6207aac64e8e80b
26,352
package romever.scan.oasisscan.service; import com.fasterxml.jackson.core.type.TypeReference; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.collect.Sets; import lombok.extern.slf4j.Slf4j; import org.elasticsearch.action.search.SearchResponse; import org.elasticsearch.client.RestHighLevelClient; import org.elasticsearch.index.query.BoolQueryBuilder; import org.elasticsearch.index.query.QueryBuilders; import org.elasticsearch.search.SearchHit; import org.elasticsearch.search.SearchHits; import org.elasticsearch.search.builder.SearchSourceBuilder; import org.elasticsearch.search.sort.SortOrder; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Isolation; import org.springframework.transaction.annotation.Transactional; import org.springframework.util.CollectionUtils; import romever.scan.oasisscan.common.ApplicationConfig; import romever.scan.oasisscan.common.Constants; import romever.scan.oasisscan.common.ESFields; import romever.scan.oasisscan.common.ElasticsearchConfig; import romever.scan.oasisscan.common.client.ApiClient; import romever.scan.oasisscan.db.JestDao; import romever.scan.oasisscan.entity.*; import romever.scan.oasisscan.repository.*; import romever.scan.oasisscan.utils.Mappers; import romever.scan.oasisscan.utils.Texts; import romever.scan.oasisscan.vo.CommitteeRoleEnum; import romever.scan.oasisscan.vo.MethodEnum; import romever.scan.oasisscan.vo.RuntimeHeaderTypeEnum; import romever.scan.oasisscan.vo.chain.runtime.Runtime; import romever.scan.oasisscan.vo.chain.*; import romever.scan.oasisscan.vo.chain.runtime.RuntimeRound; import romever.scan.oasisscan.vo.chain.runtime.RuntimeState; import java.io.IOException; import java.math.BigInteger; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; @Slf4j @Service public class ScanRuntimeService { @Autowired private ApplicationConfig applicationConfig; @Autowired private ApiClient apiClient; @Autowired private RestHighLevelClient elasticsearchClient; @Autowired private ElasticsearchConfig elasticsearchConfig; @Autowired private RuntimeRepository runtimeRepository; @Autowired private RuntimeStatsRepository runtimeStatsRepository; @Autowired private RuntimeStatsInfoRepository runtimeStatsInfoRepository; @Autowired private RuntimeNodeRepository runtimeNodeRepository; @Autowired private SystemPropertyRepository systemPropertyRepository; @Autowired private TransactionService transactionService; /** * Get all runtimes info and save in elasticsearch */ @Scheduled(fixedDelay = 10 * 60 * 1000, initialDelay = 5 * 1000) public void scanRuntime() throws IOException { if (applicationConfig.isLocal()) { return; } List<Runtime> runtimes = apiClient.runtimes(null); if (CollectionUtils.isEmpty(runtimes)) { return; } for (Runtime runtime : runtimes) { String runtimeId = runtime.getId(); Optional<romever.scan.oasisscan.entity.Runtime> optionalRuntime = runtimeRepository.findByRuntimeId(runtimeId); romever.scan.oasisscan.entity.Runtime runtimeEntity; runtimeEntity = optionalRuntime.orElseGet(romever.scan.oasisscan.entity.Runtime::new); runtimeEntity.setEntityId(runtime.getEntity_id()); runtimeEntity.setRuntimeId(runtimeId); runtimeRepository.save(runtimeEntity); } log.info("Runtime info sync done."); } /** * Scan runtimes round and save in elasticsearch */ @Scheduled(fixedDelay = 15 * 1000, initialDelay = 10 * 1000) public void scanRuntimeRound() throws IOException { if (applicationConfig.isLocal()) { return; } List<romever.scan.oasisscan.entity.Runtime> runtimes = runtimeRepository.findAll(); if (CollectionUtils.isEmpty(runtimes)) { return; } long currentChainHeight = apiClient.getCurHeight(); for (romever.scan.oasisscan.entity.Runtime runtime : runtimes) { String runtimeId = runtime.getRuntimeId(); long scanHeight = getScanRound(runtimeId); if (scanHeight == 0) { RuntimeState runtimeState = apiClient.roothashRuntimeState(runtimeId, null); long genesisTime = runtimeState.getGenesis_block().getHeader().getTimestamp().toEpochSecond(); Long genesisHeight = getGenesisRoundHeight(genesisTime); if (genesisHeight == null) { throw new RuntimeException(String.format("Genesis Height can not found. %s", runtimeId)); } scanHeight = genesisHeight; Optional<romever.scan.oasisscan.entity.Runtime> optionalRuntime = runtimeRepository.findByRuntimeId(runtimeId); if (!optionalRuntime.isPresent()) { throw new RuntimeException("Runtime db read error."); } romever.scan.oasisscan.entity.Runtime _runtime = optionalRuntime.get(); _runtime.setStartRoundHeight(genesisHeight); runtimeRepository.saveAndFlush(_runtime); } while (scanHeight < currentChainHeight) { RuntimeRound runtimeRound = apiClient.roothashLatestblock(runtimeId, scanHeight); if (runtimeRound == null) { throw new RuntimeException(String.format("Runtime round api error. %s, %s", runtimeId, scanHeight)); } RuntimeRound.Header header = runtimeRound.getHeader(); String id = header.getNamespace() + "_" + header.getRound(); JestDao.index(elasticsearchClient, elasticsearchConfig.getRuntimeRoundIndex(), Mappers.map(header), id); //save scan height saveScanRound(runtimeId, scanHeight); log.info("Runtime round sync done. {} [{}]", scanHeight, id); scanHeight++; } } } private Long getScanRound(String runtimeId) { Long storeHeight = 0L; String property = Constants.SYSTEM_RUNTIME_ROUND_PREFIX + runtimeId; Optional<SystemProperty> optionalSystemProperty = systemPropertyRepository.findByProperty(property); if (optionalSystemProperty.isPresent()) { storeHeight = Long.parseLong(optionalSystemProperty.get().getValue()); } return storeHeight; } private void saveScanRound(String runtimeId, long round) { String property = Constants.SYSTEM_RUNTIME_ROUND_PREFIX + runtimeId; SystemProperty systemProperty = systemPropertyRepository.findByProperty(property).orElse(new SystemProperty()); systemProperty.setProperty(property); systemProperty.setValue(String.valueOf(round)); systemPropertyRepository.saveAndFlush(systemProperty); } /** * See https://github.com/oasisprotocol/tools/tree/main/runtime-stats */ @Scheduled(fixedDelay = 15 * 1000, initialDelay = 20 * 1000) @Transactional(rollbackFor = Exception.class, isolation = Isolation.SERIALIZABLE) public void scanRuntimeStats() throws IOException { if (applicationConfig.isLocal()) { return; } List<romever.scan.oasisscan.entity.Runtime> runtimes = runtimeRepository.findAllByOrderByStartRoundHeightAsc(); if (CollectionUtils.isEmpty(runtimes)) { return; } long currentChainHeight = apiClient.getCurHeight(); for (romever.scan.oasisscan.entity.Runtime runtime : runtimes) { String runtimeId = runtime.getRuntimeId(); long scanHeight = runtime.getStatsHeight(); if (scanHeight == 0) { scanHeight = runtime.getStartRoundHeight(); } long curRound = 0; boolean roundDiscrepancy = false; RuntimeState.Committee committee = null; RuntimeState.Member currentScheduler = null; while (scanHeight < currentChainHeight) { Optional<romever.scan.oasisscan.entity.Runtime> optionalRuntime = runtimeRepository.findByRuntimeId(runtimeId); if (!optionalRuntime.isPresent()) { throw new RuntimeException("Runtime db read error."); } romever.scan.oasisscan.entity.Runtime _runtime = optionalRuntime.get(); _runtime.setStatsHeight(scanHeight); runtimeRepository.saveAndFlush(_runtime); List<Node> nodes = apiClient.registryNodes(scanHeight); if (nodes == null) { throw new RuntimeException(String.format("Registry nodes api error. %s, %s", runtimeId, scanHeight)); } //save node entity map Map<String, String> nodeToEntity = Maps.newHashMap(); for (Node node : nodes) { nodeToEntity.put(node.getId(), node.getEntity_id()); List<Node.Runtime> runtimeList = node.getRuntimes(); if (CollectionUtils.isEmpty(runtimeList)) { continue; } for (Node.Runtime r : runtimeList) { if (r.getId().equalsIgnoreCase(runtimeId)) { //save in db Optional<RuntimeNode> optionalRuntimeNode = runtimeNodeRepository.findByRuntimeIdAndNodeId(runtimeId, node.getId()); if (!optionalRuntimeNode.isPresent()) { RuntimeNode runtimeNode = new RuntimeNode(); runtimeNode.setRuntimeId(runtimeId); runtimeNode.setNodeId(node.getId()); runtimeNode.setEntityId(node.getEntity_id()); runtimeNodeRepository.save(runtimeNode); } } } } RuntimeRound runtimeRound = apiClient.roothashLatestblock(runtimeId, scanHeight); if (runtimeRound == null) { throw new RuntimeException(String.format("Runtime round api error. %s", scanHeight)); } // If new round, check for proposer timeout. // Need to look at submitted transactions if round failure was caused by a proposer timeout. List<Transaction> txs = null; try { txs = transactionService.getEsTransactionsByHeight(scanHeight); } catch (IOException e) { log.error("error", e); break; } boolean proposerTimeout = false; if (!CollectionUtils.isEmpty(txs) && curRound != runtimeRound.getHeader().getRound() && committee != null) { for (Transaction tx : txs) { TransactionResult.Error error = tx.getError(); if (error != null) { if (Texts.isNotBlank(error.getMessage())) { continue; } } if (!tx.getMethod().equalsIgnoreCase(MethodEnum.RoothashExecutorProposerTimeout.getName())) { continue; } if (!runtimeId.equalsIgnoreCase(tx.getBody().getId())) { continue; } saveRuntimeStats(runtimeId, scanHeight, tx.getBody().getRound(), nodeToEntity.get(tx.getSignature().getPublic_key()), RuntimeStatsType.PROPOSED_TIMEOUT); if (currentScheduler != null) { saveRuntimeStats(runtimeId, scanHeight, tx.getBody().getRound(), nodeToEntity.get(currentScheduler.getPublic_key()), RuntimeStatsType.PROPOSER_MISSED); } proposerTimeout = true; break; } } long headerType = runtimeRound.getHeader().getHeader_type(); // Go over events before updating potential new round committee info. // Even if round transition happened at this height, all events emitted // at this height belong to the previous round. List<RoothashEvent> events = apiClient.roothashEvents(scanHeight); if (events != null && curRound != 0) { for (RoothashEvent ev : events) { if (!runtimeId.equalsIgnoreCase(ev.getRuntime_id())) { continue; } if (ev.getExecution_discrepancy() != null) { roundDiscrepancy = true; } if (ev.getFinalized() != null) { RoothashEvent.Finalized _ev = ev.getFinalized(); // Skip the empty finalized event that is triggered on initial round. if (CollectionUtils.isEmpty(_ev.getGood_compute_nodes()) && CollectionUtils.isEmpty(_ev.getBad_compute_nodes()) && committee == null) { continue; } // Skip if epoch transition or suspended blocks. if (headerType == RuntimeHeaderTypeEnum.EpochTransition.getCode() || headerType == RuntimeHeaderTypeEnum.Suspended.getCode()) { continue; } if (proposerTimeout) { continue; } // Update stats. OUTER: for (RuntimeState.Member member : committee.getMembers()) { String entityId = nodeToEntity.get(member.getPublic_key()); // Primary workers are always required. if (member.getRole().equalsIgnoreCase(CommitteeRoleEnum.WORKER.getName())) { saveRuntimeStats(runtimeId, scanHeight, curRound, entityId, RuntimeStatsType.PRIMARY_INVOKED); } // In case of discrepancies backup workers were invoked as well. if (roundDiscrepancy && member.getRole().equalsIgnoreCase(CommitteeRoleEnum.BACKUPWORKER.getName())) { saveRuntimeStats(runtimeId, scanHeight, curRound, entityId, RuntimeStatsType.BCKP_INVOKED); } // Go over good commitments. if (_ev.getGood_compute_nodes() != null) { for (String g : _ev.getGood_compute_nodes()) { if (member.getPublic_key().equalsIgnoreCase(g) && member.getRole().equalsIgnoreCase(CommitteeRoleEnum.WORKER.getName())) { saveRuntimeStats(runtimeId, scanHeight, curRound, entityId, RuntimeStatsType.PRIMARY_GOOD_COMMIT); continue OUTER; } if (member.getPublic_key().equalsIgnoreCase(g) && roundDiscrepancy && member.getRole().equalsIgnoreCase(CommitteeRoleEnum.BACKUPWORKER.getName())) { saveRuntimeStats(runtimeId, scanHeight, curRound, entityId, RuntimeStatsType.BCKP_GOOD_COMMIT); continue OUTER; } } } // Go over bad commitments. if (_ev.getBad_compute_nodes() != null) { for (String g : _ev.getBad_compute_nodes()) { if (member.getPublic_key().equalsIgnoreCase(g) && member.getRole().equalsIgnoreCase(CommitteeRoleEnum.WORKER.getName())) { saveRuntimeStats(runtimeId, scanHeight, curRound, entityId, RuntimeStatsType.PRIM_BAD_COMMMIT); continue OUTER; } if (member.getPublic_key().equalsIgnoreCase(g) && roundDiscrepancy && member.getRole().equalsIgnoreCase(CommitteeRoleEnum.BACKUPWORKER.getName())) { saveRuntimeStats(runtimeId, scanHeight, curRound, entityId, RuntimeStatsType.BCKP_BAD_COMMIT); continue OUTER; } } } // Neither good nor bad - missed commitment. if (member.getRole().equalsIgnoreCase(CommitteeRoleEnum.WORKER.getName())) { saveRuntimeStats(runtimeId, scanHeight, curRound, entityId, RuntimeStatsType.PRIMARY_MISSED); } if (roundDiscrepancy && member.getRole().equalsIgnoreCase(CommitteeRoleEnum.BACKUPWORKER.getName())) { saveRuntimeStats(runtimeId, scanHeight, curRound, entityId, RuntimeStatsType.BCKP_MISSED); } } } } } if (headerType == RuntimeHeaderTypeEnum.Suspended.getCode()) { log.info(String.format("runtime stats: %s, %s", runtimeId, scanHeight)); scanHeight++; continue; } if (curRound != runtimeRound.getHeader().getRound()) { curRound = runtimeRound.getHeader().getRound(); RuntimeState runtimeState = apiClient.roothashRuntimeState(runtimeId, scanHeight); if (runtimeState == null) { throw new RuntimeException(String.format("Runtime state api error. %s", scanHeight)); } RuntimeState.ExecutorPool executorPool = runtimeState.getExecutor_pool(); if (executorPool == null) { log.info(String.format("runtime stats: %s, %s", runtimeId, scanHeight)); scanHeight++; continue; } committee = executorPool.getCommittee(); currentScheduler = getTransactionScheduler(committee.getMembers(), curRound); roundDiscrepancy = false; } // Update election stats. Set<String> seen = Sets.newHashSet(); if (committee != null) { for (RuntimeState.Member member : committee.getMembers()) { String pubKey = member.getPublic_key(); String entityId = nodeToEntity.get(pubKey); if (Texts.isBlank(entityId)) { throw new RuntimeException(String.format("Entity id not found. %s, %s", pubKey, scanHeight)); } if (!seen.contains(pubKey)) { saveRuntimeStats(runtimeId, scanHeight, curRound, entityId, RuntimeStatsType.ELECTED); } seen.add(pubKey); if (member.getRole().equalsIgnoreCase(CommitteeRoleEnum.WORKER.getName())) { saveRuntimeStats(runtimeId, scanHeight, curRound, entityId, RuntimeStatsType.PRIMARY); } if (member.getRole().equalsIgnoreCase(CommitteeRoleEnum.BACKUPWORKER.getName())) { saveRuntimeStats(runtimeId, scanHeight, curRound, entityId, RuntimeStatsType.BACKUP); } if (currentScheduler != null && pubKey.equalsIgnoreCase(currentScheduler.getPublic_key())) { saveRuntimeStats(runtimeId, scanHeight, curRound, entityId, RuntimeStatsType.PROPOSER); } } } log.info(String.format("runtime stats: %s, %s", runtimeId, scanHeight)); scanHeight++; } } } @Scheduled(fixedDelay = 30 * 1000, initialDelay = 30 * 1000) public void scanRuntimeStatsInfo() { if (applicationConfig.isLocal()) { return; } List<romever.scan.oasisscan.entity.Runtime> runtimes = runtimeRepository.findAllByOrderByStartRoundHeightAsc(); if (CollectionUtils.isEmpty(runtimes)) { return; } for (romever.scan.oasisscan.entity.Runtime runtime : runtimes) { List<String> entities = runtimeStatsRepository.entities(runtime.getRuntimeId()); if (CollectionUtils.isEmpty(entities)) { continue; } RuntimeStatsType[] types = RuntimeStatsType.class.getEnumConstants(); for (String entity : entities) { List statsList = runtimeStatsRepository.statsByRuntimeId(runtime.getRuntimeId(), entity); if (CollectionUtils.isEmpty(statsList)) { continue; } for (Object row : statsList) { Object[] cells = (Object[]) row; for (int i = 0; i < types.length; i++) { RuntimeStatsType type = types[i]; if (i == (Integer) cells[0]) { long count = ((BigInteger) cells[1]).longValue(); RuntimeStatsInfo statsInfo; Optional<RuntimeStatsInfo> optional = runtimeStatsInfoRepository.findByRuntimeIdAndEntityIdAndStatsType(runtime.getRuntimeId(), entity, type); if (optional.isPresent()) { statsInfo = optional.get(); } else { statsInfo = new RuntimeStatsInfo(); statsInfo.setRuntimeId(runtime.getRuntimeId()); statsInfo.setEntityId(entity); } statsInfo.setStatsType(type); statsInfo.setCount(count); runtimeStatsInfoRepository.save(statsInfo); break; } } } log.info(String.format("runtime stats info: %s,%s", runtime.getRuntimeId(), entity)); } } } private RuntimeState.Member getTransactionScheduler(List<RuntimeState.Member> members, long round) { List<RuntimeState.Member> workers = workers(members); int numNodes = workers.size(); if (numNodes == 0) { return null; } long schedulerIdx = round % numNodes; return workers.get((int) schedulerIdx); } private List<RuntimeState.Member> workers(List<RuntimeState.Member> members) { List<RuntimeState.Member> wokers = Lists.newArrayList(); for (RuntimeState.Member member : members) { String role = member.getRole(); if (role.equalsIgnoreCase(CommitteeRoleEnum.WORKER.getName())) { wokers.add(member); } } return wokers; } private void saveRuntimeStats(String runtimeId, long scanHeight, long round, String entityId, RuntimeStatsType statsType) { Optional<RuntimeStats> optional = runtimeStatsRepository.findByRuntimeIdAndEntityIdAndRoundAndStatsType(runtimeId, entityId, round, statsType); RuntimeStats stats; if (optional.isPresent()) { stats = optional.get(); stats.setHeight(scanHeight); } else { stats = new RuntimeStats(); stats.setRuntimeId(runtimeId); stats.setEntityId(entityId); stats.setHeight(scanHeight); stats.setRound(round); stats.setStatsType(statsType); } runtimeStatsRepository.save(stats); } private Long getGenesisRoundHeight(long timestamp) { Long height = null; SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder(); BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery(); boolQueryBuilder.filter(QueryBuilders.rangeQuery(ESFields.BLOCK_TIMESTAMP).from(timestamp, true)); searchSourceBuilder.query(boolQueryBuilder); searchSourceBuilder.sort(ESFields.BLOCK_TIMESTAMP, SortOrder.ASC); searchSourceBuilder.size(1); try { SearchResponse searchResponse = JestDao.search(elasticsearchClient, elasticsearchConfig.getBlockIndex(), searchSourceBuilder); if (searchResponse.getTotalShards() != searchResponse.getSuccessfulShards()) { return height; } SearchHits hits = searchResponse.getHits(); SearchHit[] searchHits = hits.getHits(); if (searchHits.length != 1) { return height; } SearchHit hit = searchHits[0]; Block block = Mappers.parseJson(hit.getSourceAsString(), new TypeReference<Block>() { }); if (block == null) { return height; } height = block.getHeight(); } catch (Exception e) { log.error("error", e); } return height; } }
50.482759
188
0.56565
081568e34c8d40e53a2b1230026adaa245fd7f22
1,785
package org.lahsivjar; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.messaging.MessageChannel; import org.springframework.messaging.handler.annotation.MessageMapping; import org.springframework.messaging.handler.annotation.Payload; import org.springframework.messaging.handler.annotation.SendTo; import org.springframework.messaging.simp.SimpMessageHeaderAccessor; import org.springframework.messaging.simp.stomp.StompCommand; import org.springframework.messaging.simp.stomp.StompHeaderAccessor; import org.springframework.messaging.support.MessageBuilder; import org.springframework.web.bind.annotation.RestController; import java.util.HashMap; import java.util.Map; @RestController public class MessageController { @Autowired @Qualifier("clientOutboundChannel") private MessageChannel clientOutboundChannel; @MessageMapping("/text/ping") @SendTo("/topic/ping") public String textPong(@Payload String message) { return "pong"; } @MessageMapping("/json/ping") @SendTo("/topic/ping") public Map<String, String> jsonPong(@Payload String message) { final Map<String, String> result = new HashMap<>(); result.put("msg", "pong"); return result; } @MessageMapping("/err") public void error(SimpMessageHeaderAccessor headerAccessor) { StompHeaderAccessor stompHeaderAccessor = StompHeaderAccessor.create(StompCommand.ERROR); stompHeaderAccessor.setSessionId(headerAccessor.getSessionId()); stompHeaderAccessor.setDestination("/topic/ping"); clientOutboundChannel.send(MessageBuilder.createMessage(new byte[0], stompHeaderAccessor.getMessageHeaders())); } }
37.1875
119
0.77479
bbc95fbdf890da1a0972444cb76b250f9bb508c7
229
package com.ooad.xproject.vo; import lombok.Data; @Data public class AcInfoStdUpdateVO { private String[] skills; private String[] flags; private String bio; private String email; private String iconUrl; }
16.357143
32
0.71179
ff71fce9733c3553a27fd0b03b51a15ade205735
1,894
package chat.persistence.repository.mock; import chat.model.User; import chat.persistence.repository.UserRepository; import java.util.Map; import java.util.TreeMap; /** * Created by IntelliJ IDEA. * User: grigo * Date: Mar 18, 2009 * Time: 1:13:54 PM */ public class UserRepositoryMock implements UserRepository { private Map<String, User> allUsers; public UserRepositoryMock() { allUsers = new TreeMap<String, User>(); populateUsers(); } public boolean verifyUser(User user) { User userR = allUsers.get(user.getId()); if (userR == null) return false; return userR.getPasswd().equals(user.getPasswd()); } public User[] getFriends(User user) { User userR = allUsers.get(user.getId()); if (userR != null) return userR.getFriendsArray(); return new User[0]; } private void populateUsers() { User ana = new User("ana", "ana", "Popescu Ana"); User mihai = new User("mihai", "mihai", "Ionescu Mihai"); User ion = new User("ion", "ion", "Vasilescu Ion"); User maria = new User("maria", "maria", "Marinescu Maria"); User test = new User("test", "test", "Test user"); ana.addFriend(mihai); ana.addFriend(test); mihai.addFriend(ana); mihai.addFriend(test); mihai.addFriend(ion); ion.addFriend(maria); ion.addFriend(test); ion.addFriend(mihai); maria.addFriend(ion); maria.addFriend(test); test.addFriend(ana); test.addFriend(mihai); test.addFriend(ion); test.addFriend(maria); allUsers.put(ana.getId(), ana); allUsers.put(mihai.getId(), mihai); allUsers.put(ion.getId(), ion); allUsers.put(maria.getId(), maria); allUsers.put(test.getId(), test); } }
24.282051
67
0.591341
1af42e65b3a0839a21351eefea9947a3ed89314c
1,575
/* * 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 Entidades; import java.util.*; /** * * @author CajaJL */ public class Empleado { String rifSede, nombre, ciPersona; float sueldo; char tipoE; public Empleado() { } public Empleado(String rifSede, String nombre, String cedula, float sueldo, char tipoE) { this.rifSede = rifSede; this.nombre = nombre; this.ciPersona = cedula; this.sueldo = sueldo; this.tipoE = tipoE; } public String getRifSede() { return rifSede; } public void setRifSede(String rifSede) { this.rifSede = rifSede; } public String getNombre() { return nombre; } public void setNombre(String nombre) { this.nombre = nombre; } public String getCiPersona() { return ciPersona; } public void setCiPersona(String cedula) { this.ciPersona = cedula; } public float getSueldo() { return sueldo; } public void setSueldo(float sueldo) { this.sueldo = sueldo; } public char getTipoE() { return tipoE; } public void setTipoE(char tipoE) { this.tipoE = tipoE; } @Override public String toString() { return "Encargado{" + "rifSede=" + rifSede + ", nombre=" + nombre + ", cedula=" + ciPersona + ", sueldo=" + sueldo + ", tipoE=" + tipoE + '}'; } }
19.936709
150
0.587937
a12922f98e2b724c93061a2347cd5a226b67d24d
14,310
/***************************************************************** JADE - Java Agent DEvelopment Framework is a framework to develop multi-agent systems in compliance with the FIPA specifications. Copyright (C) 2000 CSELT S.p.A. GNU Lesser General Public License This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, version 2.1 of the License. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *****************************************************************/ package jade.lang.acl; //#MIDP_EXCLUDE_FILE import java.io.*; import jade.core.AID; import jade.core.CaseInsensitiveString; import jade.util.leap.Iterator; import jade.util.leap.Properties; import java.util.Enumeration; import java.util.Date; import org.apache.commons.codec.binary.Base64; /** * This class implements the FIPA String codec for ACLMessages. * Notice that it is not possible to convey * a sequence of bytes over a StringACLCodec because the bytes with * the 8th bit ON cannot properly converted into a char. * @author Fabio Bellifemine - CSELT S.p.A. * @author Nicolas Lhuillier - Motorola * @version $Date: 2008-10-09 14:04:02 +0200 (gio, 09 ott 2008) $ $Revision: 6051 $ **/ public class StringACLCodec implements ACLCodec { /** String constant for the name of the ACL representation managed by this ACL codec. */ public static final String NAME = jade.domain.FIPANames.ACLCodec.STRING; /** Key of the user-defined parameter used to signal the automatic JADE conversion of the content into Base64 encoding **/ private static final String BASE64ENCODING_KEY = "JADE-Encoding"; /** Value of the user-defined parameter used to signal the automatic JADE conversion of the content into Base64 encoding **/ private static final String BASE64ENCODING_VALUE = "Base64"; private static final String SENDER = " :sender "; private static final String RECEIVER = " :receiver "; private static final String CONTENT = " :content "; private static final String REPLY_WITH = " :reply-with "; private static final String IN_REPLY_TO = " :in-reply-to "; private static final String REPLY_TO = " :reply-to "; private static final String LANGUAGE = " :language "; private static final String ENCODING = " :encoding "; private static final String ONTOLOGY = " :ontology "; private static final String REPLY_BY = " :reply-by "; private static final String PROTOCOL = " :protocol "; private static final String CONVERSATION_ID = " :conversation-id "; ACLParser parser = null; Writer out = null; /** * constructor for the codec. * The standard input is used as an input stream of ACL messages. * The standard output is used to write encoded ACL messages. */ public StringACLCodec() { //parser = new ACLParser(System.in); //out = new OutputStreamWriter(System.out); } /** * constructor for the codec. * @parameter r is the input stream for the ACL Parser (pass * <code>new InputStreamReader(System.in)</code> * if you want to use the standard input) * @parameter w is the writer to write encoded ACL messages (pass * <code>new OutputStreamWriter(System.out)</code> if you want to * use the standard output) */ public StringACLCodec(Reader r, Writer w) { parser = new ACLParser(r); out = w; } /** * if there was an automatical Base64 encoding, then it performs * automatic decoding. **/ private void checkBase64Encoding(ACLMessage msg) { String encoding = msg.getUserDefinedParameter(BASE64ENCODING_KEY); if (CaseInsensitiveString.equalsIgnoreCase(BASE64ENCODING_VALUE,encoding)) { try { // decode Base64 String content = msg.getContent(); if ((content != null) && (content.length() > 0)) { //char[] cc = new char[content.length()]; //content.getChars(0,content.length(),cc,0); msg.setByteSequenceContent(Base64.decodeBase64(content.getBytes("US-ASCII"))); msg.removeUserDefinedParameter(BASE64ENCODING_KEY); // reset the slot value for encoding } } catch(java.lang.StringIndexOutOfBoundsException e){ e.printStackTrace(); } catch(java.lang.NullPointerException e2){ e2.printStackTrace(); } catch(java.lang.NoClassDefFoundError jlncdfe) { System.err.println("\t\t===== E R R O R !!! =======\n"); System.err.println("Missing support for Base64 conversions"); System.err.println("Please refer to the documentation for details."); System.err.println("=============================================\n\n"); try { Thread.currentThread().sleep(3000); }catch(InterruptedException ie) { } } catch(UnsupportedEncodingException e3){ System.err.println("\t\t===== E R R O R !!! =======\n"); System.err.println("Missing support for US-ASCII encoding for Base64 conversions"); } } //end of if CaseInsensitiveString } /** * decode and parses the next message from the Reader passed in the * constructor. * @return the ACLMessage * @throws ACLCodec.CodecException if any Exception occurs during the * parsing/reading operation */ public ACLMessage decode() throws ACLCodec.CodecException { try { ACLMessage msg = parser.Message(); checkBase64Encoding(msg); return msg; } catch (jade.lang.acl.TokenMgrError e1) { throw new ACLCodec.CodecException(getName()+" ACLMessage decoding token exception",e1); } catch (Exception e) { throw new ACLCodec.CodecException(getName()+" ACLMessage decoding exception",e); } } /** Parse an agent identifier, without it being included within an ACL message. */ public AID decodeAID() throws ACLCodec.CodecException { try { return parser.parseAID(null); } catch(jade.lang.acl.TokenMgrError e1) { throw new ACLCodec.CodecException(getName() + " AID decoding token exception", e1); } catch(Exception e) { e.printStackTrace(); throw new ACLCodec.CodecException(getName() + " AID decoding exception", e); } } /** * encodes the message and writes it into the Writer passed in the * constructor. * Notice that this method does not call <code>flush</code> on the writer. @ param msg is the ACLMessage to encode and write into */ public void write(ACLMessage msg) { try { out.write(toString(msg)); } catch (Exception e) { e.printStackTrace(); } } static private String escape(String s) { // Make the stringBuffer a little larger than strictly // necessary in case we need to insert any additional // characters. (If our size estimate is wrong, the // StringBuffer will automatically grow as needed). StringBuffer result = new StringBuffer(s.length()+20); for( int i=0; i<s.length(); i++) if( s.charAt(i) == '"' ) result.append("\\\""); else result.append(s.charAt(i)); return result.toString(); } /** * Take a java String and quote it to form a legal FIPA ACL string. * Add quotation marks to the beginning/end and escape any * quotation marks inside the string. */ static private String quotedString(String str) { return "\"" + escape(str) + "\""; } /** * If a user-defined parameter contain a blank char inside, then it is skipped for FIPA-compatibility * @return a String encoded message * @see ACLMessage#toString() **/ static String toString(ACLMessage msg) { StringBuffer str = new StringBuffer("("); str.append(msg.getPerformative(msg.getPerformative()) + "\n"); AID sender = msg.getSender(); if (sender != null) str.append(SENDER + " "+ sender.toString()+"\n"); Iterator it = msg.getAllReceiver(); if (it.hasNext()) { str.append(RECEIVER + " (set "); while(it.hasNext()) str.append(it.next().toString()+" "); str.append(")\n"); } it = msg.getAllReplyTo(); if (it.hasNext()) { str.append(REPLY_TO + " (set \n"); while(it.hasNext()) str.append(it.next().toString()+" "); str.append(")\n"); } if (msg.hasByteSequenceContent()) { str.append(":X-"+ BASE64ENCODING_KEY + " " + BASE64ENCODING_VALUE + "\n"); try { String b64 = new String(Base64.encodeBase64(msg.getByteSequenceContent()), "US-ASCII"); str.append(CONTENT + " \"" + b64 + "\" \n"); } catch(java.lang.NoClassDefFoundError jlncdfe) { System.err.println("\n\t===== E R R O R !!! =======\n"); System.err.println("Missing support for Base64 conversions"); System.err.println("Please refer to the documentation for details."); System.err.println("=============================================\n\n"); System.err.println(""); try { Thread.currentThread().sleep(3000); } catch(InterruptedException ie) { } } catch(UnsupportedEncodingException e2) { System.err.println("\n\t===== E R R O R !!! =======\n"); System.err.println("Missing support for US-ASCII encoding for Base64 conversions"); System.err.println("Please refer to the documentation for details."); System.err.println("=============================================\n\n"); System.err.println(""); try { Thread.currentThread().sleep(3000); } catch(InterruptedException ie) { } } } else { String content = msg.getContent(); if (content != null) { content = content.trim(); if (content.length() > 0) str.append(CONTENT + " \"" + escape(content) + "\" \n"); } } appendACLExpression(str, REPLY_WITH, msg.getReplyWith()); appendACLExpression(str, IN_REPLY_TO, msg.getInReplyTo()); appendACLExpression(str, ENCODING, msg.getEncoding()); appendACLExpression(str, LANGUAGE, msg.getLanguage()); appendACLExpression(str, ONTOLOGY, msg.getOntology()); Date d = msg.getReplyByDate(); if (d != null) str.append(REPLY_BY + " " + ISO8601.toString(d) + "\n"); String tmp = msg.getProtocol(); if (tmp != null) { tmp = tmp.trim(); if (tmp.length() > 0) str.append(PROTOCOL + " " + tmp + "\n"); } appendACLExpression(str, CONVERSATION_ID, msg.getConversationId()); Properties userDefProps = msg.getAllUserDefinedParameters(); if (userDefProps != null) { Enumeration e = userDefProps.propertyNames(); while (e.hasMoreElements()) { String key = ((String)e.nextElement()); if (key.indexOf(' ') == -1) { if ( (!key.startsWith("X-")) && (!key.startsWith("x-")) ) appendACLExpression(str, ":X-"+key, userDefProps.getProperty(key)); else appendACLExpression(str, ":"+key, userDefProps.getProperty(key)); } else System.err.println("WARNING: The slotName of user-defined parameters cannot contain blanks inside. Therefore "+key+" is not being encoded"); } } str.append(")"); return str.toString(); } /** * If the content of the message is a byteSequence, then this * method encodes the content in Base64 and automatically sets the value * of the encoding slot. * @see ACLCodec#encode(ACLMessage msg) */ public byte[] encode(ACLMessage msg, String charset) { try { return toString(msg).getBytes(charset); } catch(IOException ioe) { ioe.printStackTrace(); return new byte[0]; } } /** * @see ACLCodec#decode(byte[] data) */ public ACLMessage decode(byte[] data, String charset) throws ACLCodec.CodecException { try { ACLMessage msg = ACLParser.create().parse(new InputStreamReader(new ByteArrayInputStream(data),charset)); checkBase64Encoding(msg); return msg; } catch (jade.lang.acl.TokenMgrError e1) { throw new ACLCodec.CodecException(getName()+" ACLMessage decoding token exception",e1); } catch (Exception e2) { throw new ACLCodec.CodecException(getName()+" ACLMessage decoding exception",e2); } } /** * @return the name of this encoding according to the FIPA specifications */ public String getName() { return NAME; } /** * append to the passed StringBuffer the slot name and value separated * by a blank char and followed by a newline. * If the value contains a blank, then it is quoted. * if the value is null or its length is zero, the method does nothing. **/ static public void appendACLExpression(StringBuffer str, String slotName, String slotValue) { if ((slotValue != null) && (slotValue.length() > 0) ) { if (!isAWord(slotValue)) { try { // if the value is a number, then leave as it is Double.valueOf(slotValue); } catch (NumberFormatException e) { // if the program is here, then slotValue is neither a // word or a number. Therefore it must be quoted slotValue = quotedString(slotValue); } } str.append(slotName + " " + slotValue + " "); } } private static final String illegalFirstChar = "#0123456789-"; /** * Test if the given string is a legal word using the FIPA ACL spec. * In addition to FIPA's restrictions, place the additional restriction * that a Word can not contain a '\"', that would confuse the parser at * the other end. */ static private boolean isAWord( String s) { // This should permit strings of length 0 to be encoded. if( s==null || s.length()==0 ) return false; // words must have at least one character if ( illegalFirstChar.indexOf(s.charAt(0)) >= 0 ) return false; for( int i=0; i< s.length(); i++) { char c = s.charAt(i); if( c == '"' || c == '(' || c == ')' || c <= 0x20 ) return false; } return true; } }
36.136364
149
0.641579
6d0ef5ff7f38c7ddb4d2b486d9f379369f82f95a
1,791
package com.frontbackend.springboot.controller; import java.io.IOException; import java.nio.file.Paths; import org.springframework.beans.factory.annotation.Value; import org.springframework.core.io.Resource; import org.springframework.core.io.UrlResource; import org.springframework.http.HttpHeaders; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.CrossOrigin; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestController; @CrossOrigin(origins = "http://localhost:4200") @RestController @RequestMapping("api/pdf") public class PDFController { @Value("${pdf.path}") private String pdfFilesPath; @GetMapping("{filename:.+}") @ResponseBody public ResponseEntity<Resource> downloadFile(@PathVariable String filename) throws IOException { Resource resource = new UrlResource(Paths.get(pdfFilesPath) .resolve(filename) .toUri()); if (resource.exists() || resource.isReadable()) { String contentDisposition = String.format("inline; filename=\"%s\"", resource.getFile() .getName()); return ResponseEntity.ok() .header(HttpHeaders.CONTENT_DISPOSITION, contentDisposition) .body(resource); } return ResponseEntity.notFound() .build(); } }
39.8
101
0.646566
9342076ab33f748ee219631111290bf3b1f4c5d8
1,860
package com.leeup.javase.day18.test; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.TreeSet; /** * * @author 李闯 * */ public class Test3 { public static void main(String[] args) { String[] num = {"3","4","5","6","7","8","9","10","J","Q","K","A","2"}; String[] color = {"方片","梅花","红桃","黑桃"}; HashMap<Integer, String> hm = new HashMap<>(); //存储索引和扑克牌 ArrayList<Integer> list = new ArrayList<>(); //存储索引 int index = 0; //索引值 //拼接扑克牌并将索引和扑克牌存储在hashMap集合中 for(String s1 : num) { //获取数字 for(String s2 : color) { //获取颜色 hm.put(index, s2.concat(s1)); //将颜色和数字拼接 list.add(index); //将索引0-51添加到list集合 index++; //索引增加,遍历索引的牌 } } //将小王添加到双列集合中 hm.put(index,"小王"); list.add(index); //将52索引添加到集合中 index++; hm.put(index, "大王"); list.add(index); //将53索引添加到集合中 //洗牌 Collections.shuffle(list); //发牌 TreeSet<Integer> gaojin = new TreeSet<>(); TreeSet<Integer> longwu = new TreeSet<>(); TreeSet<Integer> me = new TreeSet<>(); TreeSet<Integer> dipai = new TreeSet<>(); for(int i = 0; i<list.size(); i++) { if (i>=list.size()-3) { dipai.add(list.get(i)); //将三张底牌存储在底牌集合中 }else if (i%3==0) { gaojin.add(list.get(i)); }else if (i%3==1) { longwu.add(list.get(i)); }else{ me.add(list.get(i)); } } //看牌 lookPoker(hm, gaojin, "高进"); lookPoker(hm, longwu, "龙武"); lookPoker(hm, me, "我"); lookPoker(hm, dipai, "底牌"); } /** * 看牌 * 1. 返回值类型void * 2. 参数列表:HashMap 放的是键和值的关系,TreeSet 存的所有索引,String name 到底是谁的牌 */ public static void lookPoker (HashMap<Integer, String> hm,TreeSet<Integer> ts,String name) { System.out.println(name+"的牌是:"); for (Integer i : ts) { //拿到了健集合的所有的键,i代表每个键 System.out.print(hm.get(i)+" ");//根据键获取值 } System.out.println(); } }
24.155844
72
0.58871
9cd770bf49e92226df33861b94eb45bc7e94d7a2
461
/* * Query.java * * Created on August 10, 2004, 2:04 PM */ package com.cyc.baseclient.util.query; import java.util.Set; /** * @version $Id: QuerySpecification.java 150536 2014-04-15 20:54:59Z nwinant $ * @author mreimers */ public interface QuerySpecification { public String getGloss(); public Object getQuestion(); public Set getConstraints(); public Set getFilteredConstraints(Class constraintType); public Object clone(); }
17.730769
78
0.700651
d25e64227ac3d26c5e2abd96c5d885645790ac67
26,278
/* * The MIT License (MIT) * Copyright (c) 2014 longkai * The software shall be used for good, not evil. */ package org.catnut.fragment; import android.app.Activity; import android.app.Fragment; import android.content.AsyncQueryHandler; import android.content.Intent; import android.content.SharedPreferences; import android.database.Cursor; import android.graphics.Bitmap; import android.graphics.Typeface; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.provider.BaseColumns; import android.support.v4.view.PagerAdapter; import android.support.v4.view.ViewPager; import android.text.Html; import android.text.TextUtils; import android.text.format.DateUtils; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.view.ViewStub; import android.view.ViewTreeObserver; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import com.android.volley.Response; import com.android.volley.VolleyError; import com.squareup.picasso.Picasso; import com.squareup.picasso.Target; import com.viewpagerindicator.LinePageIndicator; import org.catnut.R; import org.catnut.api.FriendshipsAPI; import org.catnut.api.UserAPI; import org.catnut.core.CatnutApp; import org.catnut.core.CatnutProvider; import org.catnut.core.CatnutRequest; import org.catnut.metadata.Status; import org.catnut.metadata.User; import org.catnut.processor.UserProcessor; import org.catnut.support.QuickReturnScrollView; import org.catnut.support.TweetImageSpan; import org.catnut.support.TweetTextView; import org.catnut.ui.ProfileActivity; import org.catnut.ui.SingleFragmentActivity; import org.catnut.ui.TweetActivity; import org.catnut.util.CatnutUtils; import org.catnut.util.Constants; import org.catnut.util.DateTime; import org.json.JSONObject; /** * 用户信息界面 * * @author longkai */ public class ProfileFragment extends Fragment implements SharedPreferences.OnSharedPreferenceChangeListener, QuickReturnScrollView.Callbacks { private static final String[] PROJECTION = new String[]{ BaseColumns._ID, User.remark, User.verified, User.screen_name, User.profile_url, User.location, User.description, User.avatar_large, User.avatar_hd, User.cover_image, User.favourites_count, User.friends_count, User.statuses_count, User.followers_count, User.following, User.verified_reason }; private CatnutApp mApp; private Menu mMenu; private ScrollSettleHandler mScrollSettleHandler = new ScrollSettleHandler(); private QuickReturnScrollView mQuickReturnScrollView; private View mQuickReturnView; private View mQuickReturnPlaceHolderView; private int mMinRawY = 0; private int mState = STATE_ON_SCREEN; private int mQuickReturnHeight; private int mMaxScrollY; private long mUid; private String mScreenName; private String mCoverUrl; private String mAvatarUrl; private String mAvatarHdUrl; private boolean mVerified; private boolean mFollowing; // 哥是否关注他 private String mRemark; private String mDescription; private String mLocation; private String mProfileUrl; private String mVerifiedReason; private ViewPager mViewPager; private LinePageIndicator mIndicator; private View mPlaceHolder; private View mTweetsCount; private View mFollowingsCount; private View mFollowersCount; private View mTweetLayout; private View mRetweetLayout; private Typeface mTypeface; private float mLineSpacing = 1.0f; private View.OnClickListener tweetsOnclickListener = new View.OnClickListener() { @Override public void onClick(View v) { ProfileActivity activity = (ProfileActivity) getActivity(); activity.flipCard(UserTimelineFragment.getFragment(mUid, mScreenName), null, true); } }; private View.OnClickListener followersOnclickListener = new View.OnClickListener() { @Override public void onClick(View v) { ProfileActivity activity = (ProfileActivity) getActivity(); activity.flipCard(TransientUsersFragment.getFragment(mScreenName, false), null, true); } }; private View.OnClickListener followingsOnClickListener = new View.OnClickListener() { @Override public void onClick(View v) { ProfileActivity activity = (ProfileActivity) getActivity(); activity.flipCard(TransientUsersFragment.getFragment(mScreenName, true), null, true); } }; private Target profileTarget = new Target() { @Override public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) { try { mPlaceHolder.setBackground(new BitmapDrawable(getResources(), bitmap)); } catch (Exception e) { // no-op } } @Override public void onBitmapFailed(Drawable errorDrawable) { try { mPlaceHolder.setBackground(errorDrawable); } catch (Exception e) { // no-op } } @Override public void onPrepareLoad(Drawable placeHolderDrawable) { mPlaceHolder.setBackground(placeHolderDrawable); } }; public static ProfileFragment getFragment(long uid, String screenName) { Bundle args = new Bundle(); args.putLong(Constants.ID, uid); args.putString(User.screen_name, screenName); ProfileFragment fragment = new ProfileFragment(); fragment.setArguments(args); return fragment; } @Override public void onAttach(Activity activity) { super.onAttach(activity); mApp = CatnutApp.getTingtingApp(); Bundle args = getArguments(); mUid = args.getLong(Constants.ID); mScreenName = args.getString(User.screen_name); } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setHasOptionsMenu(true); SharedPreferences preferences = mApp.getPreferences(); mTypeface = CatnutUtils.getTypeface( preferences, getString(R.string.pref_customize_tweet_font), getString(R.string.default_typeface) ); mLineSpacing = CatnutUtils.getLineSpacing(preferences, getString(R.string.pref_line_spacing), getString(R.string.default_line_spacing)); } @Override public void onStart() { super.onStart(); getActivity().getActionBar().setTitle(mScreenName); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.profile, container, false); mQuickReturnScrollView = (QuickReturnScrollView) view; mQuickReturnScrollView.setCallbacks(this); mViewPager = (ViewPager) view.findViewById(R.id.pager); mIndicator = (LinePageIndicator) view.findViewById(R.id.indicator); mPlaceHolder = view.findViewById(R.id.place_holder); mTweetsCount = view.findViewById(R.id.tweets_count); mFollowingsCount = view.findViewById(R.id.following_count); mFollowersCount = view.findViewById(R.id.followers_count); mTweetLayout = view.findViewById(R.id.tweet_layout); view.findViewById(R.id.action_tweets).setOnClickListener(tweetsOnclickListener); view.findViewById(R.id.action_followers).setOnClickListener(followersOnclickListener); view.findViewById(R.id.action_followings).setOnClickListener(followingsOnClickListener); mQuickReturnPlaceHolderView = view.findViewById(R.id.quick_return_place_holder); mQuickReturnView = view.findViewById(R.id.place_holder); mQuickReturnScrollView.getViewTreeObserver() .addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() { @Override public void onGlobalLayout() { onScrollChanged(mQuickReturnScrollView.getScrollY()); mMaxScrollY = mQuickReturnScrollView.computeVerticalScrollRange() - mQuickReturnScrollView.getHeight(); mQuickReturnHeight = mQuickReturnView.getHeight(); } }); return view; } @Override public void onViewCreated(View view, Bundle savedInstanceState) { // 从本地抓取数据*_*,有一个时间先后的问题,所以把view的创建放到这个地方来了 String query = CatnutUtils.buildQuery(PROJECTION, User.screen_name + "=" + CatnutUtils.quote(mScreenName), User.TABLE, null, null, null); new AsyncQueryHandler(getActivity().getContentResolver()) { @Override protected void onQueryComplete(int token, Object cookie, Cursor cursor) { if (cursor.moveToNext()) { injectProfile(cursor); } else { // fall back to load from network... mApp.getRequestQueue().add(new CatnutRequest( getActivity(), UserAPI.profile(mScreenName), new UserProcessor.UserProfileProcessor(), new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject response) { injectProfile(response); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { Toast.makeText(getActivity(), getString(R.string.user_not_found), Toast.LENGTH_SHORT).show(); } } )); } cursor.close(); } }.startQuery(0, null, CatnutProvider.parse(User.MULTIPLE), null, query, null, null); // 抓最新的一条微博 if (mApp.getPreferences().getBoolean(getString(R.string.pref_show_latest_tweet), true)) { String queryLatestTweet = CatnutUtils.buildQuery( new String[]{ Status.columnText, // Status.thumbnail_pic, Status.bmiddle_pic, Status.comments_count, Status.reposts_count, Status.retweeted_status, Status.attitudes_count, Status.source, Status.created_at, }, new StringBuilder("uid=(select _id from ") .append(User.TABLE).append(" where ").append(User.screen_name) .append("=").append(CatnutUtils.quote(mScreenName)).append(")") .append(" and ").append(Status.TYPE) .append(" in(").append(Status.HOME).append(",").append(Status.RETWEET) .append(",").append(Status.OTHERS).append(")") .toString(), Status.TABLE, null, BaseColumns._ID + " desc", "1" ); new AsyncQueryHandler(getActivity().getContentResolver()) { @Override protected void onQueryComplete(int token, Object cookie, Cursor cursor) { if (cursor.moveToNext()) { mTweetLayout.setOnClickListener(tweetsOnclickListener); ViewStub viewStub = (ViewStub) mTweetLayout.findViewById(R.id.latest_tweet); View tweet = viewStub.inflate(); mRetweetLayout = tweet.findViewById(R.id.retweet); tweet.findViewById(R.id.timeline).setVisibility(View.GONE); tweet.findViewById(R.id.verified).setVisibility(View.GONE); tweet.findViewById(R.id.tweet_overflow).setVisibility(View.GONE); CatnutUtils.setText(tweet, R.id.nick, getString(R.string.latest_statues)) .setTextColor(getResources().getColor(R.color.actionbar_background)); String tweetText = cursor.getString(cursor.getColumnIndex(Status.columnText)); TweetImageSpan tweetImageSpan = new TweetImageSpan(getActivity()); TweetTextView text = (TweetTextView) CatnutUtils.setText(tweet, R.id.text, tweetImageSpan.getImageSpan(tweetText)); CatnutUtils.vividTweet(text, null); CatnutUtils.setTypeface(text, mTypeface); text.setLineSpacing(0, mLineSpacing); String thumbsUrl = cursor.getString(cursor.getColumnIndex(Status.bmiddle_pic)); if (!TextUtils.isEmpty(thumbsUrl)) { View thumbs = tweet.findViewById(R.id.thumbs); Picasso.with(getActivity()) .load(thumbsUrl) .placeholder(R.drawable.error) .error(R.drawable.error) .into((ImageView) thumbs); thumbs.setVisibility(View.VISIBLE); } int replyCount = cursor.getInt(cursor.getColumnIndex(Status.comments_count)); CatnutUtils.setText(tweet, R.id.reply_count, CatnutUtils.approximate(replyCount)); int retweetCount = cursor.getInt(cursor.getColumnIndex(Status.reposts_count)); CatnutUtils.setText(tweet, R.id.reteet_count, CatnutUtils.approximate(retweetCount)); int favoriteCount = cursor.getInt(cursor.getColumnIndex(Status.attitudes_count)); CatnutUtils.setText(tweet, R.id.like_count, CatnutUtils.approximate(favoriteCount)); String source = cursor.getString(cursor.getColumnIndex(Status.source)); CatnutUtils.setText(tweet, R.id.source, Html.fromHtml(source).toString()); String create_at = cursor.getString(cursor.getColumnIndex(Status.created_at)); CatnutUtils.setText(tweet, R.id.create_at, DateUtils.getRelativeTimeSpanString(DateTime.getTimeMills(create_at))) .setVisibility(View.VISIBLE); // retweet final String jsonString = cursor.getString(cursor.getColumnIndex(Status.retweeted_status)); try { JSONObject jsonObject = new JSONObject(jsonString); TweetTextView retweet = (TweetTextView) mRetweetLayout.findViewById(R.id.retweet_text); retweet.setText(jsonObject.optString(Status.text)); CatnutUtils.vividTweet(retweet, tweetImageSpan); CatnutUtils.setTypeface(retweet, mTypeface); retweet.setLineSpacing(0, mLineSpacing); long mills = DateTime.getTimeMills(jsonObject.optString(Status.created_at)); TextView tv = (TextView) mRetweetLayout.findViewById(R.id.retweet_create_at); tv.setText(DateUtils.getRelativeTimeSpanString(mills)); TextView retweetUserScreenName = (TextView) mRetweetLayout.findViewById(R.id.retweet_nick); JSONObject user = jsonObject.optJSONObject(User.SINGLE); if (user == null) { retweetUserScreenName.setText(getString(R.string.unknown_user)); } else { retweetUserScreenName.setText(user.optString(User.screen_name)); mRetweetLayout.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(getActivity(), TweetActivity.class); intent.putExtra(Constants.JSON, jsonString); startActivity(intent); } }); } } catch (Exception e) { mRetweetLayout.setVisibility(View.GONE); } } cursor.close(); } }.startQuery(0, null, CatnutProvider.parse(Status.MULTIPLE), null, queryLatestTweet, null, null); } } private void injectProfile(Cursor cursor) { // 暂存元数据 mUid = cursor.getLong(cursor.getColumnIndex(BaseColumns._ID)); mAvatarUrl = cursor.getString(cursor.getColumnIndex(User.avatar_large)); mAvatarHdUrl = cursor.getString(cursor.getColumnIndex(User.avatar_hd)); mVerified = CatnutUtils.getBoolean(cursor, User.verified); mRemark = cursor.getString(cursor.getColumnIndex(User.remark)); mDescription = cursor.getString(cursor.getColumnIndex(User.description)); mLocation = cursor.getString(cursor.getColumnIndex(User.location)); mProfileUrl = cursor.getString(cursor.getColumnIndex(User.profile_url)); mCoverUrl = cursor.getString(cursor.getColumnIndex(User.cover_image)); mVerifiedReason = cursor.getString(cursor.getColumnIndex(User.verified_reason)); // +关注 mFollowing = CatnutUtils.getBoolean(cursor, User.following); // menu buildMenu(); // load封面图片 if (!TextUtils.isEmpty(mCoverUrl)) { Picasso.with(getActivity()) .load(mCoverUrl) .placeholder(R.drawable.default_fantasy) .error(R.drawable.default_fantasy) .into(profileTarget); } else { mPlaceHolder.setBackground(getResources().getDrawable(R.drawable.default_fantasy)); } // 我的微博 mTweetsCount.setOnClickListener(tweetsOnclickListener); CatnutUtils.setText(mTweetsCount, android.R.id.text1, cursor.getString(cursor.getColumnIndex(User.statuses_count))); CatnutUtils.setText(mTweetsCount, android.R.id.text2, getString(R.string.tweets)); // 关注我的 mFollowersCount.setOnClickListener(followersOnclickListener); CatnutUtils.setText(mFollowersCount, android.R.id.text1, cursor.getString(cursor.getColumnIndex(User.followers_count))); CatnutUtils.setText(mFollowersCount, android.R.id.text2, getString(R.string.followers)); // 我关注的 mFollowingsCount.setOnClickListener(followingsOnClickListener); CatnutUtils.setText(mFollowingsCount, android.R.id.text1, cursor.getString(cursor.getColumnIndex(User.friends_count))); CatnutUtils.setText(mFollowingsCount, android.R.id.text2, getString(R.string.followings)); // pager adapter, not fragment pager any more mViewPager.setAdapter(coverPager); mIndicator.setViewPager(mViewPager); } private void injectProfile(JSONObject json) { // 暂存元数据 mUid = json.optLong(Constants.ID); mAvatarUrl = json.optString(User.avatar_large); mAvatarHdUrl = json.optString(User.avatar_hd); mVerified = json.optBoolean(User.verified); mRemark = json.optString(User.remark); mDescription = json.optString(User.description); mLocation = json.optString(User.location); mProfileUrl = json.optString(User.profile_url); mCoverUrl = json.optString(User.cover_image); mVerifiedReason = json.optString(User.verified_reason); // +关注 mFollowing = json.optBoolean(User.following); // menu buildMenu(); // load封面图片 if (!TextUtils.isEmpty(mCoverUrl)) { Picasso.with(getActivity()) .load(mCoverUrl) .placeholder(R.drawable.default_fantasy) .error(R.drawable.default_fantasy) .into(profileTarget); } else { mPlaceHolder.setBackground(getResources().getDrawable(R.drawable.default_fantasy)); } // 我的微博 mTweetsCount.setOnClickListener(tweetsOnclickListener); CatnutUtils.setText(mTweetsCount, android.R.id.text1, json.optString(User.statuses_count)); CatnutUtils.setText(mTweetsCount, android.R.id.text2, getString(R.string.tweets)); // 关注我的 mFollowersCount.setOnClickListener(followersOnclickListener); CatnutUtils.setText(mFollowersCount, android.R.id.text1, json.optString(User.followers_count)); CatnutUtils.setText(mFollowersCount, android.R.id.text2, getString(R.string.followers)); // 我关注的 mFollowingsCount.setOnClickListener(followingsOnClickListener); CatnutUtils.setText(mFollowingsCount, android.R.id.text1, json.optString(User.friends_count)); CatnutUtils.setText(mFollowingsCount, android.R.id.text2, getString(R.string.followings)); // pager adapter, not fragment pager any more mViewPager.setAdapter(coverPager); mIndicator.setViewPager(mViewPager); } @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { mMenu = menu; buildMenu(); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.action_follow: toggleFollow(true); break; case R.id.action_unfollow: toggleFollow(false); break; default: break; } return super.onOptionsItemSelected(item); } // 创建menu,只创建一次哦 private void buildMenu() { if (mMenu != null && mAvatarUrl != null) { // 确保数据已经从sqlite载入 // 只有当两者均为空时才创建menu if (mMenu.findItem(R.id.action_follow) == null && mMenu.findItem(R.id.action_unfollow) == null) { if (!mFollowing) { mMenu.add(Menu.NONE, R.id.action_follow, Menu.NONE, R.string.follow) .setIcon(R.drawable.ic_title_follow) .setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM); } else { mMenu.add(Menu.NONE, R.id.action_unfollow, Menu.NONE, R.string.unfollow) .setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER); } } } } private void toggleFollow(final boolean follow) { mApp.getRequestQueue().add(new CatnutRequest( getActivity(), follow ? FriendshipsAPI.create(mScreenName, null) : FriendshipsAPI.destroy(mScreenName), new UserProcessor.UserProfileProcessor(), new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject response) { Toast.makeText(getActivity(), getString(follow ? R.string.follow_success : R.string.unfollow_success), Toast.LENGTH_SHORT).show(); if (follow) { mMenu.removeItem(R.id.action_follow); mMenu.add(Menu.NONE, R.id.action_follow, Menu.NONE, R.string.unfollow) .setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER); } else { mMenu.removeItem(R.id.action_unfollow); mMenu.add(Menu.NONE, R.id.action_follow, Menu.NONE, R.string.follow) .setIcon(R.drawable.ic_title_follow) .setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM); } mFollowing = !mFollowing; // 更新本地数据库 final String str = follow ? "+1" : "-1"; new Thread(new Runnable() { @Override public void run() { long uid = mApp.getAccessToken().uid; String update = "update " + User.TABLE + " SET " + User.friends_count + "=" + User.friends_count + str + " WHERE " + BaseColumns._ID + "=" + uid; getActivity().getContentResolver().update( CatnutProvider.parse(User.MULTIPLE, uid), null, update, null ); } }).start(); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { Toast.makeText(getActivity(), error.getLocalizedMessage(), Toast.LENGTH_SHORT).show(); } } )); } private final PagerAdapter coverPager = new PagerAdapter() { private LayoutInflater mLayoutInflater; @Override public int getCount() { return 2; } @Override public boolean isViewFromObject(View view, Object object) { return view == object; } @Override public void destroyItem(ViewGroup container, int position, Object object) { container.removeView((View) object); } @Override public Object instantiateItem(ViewGroup container, int position) { if (mLayoutInflater == null) { mLayoutInflater = LayoutInflater.from(getActivity()); } switch (position) { case 0: View frontPage = mLayoutInflater.inflate(R.layout.profile_cover, container, false); ImageView avatar = (ImageView) frontPage.findViewById(R.id.avatar); Picasso.with(getActivity()) .load(mAvatarUrl) .placeholder(R.drawable.error) .error(R.drawable.error) .into(avatar); avatar.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = SingleFragmentActivity.getIntent(getActivity(), SingleFragmentActivity.PHOTO_VIEWER); intent.putExtra(Constants.PIC, mAvatarHdUrl); startActivity(intent); } }); TextView screenName = (TextView) frontPage.findViewById(R.id.screen_name); screenName.setText("@" + mScreenName); TextView remark = (TextView) frontPage.findViewById(R.id.remark); // 如果说没有备注的话那就和微博id一样 remark.setText(TextUtils.isEmpty(mRemark) ? mScreenName : mRemark); if (mVerified) { frontPage.findViewById(R.id.verified).setVisibility(View.VISIBLE); } container.addView(frontPage); return frontPage; case 1: View introPage = mLayoutInflater.inflate(R.layout.profile_intro, container, false); CatnutUtils.setText(introPage, R.id.description, TextUtils.isEmpty(mDescription) ? getString(R.string.no_description) : mDescription); CatnutUtils.setText(introPage, R.id.location, mLocation); if (!TextUtils.isEmpty(mVerifiedReason)) { CatnutUtils.setText(introPage, R.id.verified_reason, mVerifiedReason) .setVisibility(View.VISIBLE); } CatnutUtils.setText(introPage, R.id.profile_url, Constants.WEIBO_DOMAIN + mProfileUrl); container.addView(introPage); return introPage; default: return null; } } }; @Override public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) { if (key.equals(getString(R.string.pref_show_latest_tweet))) { boolean show = mApp.getPreferences().getBoolean(key, true); // 如果已经显示那么隐藏,反之,如果根本就没有初始化数据,那么不会再去抓数据 if (show) { mTweetLayout.setVisibility(View.VISIBLE); } else { mTweetLayout.setVisibility(View.GONE); } } } @Override public void onScrollChanged(int scrollY) { scrollY = Math.min(mMaxScrollY, scrollY); mScrollSettleHandler.onScroll(scrollY); int rawY = mQuickReturnPlaceHolderView.getTop() - scrollY; int translationY = 0; switch (mState) { case STATE_OFF_SCREEN: if (rawY <= mMinRawY) { mMinRawY = rawY; } else { mState = STATE_RETURNING; } translationY = rawY; break; case STATE_ON_SCREEN: if (rawY < -mQuickReturnHeight) { mState = STATE_OFF_SCREEN; mMinRawY = rawY; } translationY = rawY; break; case STATE_RETURNING: translationY = (rawY - mMinRawY) - mQuickReturnHeight; if (translationY > 0) { translationY = 0; mMinRawY = rawY - mQuickReturnHeight; } if (rawY > 0) { mState = STATE_ON_SCREEN; translationY = rawY; } if (translationY < -mQuickReturnHeight) { mState = STATE_OFF_SCREEN; mMinRawY = rawY; } break; } mQuickReturnView.animate().cancel(); mQuickReturnView.setTranslationY(translationY + scrollY); } @Override public void onDownMotionEvent() { mScrollSettleHandler.setSettleEnabled(false); } @Override public void onUpOrCancelMotionEvent() { mScrollSettleHandler.setSettleEnabled(true); mScrollSettleHandler.onScroll(mQuickReturnScrollView.getScrollY()); } private class ScrollSettleHandler extends Handler { private static final int SETTLE_DELAY_MILLIS = 100; private int mSettledScrollY = Integer.MIN_VALUE; private boolean mSettleEnabled; public void onScroll(int scrollY) { if (mSettledScrollY != scrollY) { // Clear any pending messages and post delayed removeMessages(0); sendEmptyMessageDelayed(0, SETTLE_DELAY_MILLIS); mSettledScrollY = scrollY; } } public void setSettleEnabled(boolean settleEnabled) { mSettleEnabled = settleEnabled; } @Override public void handleMessage(Message msg) { // Handle the scroll settling. if (STATE_RETURNING == mState && mSettleEnabled) { int mDestTranslationY; if (mSettledScrollY - mQuickReturnView.getTranslationY() > mQuickReturnHeight / 2) { mState = STATE_OFF_SCREEN; mDestTranslationY = Math.max( mSettledScrollY - mQuickReturnHeight, mQuickReturnPlaceHolderView.getTop()); } else { mDestTranslationY = mSettledScrollY; } mMinRawY = mQuickReturnPlaceHolderView.getTop() - mQuickReturnHeight - mDestTranslationY; mQuickReturnView.animate().translationY(mDestTranslationY); } mSettledScrollY = Integer.MIN_VALUE; // reset } } }
35.225201
119
0.730687
dd76b9a1c89c920bca945848e9c56ca524e13d13
25,546
/* * Copyright (c) 2013, 2018, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package vm.runtime.defmeth.shared; import jdk.internal.org.objectweb.asm.Handle; import jdk.internal.org.objectweb.asm.Type; import nsk.share.TestFailure; import nsk.share.test.TestUtils; import jdk.internal.org.objectweb.asm.Label; import jdk.internal.org.objectweb.asm.MethodVisitor; import static jdk.internal.org.objectweb.asm.Opcodes.*; import jdk.internal.org.objectweb.asm.ClassWriter; import static jdk.internal.org.objectweb.asm.ClassWriter.*; import vm.runtime.defmeth.shared.data.*; import vm.runtime.defmeth.shared.data.method.*; import vm.runtime.defmeth.shared.data.method.body.*; import vm.runtime.defmeth.shared.data.method.param.*; import vm.runtime.defmeth.shared.data.method.result.*; import java.lang.invoke.CallSite; import java.lang.invoke.MethodHandles; import java.lang.invoke.MethodType; import static vm.runtime.defmeth.shared.ExecutionMode.*; /** * Constructs class file from {@code Clazz} instance. */ public class ClassFileGenerator implements Visitor { private final ExecutionMode invocationType; /** Default major version for generated class files * Used when a class doesn't specify what major version should be specified. */ private final int defaultMajorVer; /** Default access flags for generated class files * Used when a class doesn't specify it's own access flags. */ private final int defaultClassAccFlags; /** Represent current state of class file traversal. * Used to avoid passing instances around. */ private ClassWriter cw; private MethodVisitor mv; private Tester t; private String className; public ClassFileGenerator() { this.defaultMajorVer = 52; this.defaultClassAccFlags = ACC_PUBLIC; this.invocationType = ExecutionMode.DIRECT; } public ClassFileGenerator(int ver, int acc, ExecutionMode invocationType) { this.defaultMajorVer = ver; this.defaultClassAccFlags = acc; this.invocationType = invocationType; } /** * Produce constructed class file as a {@code byte[]}. * * @return */ public byte[] getClassFile() { return cw.toByteArray(); } /** * Push integer constant on stack. * * Choose most suitable bytecode to represent integer constant on stack. * * @param value */ private void pushIntConst(int value) { switch (value) { case 0: mv.visitInsn(ICONST_0); break; case 1: mv.visitInsn(ICONST_1); break; case 2: mv.visitInsn(ICONST_2); break; case 3: mv.visitInsn(ICONST_3); break; case 4: mv.visitInsn(ICONST_4); break; case 5: mv.visitInsn(ICONST_5); break; default: mv.visitIntInsn(BIPUSH, value); } } @Override public void visitClass(Clazz clz) { throw new IllegalStateException("More specific method should be called"); } @Override public void visitMethod(Method m) { throw new IllegalStateException("More specific method should be called"); } @Override public void visitConcreteClass(ConcreteClass clz) { cw = new ClassWriter(COMPUTE_FRAMES | COMPUTE_MAXS); int ver = clz.ver(); int flags = clz.flags(); className = clz.intlName(); cw.visit((ver != 0) ? ver : defaultMajorVer, ACC_SUPER | ((flags != -1) ? flags : defaultClassAccFlags), className, /* signature */ clz.sig(), clz.parent().intlName(), Util.asStrings(clz.interfaces())); { // Default constructor: <init>()V mv = cw.visitMethod(ACC_PUBLIC, "<init>", "()V", null, null); mv.visitCode(); mv.visitVarInsn(ALOAD, 0); mv.visitMethodInsn(INVOKESPECIAL, clz.parent().intlName(), "<init>", "()V", false); mv.visitInsn(RETURN); mv.visitMaxs(0, 0); mv.visitEnd(); mv = null; } for (Method m : clz.methods()) { m.visit(this); } cw.visitEnd(); } @Override public void visitInterface(Interface intf) { cw = new ClassWriter(COMPUTE_FRAMES | COMPUTE_MAXS); int ver = intf.ver(); int flags = intf.flags(); className = intf.intlName(); cw.visit( (ver != 0) ? ver : defaultMajorVer, ACC_ABSTRACT | ACC_INTERFACE | ((flags != -1) ? flags : defaultClassAccFlags), className, intf.sig(), "java/lang/Object", Util.asStrings(intf.parents())); for (Method m : intf.methods()) { m.visit(this); } cw.visitEnd(); } @Override public void visitConcreteMethod(ConcreteMethod m) { mv = cw.visitMethod( m.acc(), m.name(), m.desc(), m.sig(), m.getExceptions()); m.body().visit(this); mv = null; } @Override public void visitAbstractMethod(AbstractMethod m) { cw.visitMethod( ACC_ABSTRACT | m.acc(), m.name(), m.desc(), m.sig(), m.getExceptions()); } @Override public void visitDefaultMethod(DefaultMethod m) { mv = cw.visitMethod( m.acc(), m.name(), m.desc(), m.sig(), m.getExceptions()); m.body().visit(this); mv = null; } /* ====================================================================== */ @Override public void visitEmptyBody(EmptyBody aThis) { mv.visitCode(); mv.visitInsn(RETURN); mv.visitMaxs(0, 0); mv.visitEnd(); } @Override public void visitThrowExBody(ThrowExBody body) { mv.visitCode(); mv.visitTypeInsn(NEW, body.getExc().intlName()); mv.visitInsn(DUP); //mv.visitLdcInsn(body.getMsg()); //mv.visitMethodInsn(INVOKESPECIAL, body.getExc(), "<init>", "(Ljava/lang/String;)V", false); mv.visitMethodInsn(INVOKESPECIAL, body.getExc().intlName(), "<init>", "()V", false); mv.visitInsn(ATHROW); mv.visitMaxs(0, 0); mv.visitEnd(); } @Override public void visitReturnIntBody(ReturnIntBody body) { mv.visitCode(); //mv.visitIntInsn(BIPUSH, body.getValue()); pushIntConst(body.getValue()); mv.visitInsn(IRETURN); mv.visitMaxs(0, 0); mv.visitEnd(); } @Override public void visitReturnNullBody(ReturnNullBody body) { mv.visitCode(); mv.visitInsn(ACONST_NULL); mv.visitInsn(ARETURN); mv.visitMaxs(0, 0); mv.visitEnd(); } private void generateCall(CallMethod callSite, ExecutionMode invocationType) { switch (invocationType) { case DIRECT: generateDirectCall(callSite); break; case INVOKE_EXACT: generateMHInvokeCall(callSite, /* isExact = */ true); break; case INVOKE_GENERIC: generateMHInvokeCall(callSite, /* isExact = */ false); break; case INDY: generateIndyCall(callSite); break; default: throw new UnsupportedOperationException(invocationType.toString()); } } private void prepareParams(CallMethod callSite) { // Prepare receiver switch(callSite.invokeInsn()) { case SPECIAL: // Put receiver (this) on stack mv.visitVarInsn(ALOAD,0); break; case VIRTUAL: case INTERFACE: // Construct receiver if (callSite.receiverClass() != null) { String receiver = callSite.receiverClass().intlName(); // Construct new instance mv.visitTypeInsn(NEW, receiver); mv.visitInsn(DUP); mv.visitMethodInsn(INVOKESPECIAL, receiver, "<init>", "()V", false); } else { // Use "this" mv.visitVarInsn(ALOAD, 0); } mv.visitVarInsn(ASTORE, 1); mv.visitVarInsn(ALOAD, 1); break; case STATIC: break; } // Push parameters on stack for (Param p : callSite.params()) { p.visit(this); } } private static Handle convertToHandle(CallMethod callSite) { return new Handle( /* tag */ callSite.invokeInsn().tag(), /* owner */ callSite.staticClass().intlName(), /* name */ callSite.methodName(), /* desc */ callSite.methodDesc(), /* interface */ callSite.isInterface()); } private Handle generateBootstrapMethod(CallMethod callSite) { String bootstrapName = "bootstrapMethod"; MethodType bootstrapType = MethodType.methodType(CallSite.class, MethodHandles.Lookup.class, String.class, MethodType.class); MethodVisitor bmv = cw.visitMethod(ACC_PUBLIC | ACC_STATIC, bootstrapName, bootstrapType.toMethodDescriptorString(), null, null); bmv.visitCode(); Handle mh = convertToHandle(callSite); String constCallSite = "java/lang/invoke/ConstantCallSite"; bmv.visitTypeInsn(NEW, constCallSite); bmv.visitInsn(DUP); bmv.visitLdcInsn(mh); bmv.visitMethodInsn(INVOKESPECIAL, constCallSite, "<init>", "(Ljava/lang/invoke/MethodHandle;)V", false); bmv.visitInsn(ARETURN); bmv.visitMaxs(0,0); bmv.visitEnd(); return new Handle(H_INVOKESTATIC, className, bootstrapName, bootstrapType.toMethodDescriptorString()); } private static String mhCallSiteDesc(CallMethod callSite) { return (callSite.invokeInsn() != CallMethod.Invoke.STATIC) ? prependType(callSite.methodDesc(), callSite.staticClass().intlName()) : callSite.methodDesc(); // ignore receiver for static call } private void generateIndyCall(CallMethod callSite) { Handle bootstrap = generateBootstrapMethod(callSite); String callSiteDesc = mhCallSiteDesc(callSite); prepareParams(callSite); // Call method mv.visitInvokeDynamicInsn(callSite.methodName(), callSiteDesc, bootstrap); // Pop method result, if necessary if (callSite.popReturnValue()) { mv.visitInsn(POP); } } private void generateMHInvokeCall(CallMethod callSite, boolean isExact) { // Construct a method handle for a callee mv.visitLdcInsn(convertToHandle(callSite)); prepareParams(callSite); // Call method using MH + MethodHandle.invokeExact mv.visitMethodInsn( INVOKEVIRTUAL, "java/lang/invoke/MethodHandle", isExact ? "invokeExact" : "invoke", mhCallSiteDesc(callSite), false); // Pop method result, if necessary if (callSite.popReturnValue()) { mv.visitInsn(POP); } } // Prepend type as a first parameter private static String prependType(String desc, String type) { return desc.replaceFirst("\\(", "(L"+type+";"); } private void generateDirectCall(CallMethod callSite) { prepareParams(callSite); // Call method mv.visitMethodInsn( callSite.invokeInsn().opcode(), callSite.staticClass().intlName(), callSite.methodName(), callSite.methodDesc(), callSite.isInterface()); // Pop method result, if necessary if (callSite.popReturnValue()) { mv.visitInsn(POP); } } @Override public void visitCallMethod(CallMethod callSite) { mv.visitCode(); generateCall(callSite, ExecutionMode.DIRECT); String typeName = callSite.returnType(); if (!callSite.popReturnValue()) { // Call produces some value & it isn't popped out of the stack // Need to return it switch (typeName) { // primitive types case "I" : case "B" : case "C" : case "S" : case "Z" : mv.visitInsn(IRETURN); break; case "L": mv.visitInsn(LRETURN); break; case "F": mv.visitInsn(FRETURN); break; case "D": mv.visitInsn(DRETURN); break; case "V": mv.visitInsn(RETURN); break; default: // reference type if ((typeName.startsWith("L") && typeName.endsWith(";")) || typeName.startsWith("[")) { mv.visitInsn(ARETURN); } else { throw new IllegalStateException(typeName); } } } else { // Stack is empty. Plain return is enough. mv.visitInsn(RETURN); } mv.visitMaxs(0,0); mv.visitEnd(); } @Override public void visitReturnNewInstanceBody(ReturnNewInstanceBody body) { String className = body.getType().intlName(); mv.visitCode(); mv.visitTypeInsn(NEW, className); mv.visitInsn(DUP); mv.visitMethodInsn(INVOKESPECIAL, className, "<init>", "()V", false); mv.visitInsn(ARETURN); mv.visitMaxs(0,0); mv.visitEnd(); } /* ====================================================================== */ @Override public void visitTester(Tester tester) { // If: // cw = new ClassWriter(COMPUTE_FRAMES | COMPUTE_MAXS); // then: // java.lang.RuntimeException: java.lang.ClassNotFoundException: S // at jdk.internal.org.objectweb.asm.ClassWriter.getCommonSuperClass(ClassWriter.java:1588) // at jdk.internal.org.objectweb.asm.ClassWriter.getMergedType(ClassWriter.java:1559) // at jdk.internal.org.objectweb.asm.Frame.merge(Frame.java:1407) // at jdk.internal.org.objectweb.asm.Frame.merge(Frame.java:1308) // at jdk.internal.org.objectweb.asm.MethodWriter.visitMaxs(MethodWriter.java:1353) //mv.visitMaxs(t.getParams().length > 1 ? t.getParams().length+1 : 2, 2); cw = new ClassWriter(COMPUTE_MAXS); int testMajorVer = defaultMajorVer; // JSR 292 is available starting Java 7 (major version 51) if (invocationType == INVOKE_WITH_ARGS || invocationType == INVOKE_EXACT || invocationType == INVOKE_GENERIC) { testMajorVer = Math.max(defaultMajorVer, 51); } className = tester.intlName(); cw.visit(testMajorVer, ACC_PUBLIC | ACC_SUPER, className, null, "java/lang/Object", null); { // Test.<init> mv = cw.visitMethod(ACC_PUBLIC, "<init>", "()V", null, null); mv.visitCode(); mv.visitVarInsn(ALOAD, 0); mv.visitMethodInsn(INVOKESPECIAL, "java/lang/Object", "<init>", "()V", false); mv.visitInsn(RETURN); mv.visitMaxs(0, 0); mv.visitEnd(); mv = null; } { // public static Test.test()V mv = cw.visitMethod(ACC_PUBLIC | ACC_STATIC, "test", "()V", null, null); try { // Generate result handling t = tester; try { tester.getResult().visit(this); } finally { t = null; } } finally { mv = null; } } cw.visitEnd(); } /* ====================================================================== */ @Override public void visitResultInt(IntResult res) { mv.visitCode(); generateCall(t.getCall(), invocationType); mv.visitIntInsn(BIPUSH, res.getExpected()); mv.visitMethodInsn(INVOKESTATIC, Util.getInternalName(TestUtils.class), "assertEquals", "(II)V", false); mv.visitInsn(RETURN); mv.visitMaxs(0, 0); mv.visitEnd(); } /** * Pseudo code: * <code> * { * try { * I i = new C(); i.m(...); // C.m(); if m is static * Assert.fail(); * } catch (&lt;exception&gt; e) { * Assert.assertEquals(&lt;message&gt;,e.getMessage()); * } catch (Throwable e) { * throw new RuntimeException("...", e); * } * } * </code> */ @Override public void visitResultThrowExc(ThrowExResult res) { mv.visitCode(); Label lblBegin = new Label(); Label lblBootstrapMethodError = new Label(); Label lblNoBME = new Label(); if (invocationType == INDY) { mv.visitTryCatchBlock(lblBegin, lblNoBME, lblBootstrapMethodError, "java/lang/BootstrapMethodError"); } Label lblExpected = new Label(); mv.visitTryCatchBlock(lblBegin, lblExpected, lblExpected, res.getExc().intlName()); Label lblThrowable = new Label(); mv.visitTryCatchBlock(lblBegin, lblExpected, lblThrowable, "java/lang/Throwable"); mv.visitLabel(lblBegin); generateCall(t.getCall(), invocationType); if (Util.isNonVoid(t.getCall().returnType())) { mv.visitInsn(POP); } mv.visitLabel(lblNoBME); // throw new TestFailure("No exception was thrown") mv.visitTypeInsn(NEW, "nsk/share/TestFailure"); mv.visitInsn(DUP); mv.visitLdcInsn("No exception was thrown"); mv.visitMethodInsn(INVOKESPECIAL, "nsk/share/TestFailure", "<init>", "(Ljava/lang/String;)V", false); mv.visitInsn(ATHROW); // Unwrap exception during call site resolution from BootstrapMethodError if (invocationType == INDY) { // } catch (BootstrapMethodError e) { // throw e.getCause(); // } mv.visitLabel(lblBootstrapMethodError); mv.visitFrame(F_SAME1, 0, null, 1, new Object[] {"java/lang/BootstrapMethodError"}); mv.visitVarInsn(ASTORE, 1); mv.visitVarInsn(ALOAD, 1); mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/BootstrapMethodError", "getCause", "()Ljava/lang/Throwable;", false); Label lblIsNull = new Label(); mv.visitJumpInsn(IFNULL, lblIsNull); // e.getCause() != null mv.visitVarInsn(ALOAD, 1); mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/BootstrapMethodError", "getCause", "()Ljava/lang/Throwable;", false); mv.visitInsn(ATHROW); // e.getCause() == null mv.visitLabel(lblIsNull); mv.visitFrame(F_APPEND, 2, new Object[] {TOP, "java/lang/BootstrapMethodError"}, 0, null); mv.visitVarInsn(ALOAD, 1); mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/BootstrapMethodError", "getCause", "()Ljava/lang/Throwable;", false); mv.visitInsn(ATHROW); } // } catch (<exception> e) { // //if <message> != null // Assert.assertEquals(<message>,e.getMessage()); // } mv.visitLabel(lblExpected); mv.visitFrame(F_FULL, 0, new Object[] {}, 1, new Object[] { res.getExc().intlName() }); mv.visitVarInsn(ASTORE, 1); // Exception class comparison, if exact match is requested if (res.isExact()) { mv.visitVarInsn(ALOAD, 1); mv.visitLdcInsn(Type.getType("L"+res.getExc().intlName()+";")); mv.visitMethodInsn(INVOKESTATIC, Util.getInternalName(TestUtils.class), "assertExactClass", "(Ljava/lang/Object;Ljava/lang/Class;)V", false); } // Compare exception's message, if needed if (res.getMessage() != null) { mv.visitVarInsn(ALOAD, 1); mv.visitLdcInsn(res.getMessage()); mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/Exception", "getMessage", "()Ljava/lang/String;", false); mv.visitMethodInsn(INVOKESTATIC, Util.getInternalName(TestUtils.class), "assertEquals", "(Ljava/lang/String;Ljava/lang/String;)V", false); } mv.visitInsn(RETURN); // } catch (Throwable e) { // throw new RuntimeException("Expected exception <exception>", e); // } mv.visitLabel(lblThrowable); mv.visitFrame(F_SAME1, 0, null, 1, new Object[]{"java/lang/Throwable"}); mv.visitVarInsn(ASTORE, 1); // e.printStackTrace(); //mv.visitVarInsn(ALOAD, 1); //mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/Throwable", "printStackTrace", "()V", false); // String msg = String.format("Expected exception J, got: %s: %s", // e.getClass(), e.getMessage()); // throw new RuntimeException(msg, e); mv.visitTypeInsn(NEW, Util.getInternalName(TestFailure.class)); mv.visitInsn(DUP); mv.visitLdcInsn("Expected exception " + res.getExc().name() + ", got: %s: %s"); mv.visitInsn(ICONST_2); mv.visitTypeInsn(ANEWARRAY, "java/lang/Object"); mv.visitInsn(DUP); mv.visitInsn(ICONST_0); mv.visitVarInsn(ALOAD, 1); mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/Object", "getClass", "()Ljava/lang/Class;", false); mv.visitInsn(AASTORE); mv.visitInsn(DUP); mv.visitInsn(ICONST_1); mv.visitVarInsn(ALOAD, 1); mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/Throwable", "getMessage", "()Ljava/lang/String;", false); mv.visitInsn(AASTORE); mv.visitMethodInsn(INVOKESTATIC, "java/lang/String", "format", "(Ljava/lang/String;[Ljava/lang/Object;)Ljava/lang/String;", false); mv.visitVarInsn(ALOAD, 1); mv.visitMethodInsn(INVOKESPECIAL, Util.getInternalName(TestFailure.class), "<init>", "(Ljava/lang/String;Ljava/lang/Throwable;)V", false); mv.visitInsn(ATHROW); // end of lblThrowable mv.visitMaxs(0, 0); mv.visitEnd(); } @Override public void visitResultIgnore() { mv.visitCode(); generateCall(t.getCall(), invocationType); if (Util.isNonVoid(t.getCall().returnType())) { mv.visitInsn(POP); } mv.visitInsn(RETURN); mv.visitMaxs(0, 0); mv.visitEnd(); } /* ====================================================================== */ @Override public void visitParamInt(IntParam i) { pushIntConst(i.value()); } @Override public void visitParamLong(LongParam l) { long value = l.value(); if (value == 0L) { mv.visitInsn(LCONST_0); } else { mv.visitLdcInsn(new Long(value)); } } @Override public void visitParamFloat(FloatParam f) { float value = f.value(); if (value == 0.0f) { mv.visitInsn(FCONST_0); } else if (value == 1.0f) { mv.visitInsn(FCONST_1); } else if (value == 2.0f) { mv.visitInsn(FCONST_2); } else { mv.visitLdcInsn(new Float(value)); } } @Override public void visitParamDouble(DoubleParam d) { double value = d.value(); if (value == 0.0d) { mv.visitInsn(DCONST_0); } else if (value == 1.0d) { mv.visitInsn(DCONST_1); } else { mv.visitLdcInsn(new Double(value)); } } @Override public void visitParamNewInstance(NewInstanceParam param) { String className = param.clazz().intlName(); mv.visitTypeInsn(NEW, className); mv.visitInsn(DUP); mv.visitMethodInsn(INVOKESPECIAL, className, "<init>", "()V", false); } @Override public void visitParamNull() { mv.visitInsn(ACONST_NULL); } @Override public void visitParamString(StringParam str) { mv.visitLdcInsn(str.value()); } }
33.090674
153
0.566312
b0d3f629bbc740715adc3804d47bc13698322eac
7,773
/* * 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.accumulo.core.data; import static java.nio.charset.StandardCharsets.UTF_8; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotEquals; import org.apache.accumulo.core.client.IteratorSetting; import org.apache.accumulo.core.security.ColumnVisibility; import org.apache.hadoop.io.Text; import org.junit.Before; import org.junit.Test; public class ConditionTest { private static final ByteSequence EMPTY = new ArrayByteSequence(new byte[0]); private static final String FAMILY = "family"; private static final String QUALIFIER = "qualifier"; private static final String VISIBILITY = "visibility"; private static final String VALUE = "value"; private static final IteratorSetting[] ITERATORS = {new IteratorSetting(1, "first", "someclass"), new IteratorSetting(2, "second", "someotherclass"), new IteratorSetting(3, "third", "yetanotherclass")}; private String toString(ByteSequence bs) { if (bs == null) { return null; } return new String(bs.toArray(), UTF_8); } private Condition c; @Before public void setUp() throws Exception { c = new Condition(FAMILY, QUALIFIER); } @Test public void testConstruction_CharSequence() { assertEquals(FAMILY, toString(c.getFamily())); assertEquals(QUALIFIER, toString(c.getQualifier())); assertEquals(EMPTY, c.getVisibility()); } @Test public void testConstruction_ByteArray() { c = new Condition(FAMILY.getBytes(UTF_8), QUALIFIER.getBytes(UTF_8)); assertEquals(FAMILY, toString(c.getFamily())); assertEquals(QUALIFIER, toString(c.getQualifier())); assertEquals(EMPTY, c.getVisibility()); } @Test public void testConstruction_Text() { c = new Condition(new Text(FAMILY), new Text(QUALIFIER)); assertEquals(FAMILY, toString(c.getFamily())); assertEquals(QUALIFIER, toString(c.getQualifier())); assertEquals(EMPTY, c.getVisibility()); } @Test public void testConstruction_ByteSequence() { c = new Condition(new ArrayByteSequence(FAMILY.getBytes(UTF_8)), new ArrayByteSequence(QUALIFIER.getBytes(UTF_8))); assertEquals(FAMILY, toString(c.getFamily())); assertEquals(QUALIFIER, toString(c.getQualifier())); assertEquals(EMPTY, c.getVisibility()); } @Test public void testGetSetTimestamp() { c.setTimestamp(1234L); assertEquals(Long.valueOf(1234L), c.getTimestamp()); } @Test public void testSetValue_CharSequence() { c.setValue(VALUE); assertEquals(VALUE, toString(c.getValue())); } @Test public void testSetValue_ByteArray() { c.setValue(VALUE.getBytes(UTF_8)); assertEquals(VALUE, toString(c.getValue())); } @Test public void testSetValue_Text() { c.setValue(new Text(VALUE)); assertEquals(VALUE, toString(c.getValue())); } @Test public void testSetValue_ByteSequence() { c.setValue(new ArrayByteSequence(VALUE.getBytes(UTF_8))); assertEquals(VALUE, toString(c.getValue())); } @Test public void testGetSetVisibility() { ColumnVisibility vis = new ColumnVisibility(VISIBILITY); c.setVisibility(vis); assertEquals(VISIBILITY, toString(c.getVisibility())); } @Test public void testGetSetIterators() { c.setIterators(ITERATORS); assertArrayEquals(ITERATORS, c.getIterators()); } @Test(expected = IllegalArgumentException.class) public void testSetIterators_DuplicateName() { IteratorSetting[] iterators = {new IteratorSetting(1, "first", "someclass"), new IteratorSetting(2, "second", "someotherclass"), new IteratorSetting(3, "first", "yetanotherclass")}; c.setIterators(iterators); } @Test(expected = IllegalArgumentException.class) public void testSetIterators_DuplicatePriority() { IteratorSetting[] iterators = {new IteratorSetting(1, "first", "someclass"), new IteratorSetting(2, "second", "someotherclass"), new IteratorSetting(1, "third", "yetanotherclass")}; c.setIterators(iterators); } @Test public void testEquals() { ColumnVisibility cvis = new ColumnVisibility(VISIBILITY); c.setVisibility(cvis); c.setValue(VALUE); c.setTimestamp(1234L); c.setIterators(ITERATORS); // reflexivity assertEquals(c, c); // non-nullity assertFalse(c.equals(null)); // symmetry Condition c2 = new Condition(FAMILY, QUALIFIER); c2.setVisibility(cvis); c2.setValue(VALUE); c2.setTimestamp(1234L); c2.setIterators(ITERATORS); assertEquals(c, c2); assertEquals(c2, c); Condition c3 = new Condition("nope", QUALIFIER); c3.setVisibility(cvis); c3.setValue(VALUE); c3.setTimestamp(1234L); c3.setIterators(ITERATORS); assertNotEquals(c, c3); assertNotEquals(c3, c); c3 = new Condition(FAMILY, "nope"); c3.setVisibility(cvis); c3.setValue(VALUE); c3.setTimestamp(1234L); c3.setIterators(ITERATORS); assertNotEquals(c, c3); assertNotEquals(c3, c); c2.setVisibility(new ColumnVisibility("sekrit")); assertNotEquals(c, c2); assertNotEquals(c2, c); c2.setVisibility(cvis); c2.setValue(EMPTY); assertNotEquals(c, c2); assertNotEquals(c2, c); c2.setValue(VALUE); c2.setTimestamp(2345L); assertNotEquals(c, c2); assertNotEquals(c2, c); c2.setTimestamp(1234L); c2.setIterators(); assertNotEquals(c, c2); assertNotEquals(c2, c); c2.setIterators(ITERATORS); assertEquals(c, c2); assertEquals(c2, c); // set everything but vis, so its null Condition c4 = new Condition(FAMILY, QUALIFIER); c4.setValue(VALUE); c4.setTimestamp(1234L); c4.setIterators(ITERATORS); assertNotEquals(c, c4); assertNotEquals(c4, c); // set everything but timestamp, so its null Condition c5 = new Condition(FAMILY, QUALIFIER); c5.setVisibility(cvis); c5.setValue(VALUE); c5.setIterators(ITERATORS); assertNotEquals(c, c5); assertNotEquals(c5, c); // set everything but value Condition c6 = new Condition(FAMILY, QUALIFIER); c6.setVisibility(cvis); c6.setTimestamp(1234L); c6.setIterators(ITERATORS); assertNotEquals(c, c6); assertNotEquals(c6, c); // test w/ no optional fields set Condition c7 = new Condition(FAMILY, QUALIFIER); Condition c8 = new Condition(FAMILY, QUALIFIER); assertEquals(c7, c8); assertEquals(c8, c7); } @Test public void testHashCode() { ColumnVisibility cvis = new ColumnVisibility(VISIBILITY); c.setVisibility(cvis); c.setValue(VALUE); c.setTimestamp(1234L); c.setIterators(ITERATORS); int hc1 = c.hashCode(); Condition c2 = new Condition(FAMILY, QUALIFIER); c2.setVisibility(cvis); c2.setValue(VALUE); c2.setTimestamp(1234L); c2.setIterators(ITERATORS); assertEquals(c, c2); assertEquals(hc1, c2.hashCode()); } }
30.363281
99
0.702174
453614413e0b45c03a8b0cfffcb0e3827d6d2861
4,457
/* * SPDX-License-Identifier: Apache-2.0 */ package org.ethereum.beacon.discovery.community; import org.apache.tuweni.bytes.Bytes; import org.apache.tuweni.units.bigints.UInt64; import org.ethereum.beacon.discovery.packet.AuthHeaderMessagePacket; import org.ethereum.beacon.discovery.packet.MessagePacket; import org.ethereum.beacon.discovery.packet.RandomPacket; import org.ethereum.beacon.discovery.packet.WhoAreYouPacket; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; public class PacketEncodingTest { @Test public void encodeRandomPacketTest() { RandomPacket randomPacket = RandomPacket.create( Bytes.fromHexString( "0x0101010101010101010101010101010101010101010101010101010101010101"), Bytes.fromHexString("0x020202020202020202020202"), Bytes.fromHexString( "0x0404040404040404040404040404040404040404040404040404040404040404040404040404040404040404")); Assertions.assertEquals( Bytes.fromHexString( "0x01010101010101010101010101010101010101010101010101010101010101018c0202020202020202020202020404040404040404040404040404040404040404040404040404040404040404040404040404040404040404"), randomPacket.getBytes()); } @Test public void encodeWhoAreYouTest() { WhoAreYouPacket whoAreYouPacket = WhoAreYouPacket.createFromMagic( Bytes.fromHexString( "0x0101010101010101010101010101010101010101010101010101010101010101"), Bytes.fromHexString("0x020202020202020202020202"), Bytes.fromHexString( "0x0303030303030303030303030303030303030303030303030303030303030303"), UInt64.valueOf(1)); Assertions.assertEquals( Bytes.fromHexString( "0101010101010101010101010101010101010101010101010101010101010101ef8c020202020202020202020202a0030303030303030303030303030303030303030303030303030303030303030301"), whoAreYouPacket.getBytes()); } @Test public void encodeAuthPacketTest() { Bytes tag = Bytes.fromHexString("0x93a7400fa0d6a694ebc24d5cf570f65d04215b6ac00757875e3f3a5f42107903"); Bytes authTag = Bytes.fromHexString("0x27b5af763c446acd2749fe8e"); Bytes idNonce = Bytes.fromHexString("0xe551b1c44264ab92bc0b3c9b26293e1ba4fed9128f3c3645301e8e119f179c65"); Bytes ephemeralPubkey = Bytes.fromHexString( "0xb35608c01ee67edff2cffa424b219940a81cf2fb9b66068b1cf96862a17d353e22524fbdcdebc609f85cbd58ebe7a872b01e24a3829b97dd5875e8ffbc4eea81"); Bytes authRespCiphertext = Bytes.fromHexString( "0x570fbf23885c674867ab00320294a41732891457969a0f14d11c995668858b2ad731aa7836888020e2ccc6e0e5776d0d4bc4439161798565a4159aa8620992fb51dcb275c4f755c8b8030c82918898f1ac387f606852"); Bytes messageCiphertext = Bytes.fromHexString("0xa5d12a2d94b8ccb3ba55558229867dc13bfa3648"); Bytes authHeader = AuthHeaderMessagePacket.encodeAuthHeaderRlp( authTag, idNonce, ephemeralPubkey, authRespCiphertext); AuthHeaderMessagePacket authHeaderMessagePacket = AuthHeaderMessagePacket.create(tag, authHeader, messageCiphertext); Assertions.assertEquals( Bytes.fromHexString( "0x93a7400fa0d6a694ebc24d5cf570f65d04215b6ac00757875e3f3a5f42107903f8cc8c27b5af763c446acd2749fe8ea0e551b1c44264ab92bc0b3c9b26293e1ba4fed9128f3c3645301e8e119f179c658367636db840b35608c01ee67edff2cffa424b219940a81cf2fb9b66068b1cf96862a17d353e22524fbdcdebc609f85cbd58ebe7a872b01e24a3829b97dd5875e8ffbc4eea81b856570fbf23885c674867ab00320294a41732891457969a0f14d11c995668858b2ad731aa7836888020e2ccc6e0e5776d0d4bc4439161798565a4159aa8620992fb51dcb275c4f755c8b8030c82918898f1ac387f606852a5d12a2d94b8ccb3ba55558229867dc13bfa3648"), authHeaderMessagePacket.getBytes()); } @Test public void encodeMessagePacketTest() { MessagePacket messagePacket = MessagePacket.create( Bytes.fromHexString( "0x93a7400fa0d6a694ebc24d5cf570f65d04215b6ac00757875e3f3a5f42107903"), Bytes.fromHexString("0x27b5af763c446acd2749fe8e"), Bytes.fromHexString("0xa5d12a2d94b8ccb3ba55558229867dc13bfa3648")); Assertions.assertEquals( Bytes.fromHexString( "0x93a7400fa0d6a694ebc24d5cf570f65d04215b6ac00757875e3f3a5f421079038c27b5af763c446acd2749fe8ea5d12a2d94b8ccb3ba55558229867dc13bfa3648"), messagePacket.getBytes()); } }
50.078652
534
0.795827
f480ec5250033df843fbf3acd3f748ce534ad8b7
320
package me.dev.legacy.event.events; import me.dev.legacy.event.EventStage; import net.minecraft.util.math.BlockPos; public class BlockDestructionEvent extends EventStage { BlockPos nigger; public BlockDestructionEvent(BlockPos nigger) { } public BlockPos getBlockPos() { return this.nigger; } }
20
55
0.75
a91536604ab982f573df9a40206657574d960f3a
779
package ru.prilepskiy.model; import javax.persistence.CascadeType; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.OneToMany; import javax.persistence.Table; import java.util.Set; /** * Ученик. */ @Entity @Table(name = "student") public class StudentEntity extends PeopleEntity { @ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL) @JoinColumn(name="school_class_id") private SchoolClassEntity schoolClass; public SchoolClassEntity getSchoolClass() { return schoolClass; } public void setSchoolClass(SchoolClassEntity schoolClass) { this.schoolClass = schoolClass; } }
25.129032
66
0.730424
2a880da0b4550ba4fb02af8a828f3a56c913be02
647
import jdk.nashorn.internal.objects.annotations.Attribute; import jdk.nashorn.internal.objects.annotations.Where; import jdk.nashorn.internal.runtime.JSType; class NativeMath extends ScriptObject { /** * ECMA 15.8.2.15 round(x) * * @param self self reference * @param x argument * * @return x rounded */ @Function(attributes = Attribute.NOT_ENUMERABLE, where = Where.CONSTRUCTOR) public static double round(final Object self, final Object x) { final double d = JSType.toNumber(x); if (Math.getExponent(d) &gt;= 52) { return d; } return Math.copySign(Math.floor(d + 0.5), d); } }
25.88
79
0.670788
c10c95d6ea6a07d3b86d161f1bef73ba15097195
1,442
package org.jtwig.model.tree; import org.jtwig.context.RenderContext; import org.jtwig.model.expression.Expression; import org.jtwig.model.position.Position; import org.jtwig.render.Renderable; import org.jtwig.render.model.EmptyRenderable; import java.util.Collection; public class IfNode extends Node { private final Collection<IfConditionNode> conditionNodes; public IfNode(Position position, Collection<IfConditionNode> conditionNodes) { super(position); this.conditionNodes = conditionNodes; } public Collection<IfConditionNode> getConditionNodes() { return conditionNodes; } @Override public Renderable render(RenderContext context) { for (IfConditionNode conditionNode : conditionNodes) { if (conditionNode.isTrue(context)) { return conditionNode.render(context); } } return EmptyRenderable.instance(); } public static class IfConditionNode extends ContentNode { private final Expression condition; public IfConditionNode(Position position, Expression condition, Node content) { super(position, content); this.condition = condition; } public Expression getCondition() { return condition; } public boolean isTrue(RenderContext context) { return condition.calculate(context).asBoolean(); } } }
28.27451
87
0.680305
2c12562fa25f51d6e9e35c61f5c8a52be31e1799
6,699
package com.bird.service.common.service; import com.baomidou.mybatisplus.core.conditions.Wrapper; import com.baomidou.mybatisplus.core.toolkit.support.SFunction; import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper; import com.baomidou.mybatisplus.extension.conditions.query.QueryChainWrapper; import com.baomidou.mybatisplus.extension.conditions.update.LambdaUpdateChainWrapper; import com.baomidou.mybatisplus.extension.conditions.update.UpdateChainWrapper; import com.baomidou.mybatisplus.extension.toolkit.ChainWrappers; import com.baomidou.mybatisplus.extension.toolkit.SqlHelper; import com.bird.service.common.mapper.AbstractMapper; import com.bird.service.common.model.IPO; import org.apache.commons.collections.CollectionUtils; import org.springframework.beans.BeanUtils; import org.springframework.beans.factory.annotation.Autowired; import java.io.Serializable; import java.lang.reflect.Constructor; import java.util.*; /** * @author liuxx * @date 2019/8/22 */ public abstract class AbstractService<M extends AbstractMapper<T>,T extends IPO<TKey>,TKey extends Serializable> extends BaseService implements IService<T,TKey> { @Autowired protected M mapper; /** * 根据主键查询实体 * @param id id * @return 实体 */ @Override public T getById(TKey id) { if (isEmptyKey(id)) { return null; } return mapper.selectById(id); } /** * 根据 Wrapper,查询一条记录 <br/> * 结果集,如果是多个,随机取一条 * * @param queryWrapper 实体对象封装操作类 */ @Override public T getOne(Wrapper<T> queryWrapper) { return getOne(queryWrapper, false); } /** * 根据 Wrapper,查询一条记录 * * @param queryWrapper 实体对象封装操作类 * @param throwEx 有多个 result 是否抛出异常 */ @Override public T getOne(Wrapper<T> queryWrapper, boolean throwEx){ if (throwEx) { return mapper.selectOne(queryWrapper); } List<T> list = mapper.selectList(queryWrapper); if (CollectionUtils.isNotEmpty(list)) { int size = list.size(); if (size > 1) { logger.warn(String.format("Warn: execute Method There are %s results.", size)); } return list.get(0); } return null; } /** * 查询(根据ID 批量查询) * * @param ids 主键ID列表 * @return 实体列表 */ @Override public List<T> listByIds(Collection<TKey> ids) { List<T> list = new ArrayList<>(); if (CollectionUtils.isNotEmpty(ids)) { list = mapper.selectBatchIds(ids); } return list; } /** * 查询列表 * * @param queryWrapper 实体对象封装操作类 * @return 实体列表 */ @Override public List<T> list(Wrapper<T> queryWrapper) { return mapper.selectList(queryWrapper); } /** * 查询列表 * * @param queryWrapper 实体对象封装操作类 * @return 查询结果集 */ @Override public List<Map<String, Object>> listMaps(Wrapper<T> queryWrapper) { return mapper.selectMaps(queryWrapper); } /** * 根据 Wrapper 条件,查询总记录数 * * @param queryWrapper 实体对象封装操作类 */ @Override public int count(Wrapper<T> queryWrapper) { return SqlHelper.retCount(mapper.selectCount(queryWrapper)); } /** * 校验是否存在(单条件) * * @param column 列 * @param value 值 * @param excludeId 排除的id * @return 是否存在 */ public boolean checkExist(SFunction<T, ?> column, Object value, Long excludeId) { T model = lambdaQuery().eq(column, value).last("limit 1").one(); if (model == null) { return false; } return !Objects.equals(model.getId(), excludeId); } /** * 根据Model保存数据 * @param model model * @return 保存后的model */ @Override public T save(T model) { if (isEmptyKey(model.getId())) { return this.insert(model); } else { this.update(model); return model; } } /** * 新增 * * @param model 数据 * @return 是否成功 */ @Override public T insert(T model) { mapper.insert(model); return model; } /** * 根据Id更新Model * * @param model model * @return 是否成功 */ @Override public boolean update(T model) { int result = mapper.updateById(model); return result >= 1; } /** * 根据主键删除数据 * @param id 主键 */ @Override public boolean delete(TKey id) { return SqlHelper.retBool(mapper.deleteById(id)); } /** * 根据 entity 条件,删除记录 * * @param queryWrapper 实体包装类 */ @Override public boolean delete(Wrapper<T> queryWrapper) { return SqlHelper.retBool(mapper.delete(queryWrapper)); } /** * 删除(根据ID 批量删除) * * @param ids 主键ID列表 */ @Override public boolean deleteByIds(Collection<TKey> ids) { if (CollectionUtils.isEmpty(ids)) { return false; } return SqlHelper.retBool(mapper.deleteBatchIds(ids)); } /** * 以下的方法使用介绍: * * 一. 名称介绍 * 1. 方法名带有 query 的为对数据的查询操作, 方法名带有 update 的为对数据的修改操作 * 2. 方法名带有 lambda 的为内部方法入参 column 支持函数式的 * * 二. 支持介绍 * 1. 方法名带有 query 的支持以 {@link ChainQuery} 内部的方法名结尾进行数据查询操作 * 2. 方法名带有 update 的支持以 {@link ChainUpdate} 内部的方法名为结尾进行数据修改操作 * * 三. 使用示例,只用不带 lambda 的方法各展示一个例子,其他类推 * 1. 根据条件获取一条数据: `query().eq("column", value).one()` * 2. 根据条件删除一条数据: `update().eq("column", value).remove()` * */ /** * 链式查询 普通 * * @return QueryWrapper 的包装类 */ @Override public QueryChainWrapper<T> query() { return ChainWrappers.queryChain(mapper); } /** * 链式查询 lambda 式 * <p>注意:不支持 Kotlin </p> * * @return LambdaQueryWrapper 的包装类 */ @Override public LambdaQueryChainWrapper<T> lambdaQuery() { return ChainWrappers.lambdaQueryChain(mapper); } /** * 链式更改 普通 * * @return UpdateWrapper 的包装类 */ @Override public UpdateChainWrapper<T> update() { return ChainWrappers.updateChain(mapper); } /** * 链式更改 lambda 式 * <p>注意:不支持 Kotlin </p> * * @return LambdaUpdateWrapper 的包装类 */ @Override public LambdaUpdateChainWrapper<T> lambdaUpdate() { return ChainWrappers.lambdaUpdateChain(mapper); } /** * 主键是否为空 * <p> * 子类需根据主键类型重写该方法 * 比如:Long类型的主键判断大于0;String类型的主键判断不为空字符串 * * @param id id * @return true or false */ protected boolean isEmptyKey(TKey id) { return id == null; } }
23.588028
162
0.592476
eeb41755bca017c976881187f4dc255a06da91cc
3,677
package com.ruoyi.web.controller.guangzhou; import java.util.List; import org.apache.shiro.authz.annotation.RequiresPermissions; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import com.ruoyi.common.annotation.Log; import com.ruoyi.common.enums.BusinessType; import com.ruoyi.system.domain.BorrowMoney; import com.ruoyi.system.service.IBorrowMoneyService; import com.ruoyi.common.core.controller.BaseController; import com.ruoyi.common.core.domain.AjaxResult; import com.ruoyi.common.utils.poi.ExcelUtil; import com.ruoyi.common.core.page.TableDataInfo; /** * borrow_moneyController * * @author ruoyi * @date 2020-11-23 */ @Controller @RequestMapping("/system/money") public class BorrowMoneyController extends BaseController { private String prefix = "system/money"; @Autowired private IBorrowMoneyService borrowMoneyService; @RequiresPermissions("system:money:view") @GetMapping() public String money() { return prefix + "/money"; } /** * 查询borrow_money列表 */ @RequiresPermissions("system:money:list") @PostMapping("/list") @ResponseBody public TableDataInfo list(BorrowMoney borrowMoney) { startPage(); List<BorrowMoney> list = borrowMoneyService.selectBorrowMoneyList(borrowMoney); return getDataTable(list); } /** * 导出borrow_money列表 */ @RequiresPermissions("system:money:export") @Log(title = "borrow_money", businessType = BusinessType.EXPORT) @PostMapping("/export") @ResponseBody public AjaxResult export(BorrowMoney borrowMoney) { List<BorrowMoney> list = borrowMoneyService.selectBorrowMoneyList(borrowMoney); ExcelUtil<BorrowMoney> util = new ExcelUtil<BorrowMoney>(BorrowMoney.class); return util.exportExcel(list, "money"); } /** * 新增borrow_money */ @GetMapping("/add") public String add() { return prefix + "/add"; } /** * 新增保存borrow_money */ @RequiresPermissions("system:money:add") @Log(title = "borrow_money", businessType = BusinessType.INSERT) @PostMapping("/add") @ResponseBody public AjaxResult addSave(BorrowMoney borrowMoney) { return toAjax(borrowMoneyService.insertBorrowMoney(borrowMoney)); } /** * 修改borrow_money */ @GetMapping("/edit/{id}") public String edit(@PathVariable("id") Long id, ModelMap mmap) { BorrowMoney borrowMoney = borrowMoneyService.selectBorrowMoneyById(id); mmap.put("borrowMoney", borrowMoney); return prefix + "/edit"; } /** * 修改保存borrow_money */ @RequiresPermissions("system:money:edit") @Log(title = "borrow_money", businessType = BusinessType.UPDATE) @PostMapping("/edit") @ResponseBody public AjaxResult editSave(BorrowMoney borrowMoney) { return toAjax(borrowMoneyService.updateBorrowMoney(borrowMoney)); } /** * 删除borrow_money */ @RequiresPermissions("system:money:remove") @Log(title = "borrow_money", businessType = BusinessType.DELETE) @PostMapping( "/remove") @ResponseBody public AjaxResult remove(String ids) { return toAjax(borrowMoneyService.deleteBorrowMoneyByIds(ids)); } }
28.952756
87
0.705738
801828f0e52dea7fdd19a37d42971ed932581967
2,141
/* * Class Name * * Date of Initiation * * Copyright @ 2019 Team 07, CMPUT 301, University of Alberta - All Rights Reserved. * You may use, distribute, or modify this code under terms and conditions of the Code of Student Behaviour at the University of Alberta. * You can find a copy of the license in the github wiki for this project. */ package vl.team07.com.virtuallibrary; import java.util.ArrayList; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Created by MTX on 2019-02-24. */ public class UserValidator { private User validateUser; public UserValidator(User user){ this.validateUser = user; } public UserValidator(){} public boolean isValidUsername(String username){ String regex = "[a-zA-z]{6,20}"; Pattern pattern = Pattern.compile(regex); Matcher matcher = pattern.matcher(username); return matcher.matches(); } public boolean isValidEmail(String email){ String regex = "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@" + "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$"; // Referenced: https://stackoverflow.com/questions/8204680/java-regex-email Pattern pattern = Pattern.compile(regex); Matcher matcher = pattern.matcher(email); return matcher.matches(); } public boolean isValidAge(int age){ return age >= 10 && age <= 100; } public boolean isValidName(String name){ String regex = "[a-zA-z]*"; Pattern pattern = Pattern.compile(regex); Matcher matcher = pattern.matcher(name); return matcher.matches() && name.length() <= 20; } public boolean isValidAddress(String address){ // real address // related to map return true; } public boolean isExistedUsername(ArrayList<User> UserArrayList, final String username){ // referenced:https://stackoverflow.com/questions/18852059/java-list-containsobject-with-field-value-equal-to-x boolean isExisted = UserArrayList.stream().anyMatch(user->user.getUserName().equals(username)); return isExisted; } }
30.585714
146
0.650163
47d52563c9724491b5ef7691a3be3e32ff8ee304
292
package com.testquack.dal; import org.springframework.data.repository.PagingAndSortingRepository; import com.testquack.beans.TestCase; public interface TestCaseRepository extends TestCaseRepositoryCustom, PagingAndSortingRepository<TestCase, String>, CommonRepository<TestCase> { }
32.444444
82
0.839041
3de39adf57b7d9b8651c1c2c9d1c1702b78d4efa
254
package classe; public class Comida { String nomeComida; double pesoComida; Comida (String nomeComida, double pesoComida) { this.nomeComida = nomeComida; this.pesoComida = pesoComida; } double peso() { return pesoComida; } }
11.545455
48
0.685039
309218301425dcf5c37b7341aa27dd688a253173
341
package com.training.springbootbuyitem.entity.request; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; @Data @Builder @NoArgsConstructor @AllArgsConstructor public class NotificationRequest { private String email; private String subject; private String message; }
18.944444
54
0.809384
4aae83ab4ac1048cd53eaed1c12945f546324c38
809
package com.phoenixnap.oss.ramlplugin.raml2code.github; import org.junit.Test; import com.phoenixnap.oss.ramlplugin.raml2code.plugin.TestConfig; import com.phoenixnap.oss.ramlplugin.raml2code.rules.GitHubAbstractRuleTestBase; import com.phoenixnap.oss.ramlplugin.raml2code.rules.Spring4ControllerDecoratorRule; /** * @author aleksandars * @since 2.0.5 */ public class Issue163RulesTest extends GitHubAbstractRuleTestBase { @Test public void check_http_request_as_method_parameter() throws Exception { TestConfig.setInjectHttpRequestParameter(true); loadRaml("issue-163.raml"); rule = new Spring4ControllerDecoratorRule(); rule.apply(getControllerMetadata(), jCodeModel); verifyGeneratedCode("Issue163Spring4ControllerDecoratorRule"); TestConfig.setInjectHttpRequestParameter(false); } }
32.36
84
0.822002
b9fbb36a98fe62586ef52ff8e1e051f2e1faf8f3
1,310
package io.github.mela.command.provided.interceptors; import static org.junit.jupiter.api.Assertions.assertEquals; import io.github.mela.command.provided.BindingTest; import io.github.mela.command.bind.Command; import io.github.mela.command.bind.CommandBindingsBuilder; import io.github.mela.command.provided.mappers.StringMapper; import io.github.mela.command.core.CommandContext; import org.junit.jupiter.api.Test; class DefaultInterceptorTest extends BindingTest<DefaultInterceptorTest.TestCommand> { protected DefaultInterceptorTest() { super(TestCommand::new); } @Test void testProvidedValue() { dispatcher.dispatch("foo value", CommandContext.create()); assertEquals("value", command.value); } @Test void testDefaultValue() { dispatcher.dispatch("foo", CommandContext.create()); assertEquals("default", command.value); } @Override protected CommandBindingsBuilder configure(CommandBindingsBuilder builder) { return builder .bindMapper(String.class, new StringMapper()) .bindMappingInterceptor(Default.class, new DefaultInterceptor()); } public static final class TestCommand { private String value; @Command(labels = "foo") public void execute(@Default("default") String value) { this.value = value; } } }
27.87234
86
0.748092
72dd7c2de40736adc617a6ae7bdd95f430468c43
3,532
/** * Copyright 2013 Canada Health Infoway, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Author: $LastChangedBy: tmcgrady $ * Last modified: $LastChangedDate: 2013-05-16 20:53:38 -0400 (Thu, 16 May 2013) $ * Revision: $LastChangedRevision: 6878 $ */ package ca.infoway.messagebuilder.marshalling.hl7.formatter.r2; import static ca.infoway.messagebuilder.xml.ConformanceLevel.OPTIONAL; import java.util.ArrayList; import java.util.List; import org.junit.Test; import ca.infoway.messagebuilder.SpecificationVersion; import ca.infoway.messagebuilder.datatype.BareANY; import ca.infoway.messagebuilder.datatype.TEL; import ca.infoway.messagebuilder.datatype.impl.LISTImpl; import ca.infoway.messagebuilder.datatype.impl.TELImpl; import ca.infoway.messagebuilder.datatype.lang.TelecommunicationAddress; import ca.infoway.messagebuilder.marshalling.hl7.ModelToXmlResult; import ca.infoway.messagebuilder.marshalling.hl7.formatter.FormatContextImpl; import ca.infoway.messagebuilder.marshalling.hl7.formatter.FormatterTestCase; import ca.infoway.messagebuilder.xml.Cardinality; public class BagR2PropertyFormatterTest extends FormatterTestCase { private FormatterR2Registry formatterRegistry = FormatterR2Registry.getInstance(); @Test public void testFormatValueNull() throws Exception { String result = new BagR2PropertyFormatter(this.formatterRegistry).format( new FormatContextImpl(new ModelToXmlResult(), null, "telecom", "BAG<TEL>", OPTIONAL, null, false, SpecificationVersion.R02_04_03, null, null, null, false), (BareANY) new LISTImpl<TEL, TelecommunicationAddress>(TELImpl.class)); assertXml("null", "", result); } @Test public void testFormatValueNonNull() throws Exception { String result = new BagR2PropertyFormatter(this.formatterRegistry).format( new FormatContextImpl(new ModelToXmlResult(), null, "telecom", "BAG<TEL>", OPTIONAL, Cardinality.create("1-4"), false, SpecificationVersion.R02_04_03, null, null, null, false), (BareANY) LISTImpl.<TEL, TelecommunicationAddress>create( TELImpl.class, createTelecommunicationAddressList())); assertXml("non null", "<telecom value=\"+1-519-555-2345;ext=12345\"/>" + "<telecom value=\"+1-416-555-2345;ext=12345\"/>", result); } private List<TelecommunicationAddress> createTelecommunicationAddressList() { ArrayList<TelecommunicationAddress> result = new ArrayList<TelecommunicationAddress>(); TelecommunicationAddress phone1 = createTelecommunicationAddress("+1-519-555-2345;ext=12345"); TelecommunicationAddress phone2 = createTelecommunicationAddress("+1-416-555-2345;ext=12345"); result.add(phone1); result.add(phone2); return result; } private static TelecommunicationAddress createTelecommunicationAddress(String formattedPhoneNumber) { TelecommunicationAddress telecom = new TelecommunicationAddress(); telecom.setAddress(formattedPhoneNumber); return telecom; } }
44.708861
182
0.761608
90c0078c5a89ed06c9c5790ce5bfc034f216b0cd
783
package world.md2html.plugins; import world.md2html.utils.UserError; import world.md2html.options.model.Document; public interface PageMetadataHandler { /** * Accepts document `doc` where the `metadata` was found, the metadata `marker`, the * `metadata` itself and the whole section `metadata_section` from which the `metadata` * was extracted. * Returns the text that must replace the metadata section in the source text. */ String acceptPageMetadata(Document document, String marker, String metadata, String metadataSection) throws PageMetadataException; class PageMetadataException extends UserError { public PageMetadataException(String message) { super(message); } } }
32.625
92
0.692209