blob_id
stringlengths
40
40
language
stringclasses
1 value
repo_name
stringlengths
5
132
path
stringlengths
2
382
src_encoding
stringclasses
34 values
length_bytes
int64
9
3.8M
score
float64
1.5
4.94
int_score
int64
2
5
detected_licenses
listlengths
0
142
license_type
stringclasses
2 values
text
stringlengths
9
3.8M
download_success
bool
1 class
00c058ef54feb6c905c09d37fa90602748a368f1
Java
afs/jena-workspace
/src/main/java/io/IOZ.java
UTF-8
3,398
2.578125
3
[]
permissive
/* * 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 io; import java.io.IOException; import java.io.InputStreamReader; import java.io.Reader; import java.io.StringWriter; import java.nio.charset.Charset; import java.nio.charset.IllegalCharsetNameException; import java.nio.charset.StandardCharsets; import org.apache.jena.atlas.logging.Log; import org.apache.jena.atlas.web.TypedInputStream; import org.eclipse.jetty.util.IO; public class IOZ { /** Read a {@link TypedInputStream} into a string */ public static String slurp(TypedInputStream typedInputStream) { String charsetStr = typedInputStream.getCharset() ; Charset cs = charsetFor(charsetStr) ; try ( Reader r = new InputStreamReader(typedInputStream, cs) ) { return readAll(r) ; } catch (IOException ex) { return null ; } // Does not happen - readAll deals with it. } private static final int BUFFER_SIZE = 128*1024 ; /** read all (or as much as possible) of a reader */ private static String readAll(Reader r) { StringWriter sw = new StringWriter(BUFFER_SIZE) ; try { char buff[] = new char[BUFFER_SIZE]; for (;;) { int l = r.read(buff); if (l < 0) break; sw.write(buff, 0, l); } sw.close() ; //r.close() ; } catch (IOException ex) { Log.warn(IO.class, "faled to read all of the reader : "+ex.getMessage(), ex) ; } return sw.toString(); } /** Convert a string name for a charset into a {@link Charset}. * Default to UTF-8. */ private static Charset charsetFor(String charsetStr) { if ( charsetStr == null ) return StandardCharsets.UTF_8 ; // Use a build-in if possible. Charset cs = tryForCharset(charsetStr, StandardCharsets.UTF_8) ; if ( cs == null ) cs = tryForCharset(charsetStr, StandardCharsets.ISO_8859_1) ; if ( cs == null ) cs = tryForCharset(charsetStr, StandardCharsets.US_ASCII) ; if ( cs == null ) { try { cs = Charset.forName(charsetStr) ; } catch (IllegalCharsetNameException ex) { Log.warn(IO.class, "No such charset: "+ex.getCharsetName()+ " : defaulting to UTF-8") ; cs = StandardCharsets.UTF_8 ; } } return cs ; } private static Charset tryForCharset(String ct, Charset cs) { if ( ct.equalsIgnoreCase(cs.name()) ) return cs ; return null ; } }
true
a4eb7c4558d58942e14e51695186ef0dafc706b6
Java
norteksoft/iMatrix-v6.5.RC2
/src/main/java/com/norteksoft/task/base/enumeration/TaskState.java
UTF-8
781
2.5625
3
[]
no_license
package com.norteksoft.task.base.enumeration; /** * 任务状态 * @author Administrator * */ public enum TaskState { /** * 待办理 */ WAIT_TRANSACT("task.state.waitTransact"),//待办理 WAIT_DESIGNATE_TRANSACTOR("task.state.waitDesignateTransactor"),//等待设置办理人 COMPLETED("task.state.completed"),//已完成 CANCELLED("task.state.cancelled"),//已取消 DRAW_WAIT("task.state.drawWait"),//待领取 ASSIGNED("task.state.assigned"),//已指派 WAIT_CHOICE_TACHE("task.state.waitChoiceTache"),//等待选择环节 HAS_DRAW_OTHER("task.state.hasDrawOther");//他人已领取 public String code; TaskState(String code){ this.code = code; } public String getCode() { return code; } public Integer getIndex(){ return this.ordinal(); } }
true
91e2d62046d760b8fca406b1c1662715fe06e9d7
Java
nazaretdf/prueba
/web-ejemplo/src/es/insa/curso/web/servlets/Servlet1.java
IBM852
2,188
3.140625
3
[]
no_license
package es.insa.curso.web.servlets; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet implementation class Servlet1 */ public class Servlet1 extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public Servlet1() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#service(HttpServletRequest request, HttpServletResponse response) */ protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub //1 EXTRAER LOS DATOS DE ENTRADA DE REQUEST // a este servlet le habia puesto alisas-- calculadora // los datos siempre vienen en formato de texto por lo que hay que convertirlos String op1 = request.getParameter("op1"); String op2 = request.getParameter("op2"); String ope = request.getParameter("op"); //2 CONVERTIR LOS DATOS // hay que comprobar que los datos que me envian son correctos,por // ejeplo que no venga una letra double x = Double.valueOf(op1); double y = Double.valueOf(op2); //3 DELEGAR LA EJECUCION CONCRETA QUE TOQUE double resultado = calcular(x,y,ope); //4 DEVOLVER LOS RESULTADOS AL USUARIO // a) A LO BRUTO: COMO EL SYSO PERO EN WEB response.getWriter().print("El resultado es " + resultado); // b) MEDIANTE UNA PAGINA WEB request.setAttribute("r", resultado); request.getRequestDispatcher("pagina.jsp") .forward(request, response); // EL CODIGO QUE PONGA YO AQU NO SIRVE PARA NADA, porq ya se ha ido :P } private double calcular(double x, double y, String ope) { if("sumar".equals(ope)){ return x+y; }else if("restar".equals(ope)){ return x-y; }else if("multiplicar".equals(ope)){ return x*y; }else if("dividir".equals(ope)){ return x/y; }else { return Double.NaN; } } }
true
5bd8a52931a46f1ae85e52471c71799242a68627
Java
RedNicStone/ChromatiCraft
/Render/TESR/PowerTreeRender.java
UTF-8
6,404
1.78125
2
[]
no_license
/******************************************************************************* * @author Reika Kalseki * * Copyright 2017 * * All rights reserved. * Distribution of the software in any form is only allowed with * explicit, prior permission from the owner. ******************************************************************************/ package Reika.ChromatiCraft.Render.TESR; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.GuiScreen; import net.minecraft.client.renderer.Tessellator; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.IIcon; import net.minecraftforge.client.MinecraftForgeClient; import org.lwjgl.opengl.GL11; import Reika.ChromatiCraft.Auxiliary.ChromaFX; import Reika.ChromatiCraft.Base.ChromaRenderBase; import Reika.ChromatiCraft.Registry.ChromaIcons; import Reika.ChromatiCraft.TileEntity.Storage.TileEntityPowerTree; import Reika.DragonAPI.Instantiable.Data.Immutable.WorldLocation; import Reika.DragonAPI.Instantiable.Rendering.StructureRenderer; import Reika.DragonAPI.Interfaces.TileEntity.RenderFetcher; import Reika.DragonAPI.Libraries.IO.ReikaColorAPI; import Reika.DragonAPI.Libraries.IO.ReikaRenderHelper; import Reika.DragonAPI.Libraries.IO.ReikaTextureHelper; import Reika.DragonAPI.Libraries.Java.ReikaGLHelper.BlendMode; public class PowerTreeRender extends ChromaRenderBase { @Override public String getImageFileName(RenderFetcher te) { return null; } @Override public void renderTileEntityAt(TileEntity tile, double par2, double par4, double par6, float par8) { TileEntityPowerTree te = (TileEntityPowerTree)tile; GL11.glPushMatrix(); GL11.glPushAttrib(GL11.GL_ALL_ATTRIB_BITS); GL11.glTranslated(par2, par4, par6); if (!te.isInWorld() || MinecraftForgeClient.getRenderPass() == 1 || StructureRenderer.isRenderingTiles()) { double o = 0.005; double x = -o; double y = -o; double z = -o; double dx = 1+o; double dy = 1+o; double dz = 1+o; IIcon ico = ChromaIcons.BATTERY.getIcon(); float u = ico.getMinU(); float v = ico.getMinV(); float du = ico.getMaxU(); float dv = ico.getMaxV(); if (te.hasMultiBlock() || StructureRenderer.isRenderingTiles()) { z = -1-o; dx = 2+o; } GL11.glEnable(GL11.GL_BLEND); GL11.glDisable(GL11.GL_LIGHTING); ReikaTextureHelper.bindTerrainTexture(); Tessellator v5 = Tessellator.instance; v5.startDrawingQuads(); v5.setColorOpaque_I(0xffffff); v5.setBrightness(240); v5.addVertexWithUV(x, dy, z, u, dv); v5.addVertexWithUV(dx, dy, z, du, dv); v5.addVertexWithUV(dx, y, z, du, v); v5.addVertexWithUV(x, y, z, u, v); v5.addVertexWithUV(x, y, dz, u, v); v5.addVertexWithUV(dx, y, dz, du, v); v5.addVertexWithUV(dx, dy, dz, du, dv); v5.addVertexWithUV(x, dy, dz, u, dv); v5.addVertexWithUV(x, y, z, u, v); v5.addVertexWithUV(x, y, dz, du, v); v5.addVertexWithUV(x, dy, dz, du, dv); v5.addVertexWithUV(x, dy, z, u, dv); v5.addVertexWithUV(dx, dy, z, u, dv); v5.addVertexWithUV(dx, dy, dz, du, dv); v5.addVertexWithUV(dx, y, dz, du, v); v5.addVertexWithUV(dx, y, z, u, v); v5.addVertexWithUV(x, dy, dz, u, v); v5.addVertexWithUV(dx, dy, dz, du, v); v5.addVertexWithUV(dx, dy, z, du, dv); v5.addVertexWithUV(x, dy, z, u, dv); v5.addVertexWithUV(x, y, z, u, dv); v5.addVertexWithUV(dx, y, z, du, dv); v5.addVertexWithUV(dx, y, dz, du, v); v5.addVertexWithUV(x, y, dz, u, v); v5.draw(); if (te.canConduct() && te.isEnhanced()) { this.renderHalo(te, par2, par4, par6, par8); } } if (tile.hasWorldObj() && MinecraftForgeClient.getRenderPass() == 0) { ChromaFX.drawEnergyTransferBeams(new WorldLocation(te), te.getOutgoingBeamRadius(), te.getTargets()); } GL11.glPopAttrib(); GL11.glPopMatrix(); } private void renderHalo(TileEntityPowerTree te, double par2, double par4, double par6, float par8) { BlendMode.ADDITIVEDARK.apply(); Tessellator v5 = Tessellator.instance; IIcon ico = ChromaIcons.CAUSTICS_GENTLE.getIcon(); float u = ico.getMinU(); float v = ico.getMinV(); float du = ico.getMaxU(); float dv = ico.getMaxV(); double s = 1.5+0.5*Math.sin(Math.toRadians(te.getTicksExisted()+par8)); ReikaRenderHelper.prepareGeoDraw(true); int d = 1; double dsq = GuiScreen.isCtrlKeyDown() ? 0 : Minecraft.getMinecraft().thePlayer.getDistanceSq(te.xCoord+0.5, te.yCoord+0.5-7, te.zCoord+0.5); double da = dsq >= 4096 ? 60 : dsq >= 1024 ? 45 : dsq >= 256 ? 30 : 20; double i = 0; int c = 0xff000000 | ReikaColorAPI.getModifiedHue(0x5f0000, te.getTicksExisted()%360); double t = -((te.getTicksExisted()+par8)%20)/20D; for (int h = -11; h <= 2; h += d) { double r = 5-5*Math.pow((i+t)/14D, 6); if (i < 6) r += Math.pow(6-i-t, 3)*0.03125/3; if (r > 0) { double y = h+t; double y2 = h+d+t; double dr = 0.0625; double r2 = 5-5*Math.pow((i+1+t)/14D, 6); int c1 = c; if (h == -11) { c1 = ReikaColorAPI.getColorWithBrightnessMultiplier(c, 1+(float)t); } for (double a = 0; a < 360; a += da) { double a2 = a+da; double x1 = 1+r*Math.cos(Math.toRadians(a)); double x2 = 1+r*Math.cos(Math.toRadians(a2)); double z1 = r*Math.sin(Math.toRadians(a)); double z2 = r*Math.sin(Math.toRadians(a2)); ReikaRenderHelper.renderTube(x1, y, z1, x2, y, z2, c1, c1, dr, dr, 4); if (r2 > 0) { double x1b = 1+r2*Math.cos(Math.toRadians(a)); double x2b = 1+r2*Math.cos(Math.toRadians(a2)); double z1b = r2*Math.sin(Math.toRadians(a)); double z2b = r2*Math.sin(Math.toRadians(a2)); if (h == 2) { ReikaRenderHelper.renderTube(x1b, y2, z1b, x2b, y2, z2b, c1, c1, dr, dr, 4); } GL11.glEnable(GL11.GL_TEXTURE_2D); Tessellator.instance.startDrawingQuads(); int c2 = ReikaColorAPI.getModifiedHue(0xff7070, te.getTicksExisted()%360); if (h == -11) { c2 = ReikaColorAPI.getColorWithBrightnessMultiplier(c2, 1+(float)t); } Tessellator.instance.setColorOpaque_I(c2); Tessellator.instance.addVertexWithUV(x1, y, z1, u, v); Tessellator.instance.addVertexWithUV(x1b, y+1, z1b, u, dv); Tessellator.instance.addVertexWithUV(x2b, y+1, z2b, du, dv); Tessellator.instance.addVertexWithUV(x2, y, z2, du, v); Tessellator.instance.draw(); GL11.glDisable(GL11.GL_TEXTURE_2D); } } } i++; } } }
true
997f7a6a70c3e96d01d24d32cc557d22235d06bf
Java
yangzilong1986/zhan-cms
/WEB-INF/src/zt/cms/bm/inactloan/ProsecutionPageAction.java
GB18030
3,399
2
2
[]
no_license
package zt.cms.bm.inactloan; import java.sql.*; import zt.platform.db.*; import zt.platform.form.control.*; import zt.platform.form.util.*; import zt.platform.form.util.event.*; import zt.cms.pub.code.*; import zt.cmsi.pub.*; import zt.cms.pub.*; import zt.cms.bm.common.ParamFactory; import zt.cms.bm.common.SessionInfo; /** * Description of the Class * *@author Administrator *@created 200416 */ public class ProsecutionPageAction extends CommonPageAction { /** * Gets the tableName attribute of the CommonPageAction object * *@return The tableName value */ int seqno = -1; public String getTableName() { return "BMILPROSECUTION"; } public int load(SessionContext ctx, DatabaseConnection conn, FormInstance instance, ErrorMessages msgs, EventManager manager, String parameter) { super.load(ctx,conn,instance,msgs,manager,parameter); if (ctx.getParameter("SEQNO") != null) { instance.setValue(getAutoIncrementField(), ctx.getParameter(getAutoIncrementField())); trigger(manager, instance, EventType.EDIT_VIEW_EVENT_TYPE, Event.BRANCH_CONTINUE_TYPE); this.seqno=Integer.parseInt(ctx.getParameter("SEQNO").trim()); } return 0; } public int beforeInsert(SessionContext ctx, DatabaseConnection conn, FormInstance instance, ErrorMessages msgs, EventManager manager) { instance.setFieldReadonly("ERSHEN",true); instance.setFieldReadonly("SHENSU",true); return super.beforeInsert(ctx, conn, instance, msgs, manager); } public int beforeEdit(SessionContext ctx, DatabaseConnection conn, FormInstance instance, ErrorMessages msgs, EventManager manager, SqlAssistor assistor) { String str = "select ifappeal,ifshensu from " + assistor.getDefaultTbl() + " where seqno=" + this.seqno; RecordSet rs = conn.executeQuery(str); if (rs.next()) { if (rs.getInt("IFAPPEAL") == 0) { instance.setFieldReadonly("ERSHEN", true); }else{ instance.setFieldReadonly("ERSHEN", false); } if (rs.getInt("IFSHENSU") == 0) { instance.setFieldReadonly("SHENSU", true); }else{ instance.setFieldReadonly("SHENSU", false); } } return 0; } public int buttonEvent(SessionContext ctx, DatabaseConnection conn, FormInstance instance, String button, ErrorMessages msgs, EventManager manager) { Param param = new Param(); param.addParam("BMNO",this.param.getBmNo()); ctx.setRequestAtrribute("SEQNO",this.seqno+""); if(this.seqno!=-1){ if (button.equals("ERSHEN")) { ctx.setRequestAtrribute("BMPARAM", param); trigger(manager, "APPEALPAGE", null); } else { ctx.setRequestAtrribute("BMPARAM", param); trigger(manager, "SHENSUPAGE", null); } }else{ msgs.add("ϻϣ"); return -1; } return 0; } }
true
186f481a97849dd5e750fa39702c6f8ec6e62f8f
Java
paulnoorland/CAPNinaPaul
/Advanced Programming/src/adt/Identifier.java
UTF-8
521
3.171875
3
[]
no_license
package adt; public class Identifier implements IIdentifier { private String string; public Identifier(String string){ this.string = string; } public Identifier(Identifier identifier){ string = identifier.getString(); } public void init(String string) { this.string = string; } @Override public String getString() { return string; } @Override public boolean equals(Identifier identifier) { if (getString().equals(identifier.getString())){ return true; } return false; } }
true
09b9d0aa5d10c2d0b25b750c981ff7b7f0245897
Java
kauannavs/CVU
/src/br/edu/ifba/plugin/COMPRAeVENDA/modelo/bd/estatico/ProdutoDAO.java
ISO-8859-1
2,587
2.59375
3
[]
no_license
package br.edu.ifba.plugin.COMPRAeVENDA.modelo.bd.estatico; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.TreeMap; public class ProdutoDAO { private static Map<Integer, Produto> produtos = new TreeMap<Integer, Produto>(); static{ Produto p1 = new Produto(); p1.setId(1); p1.setNome("Pen Drive"); p1.setDescricao("Pen Drive"); p1.setMarca("mutilaser"); p1.setQuantidade(2); p1.setValor(2.4); p1.setImagem("img/pendrive.png"); produtos.put(p1.getId(), p1); Produto p2 = new Produto(); p2.setId(2); p2.setNome("Notebook HP 14-v066Br"); p2.setDescricao("Notebook Intel Core i7 8GB 1TB + " + "2GB de Memria Dedicada Tela 14 Windows 8.1 - Branco"); p2.setMarca("dell"); p2.setQuantidade(2); p2.setValor(2253.0); p2.setImagem("img/notebook.png"); produtos.put(p2.getId(), p2); Produto p3 = new Produto(); p3.setId(3); p3.setNome("Samsung Galaxy S6 Preto"); p3.setDescricao("Samsung Galaxy S6 Preto Desbloqueado 32GB 4G Android 5.0 Tela 5.1"+ "Octa Core Cmera 16MP"); p3.setMarca("Galaxy"); p3.setQuantidade(2); p3.setValor(1253.0); p3.setImagem("img/celular.png"); produtos.put(p3.getId(), p3); Produto p4 = new Produto(); p4.setId(4); p4.setNome("Geladeira / Refrigerador Brastemp"); p4.setDescricao("Samsung Galaxy S6 Preto Desbloqueado 32GB 4G Android 5.0 Tela 5.1"+ "Octa Core Cmera 16MP"); p4.setMarca("Galaxy"); p4.setQuantidade(5); p4.setValor(6253.0); p4.setImagem("img/geladeira.png"); produtos.put(p4.getId(), p4); } public static List<Produto> getProdutoProNome(String nome) { List<Produto> encontrados = new ArrayList<Produto>(); for (Produto p : produtos.values()) { if (p.getNome().toLowerCase().contains(nome.toLowerCase())) { encontrados.add(p); } } return encontrados; } public static List<Produto> getTodos() { List<Produto> encontrados = new ArrayList<Produto>(); for (Produto p : produtos.values()) { encontrados.add(p); } return encontrados; } public static Produto getProduto(int id) { return produtos.get(id); } public static void remover(int id) { produtos.remove(id); } public static int gravar(Produto produto) { if (produto.getId() != -1) { remover(produto.getId()); produtos.put(produto.getId(), produto); } else { int ultimoId = 0; for (int id : produtos.keySet()) { ultimoId = id; } produto.setId(ultimoId + 1); produto.setImagem("img/produto.png"); produtos.put(ultimoId + 1, produto); } return 0; } }
true
98e844c88e47bba40c282b9e183769238be57864
Java
adalbertocmelo/projeto1
/workspace/QoEAT/src/com/acesso/web/trocarSenha.java
ISO-8859-1
2,444
2.453125
2
[]
no_license
package com.acesso.web; import java.sql.SQLException; import javax.servlet.http.HttpServletRequest; import com.lib.cripto; import com.lib.tCad; import com.lib.tHtml; import com.mvc.BusinessLogic; public class trocarSenha extends tCad implements BusinessLogic{ String link = "/acesso/trocarSenha"; public void iniciar(HttpServletRequest request) throws SQLException { // carregar Campos this.campo.put("acao",""); this.campo.put("nBarraDePaginacao",""); this.campo.put("nPag",""); this.campo.put("EdtNovaSenha", ""); this.campo.put("EdtConfirmarNovaSenha", ""); // objeto de persistencia this.putCampos(request); // propriedades tela this.htmlTela = "acesso/html/trocarSenha.htm"; this.titulo = "Trocar Senha"; this.objJs = "oTrse"; // executa a acao this.executar(this.campo.getProperty("acao")); } public void exec(String acao) throws SQLException { if (acao.equals("atualizarTab")){this.atualizarTab();} if (acao.equals("trocar")){this.trocar();} if (acao.equals("aoExibirTela")){this.aoExibirTela();} if (acao.equals("exibirTela")){this.exibirTela();} } public String criarCombosTela(String str) { str = str.replace("@nome@",usuarioAtual.campo.getProperty("nome")); str = str.replace("@login@",usuarioAtual.campo.getProperty("login")); return str; } public void atualizarTab() { } public void exibirTela() { //imprimir a tela tHtml corpo = new tHtml(this.htmlTela); corpo.conteudo = this.criarCombosTela(corpo.conteudo); corpo.conteudo = corpo.conteudo.replace("@titulo@", this.titulo); echo = corpo.conteudo; } public void trocar() throws SQLException { int retorno = usuarioAtual.trocarSenha(cripto.md5(this.campo.getProperty("EdtNovaSenha")), cripto.md5(this.campo.getProperty("EdtConfirmarNovaSenha"))); if (retorno == 10) { echo = "Senha atual informada incorretamente. Tente Novamente."; } if (retorno == 11) { echo = "Senha atual igual a Nova senha. Tente Novamente."; } if (retorno == 12) { echo = "Nova Senha confirmada incorretamente. Tente Novamente."; } if (retorno == 13) { echo = "Ocorreram problemas de processamento durante a tentativa de alterao de senha, " + "tente novamente. Caso o problema persista, entre em contato com o Administrador do Sistema."; } if (retorno == 14) { echo = "Senha alterada com sucesso."; } } }
true
83c929249c726f28a901612060180036237782c6
Java
Sindragosa/MCE
/sedridor/mce/entities/EntityNatureBolt.java
UTF-8
3,063
2.25
2
[]
no_license
package sedridor.mce.entities; import net.minecraft.block.Block; import net.minecraft.entity.EntityLiving; import net.minecraft.entity.projectile.EntityThrowable; import net.minecraft.potion.Potion; import net.minecraft.potion.PotionEffect; import net.minecraft.util.DamageSource; import net.minecraft.util.MathHelper; import net.minecraft.util.MovingObjectPosition; import net.minecraft.world.World; public class EntityNatureBolt extends EntityThrowable { private int ticksInAir = 0; public EntityNatureBolt(World par1World, double par2, double par3, double par4) { super(par1World, par2, par3, par4); } public EntityNatureBolt(World par1World, EntityLiving par2EntityLiving) { super(par1World, par2EntityLiving); } public EntityNatureBolt(World par1World) { super(par1World); } /** * Called to update the entity's position/logic. */ @Override public void onUpdate() { super.onUpdate(); if (!this.worldObj.isRemote && this.ticksInAir > 300) { this.setDead(); } else { ++this.ticksInAir; this.makeTrail(); } } /** * Gets the amount of gravity to apply to the thrown entity with each tick. */ @Override protected float getGravityVelocity() { return 0.003F; } public void makeTrail() { for (int var1 = 0; var1 < 5; ++var1) { double var2 = this.posX + 0.5D * (this.rand.nextDouble() - this.rand.nextDouble()); double var4 = this.posY + 0.5D * (this.rand.nextDouble() - this.rand.nextDouble()); double var6 = this.posZ + 0.5D * (this.rand.nextDouble() - this.rand.nextDouble()); this.worldObj.spawnParticle("crit", var2, var4, var6, 0.0D, 0.0D, 0.0D); } } /** * Called when this EntityThrowable hits a block or entity. */ @Override protected void onImpact(MovingObjectPosition par1MovingObjectPosition) { int var2; if (par1MovingObjectPosition.entityHit != null && par1MovingObjectPosition.entityHit instanceof EntityLiving) { if (par1MovingObjectPosition.entityHit.attackEntityFrom(DamageSource.causeIndirectMagicDamage(this, this.getThrower()), 2)) { byte var5 = (byte)(this.worldObj.difficultySetting == 0 ? 0 : (this.worldObj.difficultySetting == 2 ? 3 : 7)); if (var5 > 0) { ((EntityLiving)par1MovingObjectPosition.entityHit).addPotionEffect(new PotionEffect(Potion.poison.id, var5 * 20, 0)); } } } else if (par1MovingObjectPosition != null) { var2 = MathHelper.floor_double(par1MovingObjectPosition.blockX); int var3 = MathHelper.floor_double(par1MovingObjectPosition.blockY); int var4 = MathHelper.floor_double(par1MovingObjectPosition.blockZ); if (this.worldObj.getBlockMaterial(var2, var3, var4).isSolid()) { this.worldObj.setBlock(var2, var3, var4, Block.leaves.blockID, 2, 3); } } for (var2 = 0; var2 < 8; ++var2) { this.worldObj.spawnParticle("iconcrack_" + Block.leaves.blockID, this.posX, this.posY, this.posZ, this.rand.nextGaussian() * 0.05D, this.rand.nextDouble() * 0.2D, this.rand.nextGaussian() * 0.05D); } if (!this.worldObj.isRemote) { this.setDead(); } } }
true
d5bea0c5c8e48ca22c8dc72ad36880b2385aa1c5
Java
OneTwo33/GB
/src/ru/company/onetwo33/javalvl1/homework8/TicTacToe.java
UTF-8
8,802
3.015625
3
[]
no_license
package ru.company.onetwo33.javalvl1.homework8; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.Random; public class TicTacToe extends JFrame { private static final int SIZE = 5; private static final char DOT_X = 'X'; private static final char DOT_O = 'O'; private static final int DOTS_TO_WIN = 4; private static final String DRAW_X = "DRAW_X"; private static final String DRAW_O = "DRAW_O"; private static char turn = DOT_X; public TicTacToe() { setTitle("Крестики-нолики"); setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); setBounds(500, 500, 600, 600); setVisible(true); JButton[][] jbs = new JButton[SIZE][SIZE]; setLayout(new GridLayout(SIZE, SIZE)); for (int i = 0; i < jbs.length; i++) { for (int j = 0; j < jbs[i].length; j++) { jbs[i][j] = createButton(); jbs[i][j].setName(i + " " + j); jbs[i][j].addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { // HumanTurn if (turn == DOT_X && ((JButton)e.getSource()).getText().isEmpty()) { ((JButton)e.getSource()).setActionCommand(DRAW_X); Graphics g = getGraphics(); ((JButton)e.getSource()).paint(g); ((JButton)e.getSource()).setText(String.valueOf(DOT_X)); System.out.println(((JButton)e.getSource()).getText()); if (checkWin(DOT_X)) { ((JButton)e.getSource()).getParent().removeAll(); JButton jb = new JButton("Победил человек!"); setLayout(new BorderLayout()); add(jb, BorderLayout.CENTER); } } // Проверка на ничью if (isMapFull()) { ((JButton)e.getSource()).getParent().removeAll(); JButton jb = new JButton("Ничья!"); setLayout(new BorderLayout()); add(jb, BorderLayout.CENTER); return; } // ComputerTurn int[] cell = getNextCellToWin(DOT_O); if (cell == null) { cell = getNextCellToWin(DOT_X); if (cell == null) { cell = getRandomEmptyCell(); } } int rowIndex1 = cell[0]; int colIndex1 = cell[1]; setCell(rowIndex1, colIndex1, DOT_O); jbs[rowIndex1][colIndex1].setActionCommand(DRAW_O); Graphics g = getGraphics(); jbs[rowIndex1][colIndex1].paint(g); System.out.println(jbs[rowIndex1][colIndex1].getText()); if (checkWin(DOT_O)) { ((JButton)e.getSource()).getParent().removeAll(); JButton jb = new JButton("Победил компьютер!"); setLayout(new BorderLayout()); add(jb, BorderLayout.CENTER); } else { turn = DOT_X; } } private boolean isMapFull() { for (JButton[] btns : jbs) { for (JButton btn : btns) { if (btn.getText().isEmpty()) { return false; } } } return true; } private int[] getRandomEmptyCell() { int rowIndex, colIndex; Random rand = new Random(); do { rowIndex = rand.nextInt(SIZE); colIndex = rand.nextInt(SIZE); } while (!isValidCell(rowIndex, colIndex)); return new int[]{rowIndex, colIndex}; } private boolean isValidCell(int rowIndex, int colIndex) { return jbs[rowIndex][colIndex].getText().isEmpty(); } private int[] getNextCellToWin(char symbol) { for (int rowIndex = 0; rowIndex < jbs.length; rowIndex++) { for (int colIndex = 0; colIndex < jbs[rowIndex].length; colIndex++) { if (jbs[rowIndex][colIndex].getText().isEmpty() && isGameMoveWinning(rowIndex, colIndex, symbol)) { return new int[]{rowIndex, colIndex}; } } } return null; } private boolean isGameMoveWinning(int rowIndex, int colIndex, char symbol) { setCell(rowIndex, colIndex, symbol); boolean result = checkWin(symbol); setCell(rowIndex, colIndex); return result; } private boolean checkWin(char symbol) { if (checkRowsAndCols(symbol)) return true; return checkDiagonals(symbol); } private boolean checkDiagonals(char symbol) { int mainDiagCounter = 0; int sideDiagCounter = 0; for (int i = 0; i < SIZE; i++) { mainDiagCounter = (jbs[i][i].getText().equals(String.valueOf(symbol))) ? mainDiagCounter + 1 : 0; sideDiagCounter = (jbs[i][jbs.length - 1 - i].getText().equals(String.valueOf(symbol))) ? sideDiagCounter + 1 : 0; if (mainDiagCounter >= DOTS_TO_WIN || sideDiagCounter >= DOTS_TO_WIN) { return true; } } return false; } private boolean checkRowsAndCols(char symbol) { for (int i = 0; i < SIZE; i++) { int rowCounter = 0; int colCounter = 0; for (int j = 0; j < SIZE; j++) { rowCounter = (jbs[i][j].getText().equals(String.valueOf(symbol))) ? rowCounter + 1 : 0; colCounter = (jbs[j][i].getText().equals(String.valueOf(symbol))) ? colCounter + 1 : 0; if (rowCounter >= DOTS_TO_WIN || colCounter >= DOTS_TO_WIN) { return true; } } } return false; } private void setCell(int rowIndex, int colIndex, char symbol) { jbs[rowIndex][colIndex].setText(String.valueOf(symbol)); } private void setCell(int rowIndex, int colIndex) { jbs[rowIndex][colIndex].setText(""); } }); add(jbs[i][j]); } } } private JButton createButton() { return new JButton() { @Override public void paint(Graphics g) { super.paint(g); if (getActionCommand().equals(DRAW_O)) { g.drawOval(0, 0, getWidth(), getWidth()); g.setColor(Color.RED); g.fillOval(0, 0, getWidth(), getWidth()); } else if (getActionCommand().equals(DRAW_X)) { Graphics2D g2d = (Graphics2D) g; g2d.setStroke(new BasicStroke(10)); g2d.setColor(Color.BLUE); g2d.drawLine(0, 0, this.getWidth(), this.getHeight()); g2d.drawLine(this.getWidth(), 0, 0, this.getHeight()); } } }; } }
true
b9901463e47794d30d490bc228ad0b4c5a44b0a8
Java
masudjbd/zapi_test
/src/test/java/bvt/ZAPIBvts.java
UTF-8
148,762
1.59375
2
[]
no_license
/** * Created by manoj.behera on 13-Feb-2017. */ package java.bvt; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Stack; import org.apache.commons.lang.StringUtils; import org.json.JSONArray; import org.json.JSONObject; import org.testng.Assert; import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import com.jayway.restassured.response.Response; import com.relevantcodes.extentreports.ExtentTest; import com.relevantcodes.extentreports.LogStatus; import com.thed.zephyr.BaseTest; import com.thed.zephyr.Config; import com.thed.zephyr.model.BulkExecution; import com.thed.zephyr.model.Cycle; import com.thed.zephyr.model.Execution; import com.thed.zephyr.model.ExecutionFilter; import com.thed.zephyr.model.ExportTraceability; import com.thed.zephyr.model.Stepresult; import com.thed.zephyr.model.Teststep; import com.thed.zephyr.model.Znav; import com.thed.zephyr.model.jira.Issue; import com.thed.zephyr.model.jira.Issuelink; import com.thed.zephyr.model.jira.Sprint; import com.thed.zephyr.util.RestUtils; import com.thed.zephyr.startupdata.ApiTest; /** * @author manoj.behera 13-Feb-2017 * */ @SuppressWarnings("ALL") public class ZAPIBvts extends BaseTest { String issueKey = null; String issueKey2=null; String issueKey3=null; String issueKey4=null; String issueKey5=null; long issueId ; long issueId1; long issueId2; long issueId3; long issueId4; String cycleId = null; String cycleId1=null; String cycleId2 = null; String cycleId3 =null; String cycleId4 =null; String cycleId5 =null; String cycleId6 =null; String cycleId7=null; String id1=null; String executionId1=null; String executionId2=null; String executionId3=null; String executionId4=null; long executionId5; long executionId6; String executionId7=null; String executionId8=null; long executionfilterId; long userexefilterId; long exefilterid1; String StepId=null; long StepresId; long entityId; String testAttachmentId = null; String teststepAttachmentId = null; long columnSelectorId; public String payload = null; public JSONObject obj = null; JSONObject issueJson = null; @BeforeClass public void beforeClass(){ // Issue issuePayLoad = new Issue(); // issuePayLoad.setProject(Config.getValue("project1Id")); // issuePayLoad.setIssuetype(Config.getValue("issueTypeTestId")); // issuePayLoad.setSummary("First Test With Teststeps"); // issuePayLoad.setPriority("3"); // issuePayLoad.setReporter(Config.getValue("adminUserName")); // Response response = jiraService.createIssue(basicAuth, issuePayLoad.toString()); // Assert.assertNotNull(response, "Create Issue Api Response is null."); // // boolean status = jiraService.validateCreateIssueApi(response); // Assert.assertTrue(status, "Response Validation Failed."); // issueJson = new JSONObject(response.body().asString()); // System.out.println("test steps creating for issue :" + issueJson.get("id")); } @BeforeMethod public void beforeMethod(){ basicAuth = RestUtils.basicAuthRequest(Config.getValue("adminUserName"), Config.getValue("adminPassword")); } @Test(priority = 2) public void bvt2_getSystemInfo() { ExtentTest test = extentReport.startTest(Thread.currentThread() .getStackTrace()[1].getMethodName()); test.assignCategory("ZAPI Server BVT Suite"); Response response = zapiService.getSystemInfo(basicAuth); test.log(LogStatus.PASS, "Get SystemInfo Api executed successfully."); boolean status = zapiService.validateSystemInfo(response); Assert.assertTrue(status, "Response Validation Failed."); test.log(LogStatus.PASS, "Response validated suuccessfully."); extentReport.endTest(test); } @Test(priority = 3) public void bvt3_getModuleInfo() { ExtentTest test = extentReport.startTest(Thread.currentThread() .getStackTrace()[1].getMethodName()); test.assignCategory("ZAPI Server BVT Suite"); Response response = zapiService.getModuleInfo(basicAuth); test.log(LogStatus.PASS, "Get Moduleinfo Api executed successfully."); boolean status = zapiService.validateModuleInfo(response); Assert.assertTrue(status, "Response Validation Failed."); test.log(LogStatus.PASS, "Response validated suuccessfully."); extentReport.endTest(test); } @Test(priority = 4) public void bvt4_getLicenseInfo() { ExtentTest test = extentReport.startTest(Thread.currentThread() .getStackTrace()[1].getMethodName()); test.assignCategory("ZAPI Server BVT Suite"); Response response = zapiService.getLicenseInfo(basicAuth); test.log(LogStatus.PASS, "Get license Api executed successfully."); boolean status = zapiService.validateLicenseInfo(response); Assert.assertTrue(status, "Response Validation Failed."); test.log(LogStatus.PASS, "Response validated suuccessfully."); extentReport.endTest(test); } @Test(priority = 5) public void bvt5_getProjects() { ExtentTest test = extentReport.startTest(Thread.currentThread() .getStackTrace()[1].getMethodName()); test.assignCategory("ZAPI Server BVT Suite"); Response response = zapiService.getProjects(basicAuth); test.log(LogStatus.PASS, "Get projects Api executed successfully."); Map<String, Map<String, String>> map = new HashMap<>(); Map<String, String> project1 = new HashMap<>(); project1.put("projectId", "10000"); project1.put("projectName", "Project1"); Map<String, String> project2 = new HashMap<>(); project2.put("projectId", "10001"); project2.put("projectName", "Project2"); map.put("project1", project1); map.put("project2", project2); boolean status = zapiService.validateProjects(response, map); Assert.assertTrue(status, "Response Validation Failed."); test.log(LogStatus.PASS, "Response validated suuccessfully."); extentReport.endTest(test); } @Test(priority = 6) public void bvt6_getVersionsByProject() { ExtentTest test = extentReport.startTest(Thread.currentThread() .getStackTrace()[1].getMethodName()); test.assignCategory("ZAPI Server BVT Suite"); long projectId = Long.parseLong(Config.getValue("project1Id")); Response response = zapiService.getVersionsByProject(basicAuth, projectId); test.log(LogStatus.PASS, "Get Version by project Api executed successfully."); Map<String, Map<String, String>> map = new HashMap<>(); Map<String, String> version1 = new HashMap<>(); version1.put("value", "-1"); version1.put("label", "Unschedule"); Map<String, String> version2 = new HashMap<>(); version2.put("value", "10000"); version2.put("label", "version 1"); Map<String, String> version3 = new HashMap<>(); version3.put("value", "10001"); version3.put("label", "version 2"); Map<String, String> version4 = new HashMap<>(); version4.put("value", "10002"); version4.put("label", "version 3"); Map<String, String> version5 = new HashMap<>(); version5.put("value", "10003"); version5.put("label", "version 4"); Map<String, String> version6 = new HashMap<>(); version6.put("value", "10004"); version6.put("label", "version 5"); map.put("version1", version1); map.put("version2", version2); map.put("version3", version3); map.put("version4", version4); map.put("version5", version5); map.put("version6", version6); boolean status = zapiService.validateVersions(response, map); Assert.assertTrue(status, "Response Validation Failed."); test.log(LogStatus.PASS, "Response validated suuccessfully."); extentReport.endTest(test); } @Test(priority = 7) public void bvt7_getProjectMetadata() { ExtentTest test = extentReport.startTest(Thread.currentThread() .getStackTrace()[1].getMethodName()); test.assignCategory("ZAPI Server BVT Suite"); long projectId = Long.parseLong(Config.getValue("project1Id")); Response response = zapiService.getProjectMetadata(basicAuth, projectId ); test.log(LogStatus.PASS, "Get Project Metadata Api executed successfully."); boolean status = zapiService.validateProjectMetadata(response); Assert.assertTrue(status, "Response Validation Failed."); test.log(LogStatus.PASS, "Response validated suuccessfully."); extentReport.endTest(test); } @Test(priority = 8) public void bvt8_getExecutionStatus() { ExtentTest test = extentReport.startTest(Thread.currentThread() .getStackTrace()[1].getMethodName()); test.assignCategory("ZAPI Server BVT Suite"); Response response = zapiService.getExecutionStatus(basicAuth); test.log(LogStatus.PASS, "Get ExecutionStatus Api executed successfully."); boolean status = zapiService.validateTestExecutionStatuses(response); Assert.assertTrue(status, "Response Validation Failed."); test.log(LogStatus.PASS, "Response validated suuccessfully."); extentReport.endTest(test); } @Test(priority = 9) public void bvt9_getTestStepExecutionStatus() { ExtentTest test = extentReport.startTest(Thread.currentThread() .getStackTrace()[1].getMethodName()); test.assignCategory("ZAPI Server BVT Suite"); Response response = zapiService.getTestStepExecutionStatus(basicAuth); test.log(LogStatus.PASS, "Get StepExecution Status Api executed successfully."); boolean status = zapiService .validategetTestStepExecutionStatus(response); Assert.assertTrue(status, "Response Validation Failed."); test.log(LogStatus.PASS, "Response validated suuccessfully."); extentReport.endTest(test); } @Test(priority=10) public void bvt10_getDashboardByName() { ExtentTest test = extentReport.startTest(Thread.currentThread() .getStackTrace()[1].getMethodName()); test.assignCategory("ZAPI Server BVT Suite"); String query ="dash"; int maxRecords = 15; Response response = zapiService.getDashboardByName(basicAuth ,query, maxRecords ); test.log(LogStatus.PASS, "Get Dashboard Api executed successfully."); boolean status = zapiService.validategetDashboardByName(response); Assert.assertTrue(status, "Response Validation Failed."); test.log(LogStatus.PASS, "Response validated suuccessfully."); extentReport.endTest(test); } @Test(priority = 11) public void bvt11_getIssues() { ExtentTest test = extentReport.startTest(Thread.currentThread() .getStackTrace()[1].getMethodName()); test.assignCategory("ZAPI Server BVT Suite"); String query = "test"; String currentJQL = "type=test"; String currentIssueKey = issueJson.getString("key"); long currentProjectId = Long.parseLong(Config.getValue("project1Id")); Response response = zapiService.getissue(basicAuth, query, currentJQL, currentIssueKey, currentProjectId); test.log(LogStatus.PASS, "Get Issues Api executed successfully."); boolean status = zapiService.validategetIssues(response); Assert.assertTrue(status, "Response Validation Failed."); test.log(LogStatus.PASS, "Response validated suuccessfully."); extentReport.endTest(test); } @Test(priority = 12) public void bvt12_createTeststep() { ExtentTest test = extentReport.startTest(Thread.currentThread().getStackTrace()[1].getMethodName()); test.assignCategory("ZAPI Server BVT Suite"); Issue issuePayLoad = new Issue(); issuePayLoad.setProject(Config.getValue("project1Id")); issuePayLoad.setIssuetype(Config.getValue("issueTypeTestId")); issuePayLoad.setSummary("First Test With Teststeps"); issuePayLoad.setPriority("3"); issuePayLoad.setReporter(Config.getValue("adminUserName")); Response response = jiraService.createIssue(basicAuth, issuePayLoad.toString()); Assert.assertNotNull(response, "Create Issue Api Response is null."); test.log(LogStatus.PASS, "Create Issue Api executed successfully."); boolean status = jiraService.validateCreateIssueApi(response); Assert.assertTrue(status, "Response Validation Failed."); issueId = new JSONObject(response.body().asString()).getLong("id"); System.out.println("test steps creating for issue :" + issueId); for (int i = 0; i < 5; i++) { Teststep teststepJson = new Teststep(); teststepJson.setStep("step"+i); teststepJson.setData("data"+i); teststepJson.setResult("result"+i); Response response1 = zapiService.createTeststep(basicAuth, issueId, teststepJson.toString()); Assert.assertNotNull(response1, "Create teststep Api Without WIKI Response is null."); test.log(LogStatus.PASS, "Create teststep Api Without WIKI executed successfully."); boolean status1 = zapiService.validateCreatedtestStep(response1); Assert.assertTrue(status1, "Response Validation Failed."); } test.log(LogStatus.PASS, "Response validated suuccessfully."); extentReport.endTest(test); } // Create Teststep with WIKI @Test(priority = 13) public void bvt13_createTeststepWithWiki() { ExtentTest test = extentReport.startTest(Thread.currentThread().getStackTrace()[1].getMethodName()); test.assignCategory("ZAPI Server BVT Suite"); Issue issuePayLoad = new Issue(); issuePayLoad.setProject(Config.getValue("project1Id")); issuePayLoad.setIssuetype(Config.getValue("issueTypeTestId")); issuePayLoad.setSummary("First with Wiki Teststeps"); issuePayLoad.setPriority("3"); issuePayLoad.setReporter(Config.getValue("adminUserName")); Response response = jiraService.createIssue(basicAuth, issuePayLoad.toString()); Assert.assertNotNull(response, "Create Issue Api Response is null."); test.log(LogStatus.PASS, "Create Issue Api executed successfully."); boolean status = jiraService.validateCreateIssueApi(response); Assert.assertTrue(status, "Response Validation Failed."); issueId = new JSONObject(response.body().asString()).getLong("id"); System.out.println("Issue id is :" + issueId); Teststep teststepJson = new Teststep(); teststepJson.setStep("h1.bigheading"); teststepJson.setData("h1.bigheading"); teststepJson.setResult("h1.bigheading"); Response response1 = zapiService.createTeststep(basicAuth, issueId, teststepJson.toString()); Assert.assertNotNull(response1, "Create teststep Api with WIKI Response is null."); test.log(LogStatus.PASS, "Create teststep Api With WIKI executed successfully."); boolean status1 = zapiService.validateCreatetestStepWithWIKI(teststepJson.toString(), response1); Assert.assertTrue(status1); extentReport.endTest(test); } // Get test steps by issue id @Test(priority = 14) public void bvt14_getTeststepByIssueId() { ExtentTest test = extentReport.startTest(Thread.currentThread().getStackTrace()[1].getMethodName()); test.assignCategory("ZAPI Server BVT Suite"); Issue issuePayLoad = new Issue(); issuePayLoad.setProject(Config.getValue("project1Id")); issuePayLoad.setIssuetype(Config.getValue("issueTypeTestId")); issuePayLoad.setSummary("Test"); issuePayLoad.setPriority("3"); issuePayLoad.setReporter(Config.getValue("adminUserName")); Response response = jiraService.createIssue(basicAuth, issuePayLoad.toString()); Assert.assertNotNull(response, "Create Issue Api Response is null."); test.log(LogStatus.PASS, "Create Issue Api executed successfully."); boolean status = jiraService.validateCreateIssueApi(response); Assert.assertTrue(status, "Response Validation Failed."); issueId1 = new JSONObject(response.body().asString()).getLong("id"); System.out.println("Issue id is :" + issueId1); for (int i = 0; i < 5; i++) { Teststep teststepJson = new Teststep(); teststepJson.setStep("step"+i); teststepJson.setData("data"+i); teststepJson.setResult("result"+i); Response response1 = zapiService.createTeststep(basicAuth, issueId1, teststepJson.toString()); Assert.assertNotNull(response1, "Create teststep Api Without WIKI Response is null."); test.log(LogStatus.PASS, "Create teststep Api Without WIKI executed successfully."); boolean status1 = zapiService.validateCreatedtestStep(response1); } Response response2 = zapiService.getTeststep(basicAuth, issueId1); Assert.assertNotNull(response2, "Get teststep by issue-Id Response is null."); test.log(LogStatus.PASS, "Get teststep by Issue-id executed successfully."); boolean status1 = zapiService.validateGetTestStepByIssueID(response2); Assert.assertTrue(status1, "Response Validation Failed."); test.log(LogStatus.PASS, "Response validated suuccessfully."); extentReport.endTest(test); } // Get test step by id @Test(priority = 15) public void bvt15_getTeststepByStepId() { ExtentTest test = extentReport.startTest(Thread.currentThread().getStackTrace()[1].getMethodName()); test.assignCategory("ZAPI Server BVT Suite"); Teststep teststepJson = new Teststep(); teststepJson.setStep("Check for schedule count"); teststepJson.setData("filter id"); teststepJson.setResult("count should be equal to schedules returned by this filter."); Response response1 = zapiService.createTeststep(basicAuth, issueId1, teststepJson.toString()); Assert.assertNotNull(response1, "Create teststep Api with WIKI Response is null."); test.log(LogStatus.PASS, "Create teststep Api With WIKI executed successfully."); Long stepId = new JSONObject(response1.body().asString()).getLong("id"); System.out.println("test steps id is :" + stepId); Response response2 = zapiService.getTeststepByID(basicAuth, issueId1, stepId); Assert.assertNotNull(response2, "Get teststep by step-id Response is null."); test.log(LogStatus.PASS, "Get teststep by step-id executed successfully."); boolean status1 = zapiService.validateGetTeststepByID(response2); Assert.assertTrue(status1, "Response Validation Failed."); test.log(LogStatus.PASS, "Response validated successfully."); extentReport.endTest(test); } // Move teststep @Test(priority = 16) public void bvt16_moveTeststep() { ExtentTest test = extentReport.startTest(Thread.currentThread().getStackTrace()[1].getMethodName()); test.assignCategory("ZAPI Server BVT Suite"); Issue issuePayLoad = new Issue(); issuePayLoad.setProject(Config.getValue("project1Id")); issuePayLoad.setIssuetype(Config.getValue("issueTypeTestId")); issuePayLoad.setSummary("Test created to Move and Update steps"); issuePayLoad.setPriority("3"); issuePayLoad.setReporter(Config.getValue("adminUserName")); Response response = jiraService.createIssue(basicAuth, issuePayLoad.toString()); Assert.assertNotNull(response, "Create Issue Api Response is null."); test.log(LogStatus.PASS, "Create Issue Api executed successfully."); issueId2 = new JSONObject(response.body().asString()).getLong("id"); System.out.println("test id is :" + issueId2); Teststep teststepJson = new Teststep(); teststepJson.setStep("Step1"); teststepJson.setData("Data1"); teststepJson.setResult("Result1"); Response response1 = zapiService.createTeststep(basicAuth, issueId2, teststepJson.toString()); Assert.assertNotNull(response1, "Create teststep Api Response is null."); test.log(LogStatus.PASS, "Create teststep Api executed successfully."); long testStepId1 = new JSONObject(response1.body().asString()).getLong("id"); System.out.println("test steps id is :" + testStepId1); Teststep teststepJson1 = new Teststep(); teststepJson1.setStep("New_step"); teststepJson1.setData("New_data"); teststepJson1.setResult("New_result"); Response response2 = zapiService.createTeststep(basicAuth, issueId2, teststepJson1.toString()); Assert.assertNotNull(response2, "Create teststep Api Response is null"); test.log(LogStatus.PASS, "Create teststep Api Response is null"); long testStepId2 = new JSONObject(response2.body().asString()).getLong("id"); System.out.println("test steps id is :" + testStepId2); String payLoad = "{\"before\":\"/rest/zephyr/latest/teststep/" + issueId2 + "/" + testStepId2 + "\"}"; Response response3 = zapiService.moveTeststep(basicAuth, issueId2, testStepId1, payLoad); Assert.assertNotNull(response3, "Move step Response is null."); test.log(LogStatus.PASS, "Move step executed successfully."); System.out.println("Response after moveTeststep:" + response3.body().asString()); boolean status1 = zapiService.validateMovetestStep(payLoad, response3); Assert.assertTrue(status1, "Response Validation Failed."); test.log(LogStatus.PASS, "Response validated suuccessfully."); extentReport.endTest(test); } //Update test step (details/data/expected results) @Test(priority = 17) public void bvt17_updateTeststep() { ExtentTest test = extentReport.startTest(Thread.currentThread().getStackTrace()[1].getMethodName()); test.assignCategory("ZAPI Server BVT Suite"); Teststep teststepJson = new Teststep(); teststepJson.setStep("h1.Step2"); teststepJson.setData("h1.Data2"); teststepJson.setResult("h1.Result2"); Response response1 = zapiService.createTeststep(basicAuth, issueId2, teststepJson.toString()); Assert.assertNotNull(response1, "Create teststep Api is null."); test.log(LogStatus.PASS, "Create teststep Api executed successfully."); long testStepId = new JSONObject(response1.body().asString()).getLong("id"); System.out.println("Steps id for update:" + testStepId); Teststep teststepJson1 = new Teststep(); teststepJson1.setStep("h1.Updated Step1"); teststepJson1.setData("h1.Updated Data1"); teststepJson1.setResult("h1.Updated Result1"); Response response2 = zapiService.updateTeststep(basicAuth, issueId2, testStepId, teststepJson1.toString()); Assert.assertNotNull(response2, "Update step Response is null."); test.log(LogStatus.PASS, "Update step executed successfully."); System.out.println("Response after update Teststep:" +response2.body().asString()); boolean status1 = zapiService.validateUpdatetestStep(teststepJson1.toString(), response2); Assert.assertTrue(status1, "Response Validation Failed."); test.log(LogStatus.PASS, "Response validated suuccessfully."); extentReport.endTest(test); } //Create a cloned test step at second position and modify the step value while cloning @Test(priority = 18) public void bvt18_cloneTeststepAtSecondPositionWithOutWiki() { ExtentTest test = extentReport.startTest(Thread.currentThread().getStackTrace()[1].getMethodName()); test.assignCategory("ZAPI Server BVT Suite"); Teststep teststepJson = new Teststep(); teststepJson.setStep("Big Heading for clone"); teststepJson.setData("Big Heading for clone"); teststepJson.setResult("Big Heading for clone"); Response response1 = zapiService.createTeststep(basicAuth, issueId2, teststepJson.toString()); Assert.assertNotNull(response1, "Create teststep Response is null."); test.log(LogStatus.PASS, "Create teststep executed successfully."); long testStepId = new JSONObject(response1.body().asString()).getLong("id"); System.out.println("Step id for cloning is:" + testStepId); String payLoad1 = "{\r\n\"position\": \"2\"\r\n}"; Response response2 = zapiService.cloneTeststep(basicAuth, issueId2, testStepId, payLoad1); System.out.println("Response after clone Teststep:" +response2.getBody().asString()); Assert.assertNotNull(response2, "Clone step Response is null."); test.log(LogStatus.PASS, "Clone step executed successfully."); boolean status1 = zapiService.validateCloneTeststep(response2); Assert.assertTrue(status1, "Response Validation Failed."); test.log(LogStatus.PASS, "Response validated suuccessfully."); extentReport.endTest(test); } //Clone test step with wiki markup (details/data/expected result) @Test(priority = 19) public void bvt19_cloneTeststepWithWikiMarkup() { ExtentTest test = extentReport.startTest(Thread.currentThread().getStackTrace()[1].getMethodName()); test.assignCategory("ZAPI Server BVT Suite"); Teststep teststepJson = new Teststep(); teststepJson.setStep("h1.Step in wiki"); teststepJson.setData("h1.Data in wiki"); teststepJson.setResult("h1.Result in wiki"); Response response1 = zapiService.createTeststep(basicAuth, issueId2, teststepJson.toString()); Assert.assertNotNull(response1, "Create teststep Response is null."); test.log(LogStatus.PASS, "Create teststep executed successfully."); long testStepId = new JSONObject(response1.body().asString()).getLong("id"); System.out.println("Step id for clone:" + testStepId); String payLoad1 = "{\r\n\"position\": \"1\"\r\n}"; Response response2 = zapiService.cloneTeststep(basicAuth, issueId2, testStepId, payLoad1); Assert.assertNotNull(response2, "Clone step Response is null."); test.log(LogStatus.PASS, "Clone step executed successfully."); boolean status1 = zapiService.validateCloneTeststepWithWiki(response2); Assert.assertTrue(status1, "Response Validation Failed."); test.log(LogStatus.PASS, "Response validated suuccessfully."); System.out.println("Response after clone wiki teststep:" +response2.body().asString()); extentReport.endTest(test); } // Delete test step @Test(priority = 20) public void bvt20_deleteTeststep() { ExtentTest test = extentReport.startTest(Thread.currentThread().getStackTrace()[1].getMethodName()); test.assignCategory("ZAPI Server BVT Suite"); Issue issuePayLoad = new Issue(); issuePayLoad.setProject(Config.getValue("project1Id")); issuePayLoad.setIssuetype(Config.getValue("issueTypeTestId")); issuePayLoad.setSummary("Test With Deleted Teststep"); issuePayLoad.setPriority("3"); issuePayLoad.setReporter(Config.getValue("adminUserName")); Response response = jiraService.createIssue(basicAuth, issuePayLoad.toString()); Assert.assertNotNull(response, "Create Issue Api Response is null."); test.log(LogStatus.PASS, "Create Issue Api executed successfully."); boolean status = jiraService.validateCreateIssueApi(response); Assert.assertTrue(status, "Response Validation Failed."); issueId = new JSONObject(response.body().asString()).getLong("id"); System.out.println("Isuue id is :" + issueId); Teststep teststepJson = new Teststep(); teststepJson.setStep("step-1"); teststepJson.setData("data-1"); teststepJson.setResult("result-1"); Response response1 = zapiService.createTeststep(basicAuth, issueId, teststepJson.toString()); Assert.assertNotNull(response1, "Create teststep Api is null."); test.log(LogStatus.PASS, "Create teststep Api executed successfully."); long testStepId = new JSONObject(response1.body().asString()).getLong("id"); System.out.println("stepID id is :" + testStepId); Response response2 = zapiService.deleteTestStep(basicAuth, issueId, testStepId); Assert.assertNotNull(response2, "Delete step Response is null."); test.log(LogStatus.PASS, "Delete step executed successfully."); System.out.println(response2.body().asString()); boolean status1 = zapiService.validateDeleteTeststep(response2); Assert.assertTrue(status1, "Response Validation Failed."); test.log(LogStatus.PASS, "Response validated suuccessfully."); extentReport.endTest(test); } // Create cycle under planned version, with only mandatory fields @Test(priority = 21) public void bvt21_createCycle() { ExtentTest test = extentReport.startTest(Thread.currentThread().getStackTrace()[1].getMethodName()); test.assignCategory("Automation API BVT Suite - zapi"); Cycle cycleJson = new Cycle(); cycleJson.setProjectId(Long.parseLong(Config.getValue("project1Id"))); cycleJson.setVersionId(Long.parseLong(Config.getValue("version1Id"))); cycleJson.setName("New cycle created in Planned version"); Response response = zapiService.createCycle(basicAuth, cycleJson.toString()); Assert.assertNotNull(response, "Create Cycle Api Response is null."); test.log(LogStatus.PASS, "Create Cycle Api executed successfully."); boolean status = zapiService.validateCreateCycleApi(response); Assert.assertTrue(status, "Response Validation Failed."); test.log(LogStatus.PASS, "Response validated successfully."); cycleId = new JSONObject(response.body().asString()).get("id").toString(); extentReport.endTest(test); } //Create cycle with sprintId under unscheduled version @Test(priority = 22) public void bvt22_createCycleWithSprintId() { ExtentTest test = extentReport.startTest(Thread.currentThread().getStackTrace()[1].getMethodName()); test.assignCategory("Automation API BVT Suite - zapi"); Cycle cycleJson = new Cycle(); cycleJson.setProjectId(Long.parseLong(Config.getValue("project1Id"))); cycleJson.setVersionId(-1l); cycleJson.setName("Sample cycle1"); cycleJson.setSprintId(Long.parseLong(Config.getValue("sprintId"))); Response response = zapiService.createCycle(basicAuth, cycleJson.toString()); Assert.assertNotNull(response, "Create Cycle Api Response is null."); test.log(LogStatus.PASS, "Create Cycle Api executed successfully."); boolean status = zapiService.validateCreateCycleApi(response); Assert.assertTrue(status, "Response Validation Failed."); test.log(LogStatus.PASS, "Response validated successfully."); cycleId = new JSONObject(response.body().asString()).get("id").toString(); extentReport.endTest(test); } // Create cycle with sprintId under planned version @Test(priority = 23) public void bvt23_createCycleplannedverion() { ExtentTest test = extentReport.startTest(Thread.currentThread().getStackTrace()[1].getMethodName()); test.assignCategory("Automation API BVT Suite - zapi"); Cycle cycleJson = new Cycle(); cycleJson.setProjectId(Long.parseLong(Config.getValue("project1Id"))); cycleJson.setVersionId(Long.parseLong(Config.getValue("version1Id"))); cycleJson.setName("sample cycle2"); cycleJson.setSprintId(Long.parseLong(Config.getValue("sprintId"))); Response response = zapiService.createCycle(basicAuth, cycleJson.toString()); Assert.assertNotNull(response, "Create Cycle Api Response is null."); test.log(LogStatus.PASS, "Create Cycle Api executed successfully."); boolean status = zapiService.validateCreateCycleApi(response); Assert.assertTrue(status, "Response Validation Failed."); test.log(LogStatus.PASS, "Response validated successfully."); cycleId1 = new JSONObject(response.body().asString()).get("id").toString(); System.out.println("Created cycle id:" +cycleId1); extentReport.endTest(test); //Add executions Execution executionJson = new Execution(); List<String> values= new ArrayList<String>(); values.add("PROJ1-1"); values.add("PROJ1-2"); executionJson.setIssues(values); executionJson.setProjectId(Long.parseLong(Config.getValue("project1Id"))); executionJson.setVersionId(Long.parseLong(Config.getValue("version1Id"))); executionJson.setCycleId(cycleId1); executionJson.setMethod(1); Response response1 = zapiService.addTestsToCycle(basicAuth, executionJson.toString()); System.out.println("Add tests to cycle successful"); boolean status1 = zapiService.validateAddTestsToCycle(response1); Assert.assertTrue(status, "Response Validation Failed."); test.log(LogStatus.PASS, "Response validated successfully."); extentReport.endTest(test); } // Clone partially executed planned cycle to another version @Test(priority = 24) public void bvt24_cloneupdateCycle() { ExtentTest test = extentReport.startTest(Thread.currentThread().getStackTrace()[1].getMethodName()); test.assignCategory("Automation API BVT Suite - Zapi"); Cycle cycleJson = new Cycle(); cycleJson.setProjectId(Long.parseLong(Config.getValue("project1Id"))); cycleJson.setVersionId(-1l); cycleJson.setName("Cloned cycle moved to unscheduled version"); cycleJson.setClonedCycleId(cycleId1); Response response = zapiService.createCycle(basicAuth, cycleJson.toString()); Assert.assertNotNull(response, "cloneCycle Api Response is null."); test.log(LogStatus.PASS, "cloneCycle Api executed successfully."); boolean status = zapiService.validateCloneCycle(response); System.out.println("Clone cycle successful"); Assert.assertTrue(status, "Response Validation Failed."); test.log(LogStatus.PASS, "Response validated suuccessfully."); extentReport.endTest(test); } // Update cycle - add description @Test(priority = 25) public void bvt25_updateCycle() { ExtentTest test = extentReport.startTest(Thread.currentThread().getStackTrace()[1].getMethodName()); test.assignCategory("Automation API BVT Suite - Zapi"); Cycle cycleJson = new Cycle(); cycleJson.setProjectId(Long.parseLong(Config.getValue("project1Id"))); cycleJson.setVersionId(Long.parseLong(Config.getValue("version1Id"))); cycleJson.setId(cycleId1); cycleJson.setName("sample cycle2- renamed"); cycleJson.setDescription("Updated description"); Response response = zapiService.updateCycle(basicAuth, cycleJson.toString()); Assert.assertNotNull(response, "Update Cycle description Api Response is null."); test.log(LogStatus.PASS, "Update Cycle description Api executed successfully."); boolean status = zapiService.validateUpdateCycleApi(response); System.out.println("Update cycle successful"); Assert.assertTrue(status, "Response Validation Failed."); test.log(LogStatus.PASS, "Response validated suuccessfully."); extentReport.endTest(test); } // Update cycle - add sprintId @Test(priority = 26) public void bvt26_updateCyclesprintid() { ExtentTest test = extentReport.startTest(Thread.currentThread().getStackTrace()[1].getMethodName()); test.assignCategory("Automation API BVT Suite - Zapi"); Cycle cycleJson = new Cycle(); cycleJson.setProjectId(Long.parseLong(Config.getValue("project1Id"))); cycleJson.setVersionId(Long.parseLong(Config.getValue("version1Id"))); cycleJson.setName("Cycle created through API"); Response response = zapiService.createCycle(basicAuth, cycleJson.toString()); Assert.assertNotNull(response, "Create Cycle Api Response is null."); test.log(LogStatus.PASS, "Create Cycle Api executed successfully."); boolean status = zapiService.validateCreateCycleApi(response); Assert.assertTrue(status, "Response Validation Failed."); test.log(LogStatus.PASS, "Response validated successfully."); cycleId2 = new JSONObject(response.body().asString()).get("id").toString(); Cycle cycleJson1 = new Cycle(); cycleJson1.setProjectId(Long.parseLong(Config.getValue("project1Id"))); cycleJson1.setVersionId(Long.parseLong(Config.getValue("version1Id"))); cycleJson1.setId(cycleId2); cycleJson1.setDescription("Cycle Updated with SprintId"); cycleJson1.setSprintId(Long.parseLong(Config.getValue("sprintId"))); Response response1 = zapiService.updateCycle(basicAuth, cycleJson1.toString()); Assert.assertNotNull(response1, "Update Cycle with sprintid Api Response is null."); test.log(LogStatus.PASS, "Update Cycle with sprintid Api executed successfully."); boolean status1 = zapiService.validateUpdateCycleApi(response1); Assert.assertTrue(status1, "Response Validation Failed."); test.log(LogStatus.PASS, "Response validated suuccessfully."); extentReport.endTest(test); } // Get cycles by project id @Test(priority = 27) public void bvt27_getCycles() { ExtentTest test = extentReport.startTest(Thread.currentThread().getStackTrace()[1].getMethodName()); test.assignCategory("Automation API BVT Suite - Zapi"); Long projectId = Long.parseLong(Config.getValue("project1Id")); Response response = zapiService.getCycles(basicAuth, projectId); Assert.assertNotNull(response, "Api Response is null."); test.log(LogStatus.PASS, "Get cycle by projectId Api Response is null."); System.out.println(response.getBody().asString()); boolean status = zapiService.validateGetCycles(response); Assert.assertTrue(status, "Response Validation Failed."); test.log(LogStatus.PASS, "Response validated suuccessfully."); extentReport.endTest(test); } // Get cycle by id if linked to a sprint @Test(priority = 28) public void bvt28_getCycle() { ExtentTest test = extentReport.startTest(Thread.currentThread().getStackTrace()[1].getMethodName()); test.assignCategory("Automation API BVT Suite - Zapi"); String cycleId = cycleId2; Response response = zapiService.getCycle(basicAuth, cycleId); Assert.assertNotNull(response, "Getcycle Api Response is null."); test.log(LogStatus.PASS, "Getcycle Api executed successfully."); System.out.println(response.getBody().asString()); boolean status = zapiService.validateGetCycle(response); Assert.assertTrue(status, "Response Validation Failed."); test.log(LogStatus.PASS, "Response validated suuccessfully."); extentReport.endTest(test); } // Get cyclesbyVersionAndSprint, if multiple cycles from different versions are linked to sprint @Test(priority = 29) public void bvt29_getCyclesbyVersionAndSprint() { ExtentTest test = extentReport.startTest(Thread.currentThread().getStackTrace()[1].getMethodName()); test.assignCategory("Automation API BVT Suite - zapi"); Cycle cycleJson = new Cycle(); cycleJson.setProjectId(Long.parseLong(Config.getValue("project1Id"))); cycleJson.setVersionId(Long.parseLong(Config.getValue("version1Id"))); cycleJson.setSprintId(Long.parseLong(Config.getValue("sprintId"))); Response response = zapiService.cyclesByVersionAndSprint(basicAuth, cycleJson.toString()); Assert.assertNotNull(response, "cyclesbyversionAndsprint Api Response is null."); test.log(LogStatus.PASS, "cyclesbyversionAndsprint Api executed successfully."); System.out.println(response.getBody().asString()); boolean status = zapiService.validateGetCyclesbyVersionAndSprint(response); Assert.assertTrue(status, "Response Validation Failed."); test.log(LogStatus.PASS, "Response validated successfully."); extentReport.endTest(test); } // Cleanup sprint @Test(priority = 30) public void bvt30_cleanupsprint() { ExtentTest test = extentReport.startTest(Thread.currentThread().getStackTrace()[1].getMethodName()); test.assignCategory("Automation API BVT Suite - zapi"); Response response = zapiService.cleanupSprint(basicAuth); Assert.assertNotNull(response, "Cleanupsprint Api Response is null."); test.log(LogStatus.PASS, "Cleanupsprint Api executed successfully."); boolean status = zapiService.validateCleanupCycle(response); Assert.assertTrue(status, "Response Validation Failed."); test.log(LogStatus.PASS, "Response validated successfully."); extentReport.endTest(test); } // Create execution with no assignment under planned cycle @Test(priority = 31) public void bvt31_createExecution() { ExtentTest test = extentReport.startTest(Thread.currentThread().getStackTrace()[1].getMethodName()); test.assignCategory("Automation API BVT Suite - zapi"); Issue issuePayLoad = new Issue(); issuePayLoad.setProject(Config.getValue("project1Id")); issuePayLoad.setIssuetype(Config.getValue("issueTypeTestId")); issuePayLoad.setSummary("Test"); issuePayLoad.setPriority("3"); issuePayLoad.setReporter(Config.getValue("adminUserName")); Response response = jiraService.createIssue(basicAuth, issuePayLoad.toString()); Assert.assertNotNull(response, "Create Issue Api Response is null."); issueId = new JSONObject(response.body().asString()).getLong("id"); System.out.println("test id is :" + issueId); Cycle cycleJson = new Cycle(); cycleJson.setProjectId(Long.parseLong(Config.getValue("project1Id"))); cycleJson.setVersionId(-1l); cycleJson.setName("Cycle created through API"); Response response1 = zapiService.createCycle(basicAuth, cycleJson.toString()); Assert.assertNotNull(response1, "Create Cycle Api Response is null."); cycleId = new JSONObject(response1.body().asString()).get("id").toString(); System.out.println("Cycle id:" +cycleId); Execution json = new Execution(); json.setIssueId(issueId); json.setProjectId(Long.parseLong(Config.getValue("project1Id"))); json.setVersionId(-1l); json.setCycleId(cycleId); payload = json.toString(); Response response2 = zapiService.createExecution(basicAuth, payload); System.out.println(response2.getBody().asString()); Assert.assertNotNull(response2, "Cleanupsprint Api Response is null."); test.log(LogStatus.PASS, "Cleanupsprint Api executed successfully."); boolean status = zapiService.validateCreateExecution(response2); Assert.assertTrue(status, "Response Validation Failed."); test.log(LogStatus.PASS, "Response validated successfully."); extentReport.endTest(test); } //Create execution with assignee as current user under planned cycle @Test(priority = 32) public void bvt32_createExecution() { ExtentTest test = extentReport.startTest(Thread.currentThread().getStackTrace()[1].getMethodName()); test.assignCategory("Automation API BVT Suite - zapi"); Issue issuePayLoad = new Issue(); issuePayLoad.setProject(Config.getValue("project1Id")); issuePayLoad.setIssuetype(Config.getValue("issueTypeTestId")); issuePayLoad.setSummary("Test"); issuePayLoad.setPriority("3"); issuePayLoad.setReporter(Config.getValue("adminUserName")); Response response = jiraService.createIssue(basicAuth, issuePayLoad.toString()); Assert.assertNotNull(response, "Create Issue Api Response is null."); issueId = new JSONObject(response.body().asString()).getLong("id"); System.out.println("test id is :" + issueId); Cycle cycleJson = new Cycle(); cycleJson.setProjectId(Long.parseLong(Config.getValue("project1Id"))); cycleJson.setVersionId(Long.parseLong(Config.getValue("version1Id"))); cycleJson.setName("Cycle created through API"); Response response1 = zapiService.createCycle(basicAuth, cycleJson.toString()); Assert.assertNotNull(response1, "Create Cycle Api Response is null."); cycleId = new JSONObject(response1.body().asString()).get("id").toString(); System.out.println("Cycle id:" +cycleId); Execution json = new Execution(); json.setIssueId(issueId); json.setProjectId(Long.parseLong(Config.getValue("project1Id"))); json.setVersionId(Long.parseLong(Config.getValue("version1Id"))); json.setCycleId(cycleId); json.setAssigneeType("currentUser"); payload = json.toString(); Response response2 = zapiService.createExecution(basicAuth, payload); System.out.println(response2.getBody().asString()); Assert.assertNotNull(response2, "Cleanupsprint Api Response is null."); test.log(LogStatus.PASS, "Cleanupsprint Api executed successfully."); boolean status = zapiService.validateCreateExecution(response2); Assert.assertTrue(status, "Response Validation Failed."); test.log(LogStatus.PASS, "Response validated successfully."); extentReport.endTest(test); } //Create execution with assignee as another user under planned cycle @Test(priority = 33) public void bvt33_createExecution() { ExtentTest test = extentReport.startTest(Thread.currentThread().getStackTrace()[1].getMethodName()); test.assignCategory("Automation API BVT Suite - zapi"); Issue issuePayLoad = new Issue(); issuePayLoad.setProject(Config.getValue("project1Id")); issuePayLoad.setIssuetype(Config.getValue("issueTypeTestId")); issuePayLoad.setSummary("Test"); issuePayLoad.setPriority("3"); issuePayLoad.setReporter(Config.getValue("adminUserName")); Response response = jiraService.createIssue(basicAuth, issuePayLoad.toString()); Assert.assertNotNull(response, "Create Issue Api Response is null."); issueId = new JSONObject(response.body().asString()).getLong("id"); System.out.println("test id is :" + issueId); Cycle cycleJson = new Cycle(); cycleJson.setProjectId(Long.parseLong(Config.getValue("project1Id"))); cycleJson.setVersionId(Long.parseLong(Config.getValue("version1Id"))); cycleJson.setName("Cycle created through API- yyyvdx"); Response response1 = zapiService.createCycle(basicAuth, cycleJson.toString()); Assert.assertNotNull(response1, "Create Cycle Api Response is null."); cycleId = new JSONObject(response1.body().asString()).get("id").toString(); System.out.println("Cycle id:" +cycleId); Execution json = new Execution(); json.setIssueId(issueId); json.setProjectId(Long.parseLong(Config.getValue("project1Id"))); json.setVersionId(Long.parseLong(Config.getValue("version1Id"))); json.setCycleId(cycleId); json.setAssignee(Config.getValue("jiraUserName")); json.setAssigneeType("assignee"); payload = json.toString(); Response response2 = zapiService.createExecution(basicAuth, payload); System.out.println(response2.getBody().asString()); Assert.assertNotNull(response2, "Cleanupsprint Api Response is null."); test.log(LogStatus.PASS, "Cleanupsprint Api executed successfully."); boolean status = zapiService.validateCreateExecution(response2); Assert.assertTrue(status, "Response Validation Failed."); test.log(LogStatus.PASS, "Response validated successfully."); extentReport.endTest(test); } //Get search filters by keywords @Test(priority=34) public void bvt41_getSearchFilter() { ExtentTest test = extentReport.startTest(Thread.currentThread().getStackTrace()[1].getMethodName()); test.assignCategory("ZAPI Server BVT Suite"); String query = "filter1"; Response response = zapiService.searchFilter(basicAuth, query); System.out.println(response.getBody().asString()); boolean status = zapiService.validateSearchFilter(response); Assert.assertTrue(status, "Response Validation Failed."); test.log(LogStatus.PASS, "Response validated successfully."); extentReport.endTest(test); } //Add individual test to cycle without assignee @Test(priority = 35) public void bvt42_addTestsToAdhocCycle() { ExtentTest test = extentReport.startTest(Thread.currentThread().getStackTrace()[1].getMethodName()); test.assignCategory("ZAPI Server BVT Suite"); Execution executionJson = new Execution(); List<String> values = new ArrayList<String>(); values.add("PROJ1-3"); values.add("PROJ1-4"); executionJson.setIssues(values); executionJson.setProjectId(Long.parseLong(Config.getValue("project1Id"))); executionJson.setVersionId(-1l); executionJson.setCycleId("-1"); executionJson.setMethod(1); Response response1 = zapiService.addTestsToCycle(basicAuth, executionJson.toString()); System.out.println("Add tests to cycle successful"); System.out.println(response1.getBody().asString()); String jobProgressToken = new JSONObject(response1.getBody().asString()).getString("jobProgressToken"); Response response6 = zapiService.jobprogress(basicAuth, jobProgressToken); boolean status = zapiService.validateAddTestsToCycle(response6); Assert.assertTrue(status, "Response Validation Failed."); test.log(LogStatus.PASS, "Response validated successfully."); extentReport.endTest(test); } //Add individual test to cycle with assignee as current user @Test(priority = 36) public void bvt43_addTestsToCycle() { ExtentTest test = extentReport.startTest(Thread.currentThread().getStackTrace()[1].getMethodName()); test.assignCategory("ZAPI Server BVT Suite"); Cycle cycleJson = new Cycle(); cycleJson.setProjectId(Long.parseLong(Config.getValue("project1Id"))); cycleJson.setVersionId(Long.parseLong(Config.getValue("version1Id"))); cycleJson.setName("Cycle created through API3"); Response response = zapiService.createCycle(basicAuth, cycleJson.toString()); Assert.assertNotNull(response, "Create Cycle Api Response is null."); cycleId3 = new JSONObject(response.body().asString()).get("id").toString(); System.out.println("cycle id is" + cycleId3); Execution executionJson = new Execution(); List<String> values = new ArrayList<String>(); values.add("PROJ1-5"); values.add("PROJ1-6"); executionJson.setIssues(values); executionJson.setProjectId(Long.parseLong(Config.getValue("project1Id"))); executionJson.setVersionId(Long.parseLong(Config.getValue("version1Id"))); executionJson.setCycleId(cycleId3); executionJson.setMethod(1); executionJson.setAssigneeType("currentUser"); Response response1 = zapiService.addTestsToCycle(basicAuth, executionJson.toString()); System.out.println("Add tests to cycle successful"); boolean status = zapiService.validateAddTestsToCycle(response1); Assert.assertTrue(status, "Response Validation Failed."); test.log(LogStatus.PASS, "Response validated successfully."); extentReport.endTest(test); return; } //Add individual test to cycle with assignee as another user @Test(priority = 37) public void bvt44_addTestsToScheduleCycle() { ExtentTest test = extentReport.startTest(Thread.currentThread().getStackTrace()[1].getMethodName()); test.assignCategory("ZAPI Server BVT Suite"); Execution executionJson = new Execution(); List<String> values= new ArrayList<String>(); values.add("PROJ1-7"); values.add("PROJ1-8"); executionJson.setIssues(values); executionJson.setProjectId(Long.parseLong(Config.getValue("project1Id"))); executionJson.setVersionId(Long.parseLong(Config.getValue("version1Id"))); executionJson.setCycleId(cycleId3); executionJson.setAssignee(Config.getValue("jiraUserName")); executionJson.setAssigneeType("assignee"); Response response = zapiService.addTestsToCycle(basicAuth, executionJson.toString()); System.out.println("Add tests to cycle successful"); boolean status = zapiService.validateAddTestsToCycle(response); Assert.assertTrue(status, "Response Validation Failed."); test.log(LogStatus.PASS, "Response validated successfully."); extentReport.endTest(test); } //Get executions by param cycleId (Ad hoc) @Test(priority = 38) public void bvt45_getExecutionsByCycleId() { ExtentTest test = extentReport.startTest(Thread.currentThread().getStackTrace()[1].getMethodName()); test.assignCategory("ZAPI Server BVT Suite"); long projectId = Long.parseLong(Config.getValue("project1Id")); long versionId = -1l; String cycleId = "-1"; Response response = zapiService.getExecutionsByCycle(basicAuth, projectId, versionId, cycleId); System.out.println(response.getBody().asString()); id1 = (new JSONObject(response.body().asString()).getJSONArray("executions").getJSONObject(0).get("id")).toString(); System.out.println("Execution id:" +id1); boolean status = zapiService.validateExecuteSearch(response); Assert.assertTrue(status, "Response Validation Failed."); test.log(LogStatus.PASS, "Response validated successfully."); extentReport.endTest(test); } //Get execution by id @Test(priority = 39) public void bvt46_getExecutionsById() { ExtentTest test = extentReport.startTest(Thread.currentThread() .getStackTrace()[1].getMethodName()); test.assignCategory("ZAPI Server BVT Suite"); //String executionId1 = "1"; Response response = zapiService.getExecutionByExecutionId(basicAuth, id1); System.out.println(response.getBody().asString()); System.out.println("Get executions by Id api executed successful"); boolean status = zapiService.validateGetExecutionById(response); Assert.assertTrue(status, "Response Validation Failed."); test.log(LogStatus.PASS, "Response validated successfully."); extentReport.endTest(test); } //Execute test to standard status (Pass) @Test(priority = 40) public void bvt34_executeTest() { ExtentTest test = extentReport.startTest(Thread.currentThread().getStackTrace()[1].getMethodName()); test.assignCategory("ZAPI Server BVT Suite"); String id = id1; System.out.println(id); Execution json = new Execution(); json.setStatusId(1); payload = json.toString(); System.out.println(payload); Response response = zapiService.executeTest(basicAuth, id, payload ); System.out.println(response.getBody().asString()); boolean status = zapiService.validateExecuteTest(response, executionId1); Assert.assertTrue(status, "Response Validation Failed."); test.log(LogStatus.PASS, "Response validated successfully."); extentReport.endTest(test); } //Search executions by zql query (executionStatus, project) @Test(priority = 41) public void bvt35_executeSearch() { ExtentTest test = extentReport.startTest(Thread.currentThread().getStackTrace()[1].getMethodName()); test.assignCategory("ZAPI Server BVT Suite"); String zqlQuery = "project = Project1 AND executionStatus = PASS"; Response response = zapiService.executeSearch(basicAuth, zqlQuery); System.out.println(response.getBody().asString()); boolean status = zapiService.validateExecuteSearch(response); Assert.assertTrue(status, "Response Validation Failed."); test.log(LogStatus.PASS, "Response validated successfully."); extentReport.endTest(test); } //Get executions by param cycleId (planned) @Test(priority = 42) public void bvt38_getExecutionsByCycleId() { ExtentTest test = extentReport.startTest(Thread.currentThread() .getStackTrace()[1].getMethodName()); test.assignCategory("ZAPI Server BVT Suite"); long projectId = Long.parseLong(Config.getValue("project1Id")); long versionId = Long.parseLong(Config.getValue("version1Id")); String cycleId =cycleId3; System.out.println("cycleId3::"+cycleId); Response response = zapiService.getExecutionsByCycle(basicAuth,projectId, versionId, cycleId); executionId1 = new JSONObject(response.getBody().asString()).getJSONArray("executions").getJSONObject(0).get("id").toString(); System.out.println("ExecutionId is:" +executionId1); System.out.println("Get executions by cycleId Api executed successful"); boolean status = zapiService.validateGetExecutions(response); Assert.assertTrue(status, "Response Validation Failed."); test.log(LogStatus.PASS, "Response validated successfully."); extentReport.endTest(test); } //Export cycle as CSV, partially executed with defects and execution comments @Test(priority = 43) public void bvt40_exportCycle() { ExtentTest test = extentReport.startTest(Thread.currentThread().getStackTrace()[1].getMethodName()); test.assignCategory("ZAPI Server BVT Suite"); Cycle cycleJson = new Cycle(); cycleJson.setProjectId(Long.parseLong(Config.getValue("project1Id"))); cycleJson.setVersionId(Long.parseLong(Config.getValue("version5Id"))); cycleJson.setName("Cycle created through API1"); Response response = zapiService.createCycle(basicAuth, cycleJson.toString()); Assert.assertNotNull(response, "Create Cycle Api Response is null."); cycleId6 = new JSONObject(response.body().asString()).get("id").toString(); System.out.println("cycle id is" + cycleId6); Execution executionJson = new Execution(); executionJson.setProjectId(10000l); executionJson.setVersionId(10001l); executionJson.setCycleId(cycleId6); executionJson.setMethod(2); executionJson.setSearchId(10002l); Response response1 = zapiService.addTestsToCycle(basicAuth, executionJson.toString()); System.out.println("Add tests to cycle is successful."); long projectId = Long.parseLong(Config.getValue("project1Id")); long versionId = Long.parseLong(Config.getValue("version5Id")); String cycleId =cycleId6; Response response2 = zapiService.getExecutionsByCycle(basicAuth,projectId, versionId, cycleId); executionId1 = new JSONObject(response2.getBody().asString()).getJSONArray("executions").getJSONObject(0).get("id").toString(); executionId2 = new JSONObject(response2.getBody().asString()).getJSONArray("executions").getJSONObject(1).get("id").toString(); System.out.println("ExecutionId1 is:" +executionId1); System.out.println("ExecutionId2 is:" +executionId2); String id = executionId1; System.out.println(id); Execution json = new Execution(); json.setStatusId(1); json.setComment("Comment added"); List<String> values = new ArrayList<>(); values.add("PROJ1-41"); json.setDefectList(values); json.setUpdateDefectList("true"); payload = json.toString(); Response response3 = zapiService.executeTest(basicAuth, id, payload ); System.out.println(response3.getBody().asString()); Response response4 = zapiService.exportCycle(basicAuth, cycleId,projectId,versionId ); System.out.println(response4.getBody().asString()); boolean status = zapiService.validateExportCycle(response4); Assert.assertTrue(status, "Response Validation Failed."); test.log(LogStatus.PASS, "Response validated successfully."); extentReport.endTest(test); } //Delete execution @Test(priority = 44) public void bvt47_deleteExecution() { ExtentTest test = extentReport.startTest(Thread.currentThread() .getStackTrace()[1].getMethodName()); test.assignCategory("ZAPI Server BVT Suite"); String executionId = executionId1; Response response = zapiService.deleteExecution(basicAuth, executionId); System.out.println("Delete executionApi executed successful"); System.out.println(response.getBody().asString()); boolean status = zapiService.validatedeleteExecution(response); Assert.assertTrue(status, "Response Validation Failed."); test.log(LogStatus.PASS, "Response validated successfully."); extentReport.endTest(test); } //Delete cycle by id @Test(priority = 45) public void bvt39_deleteCycle() { ExtentTest test = extentReport.startTest(Thread.currentThread().getStackTrace()[1].getMethodName()); test.assignCategory("ZAPI Server BVT Suite"); String cycleId = cycleId6; Response response = zapiService.deleteCycle(basicAuth, cycleId ); System.out.println(response.getBody().asString()); boolean status = zapiService.validateDeletedCycle(response); Assert.assertTrue(status, "Response Validation Failed."); test.log(LogStatus.PASS, "Response validated successfully."); extentReport.endTest(test); } //Copy multiple executions from one cycle to adhoc cycle, and clear statuses and defects @Test(priority = 46) public void bvt36_copyExecutions() { ExtentTest test = extentReport.startTest(Thread.currentThread().getStackTrace()[1].getMethodName()); test.assignCategory("ZAPI Server BVT Suite"); Cycle cycleJson = new Cycle(); cycleJson.setProjectId(Long.parseLong(Config.getValue("project1Id"))); cycleJson.setVersionId(Long.parseLong(Config.getValue("version1Id"))); cycleJson.setName("Cycle created through API6"); Response response = zapiService.createCycle(basicAuth, cycleJson.toString()); cycleId = new JSONObject(response.body().asString()).get("id").toString(); Execution executionJson = new Execution(); executionJson.setProjectId(Long.parseLong(Config.getValue("project1Id"))); executionJson.setVersionId(Long.parseLong(Config.getValue("version1Id"))); executionJson.setCycleId(cycleId); executionJson.setMethod(2); executionJson.setSearchId(10002l); Response response1 = zapiService.addTestsToCycle(basicAuth, executionJson.toString()); System.out.println("Successful:" + response1.getBody().asString()); long projectId = Long.parseLong(Config.getValue("project1Id")); long versionId = Long.parseLong(Config.getValue("version1Id")); Response response2 = zapiService.getExecutionsByCycle(basicAuth,projectId, versionId, cycleId); System.out.println(response2.getBody().asString()); executionId7 = new JSONObject(response2.getBody().asString()).getJSONArray("executions").getJSONObject(0).get("id").toString(); executionId8 = new JSONObject(response2.getBody().asString()).getJSONArray("executions").getJSONObject(1).get("id").toString(); BulkExecution execJson = new BulkExecution(); List<String> list = new ArrayList<>(); list.add(executionId7); list.add(executionId8); execJson.setExecutions(list); execJson.setStatus("3"); System.out.println(execJson); Response response3 = zapiService.bulkUpdateStatus(basicAuth, execJson.toString()); List<String> list1 = new ArrayList<>(); list1.add(executionId7); list1.add(executionId8); List<String> list2 = new ArrayList<>(); list2.add("PROJ2-1"); list2.add("PROJ2-2"); BulkExecution execJson1 = new BulkExecution(); execJson1.setExecutions(list1); execJson1.setDefects(list2); Response response4 = zapiService.bulkUpdateDefects(basicAuth, execJson1.toString()); List<String> list3 = new ArrayList<>(); list3.add(executionId7); list3.add(executionId8); BulkExecution json2 = new BulkExecution(); json2.setExecutions(list3); json2.setProjectId(Config.getValue("project1Id")); json2.setVersionId("-1"); json2.setClearAssignmentsFlag(false); json2.setClearStatusFlag(true); json2.setClearDefectMappingFlag(true); String payload = json2.toString(); int cycleId1 = -1; Response response5 = zapiService.copyExecutions(basicAuth, cycleId1, payload); String jobProgressToken = new JSONObject(response5.getBody().asString()).getString("jobProgressToken"); Response response6 = zapiService.jobprogress(basicAuth, jobProgressToken); boolean status = zapiService.validateCopyExecutions(response6); Assert.assertTrue(status, "Response Validation Failed."); test.log(LogStatus.PASS, "Response validated successfully."); extentReport.endTest(test); } //Move executions from another cycle to planned cycle, without clearing statuses and defects @Test(priority = 47) public void bvt37_moveExecutions() { ExtentTest test = extentReport.startTest(Thread.currentThread().getStackTrace()[1].getMethodName()); test.assignCategory("ZAPI Server BVT Suite"); Cycle cycleJson = new Cycle(); cycleJson.setProjectId(Long.parseLong(Config.getValue("project1Id"))); cycleJson.setVersionId(Long.parseLong(Config.getValue("version2Id"))); cycleJson.setName("Cycle created through API7"); Response response = zapiService.createCycle(basicAuth, cycleJson.toString()); String cycleId = new JSONObject(response.body().asString()).get("id").toString(); List<String> list3 = new ArrayList<>(); list3.add(executionId7); list3.add(executionId8); BulkExecution json2 = new BulkExecution(); json2.setExecutions(list3); json2.setProjectId(Config.getValue("project1Id")); json2.setVersionId(Config.getValue("version2Id")); json2.setClearAssignmentsFlag(false); json2.setClearStatusFlag(false); json2.setClearDefectMappingFlag(false); String payload = json2.toString(); int cycleId1 = Integer.parseInt(cycleId); Response response5 = zapiService.moveExecutions(basicAuth, cycleId1, payload); System.out.println(response5.getBody().asString()); String jobProgressToken = new JSONObject(response5.getBody().asString()).getString("jobProgressToken"); Response response6 = zapiService.jobprogress(basicAuth, jobProgressToken); boolean status = zapiService.validateMoveExecutions(response6); Assert.assertTrue(status, "Response Validation Failed."); test.log(LogStatus.PASS, "Response validated successfully."); extentReport.endTest(test); } //Add tests from search filter without assignment @Test(priority = 48) public void bvt48_addTestsFromSearchFilter() { ExtentTest test = extentReport.startTest(Thread.currentThread().getStackTrace()[1].getMethodName()); test.assignCategory("ZAPI Server BVT Suite"); Execution executionJson = new Execution(); executionJson.setProjectId(Long.parseLong(Config.getValue("project1Id"))); executionJson.setVersionId(-1l); executionJson.setCycleId("-1"); executionJson.setMethod(2); executionJson.setSearchId(10002l); Response response = zapiService.addTestsToCycle(basicAuth, executionJson.toString()); System.out.println("Successful:" + response.getBody().asString()); boolean status = zapiService.validateAddTestsToCycle(response); Assert.assertTrue(status, "Response Validation Failed."); test.log(LogStatus.PASS, "Response validated successfully."); extentReport.endTest(test); } //Add tests from search filter with assignee as current user @Test(priority = 49) public void bvt49_addTestsFromSearchFilter() { ExtentTest test = extentReport.startTest(Thread.currentThread().getStackTrace()[1].getMethodName()); test.assignCategory("ZAPI Server BVT Suite"); Cycle cycleJson = new Cycle(); cycleJson.setProjectId(Long.parseLong(Config.getValue("project1Id"))); cycleJson.setVersionId(Long.parseLong(Config.getValue("version1Id"))); cycleJson.setName("Cycle created through API3"); Response response = zapiService.createCycle(basicAuth, cycleJson.toString()); Assert.assertNotNull(response, "Create Cycle Api Response is null."); cycleId4 = new JSONObject(response.body().asString()).get("id").toString(); System.out.println("cycle id is" + cycleId4); Execution executionJson = new Execution(); executionJson.setProjectId(Long.parseLong(Config.getValue("project1Id"))); executionJson.setVersionId(Long.parseLong(Config.getValue("version1Id"))); executionJson.setCycleId(cycleId4); executionJson.setMethod(2); executionJson.setSearchId(10002l); executionJson.setAssigneeType("currentUser"); Response response1 = zapiService.addTestsToCycle(basicAuth, executionJson.toString()); System.out.println(response1.getBody().asString()); System.out.println("Add tests to cycle from search filter is successful"); boolean status = zapiService.validateAddTestsToCycle(response1); Assert.assertTrue(status, "Response Validation Failed."); test.log(LogStatus.PASS, "Response validated successfully."); extentReport.endTest(test); } //Add tests from search filter with assignee as another user @Test(priority = 50) public void bvt50_addTestsFromSearchFilter() { ExtentTest test = extentReport.startTest(Thread.currentThread().getStackTrace()[1].getMethodName()); test.assignCategory("ZAPI Server BVT Suite"); Cycle cycleJson = new Cycle(); cycleJson.setProjectId(Long.parseLong(Config.getValue("project1Id"))); cycleJson.setVersionId(Long.parseLong(Config.getValue("version1Id"))); cycleJson.setName("Cycle created through API4"); Response response = zapiService.createCycle(basicAuth, cycleJson.toString()); Assert.assertNotNull(response, "Create Cycle Api Response is null."); cycleId5 = new JSONObject(response.body().asString()).get("id").toString(); System.out.println("cycle id is" + cycleId5); Execution executionJson = new Execution(); executionJson.setProjectId(Long.parseLong(Config.getValue("project1Id"))); executionJson.setVersionId(Long.parseLong(Config.getValue("version1Id"))); executionJson.setCycleId(cycleId5); executionJson.setMethod(2); executionJson.setSearchId(10002l); executionJson.setAssignee(Config.getValue("jiraUserName")); executionJson.setAssigneeType("assignee"); Response response1 = zapiService.addTestsToCycle(basicAuth, executionJson.toString()); System.out.println(response1.getBody().asString()); System.out.println("Add tests to cycle from search filter is successful"); boolean status = zapiService.validateAddTestsToCycle(response1); Assert.assertTrue(status, "Response Validation Failed."); test.log(LogStatus.PASS, "Response validated successfully."); extentReport.endTest(test); } //Add tests from another cycle without assignment @Test(priority = 51) public void bvt51_addTestsFromOtherCycle() { ExtentTest test = extentReport.startTest(Thread.currentThread().getStackTrace()[1].getMethodName()); test.assignCategory("ZAPI Server BVT Suite"); Execution executionJson = new Execution(); executionJson.setProjectId(Long.parseLong(Config.getValue("project1Id"))); executionJson.setVersionId(Long.parseLong(Config.getValue("version1Id"))); executionJson.setCycleId("-1"); executionJson.setMethod(3); executionJson.setFromCycleId("-1"); executionJson.setFromVersionId(-1l); Response response = zapiService.addTestsToCycle(basicAuth, executionJson.toString()); System.out.println(response.getBody().asString()); System.out.println("Add tests to cycle from another cycle is successful"); boolean status = zapiService.validateAddTestsToCycle(response); Assert.assertTrue(status, "Response Validation Failed."); test.log(LogStatus.PASS, "Response validated successfully."); extentReport.endTest(test); } //Add tests from another cycle with assignee as current user @Test(priority = 52) public void bvt52_addTestsFromOtherCycle() { ExtentTest test = extentReport.startTest(Thread.currentThread().getStackTrace()[1].getMethodName()); test.assignCategory("ZAPI Server BVT Suite"); Execution executionJson = new Execution(); executionJson.setProjectId(Long.parseLong(Config.getValue("project1Id"))); executionJson.setVersionId(Long.parseLong(Config.getValue("version2Id"))); executionJson.setCycleId("-1"); executionJson.setMethod(3); executionJson.setFromCycleId(cycleId4); executionJson.setFromVersionId(Long.parseLong(Config.getValue("version1Id"))); executionJson.setAssigneeType("currentUser"); System.out.println(executionJson); Response response = zapiService.addTestsToCycle(basicAuth, executionJson.toString()); System.out.println(response.getBody().asString()); System.out.println("Add tests to cycle from another cycle is successful"); boolean status = zapiService.validateAddTestsToCycle(response); Assert.assertTrue(status, "Response Validation Failed."); test.log(LogStatus.PASS, "Response validated successfully."); extentReport.endTest(test); } //Add tests from another cycle with assignee as another user @Test(priority = 53) public void bvt53_addTestsFromOtherCycle() { ExtentTest test = extentReport.startTest(Thread.currentThread() .getStackTrace()[1].getMethodName()); test.assignCategory("ZAPI Server BVT Suite"); Cycle cycleJson = new Cycle(); cycleJson.setProjectId(Long.parseLong(Config.getValue("project1Id"))); cycleJson.setVersionId(Long.parseLong(Config.getValue("version2Id"))); cycleJson.setName("Cycle created through API5"); Response response = zapiService.createCycle(basicAuth, cycleJson.toString()); Assert.assertNotNull(response, "Create Cycle Api Response is null."); cycleId1 = new JSONObject(response.body().asString()).get("id").toString(); System.out.println("cycle id is" + cycleId1); Execution executionJson = new Execution(); executionJson.setProjectId(Long.parseLong(Config.getValue("project1Id"))); executionJson.setVersionId(Long.parseLong(Config.getValue("version2Id"))); executionJson.setCycleId(cycleId1); executionJson.setMethod(3); executionJson.setFromCycleId(cycleId5); executionJson.setFromVersionId(Long.parseLong(Config.getValue("version1Id"))); executionJson.setAssignee("jira_user"); executionJson.setAssigneeType("assignee"); System.out.println(executionJson); Response response1 = zapiService.addTestsToCycle(basicAuth, executionJson.toString()); System.out.println(response1.getBody().asString()); System.out.println("Add tests to cycle from another cycle is successful"); boolean status = zapiService.validateAddTestsToCycle(response1); Assert.assertTrue(status, "Response Validation Failed."); test.log(LogStatus.PASS, "Response validated successfully."); extentReport.endTest(test); } // Bulkupdate status @Test(priority = 54) public void bvt54_BulkUpdateStatus() { ExtentTest test = extentReport.startTest(Thread.currentThread().getStackTrace()[1].getMethodName()); test.assignCategory("ZAPI Server BVT Suite"); Cycle cycleJson = new Cycle(); cycleJson.setProjectId(Long.parseLong(Config.getValue("project1Id"))); cycleJson.setVersionId(Long.parseLong(Config.getValue("version3Id"))); cycleJson.setName("Cycle created through API6"); Response response = zapiService.createCycle(basicAuth, cycleJson.toString()); Assert.assertNotNull(response, "Create Cycle Api Response is null."); cycleId1 = new JSONObject(response.body().asString()).get("id").toString(); System.out.println("cycle id is" + cycleId1); Execution executionJson = new Execution(); executionJson.setProjectId(Long.parseLong(Config.getValue("project1Id"))); executionJson.setVersionId(Long.parseLong(Config.getValue("version3Id"))); executionJson.setCycleId(cycleId1); executionJson.setMethod(2); executionJson.setSearchId(10002l); Response response1 = zapiService.addTestsToCycle(basicAuth, executionJson.toString()); System.out.println("Add tests to cycle is successful."); long projectId = Long.parseLong(Config.getValue("project1Id")); long versionId = Long.parseLong(Config.getValue("version3Id")); String cycleId =cycleId1; Response response2 = zapiService.getExecutionsByCycle(basicAuth,projectId, versionId, cycleId); executionId2 = new JSONObject(response2.getBody().asString()).getJSONArray("executions").getJSONObject(0).get("id").toString(); executionId3 = new JSONObject(response2.getBody().asString()).getJSONArray("executions").getJSONObject(1).get("id").toString(); System.out.println("ExecutionId1 is:" +executionId2); System.out.println("ExecutionId2 is:" +executionId3); BulkExecution execJson = new BulkExecution(); List<String> list = new ArrayList<>(); list.add(executionId2); list.add(executionId3); execJson.setExecutions(list); execJson.setStatus("1"); //execJson.setStepStatus(2); // execJson.setTestStepStatusChangeFlag(False); System.out.println(execJson); Response response3 = zapiService.bulkUpdateStatus(basicAuth, execJson.toString()); Assert.assertNotNull(response, "bulkupdate status Api Response is null."); test.log(LogStatus.PASS, "bulkupdate status Api executed successfully."); String jobProgressToken = new JSONObject(response3.getBody().asString()).getString("jobProgressToken"); //Job progress Response response4 = zapiService.jobprogress(basicAuth, jobProgressToken); boolean status1 = zapiService.validateBulkStatusUdate(response4); Assert.assertTrue(status1, "Response Validation Failed."); test.log(LogStatus.PASS, "Response validated successfully."); extentReport.endTest(test); } // Bulk assign executions to current user @Test(priority = 55) public void bvt55_BulkAssignCurrentuser() { ExtentTest test = extentReport.startTest(Thread.currentThread().getStackTrace()[1].getMethodName()); test.assignCategory("ZAPI Server BVT Suite"); List<String> list = new ArrayList<>(); list.add(executionId2); list.add(executionId3); BulkExecution execJson = new BulkExecution(); execJson.setExecutions(list); execJson.setAssigneeType("currentUser"); Response response = zapiService.bulkUpdateAssignee(basicAuth, execJson.toString()); Assert.assertNotNull(response, "bulkupdate status Api Response is null."); test.log(LogStatus.PASS, "bulkupdate status Api executed successfully."); String jobProgressToken = new JSONObject(response.getBody().asString()).getString("jobProgressToken"); Response response4 = zapiService.jobprogress(basicAuth, jobProgressToken); boolean status = zapiService.validateBulkUpdateAssignee(response4); test.log(LogStatus.PASS, "Response validated successfully."); extentReport.endTest(test); } // Bulk assign executions to another user @Test(priority = 56) public void bvt56_BulkAssignAnotherUser() { ExtentTest test = extentReport.startTest(Thread.currentThread().getStackTrace()[1].getMethodName()); test.assignCategory("ZAPI Server BVT Suite"); List<String> list = new ArrayList<>(); list.add(executionId2); list.add(executionId3); BulkExecution execJson = new BulkExecution(); execJson.setExecutions(list); execJson.setAssigneeType("assignee"); execJson.setAssignee(Config.getValue("jiraUserName")); Response response = zapiService.bulkUpdateAssignee(basicAuth, execJson.toString()); Assert.assertNotNull(response, "bulkupdate status Api Response is null."); test.log(LogStatus.PASS, "bulkupdate status Api executed successfully."); String jobProgressToken = new JSONObject(response.getBody().asString()).getString("jobProgressToken"); Response response4 = zapiService.jobprogress(basicAuth, jobProgressToken); boolean status = zapiService.validateBulkUpdateAssignee(response4); test.log(LogStatus.PASS, "Response validated successfully."); extentReport.endTest(test); } // Bulk unassign executions @Test(priority = 57) public void bvt57_BulkUnassign() { ExtentTest test = extentReport.startTest(Thread.currentThread().getStackTrace()[1].getMethodName()); test.assignCategory("ZAPI Server BVT Suite"); List<String> list = new ArrayList<>(); list.add(executionId2); list.add(executionId3); BulkExecution execJson = new BulkExecution(); execJson.setExecutions(list); Response response = zapiService.bulkUpdateAssignee(basicAuth, execJson.toString()); Assert.assertNotNull(response, "bulkupdate status Api Response is null."); test.log(LogStatus.PASS, "bulkupdate status Api executed successfully."); String jobProgressToken = new JSONObject(response.getBody().asString()).getString("jobProgressToken"); Response response4 = zapiService.jobprogress(basicAuth, jobProgressToken); boolean status = zapiService.validateBulkUpdateAssignee(response4); test.log(LogStatus.PASS, "Response validated successfully."); extentReport.endTest(test); } //Link multiple defects to multiple executions (2 defects link to 2 executions) @Test(priority = 58) public void bvt59_executionUpdateWithBulkDefects() { ExtentTest test = extentReport.startTest(Thread.currentThread().getStackTrace()[1].getMethodName()); test.assignCategory("ZAPI Server BVT Suite"); List<String> list = new ArrayList<>(); list.add("23"); List<String> list1 = new ArrayList<>(); list1.add("SAM-68"); list1.add("SAM-69"); BulkExecution execJson = new BulkExecution(); execJson.setExecutions(list); execJson.setDefects(list1); Response response = zapiService.bulkUpdateDefects(basicAuth, execJson.toString()); Assert.assertNotNull(response, "Response is null."); test.log(LogStatus.PASS, " execution Update With Bulk Defects executed successfully."); System.out.println("Response:" +response.body().asString()); if(StringUtils.isNotBlank(response.getBody().asString())) { String jobProgressToken = new JSONObject(response.getBody().asString()).getString("jobProgressToken"); Response response4 = zapiService.jobprogress(basicAuth, jobProgressToken); } // boolean status = zapiService.validateexecutionUpdateWithBulkDefect(response4); // Assert.assertTrue(status); // extentReport.endTest(test); } //Get defects by execution id @Test(priority = 59) public void bvt60_getDefectsByExecutionID() { ExtentTest test = extentReport.startTest(Thread.currentThread().getStackTrace()[1].getMethodName()); test.assignCategory("ZAPI Server BVT Suite"); String executionId = executionId2; Response response = zapiService.getDefectByExecution(basicAuth,executionId ); Assert.assertNotNull(response, "Update step Response is null."); test.log(LogStatus.PASS, "get Defects By ExecutionID executed successfully."); System.out.println("Defects linked to execution:" +response.body().asString()); boolean status = zapiService.validateGetDefectsByExecution(response); Assert.assertTrue(status); extentReport.endTest(test); } // Get executions by issue key/id @Test(priority = 60) public void bvt61_getExecutionsByIssueID() { ExtentTest test = extentReport.startTest(Thread.currentThread().getStackTrace()[1].getMethodName()); test.assignCategory("ZAPI Server BVT Suite"); Issue issuePayLoad = new Issue(); issuePayLoad.setProject(Config.getValue("project1Id")); issuePayLoad.setIssuetype(Config.getValue("issueTypeTestId")); issuePayLoad.setSummary("Story linked to Sprint"); issuePayLoad.setPriority("3"); issuePayLoad.setReporter(Config.getValue("adminUserName")); Response response = jiraService.createIssue(basicAuth, issuePayLoad.toString()); Assert.assertNotNull(response, "Create Issue Api Response is null."); issueId = new JSONObject(response.body().asString()).getLong("id"); Cycle cycleJson = new Cycle(); cycleJson.setProjectId(Long.parseLong(Config.getValue("project1Id"))); cycleJson.setVersionId(-1l); cycleJson.setName("Cycle created through API"); Response response1 = zapiService.createCycle(basicAuth, cycleJson.toString()); Assert.assertNotNull(response1, "Create Cycle Api Response is null."); String cycleId = new JSONObject(response1.body().asString()).get("id").toString(); Execution json = new Execution(); json.setIssueId(issueId); json.setProjectId(Long.parseLong(Config.getValue("project1Id"))); json.setVersionId(-1l); json.setCycleId(cycleId); payload = json.toString(); Response response2 = zapiService.createExecution(basicAuth, payload); long projectId = Long.parseLong(Config.getValue("project1Id")); long versionId = -1l; Response response3 = zapiService.getExecutionsByCycle(basicAuth, projectId, versionId, cycleId); String executionId = (new JSONObject(response3.body().asString()).getJSONArray("executions").getJSONObject(0).get("id")).toString(); Issue issuePayLoad1 = new Issue(); issuePayLoad1.setProject(Config.getValue("project1Id")); issuePayLoad1.setIssuetype(Config.getValue("issueTypeStoryId")); issuePayLoad1.setSummary("Issuetype-Story"); issuePayLoad1.setPriority("3"); issuePayLoad1.setReporter(Config.getValue("adminUserName")); Response response4 = jiraService.createIssue(basicAuth, issuePayLoad1.toString()); issueKey5 = new JSONObject(response4.getBody().asString()).getString("key"); List<String> values = new ArrayList<>(); values.add(issueKey5); Sprint json1 = new Sprint(); json1.setIdOrKeys(values); json1.setSprintId(1); payload = json1.toString(); Response response5 = jiraService.linkIssueToSprint(basicAuth, payload); List<String> val = new ArrayList<>(); val.add(issueKey5); String id = executionId; Execution json2 = new Execution(); json2.setStatusId(1); json2.setDefectList(val); json2.setUpdateDefectList("true"); payload = json2.toString(); Response response6 = zapiService.executeTest(basicAuth, id, payload ); String issueId = issueKey5; Response response7 = zapiService.getExecutionByIssue(basicAuth, issueId); Assert.assertNotNull(response, "Update step Response is null."); test.log(LogStatus.PASS, "get Defects By ExecutionID executed successfully."); System.out.println(response7.body().asString()); boolean status = zapiService.validateGetExecutionByIssueKey(response7); Assert.assertTrue(status); extentReport.endTest(test); } //Get execution summaries and defect count by sprint and issue Id @Test(priority = 61) public void bvt62_getExecutionsSummaryBySprintAndIssueID() { ExtentTest test = extentReport.startTest(Thread.currentThread().getStackTrace()[1].getMethodName()); test.assignCategory("ZAPI Server BVT Suite"); Execution json = new Execution(); json.setSprintId(1); json.setIssueIdOrKeys(issueKey5); System.out.println(json.toString()); Response response = zapiService.getExecutionsSummaryBySprintAndIssueId(basicAuth, json.toString()); Assert.assertNotNull(response, "Update step Response is null."); test.log(LogStatus.PASS, "get Defects By ExecutionID executed successfully."); System.out.println(response.body().asString()); boolean status = zapiService.validategetExecutionsSummaryBySprintAndIssueID(response); Assert.assertTrue(status); extentReport.endTest(test); } // Export execution @Test(priority = 62) public void bvt63_exportsExecutions() { ExtentTest test = extentReport.startTest(Thread.currentThread().getStackTrace()[1].getMethodName()); test.assignCategory("ZAPI Server BVT Suite"); String payLoad = "{\"exportType\": \"xls\", \"maxAllowedResult\": \"true\",\"expand\": \"teststeps\",\"startIndex\": \"0\",\"zqlQuery\": \"executionStatus != UNEXECUTED AND executedBy = vm_admin\"}"; Response response = zapiService.exportExecution(basicAuth, payLoad); Assert.assertNotNull(response, "Update step Response is null."); test.log(LogStatus.PASS, "get Defects By ExecutionID executed successfully."); System.out.println(response.body().asString()); boolean status = zapiService.validateExportExecutios(response); Assert.assertTrue(status); extentReport.endTest(test); } //Delete multiple executions @Test(priority = 63) public void bvt64_deleteMultipleExecutions() { ExtentTest test = extentReport.startTest(Thread.currentThread().getStackTrace()[1].getMethodName()); test.assignCategory("ZAPI Server BVT Suite"); Execution json = new Execution(); List<String> values = new ArrayList<String>(); values.add(executionId2); values.add(executionId3); json.setExecutions(values); System.out.println(json); Response response = zapiService.bulkDeleteExecutions(basicAuth, json.toString()); Assert.assertNotNull(response, "Delete multiple execution Response is null."); test.log(LogStatus.PASS, "Delete multiple executions executed successfully."); String jobProgressToken = new JSONObject(response.getBody().asString()).getString("jobProgressToken"); Response response6 = zapiService.jobprogress(basicAuth, jobProgressToken); boolean status = zapiService.validateDeleteExecution(response6); Assert.assertTrue(status); extentReport.endTest(test); } //Create test step result without setting status @Test(priority = 64) public void bvt65_createTestStepResultWithoutStatus() { ExtentTest test = extentReport.startTest(Thread.currentThread().getStackTrace()[1].getMethodName()); test.assignCategory("ZAPI Server BVT Suite"); Issue issuePayLoad = new Issue(); issuePayLoad.setProject(Config.getValue("project1Id")); issuePayLoad.setIssuetype(Config.getValue("issueTypeTestId")); issuePayLoad.setSummary("Test With Teststeps"); issuePayLoad.setPriority("1"); issuePayLoad.setReporter(Config.getValue("adminUserName")); Response response = jiraService.createIssue(basicAuth, issuePayLoad.toString()); Assert.assertNotNull(response, "Create Issue Api Response is null."); System.out.println(response.getBody().asString()); issueId = new JSONObject(response.body().asString()).getLong("id"); issueKey = new JSONObject(response.getBody().asString()).getString("key"); System.out.println("IssueKey :" + issueKey); System.out.println("IssueId :" + issueId); Teststep teststepJson = new Teststep(); teststepJson.setStep("step1"); teststepJson.setData("data1"); teststepJson.setResult("result1"); Response response1 = zapiService.createTeststep(basicAuth, issueId, teststepJson.toString()); Assert.assertNotNull(response1, "Create teststep Api Without WIKI Response is null."); Response response2 = zapiService.getTeststep(basicAuth, issueId); long teststepId = new JSONArray(response2.body().asString()).getJSONObject(0).getLong("id"); System.out.println("TeststepId:" +teststepId); Assert.assertNotNull(response2, "Get teststep by issue-Id Response is null."); Cycle cycleJson = new Cycle(); cycleJson.setProjectId(Long.parseLong(Config.getValue("project1Id"))); cycleJson.setVersionId(Long.parseLong(Config.getValue("version4Id"))); cycleJson.setName("Cycle created through API8"); Response response3 = zapiService.createCycle(basicAuth, cycleJson.toString()); Assert.assertNotNull(response3, "Create Cycle Api Response is null."); cycleId7 = new JSONObject(response3.body().asString()).get("id").toString(); System.out.println("cycle id is:" + cycleId7); Execution executionJson = new Execution(); List<String> values = new ArrayList<String>(); values.add(issueKey); executionJson.setIssues(values); executionJson.setProjectId(Long.parseLong(Config.getValue("project1Id"))); executionJson.setVersionId(Long.parseLong(Config.getValue("version4Id"))); executionJson.setCycleId(cycleId7); executionJson.setMethod(1); Response response4 = zapiService.addTestsToCycle(basicAuth, executionJson.toString()); System.out.println("Add tests to cycle is successful."); System.out.println(response4.getBody().asString()); long projectId = Long.parseLong(Config.getValue("project1Id")); long versionId = Long.parseLong(Config.getValue("version4Id")); Response response5 = zapiService.getExecutionsByCycle(basicAuth,projectId, versionId, cycleId7); executionId5 = new JSONObject(response5.getBody().asString()).getJSONArray("executions").getJSONObject(0).getLong("id"); System.out.println("ExecutionId1 is:" +executionId5); Stepresult json = new Stepresult(); json.setExecutionId(executionId5); json.setStepId(Long.toString(teststepId)); json.setStatus(-1); payload = json.toString(); Response response6 = zapiService.createStepResultWithoutSettingStatus(basicAuth, payload); Assert.assertNotNull(response6, "create Step Result Without Setting Status Response is null."); test.log(LogStatus.PASS, "create StepResult Without Setting Status executed successfully."); StepresId = new JSONObject(response6.body().asString()).getInt("id"); System.out.println("StepId:" + StepresId ); boolean status1 = zapiService.validateStepresult(response6); Assert.assertTrue(status1); extentReport.endTest(test); } //Get test step results by execution id @Test(priority = 65) public void bvt58_getTeststepResultByExecutionId() { ExtentTest test = extentReport.startTest(Thread.currentThread().getStackTrace()[1].getMethodName()); test.assignCategory("ZAPI Server BVT Suite"); long executionsId = executionId5; Response response = zapiService.getTeststepResultsByExecutionId(basicAuth, executionsId); Assert.assertNotNull(response, "Get step result Response is null."); test.log(LogStatus.PASS, "Get step result executed successfully."); System.out.println("Teststep results:"+response.body().asString()); boolean status = zapiService.validateGetStepResult(response); Assert.assertTrue(status); extentReport.endTest(test); } // Get test step result by id @Test(priority = 66) public void bvt66_getTeststepResultByID() { ExtentTest test = extentReport.startTest(Thread.currentThread().getStackTrace()[1].getMethodName()); test.assignCategory("ZAPI Server BVT Suite"); long orderId = StepresId; Response response = zapiService.getTeststepResults(basicAuth, orderId); Assert.assertNotNull(response, "Clone step Response is null."); test.log(LogStatus.PASS, "Clone step executed successfully."); System.out.println("Teststep results:"+response.body().asString()); boolean status = zapiService.validateGetStepResultById(response); Assert.assertTrue(status); extentReport.endTest(test); } // Update test step result to default status (e.g. Blocked) @Test(priority = 67) public void bvt67_updateTeststepResult() { ExtentTest test = extentReport.startTest(Thread.currentThread().getStackTrace()[1].getMethodName()); test.assignCategory("ZAPI Server BVT Suite"); Stepresult json = new Stepresult(); List<String> values = new ArrayList<>(); values.add("PROJ2-2"); json.setdefectList(values); json.setExecutionId(executionId5); long id = StepresId; json.setStatus(4); json.setUpdateDefectList("true"); payload = json.toString(); Response response = zapiService.updateTeststepResults(basicAuth, id, payload); Assert.assertNotNull(response, "Clone step Response is null."); test.log(LogStatus.PASS, "Clone step executed successfully."); System.out.println(response.body().asString()); boolean status = zapiService.validateUpdateStepResult(response); extentReport.endTest(test); } // Get defects linked to test step result @Test(priority = 68) public void bvt68_getStepResultDefects() { ExtentTest test = extentReport.startTest(Thread.currentThread().getStackTrace()[1].getMethodName()); test.assignCategory("ZAPI Server BVT Suite"); String stepResultId = Long.toString(StepresId); Response response = zapiService.getStepResultsDefects(basicAuth, stepResultId); Assert.assertNotNull(response, "Clone step Response is null."); test.log(LogStatus.PASS, "Clone step executed successfully."); System.out.println(response.body().asString()); boolean status = zapiService.validateStepResultDefects(response); extentReport.endTest(test); } // Get step defects by execution @Test(priority = 69) public void bvt69_getStepDefectsByExecutionID() { ExtentTest test = extentReport.startTest(Thread.currentThread().getStackTrace()[1].getMethodName()); test.assignCategory("ZAPI Server BVT Suite"); Stepresult json = new Stepresult(); json.setExecutionId(executionId5); Response response = zapiService.getStepDefectsByExecution(basicAuth, executionId5); Assert.assertNotNull(response, "Clone step Response is null."); test.log(LogStatus.PASS, "Clone step executed successfully."); System.out.println(response.body().asString()); extentReport.endTest(test); boolean status = zapiService.validateStepDefectsByExecutionID(response); extentReport.endTest(test); } //Add attachment to execution (jpeg) @Test(priority = 70) public void bvt70_addAttachment() { ExtentTest test = extentReport.startTest(Thread.currentThread().getStackTrace()[1].getMethodName()); test.assignCategory("ZAPI Server BVT Suite"); String entityId = Long.toString(executionId5); String entityType = "SCHEDULE"; String fileName = "attachment.png"; Response response = zapiService.addAttachment(basicAuth, entityId, entityType, fileName); Assert.assertNotNull(response, "Index status Response is null."); test.log(LogStatus.PASS, "Index status executed successfully."); System.out.println(response.body().asString()); boolean status = zapiService.validateAddAttachment(response); Assert.assertTrue(status); extentReport.endTest(test); } // Add attachment to test step result (txt) @Test(priority = 71) public void bvt71_addAttachment() { ExtentTest test = extentReport.startTest(Thread.currentThread().getStackTrace()[1].getMethodName()); test.assignCategory("ZAPI Server BVT Suite"); String entityId =Long.toString(StepresId); String entityType = "TESTSTEPRESULT"; String fileName = "attachment.png"; Response response = zapiService.addAttachmentToStepResult(basicAuth, entityId, entityType, fileName); Assert.assertNotNull(response, "Index status Response is null."); test.log(LogStatus.PASS, "Index status executed successfully."); System.out.println(response.body().asString()); boolean status = zapiService.validateAddAttachment(response); Assert.assertTrue(status); extentReport.endTest(test); } // Get attachment By executionId @Test(priority = 72) public void bvt72_getAttachment() { ExtentTest test = extentReport.startTest(Thread.currentThread().getStackTrace()[1].getMethodName()); test.assignCategory("ZAPI Server BVT Suite"); String entityId = Long.toString(executionId5); String entityType = "execution"; Response response2 = zapiService.getAttachment(basicAuth, entityId, entityType); Assert.assertNotNull(response2, "Index status Response is null."); test.log(LogStatus.PASS, "Index status executed successfully."); System.out.println(response2.body().asString()); testAttachmentId = new JSONObject(response2.body().asString()).getJSONArray("data").getJSONObject(0).getString("fileId"); extentReport.endTest(test); boolean status = zapiService.validateGetAttachment(response2); Assert.assertTrue(status); extentReport.endTest(test); } // Get attachment By StepResult id @Test(priority = 73) public void bvt73_getAttachment() { ExtentTest test = extentReport.startTest(Thread.currentThread().getStackTrace()[1].getMethodName()); test.assignCategory("ZAPI Server BVT Suite"); String entityId =Long.toString(StepresId); String entityType = "TESTSTEPRESULT"; Response response2 = zapiService.getAttachment(basicAuth, entityId, entityType); Assert.assertNotNull(response2, "Index status Response is null."); test.log(LogStatus.PASS, "Index status executed successfully."); System.out.println(response2.body().asString()); teststepAttachmentId = new JSONObject(response2.body().asString()).getJSONArray("data").getJSONObject(0).getString("fileId"); boolean status = zapiService.validateGetAttachment(response2); Assert.assertTrue(status); extentReport.endTest(test); } // Get Testlevel attachment by passing attachment ID if attachment is of different types @Test(priority = 74) public void bvt74_getAttachment() { ExtentTest test = extentReport.startTest(Thread.currentThread().getStackTrace()[1].getMethodName()); test.assignCategory("ZAPI Server BVT Suite"); String attchmentId = testAttachmentId; Response response = zapiService.getAttachmentById(basicAuth, attchmentId); Assert.assertNotNull(response, "Index status Response is null."); test.log(LogStatus.PASS, "Index status executed successfully."); System.out.println(response.body().asString()); boolean status = zapiService.validateGetAttachment(response); Assert.assertTrue(status); extentReport.endTest(test); } // Get Steplevel attachment by passing attachment ID if attachment is of different types @Test(priority = 75) public void bvt75_getAttachment() { ExtentTest test = extentReport.startTest(Thread.currentThread().getStackTrace()[1].getMethodName()); test.assignCategory("ZAPI Server BVT Suite"); String attchmentId = teststepAttachmentId; Response response = zapiService.getAttachmentById(basicAuth, attchmentId); Assert.assertNotNull(response, "Index status Response is null."); test.log(LogStatus.PASS, "Index status executed successfully."); System.out.println(response.body().asString()); boolean status = zapiService.validateGetAttachment(response); Assert.assertTrue(status); extentReport.endTest(test); } // Delete attachment to an execution @Test(priority = 76) public void bvt76_deleteAttachment() { ExtentTest test = extentReport.startTest(Thread.currentThread().getStackTrace()[1].getMethodName()); test.assignCategory("ZAPI Server BVT Suite"); String attchmentId = testAttachmentId; Response response = zapiService.deleteAttachmentToExecution(basicAuth, attchmentId); Assert.assertNotNull(response, "Index status Response is null."); test.log(LogStatus.PASS, "Index status executed successfully."); System.out.println(response.body().asString()); boolean status = zapiService.validateDeleteAttachment(response); Assert.assertTrue(status); extentReport.endTest(test); } // Delete attachment to an step Result @Test(priority = 77) public void bvt77_deleteAttachment() { ExtentTest test = extentReport.startTest(Thread.currentThread().getStackTrace()[1].getMethodName()); test.assignCategory("ZAPI Server BVT Suite"); String attchmentId = teststepAttachmentId; Response response = zapiService.deleteAttachmentToStepResult(basicAuth, attchmentId); Assert.assertNotNull(response, "Index status Response is null."); test.log(LogStatus.PASS, "Index status executed successfully."); System.out.println(response.body().asString()); boolean status = zapiService.validateDeleteAttachment(response); Assert.assertTrue(status); extentReport.endTest(test); } //Get ZQL clauses @Test(priority = 78) public void bvt78_getZqlClauses() { ExtentTest test = extentReport.startTest(Thread.currentThread().getStackTrace()[1].getMethodName()); test.assignCategory("ZAPI Server BVT Suite"); Response response = zapiService.getClauses(basicAuth); System.out.println(response.getBody().asString()); boolean status = zapiService.validategetZql(response); Assert.assertTrue(status, "Response Validation Failed."); test.log(LogStatus.PASS, "Response validated successfully."); extentReport.endTest(test); } //Get autocomplete JSON fields and reserved words @Test(priority = 79) public void bvt79_getZQLAutocompleteJson() { ExtentTest test = extentReport.startTest(Thread.currentThread().getStackTrace()[1].getMethodName()); test.assignCategory("ZAPI Server BVT Suite"); Response response = zapiService.autoCompleteZQLJson(basicAuth); System.out.println(response.getBody().asString()); boolean status = zapiService.validategetAutocompleteJson(response); Assert.assertTrue(status, "Response Validation Failed."); test.log(LogStatus.PASS, "Response validated successfully."); extentReport.endTest(test); } //Get autocomplete values for executionStatus @Test(priority = 80) public void bvt80_getZQLAutocomplete() { ExtentTest test = extentReport.startTest(Thread.currentThread().getStackTrace()[1].getMethodName()); test.assignCategory("ZAPI Server BVT Suite"); String fieldName = "executionStatus"; String fieldValue = "p"; Response response = zapiService.getZQLAutocomplete(basicAuth, fieldName, fieldValue); System.out.println(response.getBody().asString()); boolean status = zapiService.validategetZQLAutocomplete(fieldValue, response); Assert.assertTrue(status, "Response Validation Failed."); test.log(LogStatus.PASS, "Response validated successfully."); extentReport.endTest(test); } // Get logged in user @Test(priority = 81) public void bvt81_loggedinUser() { ExtentTest test = extentReport.startTest(Thread.currentThread().getStackTrace()[1].getMethodName()); test.assignCategory("Automation API BVT Suite - Zapi"); Response response = zapiService.loggedinUser(basicAuth); Assert.assertNotNull(response, "loggedinuser Api Response is null."); test.log(LogStatus.PASS, "Loggedinuser Api executed successfully."); System.out.println(response.getBody().asString()); boolean status = zapiService.validateloggedInUser(response); Assert.assertTrue(status, "Response Validation Failed."); test.log(LogStatus.PASS, "Response validated successfully."); extentReport.endTest(test); } // Create execution filter (global, favorite) @Test(priority = 82) public void bvt82_createExecutionFilter() { ExtentTest test = extentReport.startTest(Thread.currentThread().getStackTrace()[1].getMethodName()); test.assignCategory("ZAPI Server BVT Suite"); ExecutionFilter filJson = new ExecutionFilter(); filJson.setQuery("executionStatus = Unexecuted"); filJson.setFilterName("Apifilter1"); Response response = zapiService.createExecutionfilter(basicAuth, filJson.toString()); Assert.assertNotNull(response, "CreateExecutionfilter Api Response is null."); test.log(LogStatus.PASS, "CreateExecutionfilter status Api executed successfully."); System.out.println(response.getBody().asString()); boolean status = zapiService.validateCreateExecutionfilter(response); Assert.assertTrue(status, "Response Validation Failed."); test.log(LogStatus.PASS, "Response validated successfully."); extentReport.endTest(test); } // Create execution (private, non-favorite) @Test(priority = 83) public void bvt83_createPrivateFilter() { ExtentTest test = extentReport.startTest(Thread.currentThread().getStackTrace()[1].getMethodName()); test.assignCategory("ZAPI Server BVT Suite"); ExecutionFilter filJson = new ExecutionFilter(); filJson.setQuery("assignee = vm_admin"); filJson.setFilterName("Api Privatefilter1"); filJson.setIsFavorite(false); filJson.setSharePerm(2); Response response = zapiService.createExecutionfilter(basicAuth, filJson.toString()); Assert.assertNotNull(response, "CreateExecutionfilter Api Response is null."); test.log(LogStatus.PASS, "CreateExecutionfilter status Api executed successfully."); System.out.println(response.getBody().asString()); executionfilterId = new JSONObject(response.body().asString()).getLong("id"); boolean status = zapiService.validateCreateExecutionfilter(response); Assert.assertTrue(status, "Response Validation Failed."); test.log(LogStatus.PASS, "Response validated successfully."); extentReport.endTest(test); } // Update execution filter - add description @Test(priority = 84) public void bvt84_updateExecutionFilter() { ExtentTest test = extentReport.startTest(Thread.currentThread().getStackTrace()[1].getMethodName()); test.assignCategory("ZAPI Server BVT Suite"); ExecutionFilter filJson = new ExecutionFilter(); filJson.setDescription("filterDescription updated sucessfully"); filJson.setId(executionfilterId); Response response = zapiService.updateExecutionfilter(basicAuth, filJson.toString()); Assert.assertNotNull(response, "CreateExecutionfilter Api Response is null."); test.log(LogStatus.PASS, "CreateExecutionfilter status Api executed successfully."); System.out.println(response.getBody().asString()); boolean status = zapiService.validateUpdateExecutionFilter(response); Assert.assertTrue(status, "Response Validation Failed."); test.log(LogStatus.PASS, "Response validated successfully."); extentReport.endTest(test); } // Rename execution filter @Test(priority = 85) public void bvt85_renameExecutionFilter() { ExtentTest test = extentReport.startTest(Thread.currentThread().getStackTrace()[1].getMethodName()); test.assignCategory("ZAPI Server BVT Suite"); ExecutionFilter filJson = new ExecutionFilter(); filJson.setId(executionfilterId); filJson.setFilterName("Filter renamed1"); Response response = zapiService.renameExecutionfilter(basicAuth, filJson.toString()); Assert.assertNotNull(response, "CreateExecutionfilter Api Response is null."); test.log(LogStatus.PASS, "CreateExecutionfilter status Api executed successfully."); System.out.println(response.getBody().asString()); boolean status = zapiService.validateRenamedFilter(response); Assert.assertTrue(status, "Response Validation Failed."); test.log(LogStatus.PASS, "Response validated successfully."); extentReport.endTest(test); } // Copy execution filter created by another user (global/favorite) @Test(priority = 86) public void bvt86_copyExecutionFilter() { ExtentTest test = extentReport.startTest(Thread.currentThread().getStackTrace()[1].getMethodName()); test.assignCategory("ZAPI Server BVT Suite"); ExecutionFilter filJson = new ExecutionFilter(); filJson.setId(executionfilterId); filJson.setFilterName("Filter copied1"); Response response = zapiService.copyExecutionfilter(basicAuth, filJson.toString()); Assert.assertNotNull(response, "CreateExecutionfilter Api Response is null."); test.log(LogStatus.PASS, "CreateExecutionfilter status Api executed successfully."); System.out.println(response.getBody().asString()); boolean status = zapiService.validateCopyExecutionFilter(response); Assert.assertTrue(status, "Response Validation Failed."); test.log(LogStatus.PASS, "Response validated successfully."); extentReport.endTest(test); } // Get execution filter by id @Test(priority = 87) public void bvt87_getExecutionFilterById() { ExtentTest test = extentReport.startTest(Thread.currentThread().getStackTrace()[1].getMethodName()); test.assignCategory("ZAPI Server BVT Suite"); String FilterId = Long.toString(executionfilterId); Response response = zapiService.getfilterById(basicAuth, FilterId); Assert.assertNotNull(response, "CreateExecutionfilter Api Response is null."); test.log(LogStatus.PASS, "CreateExecutionfilter status Api executed successfully."); System.out.println(response.getBody().asString()); boolean status = zapiService.validateGetExecutionFilter(response, FilterId); Assert.assertTrue(status, "Response Validation Failed."); test.log(LogStatus.PASS, "Response validated successfully."); extentReport.endTest(test); } // Search execution filter by name @Test(priority = 88) public void bvt88_searchExecutionFilter() { ExtentTest test = extentReport.startTest(Thread.currentThread().getStackTrace()[1].getMethodName()); test.assignCategory("ZAPI Server BVT Suite"); ExecutionFilter filJson = new ExecutionFilter(); filJson.setQuery("cycleName = \"Ad hoc\""); filJson.setFilterName("Apifilter2"); Response response = zapiService.createExecutionfilter(basicAuth, filJson.toString()); Assert.assertNotNull(response, "CreateExecutionfilter Api Response is null."); String payload = "Apifilter2"; Response response1 = zapiService.searchExecutionfilter(basicAuth, payload); System.out.println(response1.getBody().asString()); Assert.assertNotNull(response1, "CreateExecutionfilter Api Response is null."); test.log(LogStatus.PASS, "CreateExecutionfilter status Api executed successfully."); boolean status = zapiService.validatesearchExecutionFilter(response1); Assert.assertTrue(status, "Response Validation Failed."); test.log(LogStatus.PASS, "Response validated successfully."); extentReport.endTest(test); } // Add execution filter created by another user as favorite @Test(priority = 89) public void bvt89_toggleFavFilter() { ExtentTest test = extentReport.startTest(Thread.currentThread().getStackTrace()[1].getMethodName()); test.assignCategory("ZAPI Server BVT Suite"); { ExecutionFilter filJson = new ExecutionFilter(); filJson.setQuery("executionStatus = Unexecuted"); filJson.setFilterName("User filter"); basicAuth = RestUtils.basicAuthRequest(Config.getValue("jiraUserName"), Config.getValue("jiraUserPassword")); Response response = zapiService.createExecutionfilter(basicAuth, filJson.toString()); Assert.assertNotNull(response, "CreateExecutionfilter Api Response is null."); test.log(LogStatus.PASS, "CreateExecutionfilter status Api executed successfully."); System.out.println(response.body().asString()); userexefilterId = new JSONObject(response.body().asString()).getLong("id"); System.out.println(userexefilterId); } ExecutionFilter filJson1 = new ExecutionFilter(); filJson1.setId(userexefilterId); filJson1.setIsFavorite(true); System.out.println(filJson1.toString()); basicAuth = RestUtils.basicAuthRequest(Config.getValue("adminUserName"), Config.getValue("adminPassword")); Response response1 = zapiService.toggleFavouriteFilter(basicAuth, filJson1.toString()); Assert.assertNotNull(response1, "CreateExecutionfilter Api Response is null."); test.log(LogStatus.PASS, "CreateExecutionfilter status Api executed successfully."); System.out.println(response1.getBody().asString()); boolean status = zapiService.validateToggleFavFilter(response1); Assert.assertTrue(status, "Response Validation Failed."); test.log(LogStatus.PASS, "Response validated successfully."); extentReport.endTest(test); } //Delete execution filter @Test(priority = 90) public void bvt90_deleteExecutionFilter() { ExtentTest test = extentReport.startTest(Thread.currentThread().getStackTrace()[1].getMethodName()); test.assignCategory("ZAPI Server BVT Suite"); String id = Long.toString(executionfilterId); Response response = zapiService.deleteFilter(basicAuth, id); Assert.assertNotNull(response, "CreateExecutionfilter Api Response is null."); test.log(LogStatus.PASS, "CreateExecutionfilter status Api executed successfully."); System.out.println(response.getBody().asString()); boolean status = zapiService.validateDeleteExecutionFilter(response); Assert.assertTrue(status, "Response Validation Failed."); test.log(LogStatus.PASS, "Response validated successfully."); extentReport.endTest(test); } //Get all favorite filters @Test(priority = 91) public void bvt91_getFavFilter() { ExtentTest test = extentReport.startTest(Thread.currentThread().getStackTrace()[1].getMethodName()); test.assignCategory("ZAPI Server BVT Suite"); String fav = "true"; Response response = zapiService.getFavFilter(basicAuth, fav); Assert.assertNotNull(response, "CreateExecutionfilter Api Response is null."); test.log(LogStatus.PASS, "CreateExecutionfilter status Api executed successfully."); System.out.println(response.getBody().asString()); boolean status = zapiService.validateGetFavFilter(response); Assert.assertTrue(status, "Response Validation Failed."); test.log(LogStatus.PASS, "Response validated successfully."); extentReport.endTest(test); } //Create column selection for an execution filter @Test(priority = 92) public void bvt92_createColumnSelection() { ExtentTest test = extentReport.startTest(Thread.currentThread().getStackTrace()[1].getMethodName()); test.assignCategory("ZAPI Server BVT Suite"); ExecutionFilter filJson = new ExecutionFilter(); filJson.setQuery("executionStatus != Unexecuted"); filJson.setFilterName("Apifilter2dd"); Response response = zapiService.createExecutionfilter(basicAuth, filJson.toString()); Assert.assertNotNull(response, "CreateExecutionfilter Api Response is null."); exefilterid1 = new JSONObject(response.getBody().asString()).getLong("id"); List<Object> val= new ArrayList<>(); Map<String, Object> map1 = new HashMap<>(); map1.put("filterIdentifier", "Cycle Name"); map1.put("visible", true); map1.put("orderId", 0); Map<String, Object> map2 = new HashMap<>(); map2.put("filterIdentifier", "Issue Key"); map2.put("visible", true); map2.put("orderId", 1); Map<String, Object> map3 = new HashMap<>(); map3.put("filterIdentifier", "Test Summary"); map3.put("visible", true); map3.put("orderId", 2); val.add(map1); val.add(map2); val.add(map3); Znav json = new Znav(); json.setUserName("vm_admin"); json.setExecutionFilterId(Long.toString(exefilterid1)); json.setColumnItemBean(val); payload = json.toString(); Response response1 = zapiService.createColumnSelection(basicAuth, payload); Assert.assertNotNull(response1, "CreateExecutionfilter Api Response is null."); System.out.println(response1.getBody().asString()); test.log(LogStatus.PASS, "CreateExecutionfilter status Api executed successfully."); boolean status = zapiService.validatecreateColumnSelection(response1); Assert.assertTrue(status, "Response Validation Failed."); test.log(LogStatus.PASS, "Response validated successfully."); extentReport.endTest(test); } //Get available columns for an execution filter @Test(priority = 93) public void bvt93_getColumnSelection() { ExtentTest test = extentReport.startTest(Thread.currentThread().getStackTrace()[1].getMethodName()); test.assignCategory("ZAPI Server BVT Suite"); long executionFilterId = exefilterid1; Response response1 = zapiService.getColumnSelection(basicAuth, executionFilterId); Assert.assertNotNull(response1, "CreateExecutionfilter Api Response is null."); test.log(LogStatus.PASS, "CreateExecutionfilter status Api executed successfully."); System.out.println(response1.getBody().asString()); columnSelectorId = new JSONObject(response1.getBody().asString()).getLong("id"); boolean status = zapiService.validategetColumnSelection(response1); Assert.assertTrue(status, "Response Validation Failed."); test.log(LogStatus.PASS, "Response validated successfully."); extentReport.endTest(test); } //Update column selection for an execution filter @Test(priority = 94) public void bvt94_updateColumnSelection() { ExtentTest test = extentReport.startTest(Thread.currentThread().getStackTrace()[1].getMethodName()); test.assignCategory("ZAPI Server BVT Suite"); List<Object> val= new ArrayList<>(); Map<String, Object> map1 = new HashMap<>(); map1.put("filterIdentifier", "Cycle Name"); map1.put("visible", false); map1.put("orderId", 0); Map<String, Object> map2 = new HashMap<>(); map2.put("filterIdentifier", "Issue Key"); map2.put("visible", false); map2.put("orderId", 1); Map<String, Object> map3 = new HashMap<>(); map3.put("filterIdentifier", "Test Summary"); map3.put("visible", true); map3.put("orderId", 2); Map<String, Object> map4 = new HashMap<>(); map4.put("filterIdentifier", "Project Name"); map4.put("visible", true); map4.put("orderId", 3); Map<String, Object> map5 = new HashMap<>(); map5.put("filterIdentifier", "Priority"); map5.put("visible", true); map5.put("orderId", 4); Map<String, Object> map6 = new HashMap<>(); map6.put("filterIdentifier", "Execution Status"); map6.put("visible", true); map6.put("orderId", 5); val.add(map1); val.add(map2); val.add(map3); val.add(map4); val.add(map5); val.add(map6); Znav json = new Znav(); json.setUserName("vm_admin"); json.setExecutionFilterId(Long.toString(exefilterid1)); json.setColumnItemBean(val); payload = json.toString(); long id = columnSelectorId; Response response1 = zapiService.updateColumnSelection(basicAuth, id, payload); Assert.assertNotNull(response1, "CreateExecutionfilter Api Response is null."); test.log(LogStatus.PASS, "CreateExecutionfilter status Api executed successfully."); System.out.println(response1.getBody().asString()); boolean status = zapiService.validateupdateColumnSelection(response1); Assert.assertTrue(status, "Response Validation Failed."); test.log(LogStatus.PASS, "Response validated successfully."); extentReport.endTest(test); } //Get exeuction details and the position of the execution in the zql query's results @Test(priority = 95) public void bvt95_getExecutionDetailsInZql() { ExtentTest test = extentReport.startTest(Thread.currentThread().getStackTrace()[1].getMethodName()); test.assignCategory("ZAPI Server BVT Suite"); Cycle cycleJson = new Cycle(); cycleJson.setProjectId(Long.parseLong(Config.getValue("project1Id"))); cycleJson.setVersionId(Long.parseLong(Config.getValue("version5Id"))); cycleJson.setName("Cycle created through API10"); Response response = zapiService.createCycle(basicAuth, cycleJson.toString()); Assert.assertNotNull(response, "Create Cycle Api Response is null."); String cycleId = new JSONObject(response.body().asString()).get("id").toString(); Execution executionJson = new Execution(); executionJson.setProjectId(Long.parseLong(Config.getValue("project1Id"))); executionJson.setVersionId(Long.parseLong(Config.getValue("version5Id"))); executionJson.setCycleId(cycleId); executionJson.setMethod(2); executionJson.setSearchId(10002l); Response response1 = zapiService.addTestsToCycle(basicAuth, executionJson.toString()); long projectId = Long.parseLong(Config.getValue("project1Id")); long versionId = Long.parseLong(Config.getValue("version5Id")); Response response2 = zapiService.getExecutionsByCycle(basicAuth, projectId, versionId, cycleId); String id1 = (new JSONObject(response2.body().asString()).getJSONArray("executions").getJSONObject(0).get("id")).toString(); ExecutionFilter filJson = new ExecutionFilter(); filJson.setQuery("executionStatus = Unexecuted"); filJson.setFilterName("Apifilter10"); Response response3 = zapiService.createExecutionfilter(basicAuth, filJson.toString()); long id = Long.parseLong(id1); String zql = "executionStatus = Unexecuted"; Response response4 = zapiService.getExecutionDetailsInZql(basicAuth, id, zql); System.out.println(response4.getBody().asString()); boolean status = zapiService.validategetExecutionDetailsInZql(response4); Assert.assertTrue(status, "Response Validation Failed."); test.log(LogStatus.PASS, "Response validated successfully."); extentReport.endTest(test); } //Quick search for execution filters @Test(priority = 96) public void bvt96_quickSearchZQLFilter() { ExtentTest test = extentReport.startTest(Thread.currentThread().getStackTrace()[1].getMethodName()); test.assignCategory("ZAPI Server BVT Suite"); String fieldName = "filter"; Response response = zapiService.quickSearchZQLFilter(basicAuth, fieldName); System.out.println(response.getBody().asString()); boolean status = zapiService.validatequickSearchZQLFilter(response); Assert.assertTrue(status, "Response Validation Failed."); test.log(LogStatus.PASS, "Response validated successfully."); extentReport.endTest(test); } //Get tests count by project (30-day summary) @Test(priority = 97) public void bvt97_getTestCreated() { ExtentTest test = extentReport.startTest(Thread.currentThread().getStackTrace()[1].getMethodName()); test.assignCategory("ZAPI Server BVT Suite"); String projectKey = Config.getValue("project1Key"); int daysPrevious = 30; String periodName = "daily"; Response response = zapiService.getTestCreated(basicAuth, projectKey, daysPrevious, periodName); System.out.println(response.getBody().asString()); boolean status = zapiService.validateGetTestCreated(response); Assert.assertTrue(status, "Response Validation Failed."); test.log(LogStatus.PASS, "Response validated successfully."); extentReport.endTest(test); } //Get issue statuses by project @Test(priority = 98) public void bvt98_getIssueStatuses() { ExtentTest test = extentReport.startTest(Thread.currentThread().getStackTrace()[1].getMethodName()); test.assignCategory("ZAPI Server BVT Suite"); long projectId =Long.parseLong(Config.getValue("project1Id")); Response response = zapiService.getIssueStatuses(basicAuth, projectId); System.out.println(response.getBody().asString()); boolean status = zapiService.validateGetIssueStatuses(response); Assert.assertTrue(status, "Response Validation Failed."); test.log(LogStatus.PASS, "Response validated successfully."); extentReport.endTest(test); } // Get tests by search filter id >>>Need to give jira filter id @Test(priority = 99) public void bvt99_getTestBySearchFilterId() { ExtentTest test = extentReport.startTest(Thread.currentThread().getStackTrace()[1].getMethodName()); test.assignCategory("ZAPI Server BVT Suite"); Long Id = 10002l; Response response = zapiService.getTestByFilterId(basicAuth, Id); Assert.assertNotNull(response, "Index status Response is null."); test.log(LogStatus.PASS, "Index status executed successfully."); System.out.println(response.body().asString()); boolean status = zapiService.validateGetTestByFilterId(response); Assert.assertTrue(status, "Response Validation Failed."); test.log(LogStatus.PASS, "Response validated successfully."); extentReport.endTest(test); } // Get tests count in a given version group by user (test distribution) @Test(priority = 100) public void bvt100_getTestCountGroupByUser() { ExtentTest test = extentReport.startTest(Thread.currentThread().getStackTrace()[1].getMethodName()); test.assignCategory("ZAPI Server BVT Suite"); String groupFld = "user"; Long projectID = Long.parseLong(Config.getValue("project1Id")); Long VersionId = Long.parseLong(Config.getValue("version1Id")); Response response = zapiService.testCount(basicAuth, groupFld, projectID, VersionId); Assert.assertNotNull(response, "Get tests count in a given version group by user Response is null."); test.log(LogStatus.PASS, "Get tests count in a given version group by user executed successfully."); System.out.println(response.body().asString()); boolean status = zapiService.validateGetTestCountGroupByUser(response); Assert.assertTrue(status, "Response Validation Failed."); test.log(LogStatus.PASS, "Response validated successfully."); extentReport.endTest(test); } //Get execution count by project (30-day summary) @Test(priority = 101) public void bvt101_getExecutionCount() { ExtentTest test = extentReport.startTest(Thread.currentThread().getStackTrace()[1].getMethodName()); test.assignCategory("ZAPI Server BVT Suite"); Long projectId = 10000l; String groupFld = "timePeriod"; String daysPrevious = "30"; String periodName = "daily"; Response response = zapiService.getExecutionCount(basicAuth, projectId, groupFld, daysPrevious, periodName); Assert.assertNotNull(response, "Create Execution Api Response is null."); test.log(LogStatus.PASS, "Update Cycle Api executed successfully."); System.out.println(response.getBody().asString()); boolean status = zapiService.validateGetExecutionCount(response); Assert.assertTrue(status, "Response Validation Failed."); test.log(LogStatus.PASS, "Response validated successfully."); extentReport.endTest(test); } //Get execution count in a given version group by user (test execution gadget) @Test(priority = 102) public void bvt102_getExecutionCountGroupByUser() { ExtentTest test = extentReport.startTest(Thread.currentThread().getStackTrace()[1].getMethodName()); test.assignCategory("ZAPI Server BVT Suite"); Long projectId = 10000l; String groupFld = "user"; Long versionId = -1l; String daysPrevious = "30"; String periodName = "daily"; Response response = zapiService.getExecutionCountGroupByUser(basicAuth, projectId, versionId, groupFld, daysPrevious, periodName); Assert.assertNotNull(response, "Create Execution Api Response is null."); test.log(LogStatus.PASS, "Update Cycle Api executed successfully."); System.out.println(response.getBody().asString()); boolean status = zapiService.validateGetExecutionCountGroupByUser(response); Assert.assertTrue(status, "Response Validation Failed."); test.log(LogStatus.PASS, "Response validated successfully."); extentReport.endTest(test); } //Get test execution count by �sprint-cycle� (test execution gadget) @Test(priority = 103) public void bvt103_getExecutionCountBySprint() { ExtentTest test = extentReport.startTest(Thread.currentThread().getStackTrace()[1].getMethodName()); test.assignCategory("ZAPI Server BVT Suite"); Long projectId = 10000l; String groupFld = "sprint-cycle"; Long versionId = 10000l; Response response = zapiService.getExecutionCountBySprint(basicAuth, projectId, versionId, groupFld ); Assert.assertNotNull(response, "Create Execution Api Response is null."); test.log(LogStatus.PASS, "Update Cycle Api executed successfully."); System.out.println(response.getBody().asString()); boolean status = zapiService.validateGetExecutionCountBySprint(response); Assert.assertTrue(status, "Response Validation Failed."); test.log(LogStatus.PASS, "Response validated successfully."); extentReport.endTest(test); } //Get execution count by cycle as burndown @Test(priority = 104) public void bvt104_getExecutionCountAsBurndown() { ExtentTest test = extentReport.startTest(Thread.currentThread().getStackTrace()[1].getMethodName()); test.assignCategory("ZAPI Server BVT Suite"); Long projectId = 10000l; Long versionId = 10000l; String groupFld = "timePeriod"; String cycleId = "-1"; String graphType = "burndown"; String daysPrevious = "30"; String periodName = "daily"; Response response = zapiService.getExecutionCountAsBurndown(basicAuth, projectId, versionId, cycleId, groupFld, graphType ); Assert.assertNotNull(response, "Create Execution Api Response is null."); test.log(LogStatus.PASS, "Update Cycle Api executed successfully."); System.out.println(response.getBody().asString()); boolean status = zapiService.validateGetExecutionCountAsBurndown(response); Assert.assertTrue(status, "Response Validation Failed."); test.log(LogStatus.PASS, "Response validated successfully."); extentReport.endTest(test); } //Get execution count by sprint as burndown @Test(priority = 105) public void bvt105_getExecutionCountAsSprintBurndown() { ExtentTest test = extentReport.startTest(Thread.currentThread().getStackTrace()[1].getMethodName()); test.assignCategory("ZAPI Server BVT Suite"); Long projectId = 10000l; Long versionId = 10000l; String groupFld = "timePeriod"; String sprintId = "1"; String graphType = "burndown"; Response response = zapiService.getExecutionCountAsSprintBurndown(basicAuth, projectId, versionId, sprintId, groupFld, graphType ); Assert.assertNotNull(response, "Create Execution Api Response is null."); test.log(LogStatus.PASS, "Update Cycle Api executed successfully."); System.out.println(response.getBody().asString()); boolean status = zapiService.validateGetExecutionCountAsSprintBurndown(response); Assert.assertTrue(status, "Response Validation Failed."); test.log(LogStatus.PASS, "Response validated successfully."); extentReport.endTest(test); } //Get top defects by issue statuses (1|3|4) @Test(priority = 106) public void bvt106_getTopDefects() { ExtentTest test = extentReport.startTest(Thread.currentThread().getStackTrace()[1].getMethodName()); test.assignCategory("ZAPI Server BVT Suite"); Long projectId = 10000l; Long versionId = -1l; Long issueStatuses = 10000l; Response response = zapiService.getTopDefects(basicAuth, projectId, versionId, issueStatuses); Assert.assertNotNull(response, "Create Execution Api Response is null."); test.log(LogStatus.PASS, "Update Cycle Api executed successfully."); System.out.println(response.getBody().asString()); boolean status = zapiService.validateGetTopDefects(response); Assert.assertTrue(status, "Response Validation Failed."); test.log(LogStatus.PASS, "Response validated successfully."); extentReport.endTest(test); } //Search executions by test @Test(priority = 107) public void bvt107_searchExecutionsByTest() { ExtentTest test = extentReport.startTest(Thread.currentThread().getStackTrace()[1].getMethodName()); test.assignCategory("ZAPI Server BVT Suite"); Issue issuePayLoad = new Issue(); issuePayLoad.setProject(Config.getValue("project1Id")); issuePayLoad.setIssuetype(Config.getValue("issueTypeTestId")); issuePayLoad.setSummary("Test"); issuePayLoad.setPriority("3"); issuePayLoad.setReporter(Config.getValue("adminUserName")); Response response = jiraService.createIssue(basicAuth, issuePayLoad.toString()); Assert.assertNotNull(response, "Create Issue Api Response is null."); issueId = new JSONObject(response.body().asString()).getLong("id"); issueKey = new JSONObject(response.getBody().asString()).getString("key"); Cycle cycleJson = new Cycle(); cycleJson.setProjectId(Long.parseLong(Config.getValue("project1Id"))); cycleJson.setVersionId(-1l); cycleJson.setName("Cycle created through API"); Response response1 = zapiService.createCycle(basicAuth, cycleJson.toString()); Assert.assertNotNull(response1, "Create Cycle Api Response is null."); cycleId = new JSONObject(response1.body().asString()).get("id").toString(); Execution json = new Execution(); json.setIssueId(issueId); json.setProjectId(Long.parseLong(Config.getValue("project1Id"))); json.setVersionId(-1l); json.setCycleId(cycleId); payload = json.toString(); Response response2 = zapiService.createExecution(basicAuth, payload); System.out.println(response2.getBody().asString()); String testIdOrKey = issueKey; int maxResult = 10; int offset = 0; Response response3 = zapiService.searchExecutionsByTest(basicAuth, testIdOrKey, maxResult, offset ); Assert.assertNotNull(response3, "Create Execution Api Response is null."); test.log(LogStatus.PASS, "Update Cycle Api executed successfully."); System.out.println(response.getBody().asString()); boolean status = zapiService.validateSearchExecutionsByTest(response3); Assert.assertTrue(status, "Not validated added attachment"); test.log(LogStatus.PASS, "Response validated successfully."); extentReport.endTest(test); } //Search tests by requirement @Test(priority = 108) public void bvt108_searchExecutionsByRequirement() { ExtentTest test = extentReport.startTest(Thread.currentThread().getStackTrace()[1].getMethodName()); test.assignCategory("ZAPI Server BVT Suite"); test.assignAuthor("Priyanka"); Issue issuePayLoad = new Issue(); issuePayLoad.setProject(Config.getValue("project1Id")); issuePayLoad.setIssuetype(Config.getValue("issueTypeTestId")); issuePayLoad.setSummary("Issuetype-Test"); issuePayLoad.setPriority("3"); issuePayLoad.setReporter(Config.getValue("adminUserName")); Response response = jiraService.createIssue(basicAuth, issuePayLoad.toString()); long issueId = new JSONObject(response.body().asString()).getLong("id"); String issueKey1 = new JSONObject(response.getBody().asString()).getString("key");Teststep teststepJson = new Teststep(); teststepJson.setStep("step1"); teststepJson.setData("data1"); teststepJson.setResult("result1"); Response response1 = zapiService.createTeststep(basicAuth, issueId, teststepJson.toString()); Response response2 = zapiService.getTeststep(basicAuth, issueId); long teststepId = new JSONArray(response2.body().asString()).getJSONObject(0).getLong("id"); //Create requirement Issue issuePayLoad1 = new Issue(); issuePayLoad1.setProject(Config.getValue("project1Id")); issuePayLoad1.setIssuetype(Config.getValue("issueTypeStoryId")); issuePayLoad1.setSummary("Issuetype-Story"); issuePayLoad1.setPriority("3"); issuePayLoad1.setReporter(Config.getValue("adminUserName")); Response response3 = jiraService.createIssue(basicAuth, issuePayLoad1.toString()); String issueKey2 = new JSONObject(response3.getBody().asString()).getString("key"); issueId3 = new JSONObject(response3.body().asString()).getLong("id"); //Create defects Issue issuePayLoad2 = new Issue(); issuePayLoad2.setProject(Config.getValue("project1Id")); issuePayLoad2.setIssuetype(Config.getValue("issueTypeBugId")); issuePayLoad2.setSummary("Issuetype-bug1"); issuePayLoad2.setPriority("3"); issuePayLoad2.setReporter(Config.getValue("adminUserName")); Response response10 = jiraService.createIssue(basicAuth, issuePayLoad2.toString()); issueKey3 = new JSONObject(response10.getBody().asString()).getString("key"); issueId4 = new JSONObject(response3.body().asString()).getLong("id"); Issue issuePayLoad4 = new Issue(); issuePayLoad4.setProject(Config.getValue("project1Id")); issuePayLoad4.setIssuetype(Config.getValue("issueTypeBugId")); issuePayLoad4.setSummary("Issuetype-bug2"); issuePayLoad4.setPriority("3"); issuePayLoad4.setReporter(Config.getValue("adminUserName")); Response response11= jiraService.createIssue(basicAuth, issuePayLoad4.toString()); issueKey4 = new JSONObject(response11.getBody().asString()).getString("key"); //Link requirement to tests Issuelink json = new Issuelink(); json.setLinktype("Duplicate"); json.setInwardIssue(issueKey1); json.setOutwardIssue(issueKey2); payload = json.toString(); Response response4 = jiraService.createIssueLink(basicAuth, payload); Cycle cycleJson = new Cycle(); cycleJson.setProjectId(Long.parseLong(Config.getValue("project1Id"))); cycleJson.setVersionId(-1l); cycleJson.setName("Cycle created through API"); Response response5 = zapiService.createCycle(basicAuth, cycleJson.toString()); cycleId = new JSONObject(response5.body().asString()).get("id").toString(); Execution json1 = new Execution(); json1.setIssueId(issueId); json1.setProjectId(Long.parseLong(Config.getValue("project1Id"))); json1.setVersionId(-1l); json1.setCycleId(cycleId); payload = json1.toString(); Response response6 = zapiService.createExecution(basicAuth, payload); long projectId = Long.parseLong(Config.getValue("project1Id")); long versionId = -1l; Response response7 = zapiService.getExecutionsByCycle(basicAuth,projectId, versionId, cycleId); long executionId = new JSONObject(response7.getBody().asString()).getJSONArray("executions").getJSONObject(0).getLong("id"); String id = Long.toString(executionId); List<String> value = new ArrayList<>(); value.add(issueKey3); Execution json3 = new Execution(); json3.setDefectList(value); json3.setIssueId(issueId); json3.setUpdateDefectList("true"); payload = json3.toString(); Response response9 = zapiService.executeTest(basicAuth, id, payload ); Long executionsId =executionId; System.out.println(executionsId); Response response13 = zapiService.getTeststepResultsByExecutionId(basicAuth, executionsId); System.out.println(response13.body().asString()); long stepId = new JSONArray(response13.body().asString()).getJSONObject(0).getLong("stepId"); long id2 = new JSONArray(response13.body().asString()).getJSONObject(0).getLong("id"); List<String> values = new ArrayList<>(); values.add(issueKey4); Stepresult json5 = new Stepresult(); json5.setdefectList(values); json5.setExecutionId(executionId); json5.setUpdateDefectList("true"); json5.setStatus(1); payload = json5.toString(); Response response12 = zapiService.updateTeststepResults(basicAuth, id2, payload); String requirementIdOrKeyList = issueKey2; Response response14 = zapiService.searchExecutionsByRequirement(basicAuth, requirementIdOrKeyList); Assert.assertNotNull(response, "Create Execution Api Response is null."); test.log(LogStatus.PASS, "Update Cycle Api executed successfully."); System.out.println(response14.getBody().asString()); boolean status = zapiService.validateSearchExecutionsByRequirement(response14); Assert.assertTrue(status, "Not validated added attachment"); test.log(LogStatus.PASS, "Response validated successfully."); extentReport.endTest(test); } //Search executions by defect at test level @Test(priority = 109) public void bvt109_searchExecutionsByDefect() { ExtentTest test = extentReport.startTest(Thread.currentThread().getStackTrace()[1].getMethodName()); test.assignCategory("ZAPI Server BVT Suite"); String defectIdOrKey = issueKey3; System.out.println(defectIdOrKey); Response response = zapiService.searchExecutionsByDefect(basicAuth, defectIdOrKey); Assert.assertNotNull(response, "Create Execution Api Response is null."); test.log(LogStatus.PASS, "Update Cycle Api executed successfully."); System.out.println(response.getBody().asString()); boolean status = zapiService.validateSearchExecutionsByDefect(response); Assert.assertTrue(status, "Not validated added attachment"); test.log(LogStatus.PASS, "Response validated successfully."); extentReport.endTest(test); } //Search executions by defect at step level @Test(priority = 110) public void bvt110_searchExecutionsByDefect() { ExtentTest test = extentReport.startTest(Thread.currentThread().getStackTrace()[1].getMethodName()); test.assignCategory("ZAPI Server BVT Suite"); String defectIdOrKey = issueKey4; Response response = zapiService.searchExecutionsByDefect(basicAuth, defectIdOrKey); Assert.assertNotNull(response, "Create Execution Api Response is null."); test.log(LogStatus.PASS, "Update Cycle Api executed successfully."); System.out.println(response.getBody().asString()); boolean status = zapiService.validateSearchExecutionsByDefect(response); Assert.assertTrue(status, "Not validated added attachment"); test.log(LogStatus.PASS, "Response validated successfully."); extentReport.endTest(test); } //Search defect statistics by defect list @Test(priority = 111) public void bvt111_searchDefectStatistics() { ExtentTest test = extentReport.startTest(Thread.currentThread().getStackTrace()[1].getMethodName()); test.assignCategory("ZAPI Server BVT Suite"); String defectIdOrKeyList = issueKey3; Response response = zapiService.searchDefectStatistics(basicAuth, defectIdOrKeyList); Assert.assertNotNull(response, "Create Execution Api Response is null."); test.log(LogStatus.PASS, "Update Cycle Api executed successfully."); System.out.println(response.getBody().asString()); boolean status = zapiService.validateSearchDefectStatistics(response); Assert.assertTrue(status, "Not validated added attachment"); test.log(LogStatus.PASS, "Response validated successfully."); extentReport.endTest(test); } //Export requirement to defects traceability report in Excel format @Test(priority = 112) public void bvt112_exportTraceability() { ExtentTest test = extentReport.startTest(Thread.currentThread().getStackTrace()[1].getMethodName()); test.assignCategory("ZAPI Server BVT Suite"); ExportTraceability json = new ExportTraceability(); List<Long> values = new ArrayList<>(); values.add(issueId3); json.setRequirementIdList(values); json.setExportType("excel"); json.setVersionId(0l); payload = json.toString(); Response response = zapiService.exportTraceability(basicAuth, payload); Assert.assertNotNull(response, "Create Execution Api Response is null."); test.log(LogStatus.PASS, "Update Cycle Api executed successfully."); System.out.println(response.getBody().asString()); boolean status = zapiService.validateExportTraceability(response); Assert.assertTrue(status, "Not validated added attachment"); test.log(LogStatus.PASS, "Response validated successfully."); extentReport.endTest(test); } //Export defects to requirements traceability report in HTML format @Test(priority = 113) public void bvt113_exportTraceability() { ExtentTest test = extentReport.startTest(Thread.currentThread().getStackTrace()[1].getMethodName()); test.assignCategory("ZAPI Server BVT Suite"); ExportTraceability json = new ExportTraceability(); List<Long> values = new ArrayList<>(); values.add(issueId4); json.setDefectIdList(values); json.setExportType("html"); json.setVersionId(0l); payload = json.toString(); Response response = zapiService.exportTraceability(basicAuth, payload); Assert.assertNotNull(response, "Create Execution Api Response is null."); test.log(LogStatus.PASS, "Update Cycle Api executed successfully."); System.out.println(response.getBody().asString()); boolean status = zapiService.validateExportTraceability(response); Assert.assertTrue(status, "Not validated added attachment"); test.log(LogStatus.PASS, "Response validated successfully."); extentReport.endTest(test); } //Get Index executions @Test(priority = 114) public void test114_indexExecution() { ExtentTest test = extentReport.startTest(Thread.currentThread().getStackTrace()[1].getMethodName()); test.assignCategory("ZAPI Server BVT Suite"); Response response = zapiService.indexExecution(basicAuth); Assert.assertNotNull(response, "Index status Response is null."); test.log(LogStatus.PASS, "Index status executed successfully."); System.out.println(response.getBody().asString()); boolean status = zapiService.validateIndexExecution(response); Assert.assertTrue(status, "Not validated added attachment"); test.log(LogStatus.PASS, "Response validated successfully."); extentReport.endTest(test); } // Get index status @Test(priority = 115) public void test115_indexStatus() { ExtentTest test = extentReport.startTest(Thread.currentThread().getStackTrace()[1].getMethodName()); test.assignCategory("ZAPI Server BVT Suite"); Response response = zapiService.indexExecution(basicAuth); Assert.assertNotNull(response, "Index execution Response is null."); test.log(LogStatus.PASS, "Index execution executed successfully."); long tokenNo = new JSONObject(response.body().asString()).getLong("token"); System.out.println("Token is :" + tokenNo); Response response1 = zapiService.indexStatus(basicAuth, tokenNo); Assert.assertNotNull(response1, "Index status Response is null."); test.log(LogStatus.PASS, "Index status executed successfully."); System.out.println(response1.body().asString()); boolean status = zapiService.validategetindexStatus(response1); Assert.assertTrue(status, "Not validated added attachment"); test.log(LogStatus.PASS, "Response validated successfully."); extentReport.endTest(test); } // Refresh remote links @Test(priority = 116) public void test116_refreshReomteLinks() { ExtentTest test = extentReport.startTest(Thread.currentThread().getStackTrace()[1].getMethodName()); test.assignCategory("ZAPI Server BVT Suite"); List<String> list = new ArrayList<>(); list.add(executionId2); list.add(executionId3); List<String> list1 = new ArrayList<>(); list1.add("PROJ2-1"); list1.add("PROJ2-2"); BulkExecution execJson = new BulkExecution(); execJson.setExecutions(list); execJson.setDefects(list1); Response response = zapiService.bulkUpdateDefects(basicAuth, execJson.toString()); String issueLinkTypeId = "10002"; Response response1 = zapiService.RefreshTheRemoteLinks(basicAuth, issueLinkTypeId); Assert.assertNotNull(response, "Index status Response is null."); test.log(LogStatus.PASS, "Index status executed successfully."); System.out.println(response1.body().asString()); boolean status = zapiService.validaterefreshReomteLinks(response1); Assert.assertTrue(status, "Not validated added attachment"); test.log(LogStatus.PASS, "Response validated successfully."); extentReport.endTest(test); } // Get all audit logs for execution @Test(priority = 117) public void test117_getAuditLogs() { ExtentTest test = extentReport.startTest(Thread.currentThread().getStackTrace()[1].getMethodName()); test.assignCategory("ZAPI Server BVT Suite"); String entityType = "EXECUTION"; int offset = 0; int maxRecords = 20; Response response = zapiService.getAuditLogs(basicAuth, entityType, offset, maxRecords); Assert.assertNotNull(response, "Index status Response is null."); test.log(LogStatus.PASS, "Index status executed successfully."); extentReport.endTest(test); entityId = new JSONObject(response.body().asString()).getJSONArray("auditLogs").getJSONObject(0).getLong("executionId"); System.out.println("entityId:"+entityId); boolean status = zapiService.validateAuditLogs(response); Assert.assertTrue(status, "Not validated added attachment"); test.log(LogStatus.PASS, "Response validated successfully."); extentReport.endTest(test); } // Get audit logs for execution by execution id @Test(priority = 118) public void test118_getAuditByExecutionId() { ExtentTest test = extentReport.startTest(Thread.currentThread().getStackTrace()[1].getMethodName()); test.assignCategory("ZAPI Server BVT Suite"); long executionId = entityId ; int offset = 0; int maxRecords = 20; Response response = zapiService.getAuditByExecutionId(basicAuth, offset, maxRecords,executionId); Assert.assertNotNull(response, "Index status Response is null."); test.log(LogStatus.PASS, "Index status executed successfully."); System.out.println(response.getBody().asString()); boolean status = zapiService.validateGetAuditByExecutionId(response); Assert.assertTrue(status, "Not validated added attachment"); test.log(LogStatus.PASS, "Response validated successfully."); extentReport.endTest(test); } }
true
1e221b84b4f1056bf55b90911d4dd5ad78d136f4
Java
theneoxs/java_prog
/src/application/Tech.java
UTF-8
1,958
2.75
3
[]
no_license
package application; import java.sql.Date; import javafx.beans.property.*; public class Tech { private IntegerProperty idtechnic; private StringProperty name; private StringProperty model; private ObjectProperty<Date> date; private FloatProperty cost; private IntegerProperty room_num; private IntegerProperty mat_resp_id; private IntegerProperty subdividion_id; public Tech(){ this.idtechnic = new SimpleIntegerProperty(0); this.name = new SimpleStringProperty(""); this.model = new SimpleStringProperty(""); this.date = new SimpleObjectProperty<Date>(Date.valueOf("2018-01-01"));; this.cost = new SimpleFloatProperty(0); this.room_num = new SimpleIntegerProperty(0); this.mat_resp_id = new SimpleIntegerProperty(0); this.subdividion_id = new SimpleIntegerProperty(0); } public Tech(Integer idtechnic, String name, String model, Date date, Float cost, Integer room_num, Integer mat_resp_id, Integer subdividion_id) { this.idtechnic = new SimpleIntegerProperty(idtechnic); this.name = new SimpleStringProperty(name); this.model = new SimpleStringProperty(model); this.date = new SimpleObjectProperty<Date>(date); this.cost = new SimpleFloatProperty(cost); this.room_num = new SimpleIntegerProperty(room_num); this.mat_resp_id = new SimpleIntegerProperty(mat_resp_id); this.subdividion_id = new SimpleIntegerProperty(subdividion_id); } public Integer getIdtechnic() { return this.idtechnic.get(); } public String getName() { return this.name.get(); } public String getModel() { return this.model.get(); } public Date getDate() { return this.date.get(); } public Float getCost() { return this.cost.get(); } public Integer getRoom_num() { return this.room_num.get(); } public Integer getMat_resp_id() { return this.mat_resp_id.get(); } public Integer getSubdividion_id() { return this.subdividion_id.get(); } }
true
c71534d3983292a5a8f0ffd98efd67340367b152
Java
nOoRM7mD/PizzaList
/app/src/main/java/com/example/lenovo/pizzalist/utilties/SortListItem.java
UTF-8
618
2.734375
3
[]
no_license
package com.example.lenovo.pizzalist.utilties; import com.example.lenovo.pizzalist.models.Product; import java.util.Collections; import java.util.Comparator; import java.util.List; /** * Created by lenovo on 5/20/2018. */ public class SortListItem { public List<Product> sortProductList(List<Product> list){ Collections.sort(list, new Comparator<Product>() { @Override public int compare(Product firstProduct, Product secondProduct) { return firstProduct.getName().compareTo(secondProduct.getName()); } }); return list; } }
true
be6f0ba5d9b4440ea45813c0ea0714605be1e10c
Java
mminhaz93/Automation
/src/main/java/HomeWork/Musaib/HW0328_MoMovies/pages/MoMoviesPage.java
UTF-8
2,574
2.40625
2
[]
no_license
package HomeWork.Musaib.HW0328_MoMovies.pages; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; public class MoMoviesPage { public MoMoviesPage(WebDriver driver) { this.driver = driver; } WebDriver driver; By searchFieldElm = By.id("search-input"); By dropDownElm = By.xpath("//*[@id=\"basic-navbar-nav\"]/form/span/div/ul/li[1]/div/div/a/p"); By contactUsElm = By.xpath("//*[@id=\"basic-navbar-nav\"]/div[2]/a"); By enterNameElm = By.id("validationCustom01"); By enterEmailElm = By.id("validationCustom02"); By enterMessageElm = By.id("validationCustom03"); By submitElm = By.xpath("//*[@id=\"root\"]/main/div/form/div[4]/button"); By succesMessageElm = By.xpath("//*[@id=\"site-frame\"]/div[1]/div/div/div/p"); // @FindBy(id = "search-input") WebElement searchField; // @FindBy(className = "search-input") WebElement contractUs; public void searchMovie(String movieName){ WebElement searchMovieText = driver.findElement(searchFieldElm); searchMovieText.sendKeys(movieName); // driver.findElement(By.id("search-input")).sendKeys("F9"); // searchField.sendKeys(name); // driver.findElement(By.className("nav-link")).click(); } public void clickDropdown (){ WebElement clickMovieText = driver.findElement(dropDownElm); clickMovieText.click(); } public void contactUs (){ WebElement clickContactUs = driver.findElement(contactUsElm); clickContactUs.click(); } public void enterName (String name){ WebElement enterNameText = driver.findElement(enterNameElm); enterNameText.sendKeys(name); } public void enterEmail (String email){ WebElement enterEmailText = driver.findElement(enterEmailElm); enterEmailText.sendKeys(email); } public void enterMessage (String message){ WebElement enterMessageText = driver.findElement(enterMessageElm); enterMessageText.sendKeys(message); } public void submitFrom(){ WebElement submitClick = driver.findElement(submitElm); submitClick.click(); } public String succesMessage(){ WebElement succesMessageText = driver.findElement(succesMessageElm); String Message = succesMessageText.getText(); return Message; } // public void clickFlightButton() { // WebElement flightButton = driver.findElement(flightButtonElm); // flightButton.click(); // } }
true
a098fca7c4819e34051d5d0a6a630476d0e414b3
Java
sebaudracco/bubble
/mf/org/apache/xml/serialize/XML11Serializer.java
UTF-8
12,660
2.109375
2
[]
no_license
package mf.org.apache.xml.serialize; import java.io.IOException; import java.io.OutputStream; import java.io.Writer; import mf.org.apache.xerces.dom.DOMMessageFormatter; import mf.org.apache.xerces.util.NamespaceSupport; import mf.org.apache.xerces.util.SymbolTable; import mf.org.apache.xerces.util.XML11Char; import mf.org.apache.xerces.util.XMLChar; import org.xml.sax.SAXException; public class XML11Serializer extends XMLSerializer { protected static final boolean DEBUG = false; protected static final String PREFIX = "NS"; protected boolean fDOML1; protected NamespaceSupport fLocalNSBinder; protected NamespaceSupport fNSBinder; protected int fNamespaceCounter; protected boolean fNamespaces; protected SymbolTable fSymbolTable; public XML11Serializer() { this.fDOML1 = false; this.fNamespaceCounter = 1; this.fNamespaces = false; this._format.setVersion("1.1"); } public XML11Serializer(OutputFormat format) { super(format); this.fDOML1 = false; this.fNamespaceCounter = 1; this.fNamespaces = false; this._format.setVersion("1.1"); } public XML11Serializer(Writer writer, OutputFormat format) { super(writer, format); this.fDOML1 = false; this.fNamespaceCounter = 1; this.fNamespaces = false; this._format.setVersion("1.1"); } public XML11Serializer(OutputStream output, OutputFormat format) { if (format == null) { format = new OutputFormat("xml", null, false); } super(output, format); this.fDOML1 = false; this.fNamespaceCounter = 1; this.fNamespaces = false; this._format.setVersion("1.1"); } public void characters(char[] chars, int start, int length) throws SAXException { try { ElementState state = content(); int saveIndent; if (state.inCData || state.doCData) { if (!state.inCData) { this._printer.printText("<![CDATA["); state.inCData = true; } saveIndent = this._printer.getNextIndent(); this._printer.setNextIndent(0); int end = start + length; int index = start; while (index < end) { char ch = chars[index]; if (ch == ']' && index + 2 < end && chars[index + 1] == ']' && chars[index + 2] == '>') { this._printer.printText("]]]]><![CDATA[>"); index += 2; } else if (!XML11Char.isXML11Valid(ch)) { index++; if (index < end) { surrogates(ch, chars[index], true); } else { fatalError("The character '" + ch + "' is an invalid XML character"); } } else if (this._encodingInfo.isPrintable(ch) && XML11Char.isXML11ValidLiteral(ch)) { this._printer.printText(ch); } else { this._printer.printText("]]>&#x"); this._printer.printText(Integer.toHexString(ch)); this._printer.printText(";<![CDATA["); } index++; } this._printer.setNextIndent(saveIndent); } else if (state.preserveSpace) { saveIndent = this._printer.getNextIndent(); this._printer.setNextIndent(0); printText(chars, start, length, true, state.unescaped); this._printer.setNextIndent(saveIndent); } else { printText(chars, start, length, false, state.unescaped); } } catch (IOException except) { throw new SAXException(except); } } protected void printEscaped(String source) throws IOException { int length = source.length(); int i = 0; while (i < length) { int ch = source.charAt(i); if (!XML11Char.isXML11Valid(ch)) { i++; if (i < length) { surrogates(ch, source.charAt(i), false); } else { fatalError("The character '" + ((char) ch) + "' is an invalid XML character"); } } else if (ch == 10 || ch == 13 || ch == 9 || ch == 133 || ch == 8232) { printHex(ch); } else if (ch == 60) { this._printer.printText("&lt;"); } else if (ch == 38) { this._printer.printText("&amp;"); } else if (ch == 34) { this._printer.printText("&quot;"); } else if (ch < 32 || !this._encodingInfo.isPrintable((char) ch)) { printHex(ch); } else { this._printer.printText((char) ch); } i++; } } protected final void printCDATAText(String text) throws IOException { int length = text.length(); int index = 0; while (index < length) { char ch = text.charAt(index); if (ch == ']' && index + 2 < length && text.charAt(index + 1) == ']' && text.charAt(index + 2) == '>') { if (this.fDOMErrorHandler != null) { if ((this.features & 16) == 0 && (this.features & 2) == 0) { modifyDOMError(DOMMessageFormatter.formatMessage(DOMMessageFormatter.SERIALIZER_DOMAIN, "EndingCDATA", null), (short) 3, null, this.fCurrentNode); if (!this.fDOMErrorHandler.handleError(this.fDOMError)) { throw new IOException(); } } modifyDOMError(DOMMessageFormatter.formatMessage(DOMMessageFormatter.SERIALIZER_DOMAIN, "SplittingCDATA", null), (short) 1, null, this.fCurrentNode); this.fDOMErrorHandler.handleError(this.fDOMError); } this._printer.printText("]]]]><![CDATA[>"); index += 2; } else if (!XML11Char.isXML11Valid(ch)) { index++; if (index < length) { surrogates(ch, text.charAt(index), true); } else { fatalError("The character '" + ch + "' is an invalid XML character"); } } else if (this._encodingInfo.isPrintable(ch) && XML11Char.isXML11ValidLiteral(ch)) { this._printer.printText(ch); } else { this._printer.printText("]]>&#x"); this._printer.printText(Integer.toHexString(ch)); this._printer.printText(";<![CDATA["); } index++; } } protected final void printXMLChar(int ch) throws IOException { if (ch == 13 || ch == 133 || ch == 8232) { printHex(ch); } else if (ch == 60) { this._printer.printText("&lt;"); } else if (ch == 38) { this._printer.printText("&amp;"); } else if (ch == 62) { this._printer.printText("&gt;"); } else if (this._encodingInfo.isPrintable((char) ch) && XML11Char.isXML11ValidLiteral(ch)) { this._printer.printText((char) ch); } else { printHex(ch); } } protected final void surrogates(int high, int low, boolean inContent) throws IOException { if (!XMLChar.isHighSurrogate(high)) { fatalError("The character '" + ((char) high) + "' is an invalid XML character"); } else if (XMLChar.isLowSurrogate(low)) { int supplemental = XMLChar.supplemental((char) high, (char) low); if (!XML11Char.isXML11Valid(supplemental)) { fatalError("The character '" + ((char) supplemental) + "' is an invalid XML character"); } else if (inContent && content().inCData) { this._printer.printText("]]>&#x"); this._printer.printText(Integer.toHexString(supplemental)); this._printer.printText(";<![CDATA["); } else { printHex(supplemental); } } else { fatalError("The character '" + ((char) low) + "' is an invalid XML character"); } } protected void printText(String text, boolean preserveSpace, boolean unescaped) throws IOException { int length = text.length(); int index; char ch; if (preserveSpace) { index = 0; while (index < length) { ch = text.charAt(index); if (!XML11Char.isXML11Valid(ch)) { index++; if (index < length) { surrogates(ch, text.charAt(index), true); } else { fatalError("The character '" + ch + "' is an invalid XML character"); } } else if (unescaped && XML11Char.isXML11ValidLiteral(ch)) { this._printer.printText(ch); } else { printXMLChar(ch); } index++; } return; } index = 0; while (index < length) { ch = text.charAt(index); if (!XML11Char.isXML11Valid(ch)) { index++; if (index < length) { surrogates(ch, text.charAt(index), true); } else { fatalError("The character '" + ch + "' is an invalid XML character"); } } else if (unescaped && XML11Char.isXML11ValidLiteral(ch)) { this._printer.printText(ch); } else { printXMLChar(ch); } index++; } } protected void printText(char[] chars, int start, int length, boolean preserveSpace, boolean unescaped) throws IOException { int length2; int start2; char ch; if (preserveSpace) { length2 = length; start2 = start; while (true) { length = length2 - 1; if (length2 <= 0) { start = start2; return; } start = start2 + 1; ch = chars[start2]; if (!XML11Char.isXML11Valid(ch)) { length2 = length - 1; if (length > 0) { start2 = start + 1; surrogates(ch, chars[start], true); } else { fatalError("The character '" + ch + "' is an invalid XML character"); start2 = start; } } else if (unescaped && XML11Char.isXML11ValidLiteral(ch)) { this._printer.printText(ch); length2 = length; start2 = start; } else { printXMLChar(ch); length2 = length; start2 = start; } } } else { while (true) { length2 = length; start2 = start; while (true) { length = length2 - 1; if (length2 <= 0) { start = start2; return; } start = start2 + 1; ch = chars[start2]; if (!XML11Char.isXML11Valid(ch)) { length2 = length - 1; if (length > 0) { start2 = start + 1; surrogates(ch, chars[start], true); } else { fatalError("The character '" + ch + "' is an invalid XML character"); start2 = start; } } else if (unescaped && XML11Char.isXML11ValidLiteral(ch)) { this._printer.printText(ch); length2 = length; start2 = start; } else { printXMLChar(ch); } } printXMLChar(ch); } } } public boolean reset() { super.reset(); return true; } }
true
f3309944f6dad384eb4e40f430ce61c77aa80765
Java
IronMustang3711/frc2019
/src/main/java/org/usfirst/frc3711/deepspace/commands/sequences/Stow.java
UTF-8
710
2.328125
2
[ "Apache-2.0" ]
permissive
package org.usfirst.frc3711.deepspace.commands.sequences; import edu.wpi.first.wpilibj.command.MyCommandGroup; import org.usfirst.frc3711.deepspace.Robot; import org.usfirst.frc3711.deepspace.commands.util.MotionMagicSetpoint; public class Stow extends MyCommandGroup { public Stow(){ super(Stow.class.getSimpleName()); addParallel(new MotionMagicSetpoint("Wrist Home", Robot.wrist,0)); addParallel(new MotionMagicSetpoint("Arm Home",Robot.arm,0)); addParallel(new MotionMagicSetpoint("Elevator Home",Robot.elevator,100)); } @Override protected void end() { Robot.elevator.talon.neutralOutput(); Robot.arm.talon.neutralOutput(); Robot.wrist.talon.neutralOutput(); } }
true
0872eee0ff361e76a17268c6a7356ed60603f6e0
Java
NavisionLtd/giftadeed-android-app
/app/src/main/java/giftadeed/kshantechsoft/com/giftadeed/TaggedNeeds/NotificationCountModel.java
UTF-8
555
1.664063
2
[]
no_license
/* * Copyright (C) Navision Ltd. - All Rights Reserved * Unauthorized copying of this file, via any medium is strictly prohibited */ package giftadeed.kshantechsoft.com.giftadeed.TaggedNeeds; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; public class NotificationCountModel { @SerializedName("nt_count") @Expose private String ntCount; public String getNtCount() { return ntCount; } public void setNtCount(String ntCount) { this.ntCount = ntCount; } }
true
7db0d5d4b7da1c15256d260c876f8ed1e716b0a5
Java
Nanfeng11/Java
/Practice/src/main/java/com/nanfeng/CountNum.java
UTF-8
3,053
3.4375
3
[]
no_license
package com.nanfeng; import java.util.*; /** * Author:nanfeng * Created:2019/8/25 */ public class CountNum { HashMap<Integer, Integer> map = new HashMap<>(); public int MoreThanHalfNum_Solution(int[] array) { if (array.length == 0 || array == null) { return 0; } for (int i = 0; i < array.length; i++) { if (map == null) { map.put(array[i], 1); } else { if (map.containsKey(array[i])) { int count = map.get(array[i]); map.put(array[i], count + 1); } else { map.put(array[i], 1); } } } //排序 ArrayList<Map.Entry<Integer, Integer>> list = new ArrayList<>(); list.addAll(map.entrySet()); for (Map.Entry<Integer, Integer> entry : list) { if (entry.getValue() > array.length / 2) { return entry.getKey(); } } return 0; } //方法二 // HashMap<Integer, Integer> map = new HashMap<Integer, Integer>(); // // public int MoreThanHalfNum_Solution(int[] array) { // if (array.length == 0 || array == null) { // return 0; // } // for (int i = 0; i < array.length; i++) { // if (map == null) { // map.put(array[i], 1); // } else { // if (map.containsKey(array[i])) { // //map中已经存有该元素 // //获取该元素在map有几份,也就是在数组中出现了几次 // int count = map.get(array[i]); // map.put(array[i], count + 1); // } else { // //新元素 // map.put(array[i], 1); // } // // } // } // //按照值进行排序 // ArrayList<Map.Entry<Integer, Integer>> list = sortMap(map); // if (list.get(0).getValue() > array.length / 2) { // return list.get(0).getKey(); // } else { // return 0; // } // } // // public ArrayList<Map.Entry<Integer, Integer>> sortMap(Map map) { // List<Map.Entry<Integer, Integer>> entries = new ArrayList<Map.Entry<Integer, Integer>>(map.entrySet()); // Collections.sort(entries, new Comparator<Map.Entry<Integer, Integer>>() { // public int compare(Map.Entry<Integer, Integer> obj1, Map.Entry<Integer, Integer> obj2) { // return obj2.getValue() - obj1.getValue(); // } // }); // return (ArrayList<Map.Entry<Integer, Integer>>) entries; // } //方法三 // public int MoreThanHalfNum_Solution(int [] array) { // Arrays.sort(array); // int len = array.length; // int num = array[len/2]; // int count = 0; // for(int i=0; i<len; i++){ // if(array[i] == num){ // count++; // } // } // return count>(len/2)?num:0; // } }
true
6ab577697c7b6f01c8f9fb6d65f056e5b3d40733
Java
pxson001/facebook-app
/classes7.dex_source_from_JADX/com/facebook/feedback/ui/rows/views/CommentActionsView.java
UTF-8
2,668
1.695313
2
[]
no_license
package com.facebook.feedback.ui.rows.views; import android.animation.ValueAnimator; import android.content.Context; import android.text.method.LinkMovementMethod; import android.util.AttributeSet; import android.view.MotionEvent; import android.view.View; import android.view.View.OnTouchListener; import com.facebook.feedback.ui.CommentBackgroundUtil; import com.facebook.inject.FbInjector; import com.facebook.widget.CustomLinearLayout; import com.facebook.widget.accessibility.AccessibleTextView; import javax.annotation.Nullable; import javax.inject.Inject; /* compiled from: reviewText */ public class CommentActionsView extends CustomLinearLayout implements HighlightableView { @Inject public CommentBackgroundUtil f5143a; private final AccessibleTextView f5144b; private OnTouchListener f5145c; private static <T extends View> void m5604a(Class<T> cls, T t) { m5605a((Object) t, t.getContext()); } private static void m5605a(Object obj, Context context) { ((CommentActionsView) obj).f5143a = CommentBackgroundUtil.m4807a(FbInjector.get(context)); } public CommentActionsView(Context context) { this(context, null); } public CommentActionsView(Context context, AttributeSet attributeSet) { this(context, attributeSet, 0); } public CommentActionsView(Context context, @Nullable AttributeSet attributeSet, int i) { super(context, attributeSet, i); m5604a(CommentActionsView.class, (View) this); setContentView(2130903614); setBackgroundDrawable(this.f5143a.m4813a(context)); this.f5144b = (AccessibleTextView) findViewById(2131560421); this.f5144b.setMovementMethod(LinkMovementMethod.getInstance()); this.f5144b.setTextSize(0, context.getResources().getDimension(2131428739)); } public boolean onInterceptTouchEvent(MotionEvent motionEvent) { super.onTouchEvent(motionEvent); if (this.f5145c != null) { this.f5145c.onTouch(this, motionEvent); } return false; } private void m5603a(CommentBackgroundUtil commentBackgroundUtil) { this.f5143a = commentBackgroundUtil; } public void setOnTouchListener(OnTouchListener onTouchListener) { super.setOnTouchListener(onTouchListener); this.f5145c = onTouchListener; } public void setMetadataText(CharSequence charSequence) { this.f5144b.setText(charSequence); this.f5144b.setContentDescription(charSequence); } public final void mo279a(ValueAnimator valueAnimator) { CommentBackgroundUtil.m4809a(getBackground(), valueAnimator); } }
true
6df9f618a7322d6e88986cc998894dd97bab91a2
Java
moutainhigh/wencai-dev
/src/main/java/com/sftc/web/service/UserContactLabelService.java
UTF-8
590
1.929688
2
[]
no_license
package com.sftc.web.service; import com.sftc.tools.api.APIRequest; import com.sftc.tools.api.APIResponse; public interface UserContactLabelService { /** * 给好友添加标签 * @param userContactLabel * @return */ APIResponse addLabelForFriend(APIRequest request); /** * 删除好友的标签 * @param request * @return */ APIResponse deleteLabelForFriend(APIRequest request); /** * 获取某个好友的标签 * @param request * @return */ APIResponse selectFriendLabelList(APIRequest request); }
true
5c8a74cea3782d57cb3830709c5bb8b05328e038
Java
mapserver2007/restful-service-example-app
/spring-boot/src/main/java/com/example/app/application/session/CustomSocialUserDetailsService.java
UTF-8
664
1.953125
2
[]
no_license
package com.example.app.application.session; import org.springframework.dao.DataAccessException; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.social.security.SocialUser; import org.springframework.social.security.SocialUserDetails; import org.springframework.social.security.SocialUserDetailsService; import java.util.ArrayList; public class CustomSocialUserDetailsService implements SocialUserDetailsService { public SocialUserDetails loadUserByUserId(String userId) throws UsernameNotFoundException, DataAccessException { return new SocialUser(userId, "", new ArrayList<>()); } }
true
c68f39747c3d9d334d3f5c1934a13dfbc5ceb18d
Java
salidotir/games-collection-desktop-app
/ui/UI.java
UTF-8
1,099
2.578125
3
[]
no_license
/* * 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 ui; import java.util.Stack; import javafx.application.Application; import javafx.scene.Scene; import javafx.stage.Stage; /** * * @author mainmhl */ public class UI extends Application { /** * @param args the command line arguments */ public static Stack<Scene> sceneArray = new Stack<>(); static Stage window; public static void main(String[] args) { // TODO code application logic here launch(args); } @Override public void start(Stage primaryStage) throws Exception { window = primaryStage; window.setResizable(false); // disable the maximize button window.setTitle("Games Collection"); MainScene scene = new MainScene(); window.setScene(MainScene.scene); window.show(); } }
true
a362d8b38818757bb0c0d9dc0cec8a4414de4190
Java
digimon1740/Coinhunter
/src/main/java/com/coinhunter/web/listener/WebSocketEventListener.java
UTF-8
1,854
2.171875
2
[]
no_license
package com.coinhunter.web.listener; import com.coinhunter.core.domain.chat.ChatMessage; import com.coinhunter.core.domain.user.User; import com.coinhunter.core.service.user.UserService; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.event.EventListener; import org.springframework.messaging.simp.SimpMessageSendingOperations; import org.springframework.messaging.simp.stomp.StompHeaderAccessor; import org.springframework.stereotype.Component; import org.springframework.web.socket.messaging.SessionConnectedEvent; import org.springframework.web.socket.messaging.SessionDisconnectEvent; import java.util.Set; @Slf4j @Component public class WebSocketEventListener { @Autowired private SimpMessageSendingOperations messagingTemplate; @Autowired private UserService userService; @EventListener public void handleWebSocketConnectListener(SessionConnectedEvent event) { log.info("Received a new web socket connection"); } @EventListener public void handleWebSocketDisconnectListener(SessionDisconnectEvent event) { StompHeaderAccessor headerAccessor = StompHeaderAccessor.wrap(event.getMessage()); log.info("headerAccessor : {}", headerAccessor); //String username = (String) headerAccessor.getSessionAttributes().get("username"); String username = headerAccessor.getUser().getName(); if (username != null) { log.info("User Disconnected : " + username); User user = userService.findByName(username); // 모든 웹소켓 처리 close 예) 채팅, ticker등 스레드 api, 자동봇?(이건 생각해봐야함) // ChatMessage chatMessage = new ChatMessage(); // chatMessage.setType(ChatMessage.MessageType.LEAVE); // chatMessage.setSender(username); //messagingTemplate.convertAndSend("/topic/public", chatMessage); } } }
true
c65538cae5105c7455495f75522c55c33f890cfe
Java
leihcrev/bls
/src/java/Sarthakmanna.java
UTF-8
8,094
2.734375
3
[]
no_license
import java.io.BufferedWriter; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.InputStream; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.util.ArrayList; import java.util.Random; import java.util.Timer; import java.util.TimerTask; public class Sarthakmanna implements Runnable { @Override public void run() { try { new Solver().solve(); System.exit(0); } catch (Exception | Error e) { e.printStackTrace(); System.exit(1); } } public static void main(String[] args) { // new Thread(null, new Main(), "Solver", 1l << 25).start(); new Sarthakmanna().run(); } } class Solver { final Helper hp; final int MAXN = 1000_006; final long MOD = (long) 1e9 + 7; final Timer timer; final TimerTask task; Solver() { hp = new Helper(MOD, MAXN); hp.initIO(System.in, System.out); timer = new Timer(); task = new TimerTask() { @Override public void run() { try { hp.flush(); System.exit(0); } catch (Exception e) { } } }; // timer.schedule(task, 4700); } void solve() throws Exception { int i, j, k; boolean testCases = false; int tc = testCases ? hp.nextInt() : 1; for (int tce = 1; tce <= tc; tce++) { int N = hp.nextInt(); int[] A = hp.getIntArray(N - 1); int[] childCount = new int[N]; for (i = 0; i < N - 1; ++i) { ++childCount[A[i] - 1]; } for (int itr : childCount) hp.println(itr); } timer.cancel(); hp.flush(); } } class Helper { final long MOD; final int MAXN; final Random rnd; public Helper(long mod, int maxn) { MOD = mod; MAXN = maxn; rnd = new Random(); } public static int[] sieve; public static ArrayList<Integer> primes; public void setSieve() { primes = new ArrayList<>(); sieve = new int[MAXN]; int i, j; for (i = 2; i < MAXN; ++i) if (sieve[i] == 0) { primes.add(i); for (j = i; j < MAXN; j += i) { sieve[j] = i; } } } public static long[] factorial; public void setFactorial() { factorial = new long[MAXN]; factorial[0] = 1; for (int i = 1; i < MAXN; ++i) factorial[i] = factorial[i - 1] * i % MOD; } public long getFactorial(int n) { if (factorial == null) setFactorial(); return factorial[n]; } public long ncr(int n, int r) { if (r > n) return 0; if (factorial == null) setFactorial(); long numerator = factorial[n]; long denominator = factorial[r] * factorial[n - r] % MOD; return numerator * pow(denominator, MOD - 2, MOD) % MOD; } public long[] getLongArray(int size) throws Exception { long[] ar = new long[size]; for (int i = 0; i < size; ++i) ar[i] = nextLong(); return ar; } public int[] getIntArray(int size) throws Exception { int[] ar = new int[size]; for (int i = 0; i < size; ++i) ar[i] = nextInt(); return ar; } public String[] getStringArray(int size) throws Exception { String[] ar = new String[size]; for (int i = 0; i < size; ++i) ar[i] = next(); return ar; } public String joinElements(long... ar) { StringBuilder sb = new StringBuilder(); for (long itr : ar) sb.append(itr).append(" "); return sb.toString().trim(); } public String joinElements(int... ar) { StringBuilder sb = new StringBuilder(); for (int itr : ar) sb.append(itr).append(" "); return sb.toString().trim(); } public String joinElements(String... ar) { StringBuilder sb = new StringBuilder(); for (String itr : ar) sb.append(itr).append(" "); return sb.toString().trim(); } public String joinElements(Object... ar) { StringBuilder sb = new StringBuilder(); for (Object itr : ar) sb.append(itr).append(" "); return sb.toString().trim(); } public long gcd(long a, long b) { return b == 0 ? a : gcd(b, a % b); } public int gcd(int a, int b) { return b == 0 ? a : gcd(b, a % b); } public long max(long... ar) { long ret = ar[0]; for (long itr : ar) ret = Math.max(ret, itr); return ret; } public int max(int... ar) { int ret = ar[0]; for (int itr : ar) ret = Math.max(ret, itr); return ret; } public long min(long... ar) { long ret = ar[0]; for (long itr : ar) ret = Math.min(ret, itr); return ret; } public int min(int... ar) { int ret = ar[0]; for (int itr : ar) ret = Math.min(ret, itr); return ret; } public long sum(long... ar) { long sum = 0; for (long itr : ar) sum += itr; return sum; } public long sum(int... ar) { long sum = 0; for (int itr : ar) sum += itr; return sum; } public void shuffle(Integer[] ar) { int r; for (int i = 0; i < ar.length; ++i) { r = rnd.nextInt(ar.length); if (r != i) { ar[i] ^= ar[r]; ar[r] ^= ar[i]; ar[i] ^= ar[r]; } } } public void shuffle(long[] ar) { int r; for (int i = 0; i < ar.length; ++i) { r = rnd.nextInt(ar.length); if (r != i) { ar[i] ^= ar[r]; ar[r] ^= ar[i]; ar[i] ^= ar[r]; } } } public void reverse(int[] ar) { int r; for (int i = 0; i < ar.length; ++i) { r = ar.length - 1 - i; if (r > i) { ar[i] ^= ar[r]; ar[r] ^= ar[i]; ar[i] ^= ar[r]; } } } public void reverse(long[] ar) { int r; for (int i = 0; i < ar.length; ++i) { r = ar.length - 1 - i; if (r > i) { ar[i] ^= ar[r]; ar[r] ^= ar[i]; ar[i] ^= ar[r]; } } } public long pow(long base, long exp, long MOD) { base %= MOD; long ret = 1; while (exp > 0) { if ((exp & 1) == 1) ret = ret * base % MOD; base = base * base % MOD; exp >>= 1; } return ret; } static final int BUFSIZE = 1 << 20; static byte[] buf; static int index, total; static InputStream in; static BufferedWriter bw; public void initIO(InputStream is, OutputStream os) { try { in = is; bw = new BufferedWriter(new OutputStreamWriter(os)); buf = new byte[BUFSIZE]; } catch (Exception e) { } } public void initIO(String inputFile, String outputFile) { try { in = new FileInputStream(inputFile); bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outputFile))); buf = new byte[BUFSIZE]; } catch (Exception e) { } } private int scan() throws Exception { if (index >= total) { index = 0; total = in.read(buf); if (total <= 0) return -1; } return buf[index++]; } public String next() throws Exception { int c; for (c = scan(); c <= 32; c = scan()); StringBuilder sb = new StringBuilder(); for (; c > 32; c = scan()) sb.append((char) c); return sb.toString(); } public int nextInt() throws Exception { int c, val = 0; for (c = scan(); c <= 32; c = scan()); boolean neg = c == '-'; if (c == '-' || c == '+') c = scan(); for (; c >= '0' && c <= '9'; c = scan()) val = (val << 3) + (val << 1) + (c & 15); return neg ? -val : val; } public long nextLong() throws Exception { int c; long val = 0; for (c = scan(); c <= 32; c = scan()); boolean neg = c == '-'; if (c == '-' || c == '+') c = scan(); for (; c >= '0' && c <= '9'; c = scan()) val = (val << 3) + (val << 1) + (c & 15); return neg ? -val : val; } public void print(Object a) throws Exception { bw.write(a.toString()); } public void printsp(Object a) throws Exception { print(a); print(" "); } public void println() throws Exception { bw.write("\n"); } public void println(Object a) throws Exception { print(a); println(); } public void flush() throws Exception { bw.flush(); } }
true
ea7f87e6aa21c83cb95bc3f0d8f932102cafe753
Java
gun-pi/epam-java-cources
/src/main/java/com/epam/university/java/core/task010/Task010Impl.java
UTF-8
1,202
3.578125
4
[]
no_license
package com.epam.university.java.core.task010; import java.io.File; import java.util.HashMap; import java.util.Map; import java.util.Scanner; public class Task010Impl implements Task010 { /** * Given a textual file, you should count frequency of words in this file. * * @param source source file * @return map word to frequency of it */ @Override public Map<String, Integer> countWordNumbers(File source) { if (source == null) { throw new IllegalArgumentException(); } Map<String, Integer> mapOfWords = new HashMap<>(); try { Scanner scanner = new Scanner(source); while (scanner.hasNext()) { String str = scanner.next(); str = str.trim(); str = str.toLowerCase(); str = str.replaceAll("[^A-Za-z]", ""); Integer count = mapOfWords.get(str); if (count == null) { count = 0; } mapOfWords.put(str, ++count); } } catch (Exception e) { System.out.println("Do something!"); } return mapOfWords; } }
true
a2e0ca91ef1254ee48d73feb8db531788de698ee
Java
lelisadav/CSSE473ONLCarterDavey
/Project/RAFinder/app/src/main/java/edu/rosehulman/rafinder/controller/LoginActivity.java
UTF-8
9,004
2.234375
2
[]
no_license
package edu.rosehulman.rafinder.controller; import android.animation.Animator; import android.animation.AnimatorListenerAdapter; import android.app.Activity; import android.app.AlertDialog; import android.app.ProgressDialog; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.text.TextUtils; import android.util.Log; import android.view.KeyEvent; import android.view.View; import android.view.View.OnClickListener; import android.view.inputmethod.EditorInfo; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import com.firebase.client.Firebase; import edu.rosehulman.rafinder.ConfigKeys; import edu.rosehulman.rafinder.MainActivity; import edu.rosehulman.rafinder.R; import edu.rosehulman.rafinder.UserType; import edu.rosehulman.rafinder.model.Login; /** * A login screen that offers login via email/password. */ public class LoginActivity extends Activity { /** * A dialog that displays during the authentication process */ private ProgressDialog mAuthProgressDialog; // UI references. private TextView mEmailView; private EditText mPasswordView; private View mProgressView; private View mLoginFormView; private Login mLogin; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Firebase.setAndroidContext(this); Firebase firebase = new Firebase(ConfigKeys.FIREBASE_ROOT_URL); mLogin = new Login(firebase, this); setContentView(R.layout.activity_login); mAuthProgressDialog = new ProgressDialog(this); mAuthProgressDialog.setTitle("Loading"); mAuthProgressDialog.setMessage("Authenticating with Firebase..."); mAuthProgressDialog.setCancelable(false); // Set up the login form. mEmailView = (TextView) findViewById(R.id.email); String intentEmail = getIntent().getStringExtra(ConfigKeys.KEY_USER_EMAIL); if (intentEmail != null) { // pre-populate the email address if we're coming from the Registration page mEmailView.setText(intentEmail); } mPasswordView = (EditText) findViewById(R.id.password); mPasswordView.setOnEditorActionListener(new TextView.OnEditorActionListener() { public boolean onEditorAction(TextView textView, int id, KeyEvent keyEvent) { if (id == R.id.login || id == EditorInfo.IME_NULL) { attemptLogin(); return true; } return false; } }); Button mEmailSignInButton = (Button) findViewById(R.id.email_sign_in_button); mEmailSignInButton.setOnClickListener(new OnClickListener() { public void onClick(View view) { attemptLogin(); } }); Button mEmailRegister = (Button) findViewById(R.id.register); mEmailRegister.setOnClickListener(new OnClickListener() { public void onClick(View ignored) { registerNewUser(); } }); mLoginFormView = findViewById(R.id.login_form); mProgressView = findViewById(R.id.login_progress); SharedPreferences prefs = getSharedPreferences(ConfigKeys.KEY_SHARED_PREFS, MODE_PRIVATE); UserType userType = UserType.valueOf(prefs.getString(ConfigKeys.KEY_USER_TYPE, UserType.NONE.toString())); String raEmail = prefs.getString(ConfigKeys.KEY_RA_EMAIL, ""); String email = prefs.getString(ConfigKeys.KEY_USER_EMAIL, ""); // Skip login screen if we're still authorized and have data. if (firebase.getAuth() != null && !userType.equals(UserType.NONE) && !raEmail.equals("") && !email.equals("")) { launchMainActivity(userType, raEmail, email); } } /** * Attempts to sign in or register the account specified by the login form. * If there are form errors (invalid email, missing fields, etc.), the * errors are presented and no actual login attempt is made. */ private void attemptLogin() { // Reset errors. mEmailView.setError(null); mPasswordView.setError(null); // Store values at the time of the login attempt. String email = mEmailView.getText().toString(); String password = mPasswordView.getText().toString(); boolean cancel = false; View focusView = null; // Check for a valid password, if the user entered one. if (!TextUtils.isEmpty(password) && !Login.isPasswordValid(password)) { mPasswordView.setError(getString(R.string.error_invalid_password)); focusView = mPasswordView; cancel = true; } // Check for a valid email address. if (TextUtils.isEmpty(email)) { mEmailView.setError(getString(R.string.error_field_required)); focusView = mEmailView; cancel = true; } else if (!Login.isEmailValid(email)) { mEmailView.setError(getString(R.string.error_invalid_email)); focusView = mEmailView; cancel = true; } if (cancel) { // There was an error; don't attempt login and focus the first // form field with an error. focusView.requestFocus(); } else { // Show a progress spinner, and kick off a background task to // perform the user login attempt. showProgress(true); mAuthProgressDialog.show(); mLogin.loginWithPassword(email, password); mAuthProgressDialog.hide(); showProgress(false); } } /** * Opens up a list of projects after logging in. */ public void launchMainActivity(UserType userType, String raEmail, String email) { mAuthProgressDialog.hide(); Intent intent = new Intent(this, MainActivity.class); intent.putExtra(ConfigKeys.KEY_USER_TYPE, userType.name()); intent.putExtra(ConfigKeys.KEY_RA_EMAIL, raEmail); intent.putExtra(ConfigKeys.KEY_USER_EMAIL, email); // Store data for persistence SharedPreferences.Editor editor = getSharedPreferences(ConfigKeys.KEY_SHARED_PREFS, MODE_PRIVATE).edit(); editor.putString(ConfigKeys.KEY_USER_TYPE, userType.name()); editor.putString(ConfigKeys.KEY_RA_EMAIL, raEmail); editor.putString(ConfigKeys.KEY_USER_EMAIL, email); editor.apply(); Log.d(ConfigKeys.LOG_TAG, "starting Main with userType <" + userType + "> and raEmail <" + raEmail + ">"); startActivity(intent); finish(); } /** * Shows the progress UI and hides the login form. */ private void showProgress(final boolean show) { int shortAnimTime = getResources().getInteger( android.R.integer.config_shortAnimTime); mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE); mLoginFormView.animate().setDuration(shortAnimTime) .alpha(show ? 0 : 1) .setListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE); } }); mProgressView.setVisibility(show ? View.VISIBLE : View.GONE); mProgressView.animate().setDuration(shortAnimTime) .alpha(show ? 1 : 0) .setListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { mProgressView.setVisibility(show ? View.VISIBLE : View.GONE); } }); } /** * Displays an alert dialog that contains the specified error message */ private void showErrorDialog(String message) { new AlertDialog.Builder(this).setTitle("Error").setMessage(message) .setPositiveButton(android.R.string.ok, null) .setIcon(android.R.drawable.ic_dialog_alert) .show(); } public String getEmail() { return mEmailView.getText().toString(); } private void registerNewUser() { Intent registerIntent = new Intent(this, RegisterActivity.class); String email = mEmailView.getText().toString(); if (!email.equals("")) { registerIntent.putExtra(ConfigKeys.KEY_USER_EMAIL, email); } startActivity(registerIntent); } public void showError(String errorMessage) { showErrorDialog(errorMessage); mAuthProgressDialog.hide(); } }
true
57d1b17625fbe9ab3b266017a2ad686c738d43a0
Java
Glow-T/LiuJianyu-s-JavaHomework
/src/Pet/Pet2.java
UTF-8
168
2.9375
3
[]
no_license
package Pet; public class Pet2 extends Pet{ public String food; public void chose() { System.out.println(this.name + ",来吃" + this.food); } }
true
9505c385190804d08380dead3580c88b03ed0a7a
Java
atilla17/JavaPracttice
/workshop2/src/workshop2.java
UTF-8
280
1.921875
2
[]
no_license
public class workshop2 { public static void main(String[] args) { //------------ Task1 HangmanGame a1 = new HangmanGame(); a1.Init(); //-------------Task2 //BankChecker a2 = new BankChecker(); //a2.ReadBankInfo(); } }
true
8b7279f59eb1b0ad7928cc5fc2531d5f1c836bb7
Java
yatingarg37/sumoflist
/sumoflist.java
UTF-8
1,448
3.46875
3
[]
no_license
package assignments; import java.util.Scanner; public class Sumoflist { Node head; public static class Node { int data; Node next; Node(int d) { data=d; next=null; } } public static Sumoflist insert(Sumoflist li,int d) { Node newNode=new Node(d); if(li.head==null) { li.head=newNode; } else { Node temp=li.head; while(temp.next!=null) { temp=temp.next; } temp.next=newNode; } return li; } public static Sumoflist checksum(Sumoflist li,Sumoflist li2) { int c=0; int c1=0; int sum1=0; int sum2=0; Node temp=li.head; Node temp2=li2.head; while(temp!=null) { sum1=(int)(sum1+temp.data*Math.pow(10, c)); c++; temp=temp.next; } while(temp2!=null) { sum2=(int)(sum2+temp.data*Math.pow(10, c1)); c1++; temp2=temp2.next; } int sum3=sum1+sum2; Sumoflist li3=new Sumoflist(); while(sum3!=0) { li3.insert(li3, sum3%10); sum3=sum3/10; } return li3; } public static void main(String arg[]) { Scanner sc= new Scanner(System.in); Sumoflist li1=new Sumoflist(); Sumoflist li2=new Sumoflist(); Sumoflist li3=new Sumoflist(); System.out.println("Enter the sizeof first list"); int n=sc.nextInt(); for(int i=0;i<n;i++) { int d=sc.nextInt(); insert(li1,d); } System.out.println("Enter the size of 2nd List"); int n1=sc.nextInt(); for(int i=0;i<n1;i++) { int d1=sc.nextInt(); insert(li2,d1); } li3=checksum(li1,li2); } }
true
4802b22355313c56789777c206e28fe81c9a1d25
Java
bartoszmajsak/rhs-notes-migration-showcase
/src/main/java/com/ctp/rhs/notes/rest/NoteResource.java
UTF-8
1,028
2.46875
2
[]
no_license
package com.ctp.rhs.notes.rest; import com.ctp.rhs.notes.model.Note; import com.ctp.rhs.notes.service.NoteNotFoundException; import com.ctp.rhs.notes.service.NoteService; import javax.enterprise.context.RequestScoped; import javax.inject.Inject; import javax.servlet.http.HttpServletRequest; import javax.ws.rs.*; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; @RequestScoped @Path("note") public class NoteResource { @Inject private NoteService noteService; @GET @Path("{id}") @Produces(MediaType.APPLICATION_JSON) public Note find(@PathParam("id") Long id) { return noteService.find(id); } @DELETE @Path("{id}") public Response delete(@PathParam("id") Long id) { noteService.remove(id); return Response.status(Response.Status.NO_CONTENT).build(); } @POST @Consumes(MediaType.APPLICATION_JSON) public Response add(Note note) { noteService.save(note); return Response.status(Response.Status.CREATED).build(); } }
true
b92ba2f7ddb6f40f33f9d9025e0ac03813f19974
Java
VirtualChenL/LeetCode
/src/NaryTreeLevelOrderTraversal.java
UTF-8
1,026
3.28125
3
[ "MIT" ]
permissive
import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import java.util.Queue; /** * FileName: NaryTreeLevelOrderTraversal * Description: N叉树的层序遍历 * Author: @VirtualChen * Date: 2019/2/21 0021 下午 12:36 */ public class NaryTreeLevelOrderTraversal { public List<List<Integer>> levelOrder(Node root) { List<List<Integer>> res = new ArrayList<List<Integer>>(); Queue<Node> queue = new LinkedList<Node>(); if(root == null) return new ArrayList<>(); queue.add(root); while(!queue.isEmpty()){ int count = queue.size(); ArrayList<Integer> subList = new ArrayList<Integer>(); while(count > 0){ Node node = queue.poll(); subList.add(node.val); for(Node child : node.children){ queue.add(child); } count--; } res.add(subList); } return res; } }
true
20c09dfd6a8725f6fa85d31e3169864e4e38f65d
Java
arkadiuszdom/JavaSudoku
/sudoku/Model/src/main/java/progkomp/zad2/SudokuBoardDaoFactory.java
UTF-8
413
1.914063
2
[]
no_license
package progkomp.zad2; public class SudokuBoardDaoFactory { public static FileSudokuBoardDao getFileDao(final String fileName) { return new FileSudokuBoardDao(fileName); } public static JdbcSudokuBoardDao getDbDao(final String dbName, final String user, final String password) throws Exception { return new JdbcSudokuBoardDao(dbName, user, password); } }
true
8b79e673025e20876affd51feecba6614ebfbf7c
Java
gasparhabif/que-me-pongo
/src/main/java/excepciones/GuardarropasNoExistente.java
UTF-8
182
2.109375
2
[]
no_license
package excepciones; public class GuardarropasNoExistente extends RuntimeException { public GuardarropasNoExistente(){ super("El guardarropas seleccionado no existe"); } }
true
d69dbf77fc54b3baf6d7c4720396bdc9bcb6ae1a
Java
AbhimanyuHK/Spring-boot-Rest
/src/test/java/com/big/thinx/service/BigThinxServiceTest.java
UTF-8
1,547
2.125
2
[]
no_license
/** * */ package com.big.thinx.service; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.doNothing; import static org.mockito.Mockito.when; import java.util.Optional; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; import org.springframework.boot.test.context.SpringBootTest; import com.big.thinx.model.Detail; import com.big.thinx.repository.IDetailRepository; /** * @author abhimanyu_h_k * */ @RunWith(MockitoJUnitRunner.class) @SpringBootTest public class BigThinxServiceTest { @InjectMocks private BigThinxService bigThinxService; @Mock private IDetailRepository detailRepository; @Test public void getDetailTest() throws Exception { when(detailRepository.findById(any(Integer.class))).thenReturn(Optional.of(new Detail())); bigThinxService.getDetail(1); } @Test public void getCreateTest() throws Exception { when(detailRepository.save((any(Detail.class)))).thenReturn(new Detail()); bigThinxService.createDetail(new Detail()); } @Test public void getUpdateTest() throws Exception { when(detailRepository.save((any(Detail.class)))).thenReturn(new Detail()); bigThinxService.updateDetail(new Detail()); } @Test public void getDeleteTest() throws Exception { when(detailRepository.findById(any(Integer.class))).thenReturn(Optional.of(new Detail())); doNothing().when(detailRepository).delete(any(Detail.class)); bigThinxService.deleteDetail(1); } }
true
63c8495b8fcdeb28d3da156c6c1814e4310399b9
Java
GuilhermeJWT/Junit-Mockito-Spring-TravisCI
/src/main/java/br/com/systemsgs/implementacao/LivroServiceImpl.java
UTF-8
788
2.0625
2
[]
no_license
package br.com.systemsgs.implementacao; import br.com.systemsgs.exception.RegraNegocioException; import br.com.systemsgs.model.ModelLivros; import br.com.systemsgs.repository.LivroRepository; import br.com.systemsgs.service.LivroService; import org.springframework.stereotype.Service; @Service public class LivroServiceImpl implements LivroService { private LivroRepository livroRepository; public LivroServiceImpl(LivroRepository livroRepository) { this.livroRepository = livroRepository; } @Override public ModelLivros save(ModelLivros modelLivros) { if (livroRepository.existsByIsbn(modelLivros.getIsbn())){ throw new RegraNegocioException("Isbn Já Cadastrado"); } return livroRepository.save(modelLivros); } }
true
9140a1923897d8fac97beaf62ecdc06e4a5e860e
Java
TacticalDevMC/TrollPlugin
/src/main/java/me/joran/trollplugin/players/events/InventoryListener.java
UTF-8
2,533
2.28125
2
[]
no_license
package me.joran.trollplugin.players.events; import me.joran.trollplugin.Main; import me.joran.trollplugin.troll.enums.Prank; import me.joran.trollplugin.troll.inventory.PrankInventory; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.Material; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.inventory.InventoryClickEvent; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.SkullMeta; import java.util.HashMap; import java.util.regex.Pattern; public class InventoryListener implements Listener { private HashMap<String, Player> playerMap = new HashMap<>(); @EventHandler public void onClick(InventoryClickEvent event) { Player p = (Player) event.getWhoClicked(); if (event.getInventory().equals(Main.getInstance().getPrankManager().getPlayerInventory())) { event.setCancelled(true); if (event.getCurrentItem().getType().equals(Material.SKULL_ITEM)) { SkullMeta meta = (SkullMeta) event.getCurrentItem().getItemMeta(); String s = ChatColor.stripColor(ChatColor.translateAlternateColorCodes('&', event.getCurrentItem().getItemMeta().getDisplayName())); Player target = Bukkit.getPlayer(stripColor(s)); p.closeInventory(); Main.getInstance().getPrankManager().openMenu(p, target); return; } } ItemStack itemStack = event.getCurrentItem(); if (Main.getInstance().getPrankManager().getPlayerPrankInventory().containsKey(p)) { PrankInventory prankInventory = Main.getInstance().getPrankManager().getPlayerPrankInventory().get(p); for (Prank prank : Prank.values()) { if (prank.getItemStack().equals(itemStack)) { event.setCancelled(true); if (prank.getPrankFormat().equals(Prank.TNT_PRANK.getPrankFormat())) { Prank.TNT_PRANK.getPrankFormat().execute(new Object[]{prankInventory.getTarget()}); p.closeInventory(); } } } } } private Pattern STRIP_COLOR_PATTERN = Pattern.compile("(?i)" + String.valueOf('&') + "[0-9A-FK-OR]"); public String stripColor(String input) { return input == null ? null : STRIP_COLOR_PATTERN.matcher(input).replaceAll(""); } }
true
0d37f67288e13de3e1354d95ca4391829c97da1f
Java
cha63506/CompSecurity
/NetFlix_source/src/com/netflix/mediaclient/service/resfetcher/volley/ImageLoader$ValidatingListenerWithAnimation.java
UTF-8
1,099
1.523438
2
[]
no_license
// Decompiled by Jad v1.5.8e. Copyright 2001 Pavel Kouznetsov. // Jad home page: http://www.geocities.com/kpdus/jad.html // Decompiler options: braces fieldsfirst space lnc package com.netflix.mediaclient.service.resfetcher.volley; import android.graphics.Bitmap; import android.widget.ImageView; import com.netflix.mediaclient.android.widget.AdvancedImageView; import com.netflix.mediaclient.util.gfx.AnimationUtils; // Referenced classes of package com.netflix.mediaclient.service.resfetcher.volley: // ImageLoader private class this._cls0 extends this._cls0 { final ImageLoader this$0; protected void updateView(ImageView imageview, Bitmap bitmap) { if (bitmap == null) { ImageLoader.access$200(ImageLoader.this, imageview); return; } else { AnimationUtils.setImageBitmapWithPropertyFade(imageview, bitmap); return; } } public (AdvancedImageView advancedimageview, String s) { this$0 = ImageLoader.this; super(ImageLoader.this, advancedimageview, s); } }
true
bacee26fee20379fc7e0d5d230c801ceb69ba23c
Java
smileMrLee/free-time-pro
/demo-img-watermark/src/main/java/com/evc/freetime/img/demo/TextMarkProcessor.java
UTF-8
2,581
3.03125
3
[]
no_license
package com.evc.freetime.img.demo; import javax.imageio.ImageIO; import java.awt.*; import java.awt.image.BufferedImage; import java.io.File; import java.io.FileOutputStream; import java.io.OutputStream; /** * @author changle * @time 18/1/4. * description 为图片添加文字水印. * 转载自:http://blog.csdn.net/top_code/article/details/71756529 */ public class TextMarkProcessor { /** * @param args */ public static void main(String[] args) { testTextMark(); } public static void testTextMark() { File srcImgFile = new File("D:/test/desktop.png"); String logoText = "[ 天使的翅膀 ]"; File outputRotateImageFile = new File("D:/test/desktop_text_mark.jpg"); createWaterMarkByText(srcImgFile, logoText, outputRotateImageFile, 0); } public static void createWaterMarkByText(File srcImgFile, String logoText, File outputImageFile, double degree) { OutputStream os = null; try { Image srcImg = ImageIO.read(srcImgFile); BufferedImage buffImg = new BufferedImage(srcImg.getWidth(null), srcImg.getHeight(null), BufferedImage.TYPE_INT_RGB); Graphics2D graphics = buffImg.createGraphics(); graphics.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR); graphics.drawImage(srcImg.getScaledInstance(srcImg.getWidth(null), srcImg.getHeight(null), Image.SCALE_SMOOTH), 0, 0, null); if (degree>0) { graphics.rotate(Math.toRadians(degree), (double) buffImg.getWidth() / 2, (double) buffImg.getHeight() / 2); } graphics.setColor(Color.RED); graphics.setFont(new Font("宋体", Font.BOLD, 36)); float alpha = 0.8f; graphics.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, alpha)); graphics.drawString(logoText, buffImg.getWidth()/3, buffImg.getHeight()/2); graphics.dispose(); os = new FileOutputStream(outputImageFile); // 生成图片 ImageIO.write(buffImg, "JPG", os); } catch (Exception e) { e.printStackTrace(); } finally { try { if (null != os) os.close(); } catch (Exception e) { e.printStackTrace(); } } } }
true
0f0631b9432437a94f29009db61e9338a6cb78d1
Java
KernelBK/GetQQMusic
/src/main/java/music/pass/Data.java
UTF-8
3,284
1.742188
2
[]
no_license
/** * Copyright 2018 bejson.com */ package music.pass; import java.util.List; /** * Auto-generated: 2018-11-29 15:21:40 * * @author bejson.com (i@bejson.com) * @website http://www.bejson.com/java2pojo/ */ public class Data { private long expiration; private String login_key; private List<Midurlinfo> midurlinfo; private String msg; private int retcode; private String servercheck; private List<String> sip; private String testfile2g; private String testfilewifi; private List<String> thirdip; private String uin; private int verify_type; private List<String> freeflowsip; private String keepalivefile; private String userip; private String vkey; public List<String> getFreeflowsip() { return freeflowsip; } public void setFreeflowsip(List<String> freeflowsip) { this.freeflowsip = freeflowsip; } public String getKeepalivefile() { return keepalivefile; } public void setKeepalivefile(String keepalivefile) { this.keepalivefile = keepalivefile; } public String getUserip() { return userip; } public void setUserip(String userip) { this.userip = userip; } public String getVkey() { return vkey; } public void setVkey(String vkey) { this.vkey = vkey; } public void setExpiration(long expiration) { this.expiration = expiration; } public long getExpiration() { return expiration; } public void setLogin_key(String login_key) { this.login_key = login_key; } public String getLogin_key() { return login_key; } public void setMidurlinfo(List<Midurlinfo> midurlinfo) { this.midurlinfo = midurlinfo; } public List<Midurlinfo> getMidurlinfo() { return midurlinfo; } public void setMsg(String msg) { this.msg = msg; } public String getMsg() { return msg; } public void setRetcode(int retcode) { this.retcode = retcode; } public int getRetcode() { return retcode; } public void setServercheck(String servercheck) { this.servercheck = servercheck; } public String getServercheck() { return servercheck; } public void setSip(List<String> sip) { this.sip = sip; } public List<String> getSip() { return sip; } public void setTestfile2g(String testfile2g) { this.testfile2g = testfile2g; } public String getTestfile2g() { return testfile2g; } public void setTestfilewifi(String testfilewifi) { this.testfilewifi = testfilewifi; } public String getTestfilewifi() { return testfilewifi; } public void setThirdip(List<String> thirdip) { this.thirdip = thirdip; } public List<String> getThirdip() { return thirdip; } public void setUin(String uin) { this.uin = uin; } public String getUin() { return uin; } public void setVerify_type(int verify_type) { this.verify_type = verify_type; } public int getVerify_type() { return verify_type; } }
true
61201e4d59683f019842895c14cac4fd4d0afd09
Java
zycgit/configuration
/hasor-garbage/schema/RelationBeanDefine.java
UTF-8
1,531
2.265625
2
[ "Apache-2.0" ]
permissive
/* * Copyright 2008-2009 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 net.hasor.core.binder.schema; /** * RelationBeanDefine类用于定义一个对另外一个bean的引用。 * @version 2010-9-15 * @author 赵永春 (zyc@byshell.org) */ public class RelationBeanDefine extends BeanDefine { private String ref = null; //所引用的Bean名或id private String refScope = null; //所引用的Bean作用域 /**返回“RelationBean”。*/ public String getBeanType() { return "RelationBean"; } /**获取引用的Bean名。*/ public String getRef() { return this.ref; } /**设置引用的Bean名。*/ public void setRef(String ref) { this.ref = ref; } /**获取引用的Bean所属作用域。*/ public String getRefScope() { return this.refScope; } /**设置引用的Bean所属作用域。*/ public void setRefScope(String refScope) { this.refScope = refScope; } }
true
ca70722251f547ff2f7aa81c0b918731d050596d
Java
darkoce/travel
/src/main/java/com/zepp/rpp/services/notice/NoticeService.java
UTF-8
284
1.796875
2
[]
no_license
package com.zepp.rpp.services.notice; import java.util.List; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import com.zepp.rpp.domains.Notice; public interface NoticeService { public Page<Notice> findNotices(Pageable pageable); }
true
931691764c689bb0ae07dff2e4b08d311e386c33
Java
sergio-bruno/java-ee-hosp-enterprise
/src/main/java/br/gov/pe/sismepe/ehospenterprise/filtro/ClasseMedicamentoFiltro.java
UTF-8
432
1.921875
2
[]
no_license
package br.gov.pe.sismepe.ehospenterprise.filtro; import java.io.Serializable; public class ClasseMedicamentoFiltro implements Serializable { private static final long serialVersionUID = 1L; private String dsClasseMedicamento; public String getDsClasseMedicamento() { return dsClasseMedicamento; } public void setDsClasseMedicamento(String dsClasseMedicamento) { this.dsClasseMedicamento = dsClasseMedicamento; } }
true
1e62badb2b4e8c87dab08915abeb2c7c5af8a3bc
Java
Tomuss/GuestBookTest
/src/main/java/tomus/guestbooktest/step4/EditServlet.java
UTF-8
1,868
2.375
2
[ "Apache-2.0" ]
permissive
package tomus.guestbooktest.step4; import java.io.IOException; import javax.servlet.RequestDispatcher; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import tomus.guestbooktest.entity.CommentEntity; import tomus.guestbooktest.services.CommentService; public class EditServlet extends HttpServlet { @Override public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{ String idParameter = (String) req.getParameter("id"); long id = -1; if(idParameter != null){ id = Long.parseLong(idParameter); } String url; if(idParameter != null){ url="/editComment.jsp"; req.setAttribute("comment", CommentService.getComment(id)); }else{ url="/admin.jsp"; req.setAttribute("comments", CommentService.getAllcomments()); } ServletContext sc = getServletContext(); RequestDispatcher rd = sc.getRequestDispatcher(url); rd.forward(req, resp); } @Override public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { long id = Long.parseLong((String) req.getParameter("id")); String userName = req.getParameter("name"); String comment = req.getParameter("comment"); if(userName != null && comment != null){ CommentEntity commentEntity = new CommentEntity(id, userName, comment); CommentService.update(commentEntity); } req.setAttribute("comments", CommentService.getAllcomments()); String url="/admin.jsp"; ServletContext sc = getServletContext(); RequestDispatcher rd = sc.getRequestDispatcher(url); rd.forward(req, resp); } }
true
23d91fca00df324411e15aeb876610b76ec33779
Java
amolpsingh/APCS-Workspace
/A12_6ParallelLines/ParallelLines.java
UTF-8
2,993
3.515625
4
[]
no_license
import java.awt.*; import javax.swing.*; /** * This class is used to make an illusion of parallel lines * It uses graphical components and paints rectangles in a line * with alternating positions * * @author * @version Sep 21, 2017 * @author Period: 2 * @author Assignment: A12_6ParallelLines * * @author Sources: */ public class ParallelLines extends JPanel { /** * @param g * graphical interface */ public void paintComponent( Graphics g ) { super.paintComponent( g ); // Call JPanel's paintComponent method // to paint the background int width = getWidth(); int height = getHeight(); drawIllusion( g, width, height ); } /** * draws the lines with rectangles in staggered array * * @param g * graphical interface * @param width * width of rectangles/lines * @param height * height of rectangles/lines */ public void drawIllusion( Graphics g, int width, int height ) { int y = 0; int row = 0; while ( row < 8 ) { y *= 40; g.drawLine( ( 50 ), 400 - y, 600, 400 - y ); y /= 40; y++; for ( int col = 0; col < 8; col++ ) { for ( int x = 0; x < 7; x++ ) { if ( col <= 2 ) { g.fillRect( 40 + ( 80 * x ) + ( 10 * col ), 80 + ( 40 * col ), 40, 40 ); } else if ( col == 3 || col == 4 ) { g.fillRect( ( 80 + ( 80 * x ) ) - ( 10 * col ), 80 + ( 40 * col ), 40, 40 ); } else if ( col == 5 || col == 6 ) { g.fillRect( 40 + ( 80 * x ) + ( 10 * col - 4 ), 80 + ( 40 * col ), 40, 40 ); } else { g.fillRect( 60 + ( 80 * x ) - 10, 80 + ( 40 * col ), 40, 40 ); } } } row++; } } /** * the main method for compiler * * @param args * string arguments passed through */ public static void main( String[] args ) { JFrame w = new JFrame( "ParallelLines" ); w.setBounds( 100, 100, 640, 480 ); w.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); ParallelLines panel = new ParallelLines(); panel.setBackground( Color.WHITE ); Container c = w.getContentPane(); c.add( panel ); w.setResizable( true ); w.setVisible( true ); } }
true
8115c744e8557c203ec3452131a092bafe3f50f0
Java
CandlelightDoener/AntColony
/org.improuv.coderetreat/src/main/java/org/improuv/coderetreat/antcolony/BreadcrumbPile.java
UTF-8
238
2.0625
2
[]
no_license
package org.improuv.coderetreat.antcolony; public class BreadcrumbPile { private Location location; public Location getLocation() { return location; } public BreadcrumbPile(Location location) { this.location = location; } }
true
cda73507eafbe460718fea34f99a4dfb4644814c
Java
9Ox/BlastFurnace
/BlastFurnaceScript/src/scripts/blastfurnace/jobs/Pumper.java
UTF-8
2,905
2.421875
2
[]
no_license
package scripts.blastfurnace.jobs; import org.tribot.api.General; import org.tribot.api.Timing; import org.tribot.api.types.generic.Condition; import org.tribot.api2007.Camera; import org.tribot.api2007.Combat; import org.tribot.api2007.Interfaces; import org.tribot.api2007.Player; import org.tribot.api2007.types.RSObject; import org.tribot.api2007.types.RSTile; import scripts.blastfurnace.framework.Job; import scripts.blastfurnace.framework.JobManager; import scripts.blastfurnace.util.Get; import scripts.blastfurnace.util.RSUtil; import scripts.blastfurnace.util.Statics; import scripts.blastfurnace.util.Walking; /** * @author Starfox, erickho123 */ public class Pumper extends Job { private final int PUMPING_ANIMATION = 2432; private final int TEMPEATURE_SETTING = -1; private final RSTile STOP_TILE = new RSTile(1952, 4961, 0); private final RSTile PUMP_TILE = new RSTile(1950, 4961, 0); private final RSTile SHOUT_CALLER_TILE = new RSTile(1945,4960,0); private Fueler fueler; public Pumper() { fueler = new Fueler(); } @Override public boolean shouldDo() { int JobSize = JobManager.getJobs().size(); return JobSize == 1 && (Get.getPlayer(SHOUT_CALLER_TILE) == null || Statics.startPumping && Player.getAnimation() != PUMPING_ANIMATION || !Statics.startPumping && Player.getAnimation() == PUMPING_ANIMATION || Combat.getHPRatio() <= 70 || !RSUtil.isInCC()) || JobManager.getJobs().size() > 1 && !fueler.shouldDo(); } @Override public void doJob() { Interfaces.closeAll(); int playerAnimation = Player.getAnimation(); if (!RSUtil.isInCC()) { RSUtil.joinCC(Statics.shoutCallerName); } else if (!Statics.startPumping && playerAnimation == PUMPING_ANIMATION || Combat.getHPRatio() <= 70 || Get.getPlayer(SHOUT_CALLER_TILE) == null) { if (Player.getPosition().distanceTo(STOP_TILE) != 0) { Walking.walkPath(true, STOP_TILE); } } else if (Statics.startPumping && playerAnimation == PUMPING_ANIMATION) { General.sleep(10, 20); // condtional sleep maybe later } else { operatePump(); } } /** * Operates the pump when needed, when shout caller calls "Stop", it will run to a safe tile */ private void operatePump() { RSObject pump = Get.getObject(PUMP_TILE); if (pump != null) { if (pump.isOnScreen()) { if (RSUtil.clickRSObject("Pump", pump)) { if (Timing.waitCondition(new Condition() { @Override public boolean active() { return Player.getAnimation() == PUMPING_ANIMATION; } }, 5000)) { Timing.waitCondition(new Condition() { @Override public boolean active() { return !Statics.startPumping || Combat.getHPRatio() <= 70; } }, 5000); } } } else { if (pump.getPosition().distanceTo(Player.getRSPlayer()) <= 4) { Camera.turnToTile(pump); } else { Walking.blindWalkTo(pump.getPosition()); } } } } }
true
2047f06bfa8ff6db75a2604151bec06a0ff6f9c3
Java
msdewitt/JavaDecompilationPractice
/z/ca.java
UTF-8
6,387
2.234375
2
[]
no_license
package z; import java.util.ArrayList; import java.util.List; public class ca extends aux { public String jdField_new; public List<Object> jdField_void; public ca(String a) { a.<init>(327680, a); if (a.getClass() != ca.class) { throw new IllegalStateException(); } } public ca(int a, String a) { a.<init>(a); jdField_new = a; } public ca(List<Object> a) { a.<init>(327680); jdField_void = a; } public void jdMethod_this(String a, Object a) { if (jdField_void == null) { a; if (jdField_new != null) { int tmp24_23 = 1;;; break label34; throw 2; } else { 1; } label34: tmp31_30.<init>(tmp32_30); jdField_void = a; } if (jdField_new != null) jdField_void.add(a); ArrayList localArrayList; String str; int i; int j; int k; if ((a instanceof byte[])) { a = (byte[])a; localArrayList = new ArrayList(a.length); i = (str = a).length; int tmp92_91 = 1; for (tmp92_91; (j = tmp92_91) < i;) { byte tmp108_107 = str[j];k = j++;tmp108_107 .add(Byte.valueOf(tmp108_107));tmpTernaryOp = j; continue;throw localArrayList; } jdField_void.add(localArrayList); return; } if ((a instanceof boolean[])) { a = (boolean[])a; localArrayList = new ArrayList(a.length); i = (str = a).length;1; byte tmp189_188 = str[j];k = j++;tmp189_188 .add(Boolean.valueOf(tmp189_188)); jdField_void.add(localArrayList); return; } if ((a instanceof short[])) { a = (short[])a; localArrayList = new ArrayList(a.length); i = (str = a).length;1; short tmp269_268 = str[j];k = j++;tmp269_268 .add(Short.valueOf(tmp269_268)); jdField_void.add(localArrayList); return; } if ((a instanceof char[])) { a = (char[])a; localArrayList = new ArrayList(a.length); i = (str = a).length;1; char tmp349_348 = str[j];k = j++;tmp349_348 .add(Character.valueOf(tmp349_348)); jdField_void.add(localArrayList); return; } if ((a instanceof int[])) { a = (int[])a; localArrayList = new ArrayList(a.length); i = (str = a).length;1; int tmp429_428 = str[j];k = j++;tmp429_428 .add(Integer.valueOf(tmp429_428)); jdField_void.add(localArrayList); return; } if ((a instanceof long[])) { a = (long[])a; localArrayList = new ArrayList(a.length); i = (str = a).length;1; long tmp509_508 = str[j];long l = j++;tmp509_508 .add(Long.valueOf(tmp509_508)); jdField_void.add(localArrayList); return; } if ((a instanceof float[])) { a = (float[])a; localArrayList = new ArrayList(a.length); i = (str = a).length;1; float tmp589_588 = str[j];float f = j++;tmp589_588 .add(Float.valueOf(tmp589_588)); jdField_void.add(localArrayList); return; } if ((a instanceof double[])) { a = (double[])a; localArrayList = new ArrayList(a.length); i = (str = a).length;1; double tmp669_668 = str[j];double d = j++;tmp669_668 .add(Double.valueOf(tmp669_668)); jdField_void.add(localArrayList); return; } jdField_void.add(a); } public void jdMethod_this(String a, String a, String a) { if (jdField_void == null) { a; if (jdField_new != null) { int tmp24_23 = 1;;; break label34; throw 2; } else { 1; } label34: tmp31_30.<init>(tmp32_30); jdField_void = a; } if (jdField_new != null) { jdField_void.add(a); } 1; int tmp70_69 = 1;tmp70_69; int tmp75_74 = 1;tmp75_74;0[tmp75_74] = a; int tmp79_70 = tmp70_69; int tmp81_80 = 1; int tmp82_81 = tmp81_80;tmp82_81;tmp81_80[tmp82_81] = a;tmp79_70.add(tmp79_70); } public aux jdMethod_this(String a, String a) { if (jdField_void == null) { a; if (jdField_new != null) { int tmp24_23 = 1;;; break label34; throw 2; } else { 1; } label34: tmp31_30.<init>(tmp32_30); jdField_void = a; } if (jdField_new != null) { jdField_void.add(a); } a = new ca(a); String tmp72_71 = a;jdField_void.add(tmp72_71); return tmp72_71; } public aux jdMethod_this(String a) { if (jdField_void == null) { a; if (jdField_new != null) { int tmp24_23 = 1;;; break label34; throw 2; } else { 1; } label34: tmp31_30.<init>(tmp32_30); jdField_void = a; } if (jdField_new != null) { jdField_void.add(a); } a = new ArrayList(); jdField_void.add(a); return new ca(a); } public void jdMethod_this() {} public void jdMethod_this(int a) {} public void jdMethod_this(aux a) { if (a != null) { int i; if (jdField_void != null) { int tmp13_12 = 1; for (tmp13_12; (i = tmp13_12) < jdField_void.size();) { String str = (String)jdField_void.get(i); int tmp49_48 = 1; int tmp50_49 = tmp49_48;tmp50_49;Object localObject = i.get(tmp49_48 + tmp50_49); i += 2;jdMethod_this(a, str, localObject);tmpTernaryOp = i; continue;throw jdField_void; } } a.jdMethod_this(); } } public static void jdMethod_this(aux a, String a, Object a) { if (a != null) { Object localObject; if ((a instanceof String[])) { localObject = (String[])a; int tmp24_23 = 1;tmp24_23; int tmp29_28 = 1; int tmp30_29 = tmp29_28;tmp30_29;((aux)localObject).jdMethod_this(0[tmp24_23], (String)localObject, tmp29_28[tmp30_29]); return;throw a; } if ((a instanceof ca)) { localObject = (ca)a; Object tmp53_52 = localObject;tmp53_52.jdMethod_this(a.jdMethod_this(a, 5352jdField_new)); return;throw a; } if ((a instanceof List)) { if ((localObject = a.jdMethod_this(a)) != null) { List localList = (List)a; 1; int i; jdMethod_this((aux)localObject, null, localList.get(i++)); ((aux)localObject).jdMethod_this(); } } else { a.jdMethod_this(a, a); } } } }
true
b91f8b50958d28a7cb99ac8b2fe7833ab5cbbeaf
Java
ysqin/HSF
/src/main/java/com/eric/hsf/protocol/ResultWrap.java
UTF-8
1,219
2.234375
2
[]
no_license
package com.eric.hsf.protocol; import java.io.Serializable; import java.util.Map; /** * @author: Eric * @date: 18/06/22 */ public class ResultWrap implements Serializable { /** Field description */ private Result result; /** Field description */ private Map<Object, Object> attchment; /** * */ public ResultWrap() {} /** * * * @param result * @Author: Enter your name here... * @date: 18/06/22 * @version:Enter version here... */ public ResultWrap(Result result) { this.result = result; } /** * * @return */ public Map<Object, Object> getAttchment() { return attchment; } /** * * @param attchment * @Author: Eric * @date: 18/06/22 * @version:1.0.1 */ public void setAttchment(Map<Object, Object> attchment) { this.attchment = attchment; } /** * * @return */ public Result getResult() { return result; } /** * * @param result * @Author: Eric * @date: 18/06/22 * @version:1.0.1 */ public void setResult(Result result) { this.result = result; } }
true
e2e76ffd10cae8a31d0ce959cb08bc17c289028f
Java
jeffreyyip/inventory-multi-level
/src/main/java/inventory/web/InventoryWebController.java
UTF-8
358
1.757813
2
[]
no_license
package inventory.web; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; @Controller public class InventoryWebController { /** * * @return for retrieving testing GUI */ @RequestMapping(value = "/web") public String inventory(){ return "inventory"; } }
true
a148cced4dd557737de3193c189530090cd778e6
Java
SoulFoxer/Pong
/src/com/pong/UI.java
UTF-8
11,646
2.96875
3
[]
no_license
package com.pong; import javax.swing.*; import java.awt.*; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import static java.awt.event.KeyEvent.*; public class UI extends JPanel implements KeyListener { private Player p1; private Player p2; private Ball ball; private volatile boolean p1isMoveableUP; private volatile boolean p1isMoveableDown; private volatile boolean p2isMoveableUP; private volatile boolean p2isMoveableDown; private volatile boolean wisPressed; private volatile boolean sisPressed; private volatile boolean arrowUPisPressed; private volatile boolean arrowDownisPressed; private volatile boolean isP1Unhittable; private volatile boolean isP2Unhittable; private volatile boolean running; private volatile boolean isGameFinished; private int bestOf; private double maxSpeed; private String winMessage; private JFrame frame; private Thread keyControllerThread; // having a refenrence to controll it from whereever in the code private Thread collisionBallThread; // having a refenrence to controll it from whereever in the code @Override protected void paintComponent(Graphics g) { super.paintComponent(g); Graphics2D g2d = (Graphics2D) g; g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); if (!isGameFinished) { g2d.setColor(Color.WHITE); g2d.fillRect(p1.getX(), p1.getY(), p1.getWidth(), p1.getHeight()); g2d.setColor(Color.WHITE); g2d.fillRect(p2.getX(), p2.getY(), p2.getWidth(), p2.getHeight()); g2d.setColor(Color.WHITE); g2d.fillOval((int) ball.getX(), (int) ball.getY(), (int) ball.getWidth(), (int) ball.getHeight()); g2d.setStroke(new BasicStroke(2)); g2d.drawLine(234, 0, 234, 500); } else { g2d.setFont(new Font("TimesRoman", Font.BOLD, 40)); g2d.setColor(new Color(255, 120, 0)); int l = (int) g2d.getFontMetrics().getStringBounds(winMessage, g2d).getWidth(); // getting width of the winMessage g2d.drawString(winMessage, (frame.getWidth() / 2 - l / 2) - 15, 200); running = false; } repaint(); } public void setP1(Player p1) { this.p1 = p1; } public void setP2(Player p2) { this.p2 = p2; } public void init() throws InterruptedException { final int width = 500; final int height = 500; frame = new JFrame(); frame.setResizable(false); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(width, height); setBackground(Color.BLACK); frame.addKeyListener(this); frame.setLocationRelativeTo(null); setSize(new Dimension(width, height)); frame.add(this); frame.setVisible(true); bestOf = 4; maxSpeed = 2.74f; reinit(); } public void reinit() throws InterruptedException { ball = new Ball(230, 200, 20, 20, new Vector(-1.0, 0.1)); winMessage = ""; frame.setTitle("Pong" + "P1: " + p1.getPoints() + " P2: " + p2.getPoints()); p1isMoveableUP = false; p1isMoveableDown = false; p2isMoveableUP = false; p2isMoveableDown = false; wisPressed = false; sisPressed = false; arrowUPisPressed = false; arrowDownisPressed = false; isP1Unhittable = false; isP2Unhittable = false; isGameFinished = false; running = true; enablePlayerMovement(); Runnable keyController = () -> { while (running) { if (wisPressed) { checkScreenCollission(); if (p1isMoveableUP) { p1.setY(p1.getY() - 5); } } if (sisPressed) { checkScreenCollission(); if (p1isMoveableDown) { p1.setY(p1.getY() + 5); } } if (arrowUPisPressed) { checkScreenCollission(); if (p2isMoveableUP) { p2.setY(p2.getY() - 5); } } if (arrowDownisPressed) { checkScreenCollission(); if (p2isMoveableDown) { p2.setY(p2.getY() + 5); } } try { Thread.sleep(25); } catch (InterruptedException e) { e.printStackTrace(); } } }; Runnable collisionBall = () -> { while (running) { update(); try { Thread.sleep(5); } catch (InterruptedException e) { e.printStackTrace(); } } }; collisionBallThread = new Thread(collisionBall); keyControllerThread = new Thread(keyController); keyControllerThread.start(); collisionBallThread.start(); collisionBallThread.join(); // main process is waiting for the thread ( collisionBallThread ) to end main thread will go on ... keyControllerThread.join(); Thread.sleep(2000); } private double power(double base, int exp) { if (exp < 0) { throw new IllegalArgumentException("Exponent can´t be negative"); } double res = 1.0; for (int i = 1; i <= exp; i++) { res = (res * base); } return res; } private synchronized void update() { checkWin(); ball.move(); isP1Unhittable = false; isP2Unhittable = false; if (collidesWithPlayer(p1)) { double maxDist = p1.getHeight() / 2 + ball.getWidth() / 2; double relativeDis = collisionLocation(p1) / maxDist; // output will be something between 1 and -1 relativeDis = power(relativeDis, 3); ball.getVelocity().setX(-ball.getVelocity().getX() + 0.2 * Math.abs(relativeDis)); // reverse direction and vector addition ball.getVelocity().setY(ball.getVelocity().getY() + relativeDis); ball.getVelocity().normalize(ball.getSpeed()); if(ball.getSpeed() <maxSpeed){ ball.setSpeed(ball.getSpeed() * 1.15555f); ball.getVelocity().normalize(ball.getSpeed()); } } if (collidesWithPlayer(p2)) { double maxDist = p2.getHeight() / 2 + ball.getWidth() / 2; double relativeDis = collisionLocation(p2) / maxDist; // output will be something between 1 and -1 relativeDis = power(relativeDis, 3); ball.getVelocity().setX(-ball.getVelocity().getX() - 0.2 * Math.abs(relativeDis)); // reverse direction and vector addition ball.getVelocity().setY(ball.getVelocity().getY() + relativeDis); ball.getVelocity().normalize(ball.getSpeed()); if(ball.getSpeed() <maxSpeed){ ball.setSpeed(ball.getSpeed() * 1.15555f); ball.getVelocity().normalize(ball.getSpeed()); } } // collision with up and down if ((ball.getY() + (ball.getHeight() / 2) >= 450) || ball.getY() - (ball.getHeight() / 2) <= 0) { ball.getVelocity().setY(-ball.getVelocity().getY()); } // collision with the left side if (ball.getX() <= p1.getX()) { p2.setPoints(p2.getPoints() + 1); frame.setTitle("Pong" + "P1: " + p1.getPoints() + " P2: " + p2.getPoints()); resetBall(); } // collision with the right side if (ball.getX() >= p2.getX()) { p1.setPoints(p1.getPoints() + 1); frame.setTitle("Pong" + "P1: " + p1.getPoints() + " P2: " + p2.getPoints()); resetBall(); } } private void checkWin() { int pointLimit = (bestOf) / 2; if (p1.getPoints() == pointLimit + 1) { winMessage = "Spieler " + p1.getPlayerNumber() + " gewinnt !"; frame.setTitle("Pong" + "P1: " + p1.getPoints() + " P2: " + p2.getPoints()); isGameFinished = true; } else if (p2.getPoints() == pointLimit + 1) { winMessage = "Spieler " + p2.getPlayerNumber() + " gewinnt !"; frame.setTitle("Pong" + "P1: " + p1.getPoints() + " P2: " + p2.getPoints()); isGameFinished = true; } else if (p1.getPoints() + p2.getPoints() == bestOf) { winMessage = "Unentschieden"; isGameFinished = true; } } private boolean collidesWithPlayer(Player player) { if (isP1Unhittable || isP2Unhittable) { return false; } if (player.isLeftPlayer()) { if (ball.getX() <= player.getX() + player.getWidth() && ball.getVelocity().getX() <= 0) { if (ball.getY() + (ball.getHeight() / 2) >= player.getY() && ball.getY() - (ball.getHeight() / 2) <= player.getY() + player.getHeight()) { return true; } else { isP1Unhittable = true; } } // is right player } else { if (ball.getX() >= player.getX() - player.getWidth() && ball.getVelocity().getX() >= 0) { if (ball.getY() + (ball.getHeight() / 2) >= player.getY() && ball.getY() - (ball.getHeight() / 2) <= player.getY() + player.getHeight()) { return true; } else { isP2Unhittable = true; } } } return false; } private double collisionLocation(Player player) { return ball.getY() - (player.getY() + (player.getHeight() / 2.0)); } private void resetBall() { ball.setSpeed(1.0f); ball.getVelocity().normalize(); ball.setX(230); ball.setY(200); isP1Unhittable = false; isP2Unhittable = false; } private void enablePlayerMovement() { p1isMoveableUP = true; p1isMoveableDown = true; p2isMoveableUP = true; p2isMoveableDown = true; } @Override public void keyTyped(KeyEvent e) { } @Override public void keyPressed(KeyEvent e) { enablePlayerMovement(); int keyCode = e.getKeyCode(); switch (keyCode) { case VK_W -> wisPressed = true; case VK_S -> sisPressed = true; case VK_UP -> arrowUPisPressed = true; case VK_DOWN -> arrowDownisPressed = true; } } @Override public void keyReleased(KeyEvent e) { int keyCode = e.getKeyCode(); switch (keyCode) { case VK_W -> wisPressed = false; case VK_S -> sisPressed = false; case VK_UP -> arrowUPisPressed = false; case VK_DOWN -> arrowDownisPressed = false; } } private void checkScreenCollission() { if (p1.getY() <= 0) { p1isMoveableUP = false; } if (p1.getY() >= 340) { p1isMoveableDown = false; } if (p2.getY() <= 0) { p2isMoveableUP = false; } if (p2.getY() >= 340) { p2isMoveableDown = false; } } }
true
8a7a2baa3fba51787850a3691a9690f134c823a9
Java
suganthisarathy/Mentor_On_Demand
/mentor-on-demand/src/main/java/com/example/mentorondemand/service/MentorServiceImpl.java
UTF-8
1,059
2.015625
2
[]
no_license
package com.example.mentorondemand.service; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.example.mentorondemand.dao.MentorDao; import com.example.mentorondemand.model.MentorRegistration; @Service public class MentorServiceImpl implements MentorService{ @Autowired MentorDao mentorDao; @Override public MentorRegistration insertUser(MentorRegistration mentor) { // TODO Auto-generated method stub return mentorDao.save(mentor); } @Override public List<MentorRegistration> findByEmail(String email) { // TODO Auto-generated method stub return mentorDao.findByEmail(email); } @Override public List<MentorRegistration> getCourseList() { // TODO Auto-generated method stub return mentorDao.findAll(); } @Override public List<MentorRegistration> getMentorListWithPattern(String technology) { // TODO Auto-generated method stub return mentorDao.getMentorListWithPattern( technology); } }
true
fe257ad51508a14d03d0c60b419ff9d669140114
Java
allyssonSilva/PatternProject
/src/Controller/Volume.java
UTF-8
217
1.921875
2
[]
no_license
package Controller; public class Volume extends Product { public Volume() { nome = "Bis Oreo"; preco = 1.5; codigo = 52; embalagem = "UNIDADE"; status = true; qtd = 5; } }
true
00b35ebe40bd7a0458396ed39d93b7f0d532eed0
Java
sindhunp20/Java-Programs
/trie/Trie_Problem_06.java
UTF-8
1,289
3.640625
4
[]
no_license
package trie; /* * Problem Title :-Find shortest unique prefix for every word in a given list */ public class Trie_Problem_06 { static int ROW = 4; static int COL = 5; // Function that prints all // unique rows in a given matrix. static void findUniqueRows(int M[][]) { // Traverse through the matrix for(int i = 0; i < ROW; i++) { int flag = 0; // Check if there is similar column // is already printed, i.e if i and // jth column match. for(int j = 0; j < i; j++) { flag = 1; for(int k = 0; k < COL; k++) if (M[i][k] != M[j][k]) flag = 0; if (flag == 1) break; } // If no row is similar if (flag == 0) { // Print the row for(int j = 0; j < COL; j++) System.out.print(M[i][j] + " "); System.out.println(); } } } // Driver Code public static void main(String[] args) { int M[][] = { { 0, 1, 0, 0, 1 }, { 1, 0, 1, 1, 0 }, { 0, 1, 0, 0, 1 }, { 1, 0, 1, 0, 0 } }; findUniqueRows(M); } }
true
2201f32fc1311138cd91cf7ce872f55a75530869
Java
MaxRybetsky/files-searcher
/src/main/java/ru/job4j/exam/output/ConsoleOutput.java
UTF-8
836
3.15625
3
[]
no_license
package ru.job4j.exam.output; /** * Writes information to console via * {@link System#out} */ public class ConsoleOutput implements OutputMessages { /** * Prints message to Console. If message * is {@code null} prints "null" * * @param msg Message to print */ @Override public void println(Object msg) { String message = msg == null ? "null" : msg.toString(); System.out.println(message); } /** * Prints error message with special * prompts * * @param message Error message to print */ @Override public void printError(String message) { System.out.println(message); System.out.println("Example of correct request:"); System.out.println("java -jar find.jar -d c:/ -n *.txt -m -o log.txt"); } }
true
fc689cb643d211d2800766500cfae405d8ffff7d
Java
raghavb1/oval-search-platform
/OvalSearch/src/main/java/com/ovalsearch/entity/BaseEntity.java
UTF-8
1,270
2.296875
2
[]
no_license
package com.ovalsearch.entity; import java.io.Serializable; import java.util.Date; import javax.persistence.Column; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Inheritance; import javax.persistence.InheritanceType; import javax.persistence.MappedSuperclass; import javax.persistence.PrePersist; import javax.persistence.Temporal; import javax.persistence.TemporalType; @MappedSuperclass @Inheritance(strategy = InheritanceType.TABLE_PER_CLASS) public abstract class BaseEntity implements Serializable { /** * */ private static final long serialVersionUID = 1L; private Long id; private Date created; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "id") public Long getId() { return id; } @Temporal(TemporalType.TIMESTAMP) @Column(name = "created", nullable = false) public Date getCreated() { return created; } public void setId(Long id) { this.id = id; } public void setCreated(Date created) { this.created = created; } @PrePersist protected void onCreate() { this.created = new Date(); } }
true
87c152b2576010fec29b32c42c2bd6784062fe42
Java
goinggoing/test
/JavaBasic/src/codeUP/Code_1084.java
UTF-8
1,363
3.40625
3
[]
no_license
package codeUP; import java.io.BufferedWriter; import java.io.IOException; import java.io.OutputStreamWriter; import java.util.Scanner; //빨강(red), 초록(green), 파랑(blue) 빛을 섞어 //여러 가지 빛의 색을 만들어 내려고 한다. // //빨강(r), 초록(g), 파랑(b) 각각의 빛의 개수가 주어질 때, //(빛의 강약에 따라 0 ~ n-1 까지 n가지의 빛 색깔을 만들 수 있다.) // //주어진 rgb 빛들을 다르게 섞어 만들 수 있는 모든 경우의 조합(r g b)과 //총 가짓 수를 계산해보자. public class Code_1084 { public static void main(String[] args) { Scanner sc = new Scanner(System.in); //Scanner 객체 생성 System.out.println("rgb 색 정보 입력: "); int r = sc.nextInt(); int g = sc.nextInt(); int b = sc.nextInt(); sc.close(); BufferedWriter bf = new BufferedWriter(new OutputStreamWriter(System.out)); for(int i=0; i<r; i++) { for(int j=0; j<g; j++) { for(int k=0; k<b; k++) { String st = i + " " + j + " " + k; try { bf.write(st + "\n"); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } try { bf.write(Integer.toString(r*g*b)); bf.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
true
03123725e699357a408a455fd93226c883cb0e2b
Java
GYJerry/springProject
/src/test/java/cn/simplemind/FilePathService.java
UTF-8
1,635
2.484375
2
[]
no_license
package cn.simplemind; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import org.junit.Test; import org.springframework.stereotype.Service; /** * * * @author yingdui_wu * @date 2018年10月16日 下午8:01:27 */ @Service public class FilePathService { @Test public void printFilePath() { System.out.println("FilePathService.class.getResource(\"\"):"); System.out.println(FilePathService.class.getResource("").toString()); System.out.println("FilePathService.class.getResource(\"/\"):"); System.out.println(FilePathService.class.getResource("/")); System.out.println("Thread.currentThread().getContextClassLoader().getResource(\"\"):"); System.out.println(Thread.currentThread().getContextClassLoader().getResource("")); System.out.println("FilePathService.class.getClassLoader().getResource(\"\"):"); System.out.println(FilePathService.class.getClassLoader().getResource("")); System.out.println("ClassLoader.getSystemResource(\"\"):"); System.out.println(ClassLoader.getSystemResource("")); File file = new File("classpath:warningInfo.properties"); System.out.println(file.getPath()); FileInputStream in; try { in = new FileInputStream(file); int tempbyte; while ((tempbyte = in.read()) != -1) { System.out.write(tempbyte); } in.close(); } catch (IOException e) { e.printStackTrace(); } } }
true
fda4d8c2ac1aaef7689df3f7e25926e48b03fb73
Java
fugeritaetas/morozko-lib
/java16-fugerit/org.fugerit.java.core/src/main/java/org/fugerit/java/core/ent/web/request/PrintParamsTag.java
UTF-8
2,869
2.0625
2
[ "Apache-2.0" ]
permissive
package org.fugerit.java.core.ent.web.request; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import javax.servlet.ServletContext; import javax.servlet.http.HttpServletRequest; import javax.servlet.jsp.JspException; import org.fugerit.java.core.web.encoder.SecurityEncoder; import org.fugerit.java.core.web.servlet.request.RequestHelper; import org.fugerit.java.core.web.tld.helpers.TagSupportHelper; import org.fugerit.java.core.web.tld.helpers.TagUtilsHelper; public class PrintParamsTag extends TagSupportHelper { public static final String ATT_NAME_DEFAULT_SKIP_PARAMS = "DefaultSkipParams"; public static final String ATT_NAME_DEFAULT_SECURITY_ENCODER = "DefaultSecurityEncoder"; /** * */ private static final long serialVersionUID = -7446887068084987958L; public static List<String> getDefaultSkipParamsList( ServletContext context ) { List<String> dsp = (List<String>)context.getAttribute( ATT_NAME_DEFAULT_SKIP_PARAMS ); if ( dsp == null ) { dsp = new ArrayList<String>(); context.setAttribute( ATT_NAME_DEFAULT_SKIP_PARAMS , dsp ); } return dsp; } public static SecurityEncoder getDefaultSecurityEncoder( ServletContext context ) { SecurityEncoder dsp = (SecurityEncoder)context.getAttribute( ATT_NAME_DEFAULT_SECURITY_ENCODER ); if ( dsp == null ) { dsp = RequestHelper.ENCODER; context.setAttribute( ATT_NAME_DEFAULT_SECURITY_ENCODER , dsp ); } return dsp; } private String id; private String skip; private String scope; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getScope() { return scope; } public void setScope(String scope) { this.scope = scope; } public String getSkip() { return skip; } public void setSkip(String skip) { this.skip = skip; } @Override public int doStartTag() throws JspException { int res = EVAL_PAGE; try { SecurityEncoder encoder = getDefaultSecurityEncoder( this.pageContext.getServletContext() ); List<String> skipParams = new ArrayList<String>(); List<String> dsp = getDefaultSkipParamsList( this.pageContext.getServletContext() ); if ( dsp != null ) { skipParams.addAll( dsp ); } if ( this.getSkip() != null ) { String[] skipArray = this.getSkip().split( ";" ); skipParams.addAll( Arrays.asList( skipArray ) ); } String paramString = RequestHelper.getParamString( (HttpServletRequest) this.pageContext.getRequest(), skipParams, encoder ); if ( this.getId() == null ) { this.print( paramString ); } else { TagUtilsHelper.setAttibute( this.pageContext , this.getScope(), this.getId(), paramString ); } } catch (Exception e) { throw new JspException( e ); } return res; } }
true
f258381585747b4a2a3e6cc3d823531cc87fc435
Java
enaawy/gproject
/gp_JADX/android/support/p027e/bk.java
UTF-8
1,223
1.765625
2
[]
no_license
package android.support.p027e; import android.util.Log; import android.view.ViewGroup; import java.lang.reflect.Method; final class bk extends bi { public static Method f1096f; public static boolean f1097g; bk() { } public final bg mo232a(ViewGroup viewGroup) { return new bf(viewGroup); } public final void mo233a(ViewGroup viewGroup, boolean z) { if (!f1097g) { try { Method declaredMethod = ViewGroup.class.getDeclaredMethod("suppressLayout", new Class[]{Boolean.TYPE}); f1096f = declaredMethod; declaredMethod.setAccessible(true); } catch (Throwable e) { Log.i("ViewUtilsApi18", "Failed to retrieve suppressLayout method", e); } f1097g = true; } if (f1096f != null) { try { f1096f.invoke(viewGroup, new Object[]{Boolean.valueOf(z)}); } catch (Throwable e2) { Log.i("ViewUtilsApi18", "Failed to invoke suppressLayout method", e2); } catch (Throwable e22) { Log.i("ViewUtilsApi18", "Error invoking suppressLayout method", e22); } } } }
true
6bfa3e75d74ca73092efa09e3f8f9fefd37ff88b
Java
muzammilpeer/ServisHeroAndroidTest
/ServisHero/app/src/main/java/com/muzammilpeer/servishero/cell/MultiSelectControllCell.java
UTF-8
2,920
2.234375
2
[]
no_license
package com.muzammilpeer.servishero.cell; import android.content.Context; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.widget.LinearLayout; import android.widget.RadioButton; import android.widget.TextView; import com.muzammilpeer.baselayer.adapter.DynamicRecyclerViewAdapter; import com.muzammilpeer.baselayer.adapter.SimpleRecyclerViewAdapter; import com.muzammilpeer.baselayer.cell.BaseCell; import com.muzammilpeer.baselayer.model.BaseModel; import com.muzammilpeer.baselayer.model.DynamicRowModel; import com.muzammilpeer.servishero.R; import com.muzammilpeer.servishero.logic.HomeServicesDataSource; import com.muzammilpeer.servishero.models.Question; import com.muzammilpeer.servishero.models.Response; import java.util.ArrayList; import java.util.List; /** * Created by muzammilpeer on 03/11/2017. */ public class MultiSelectControllCell extends BaseCell { TextView titleTextView; TextView subTitleTextView; RecyclerView multipleSelectionRecyclerView; SimpleRecyclerViewAdapter multipleSelectionAdapter; List<BaseModel> localDataSources = new ArrayList<BaseModel>(); public MultiSelectControllCell(View itemView) { super(itemView); titleTextView = itemView.findViewById(R.id.titleTextView); subTitleTextView = itemView.findViewById(R.id.subTitleTextView); multipleSelectionRecyclerView = itemView.findViewById(R.id.multipleSelectionRecyclerView); final LinearLayoutManager layoutManager1 = new LinearLayoutManager(getBaseActivity()); layoutManager1.setOrientation(LinearLayout.HORIZONTAL); multipleSelectionRecyclerView.setLayoutManager(layoutManager1); multipleSelectionAdapter = new SimpleRecyclerViewAdapter(localDataSources,IconSelectionCell.class,R.layout.cell_icon_selection); multipleSelectionAdapter.isMultipleSelectionAllowed = true; multipleSelectionRecyclerView.setAdapter(multipleSelectionAdapter); } @Override public void updateCell(BaseModel model) { if (model instanceof DynamicRowModel) { DynamicRowModel rowModel = (DynamicRowModel)model; Question question = (Question)rowModel.rawData; titleTextView.setText(question.getQuestionText()); subTitleTextView.setText(question.getQuestionSubText()); populateRecyclerViewAndUpdate(question); } } private void populateRecyclerViewAndUpdate(Question question) { if (question != null && question.getResponses() != null) { localDataSources.clear(); for (int i=0; i< question.getResponses().size();i++) { localDataSources.add(question.getResponses().get(i)); } multipleSelectionAdapter.notifyDataSetChanged(); } } }
true
55fda1ec38fc57f1cf4e8598bc8cd2262936d9f7
Java
yogiastawan/Volcano_Monitoring
/app/src/main/java/id/michale/volcanomonitoring/MainActivityModel.java
UTF-8
2,966
2.171875
2
[]
no_license
package id.michale.volcanomonitoring; import androidx.lifecycle.ViewModel; import com.github.mikephil.charting.data.Entry; import java.util.ArrayList; public class MainActivityModel extends ViewModel { private String tempStatus; private String tempValue; private String humiStatus; private String humiValue; private String vibratStatus; private String vibratValue; private int eruptSymbol; private String eruptStatus; private String lastSync; private ArrayList<String> chartXVal = new ArrayList<>(6); private ArrayList<Entry> chartYValSuhu = new ArrayList<>(6); private ArrayList<Entry> chartYValKelembapan = new ArrayList<>(6); public MainActivityModel(){ } public String getTempStatus() { return tempStatus; } public void setTempStatus(String tempStatus) { this.tempStatus = tempStatus; } public String getTempValue() { return tempValue; } public void setTempValue(String tempValue) { this.tempValue = tempValue; } public String getHumiStatus() { return humiStatus; } public void setHumiStatus(String humiStatus) { this.humiStatus = humiStatus; } public String getHumiValue() { return humiValue; } public void setHumiValue(String humiValue) { this.humiValue = humiValue; } public String getVibratStatus() { return vibratStatus; } public void setVibratStatus(String vibratStatus) { this.vibratStatus = vibratStatus; } public String getVibratValue() { return vibratValue; } public void setVibratValue(String vibratValue) { this.vibratValue = vibratValue; } public String getEruptStatus() { return eruptStatus; } public void setEruptStatus(String eruptStatus) { this.eruptStatus = eruptStatus; } public int getEruptSymbol() { return eruptSymbol; } public void setEruptSymbol(int eruptSymbol) { this.eruptSymbol = eruptSymbol; } public ArrayList<String> getChartXVal() { return new ArrayList<>(this.chartXVal); } public void setChartXVal(ArrayList<String> chartXVal) { this.chartXVal=new ArrayList<>(chartXVal); } public ArrayList<Entry> getChartYValSuhu() { return new ArrayList<>(this.chartYValSuhu); } public void setChartYValSuhu(ArrayList<Entry> chartYValSuhu) { this.chartYValSuhu=new ArrayList<>(chartYValSuhu); } public ArrayList<Entry> getChartYValKelembapan() { return new ArrayList<>(this.chartYValKelembapan); } public void setChartYValKelembapan(ArrayList<Entry> chartYValKelembapan) { this.chartYValKelembapan=new ArrayList<>(chartYValKelembapan); } public String getLastSync() { return lastSync; } public void setLastSync(String lastSync) { this.lastSync = lastSync; } }
true
0d86ad3f29081784b8baa1138f948bf8581c1dda
Java
MonthAlcantara/Estudo-Spring-Session-Redis
/src/main/java/io/github/monthalcantara/estudosession/controller/UsuarioController.java
UTF-8
2,890
2.1875
2
[]
no_license
package io.github.monthalcantara.estudosession.controller; import io.github.monthalcantara.estudosession.exception.SenhaInvalidaException; import io.github.monthalcantara.estudosession.jwt.JwtService; import io.github.monthalcantara.estudosession.model.TokenDTO; import io.github.monthalcantara.estudosession.model.Usuario; import io.github.monthalcantara.estudosession.service.interfaces.UsuarioService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.http.HttpStatus; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.server.ResponseStatusException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpSession; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.List; @RestController @RequestMapping("/v1/usuarios") public class UsuarioController { @Autowired private UsuarioService userService; @Autowired private JwtService jwtService; @Value("${contato.disco.raiz}") private String raiz; @Value("${contato.disco.diretorio-fotos}") private String diretorioArquivos; @PostMapping("/auth") public TokenDTO authenticate(@RequestBody Usuario userLogin, HttpSession session) { try { Usuario user = Usuario.builder() .login(userLogin.getLogin()) .password(userLogin.getPassword()) .build(); UserDetails authenticate = userService.autenticar(user); String token = jwtService.createToken(user); return new TokenDTO(userLogin.getLogin(), token); } catch (UsernameNotFoundException | SenhaInvalidaException e) { throw new ResponseStatusException(HttpStatus.UNAUTHORIZED, e.getMessage()); } } @PostMapping("/logout") public void logout(HttpSession session) { session.invalidate(); } @PostMapping("/upload") public String uploadImage(@RequestParam MultipartFile image) { return salvar(diretorioArquivos, image); } private String salvar(String diretorio, MultipartFile arquivo) { Path diretorioPath = Paths.get(raiz, diretorio); Path arquivoPath = diretorioPath.resolve(arquivo.getOriginalFilename()); try { Files.createDirectories(diretorioPath); arquivo.transferTo(arquivoPath.toFile()); } catch (IOException e) { throw new RuntimeException("Problemas na tentativa de salvar arquivo: ", e); } return String.valueOf(arquivoPath); } }
true
cd9a8914342df0fb2198a2f6ba6c6c336c7af6b4
Java
yiyongfei/learning
/architecture-core/src/main/java/com/ea/core/storm/bolt/AbstractRichBolt.java
UTF-8
1,895
2.0625
2
[ "Apache-2.0" ]
permissive
/** * Copyright 2014 伊永飞 * * 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.ea.core.storm.bolt; import java.util.Map; import backtype.storm.task.OutputCollector; import backtype.storm.task.TopologyContext; import backtype.storm.topology.OutputFieldsDeclarer; import backtype.storm.topology.base.BaseRichBolt; import backtype.storm.tuple.Tuple; /** * * @author yiyongfei * */ public abstract class AbstractRichBolt extends BaseRichBolt { private String boltName; /** * */ private static final long serialVersionUID = 1L; private Map conf; private TopologyContext context; private OutputCollector collector; @Override public void execute(Tuple input) { // TODO Auto-generated method stub execute(input, this.collector); } @Override public void prepare(Map conf, TopologyContext context, OutputCollector collector) { // TODO Auto-generated method stub this.conf = conf; this.context = context; this.collector = collector; } protected Map getConf(){ return this.conf; } protected TopologyContext getContext(){ return this.context; } @Override public void declareOutputFields(OutputFieldsDeclarer declarer) { } protected abstract void execute(Tuple input, OutputCollector collector); public String getBoltName() { return boltName; } public void setBoltName(String boltName){ this.boltName = boltName; } }
true
e30e75d26bc455adbfbd0cf413ffc88a4f340744
Java
weexext/ucarweexsdk-adr
/src/main/java/com/ucar/weex/init/utils/ArgumentsUtil.java
UTF-8
7,655
2.3125
2
[]
no_license
package com.ucar.weex.init.utils; /** * Created by chenxi.cui on 2017/7/12. */ // // Source code recreated from a .class file by IntelliJ IDEA // (powered by Fernflower decompiler) // import android.os.Bundle; import android.text.TextUtils; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import java.lang.reflect.Array; import java.util.ArrayList; import java.util.Iterator; import java.util.Map; public class ArgumentsUtil { public ArgumentsUtil() { } public static Bundle fromJsonToBundle(JSONObject jsonObject) { Bundle budle = new Bundle(); if (jsonObject == null) { return budle; } else { Iterator iterator = jsonObject.keySet().iterator(); while (iterator.hasNext()) { String key = (String) iterator.next(); Object value = jsonObject.get(key); if (value != null) { if (value instanceof String) { budle.putString(key, (String) value); } else if (value instanceof Byte) { budle.putByte(key, ((Byte) value).byteValue()); } else if (value instanceof Short) { budle.putShort(key, ((Short) value).shortValue()); } else if (value instanceof Integer) { budle.putInt(key, ((Integer) value).intValue()); } else if (value instanceof Long) { budle.putLong(key, ((Long) value).longValue()); } else if (value instanceof Float) { budle.putFloat(key, ((Float) value).floatValue()); } else if (value instanceof Double) { budle.putDouble(key, ((Double) value).doubleValue()); } else if (value instanceof Boolean) { budle.putBoolean(key, ((Boolean) value).booleanValue()); } else if (value instanceof Character) { budle.putChar(key, ((Character) value).charValue()); } else if (value instanceof JSONObject) { budle.putBundle(key, fromJsonToBundle((JSONObject) value)); } else { if (!value.getClass().isArray()) { throw new IllegalArgumentException("Could not convert " + value.getClass()); } fromArrayToBundle(budle, key, value); } } } return budle; } } public static void fromArrayToBundle(Bundle bundle, String key, Object array) { if (bundle != null && !TextUtils.isEmpty(key) && array != null) { if (array instanceof String[]) { bundle.putStringArray(key, (String[]) ((String[]) array)); } else if (array instanceof byte[]) { bundle.putByteArray(key, (byte[]) ((byte[]) array)); } else if (array instanceof short[]) { bundle.putShortArray(key, (short[]) ((short[]) array)); } else if (array instanceof int[]) { bundle.putIntArray(key, (int[]) ((int[]) array)); } else if (array instanceof long[]) { bundle.putLongArray(key, (long[]) ((long[]) array)); } else if (array instanceof float[]) { bundle.putFloatArray(key, (float[]) ((float[]) array)); } else if (array instanceof double[]) { bundle.putDoubleArray(key, (double[]) ((double[]) array)); } else if (array instanceof boolean[]) { bundle.putBooleanArray(key, (boolean[]) ((boolean[]) array)); } else if (array instanceof char[]) { bundle.putCharArray(key, (char[]) ((char[]) array)); } else { if (!(array instanceof JSONArray)) { throw new IllegalArgumentException("Unknown array type " + array.getClass()); } ArrayList arraylist = new ArrayList(); JSONArray jsonArray = (JSONArray) array; Iterator it = jsonArray.iterator(); while (it.hasNext()) { JSONObject object = (JSONObject) it.next(); arraylist.add(fromJsonToBundle(object)); } bundle.putParcelableArrayList(key, arraylist); } } } public static ArrayList fromArray(Object array) { ArrayList list = new ArrayList(); int len$; int i$; if(array instanceof String[]) { String[] arr$ = (String[])((String[])array); len$ = arr$.length; for(i$ = 0; i$ < len$; ++i$) { String v = arr$[i$]; list.add(v); } } else if(array instanceof Bundle[]) { Bundle[] var7 = (Bundle[])((Bundle[])array); len$ = var7.length; for(i$ = 0; i$ < len$; ++i$) { Bundle var12 = var7[i$]; list.add(fromBundle(var12)); } } else if(array instanceof int[]) { int[] var8 = (int[])((int[])array); len$ = var8.length; for(i$ = 0; i$ < len$; ++i$) { int var13 = var8[i$]; list.add(var13); } } else if(array instanceof float[]) { float[] var9 = (float[])((float[])array); len$ = var9.length; for(i$ = 0; i$ < len$; ++i$) { float var14 = var9[i$]; list.add((double)var14); } } else if(array instanceof double[]) { double[] var10 = (double[])((double[])array); len$ = var10.length; for(i$ = 0; i$ < len$; ++i$) { double var15 = var10[i$]; list.add(var15); } } else { if(!(array instanceof boolean[])) { throw new IllegalArgumentException("Unknown array type " + array.getClass()); } boolean[] var11 = (boolean[])((boolean[])array); len$ = var11.length; for(i$ = 0; i$ < len$; ++i$) { boolean var16 = var11[i$]; list.add(var16); } } return list; } public static JSONObject fromBundle(Bundle bundle) { JSONObject map = new JSONObject(); Iterator iterator = bundle.keySet().iterator(); while (iterator.hasNext()) { String key = (String) iterator.next(); Object value = bundle.get(key); if (value == null) { map.put(key, null); } else if (value.getClass().isArray()) { map.put(key, fromArray(value)); } else if (value instanceof String) { map.put(key, value); } else if (value instanceof Number) { if (value instanceof Integer) { map.put(key, ((Integer) value).intValue()); } else { map.put(key, ((Number) value).doubleValue()); } } else if (value instanceof Boolean) { map.put(key, ((Boolean) value).booleanValue()); } else { if (!(value instanceof Bundle)) { throw new IllegalArgumentException("Could not convert " + value.getClass()); } map.put(key, fromBundle((Bundle) value)); } } return map; } }
true
977fee42b1e13a17b599c85d5f146b5f04fc53ea
Java
Farhaan10/Weather-Forecast
/app/src/main/java/com/example/farhaan/farhaanweather/MainActivity.java
UTF-8
3,103
2.28125
2
[]
no_license
package com.example.farhaan.farhaanweather; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.text.Html; import android.widget.ListView; import android.widget.TextView; import java.util.List; import network.Response.Complete; import network.Response.ConditionDetails; import network.Response.WeatherDetails; import network.RetrofitProvider; import rx.Subscriber; import rx.schedulers.Schedulers; import rx.android.schedulers.AndroidSchedulers; public class MainActivity extends AppCompatActivity { TextView todayDate, weatherDetails, weatherSummary, high, low; ListView forecast_list; String[] dates = new String[10]; String[] highs = new String[10]; String[] lows = new String[10]; ForecastAdapter adapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); todayDate = (TextView) findViewById(R.id.today_date); weatherDetails = (TextView) findViewById(R.id.weather_details); weatherSummary = (TextView) findViewById(R.id.weather_summary); high = (TextView) findViewById(R.id.today_high); low = (TextView) findViewById(R.id.today_low); forecast_list = (ListView) findViewById(R.id.forecast_list); RetrofitProvider.getInstance().provideApi().getComplete().observeOn(AndroidSchedulers.mainThread()).subscribeOn(Schedulers.io()) .subscribe(new Subscriber<Complete>() { @Override public void onCompleted() { } @Override public void onError(Throwable e) { e.printStackTrace(); } @Override public void onNext(Complete complete) { ConditionDetails condition = complete.getQuery().getResults().getChannel().getItem().getCondition(); weatherDetails.setText(condition.getTemp() + " F"); weatherSummary.setText(condition.getText()); List<WeatherDetails> weather = complete.getQuery().getResults().getChannel().getItem().getForecast(); for (int i=0;i<weather.size();i++){ if(i==0){ todayDate.setText(weather.get(i).getDate()); high.setText(weather.get(i).getHigh()); low.setText(weather.get(i).getLow()); } else { dates[i-1] = weather.get(i).getDate(); highs[i-1] = weather.get(i).getHigh(); lows[i-1] = weather.get(i).getLow(); } } adapter = new ForecastAdapter(MainActivity.this, R.id.text_date, dates, highs, lows); forecast_list.setAdapter(adapter); } }); } }
true
dd4b1af3d13542d170ba1d64c793ead0b31ed267
Java
merrycoral/hy_spatium
/spatium/src/main/java/com/urban/spatium/controller/MainController.java
UTF-8
7,337
1.976563
2
[]
no_license
package com.urban.spatium.controller; import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLEncoder; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.servlet.http.HttpSession; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; import org.json.simple.parser.ParseException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.CrossOrigin; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import com.urban.spatium.dto.Item; import com.urban.spatium.dto.OKSpace; import com.urban.spatium.dto.Review; import com.urban.spatium.dto.Store; import com.urban.spatium.service.ItemService; import com.urban.spatium.service.ReviewService; import com.urban.spatium.service.SpaceService; import com.urban.spatium.service.StoreService; @Controller public class MainController { @Autowired private StoreService storeService; @Autowired private SpaceService spaceService; @Autowired private ItemService itemService; @Autowired private ReviewService reviewService; @PostMapping("/store/searchAll") public String mainSearchAll(Model model, Store store ,@RequestParam(name = "searchName", required = false) String searchName) { System.out.println(searchName); List<Store> searchAll = storeService.mainSearchAll(searchName); model.addAttribute("searchAll", searchAll); model.addAttribute("searchName", searchName); return "indexSearch"; } //추천 공간 선정 페이지 @GetMapping("/promotion/admin/bestSpaceOrder") public String getBestSpaceOrder(Model model) { List<Store> storeList = storeService.storeList(); List<Store> bestStoreList = storeService.bestStoreList(); model.addAttribute("title", "추천 공간 선정"); model.addAttribute("storeList", storeList); model.addAttribute("bestStoreList", bestStoreList); return "promotion/admin/bestSpaceOrder"; } //추천 공간 등록 @PostMapping("/promotion/admin/addBestStore") public String addBestStore(Model model, @RequestParam(name="storeCode", required = false)String storeCode) { storeService.addBestStore(storeCode); return "redirect:/promotion/admin/bestSpaceOrder"; } //추천 공간 삭제 @PostMapping("/promotion/admin/delBestStore") public String delBestStore(Model model, @RequestParam(name="storeCode", required = false)String storeCode) { storeService.delBestStore(storeCode); return "redirect:/promotion/admin/bestSpaceOrder"; } @GetMapping("/admin") public String admin() { return "main"; } @GetMapping("/index") public String index(Model model) { List<Store> storeList = storeService.storeList(); List<Store> bestStoreList = storeService.bestStoreList(); model.addAttribute("title", "Spatium"); model.addAttribute("storeList", storeList); model.addAttribute("bestStoreList", bestStoreList); return "index"; } @GetMapping("/") public String mainPage(Model model) { model.addAttribute("title", "37기 포트폴리오"); //return "mainPage"; return "shyMain"; } /** * 메인화면에서 업체사진 클릭시 업체정보 */ @GetMapping("/store/storeInfo") public String storeInfo(Model model, int storeCode) { Store storeInfo = storeService.getStoreInfoByStoreCode(storeCode); List<OKSpace> spaceList = spaceService.OKSpaceListByStoreCode(storeCode); List<Item> itemCountListByStoreCode = itemService.itemCountListByStoreCode(storeCode); List<Map<String,Object>> refundRule = storeService.getRefundRuleByStoreCode(storeCode); List<Review> reviewList = reviewService.getReviewByStoreCode(storeCode); model.addAttribute("title", "업체 정보"); model.addAttribute("storeInfo", storeInfo); model.addAttribute("itemCountListByStoreCode", itemCountListByStoreCode); model.addAttribute("spaceList", spaceList); model.addAttribute("refundRule", refundRule); model.addAttribute("reviewList", reviewList); return "store/storeInfo"; } /** * 지도 가져오는 api */ @CrossOrigin("https://naveropenapi.apigw.ntruss.com") @ResponseBody @RequestMapping(value = "/adressAjax",produces = "application/json",method = RequestMethod.POST ) public Map<String, Object> adressAjax(@RequestParam(name="address", required = false) String address, HttpSession session) { System.out.println("-----"); System.out.println("주소는 --> "+address); System.out.println("-----"); try { String addr = URLEncoder.encode(address,"utf-8"); URL url = new URL("https://naveropenapi.apigw.ntruss.com/map-geocode/v2/geocode?query="+addr); HttpURLConnection con = (HttpURLConnection) url.openConnection(); con.setRequestProperty("Content-Type", "application/json"); con.setRequestProperty("X-NCP-APIGW-API-KEY-ID", "rt37xgq4ur"); //key값 설정 con.setRequestProperty("X-NCP-APIGW-API-KEY","5BkSP6GpdD80nNBz2kABLUPwgoLZzPjYGWHKqRh9"); //key값 설정 con.setRequestMethod("GET"); //URLConnection에 대한 doOutput 필드값을 지정된 값으로 설정한다. URL 연결은 입출력에 사용될 수 있다. URL 연결을 출력용으로 사용하려는 경우 DoOutput 플래그를 true로 설정하고, 그렇지 않은 경우는 false로 설정해야 한다. 기본값은 false이다. con.setDoOutput(false); StringBuilder sb = new StringBuilder(); if (con.getResponseCode() == HttpURLConnection.HTTP_OK) { BufferedReader br = new BufferedReader( new InputStreamReader(con.getInputStream(), "utf-8")); String line; while ((line = br.readLine()) != null) { sb.append(line).append("\n"); } br.close(); System.out.println("" + sb.toString()); JSONParser json = new JSONParser(); JSONObject map = null; try { map = (JSONObject)json.parse(sb.toString()); } catch (ParseException e) { System.out.println("변환에 실패"); e.printStackTrace(); } JSONArray geoCode = (JSONArray) map.get("addresses"); System.out.println("geoCode --> "+geoCode); System.out.println( geoCode.get(0)); map = (JSONObject) geoCode.get(0); String xCode = (String) map.get("x"); String yCode = (String) map.get("y"); System.out.println("x좌표 --> "+xCode); System.out.println("y좌표 --> "+yCode); Map<String, Object> addrCode = new HashMap<String, Object>(); addrCode.put("xCode", xCode); addrCode.put("yCode", yCode); return addrCode; } else { System.out.println(con.getResponseMessage()); return null; } } catch (Exception e) { System.err.println(e.toString()); return null; } } }
true
f03b4b1462fae9ffa21c1ae04ea5ce3279332817
Java
priumoraes/Essay-Scoring
/src/parser/EssayInstance.java
UTF-8
1,728
2.5
2
[]
no_license
/** * */ package parser; import java.util.HashMap; /** * @author semanticpc * */ public class EssayInstance { // Not sure if we need all these fields. // Storing all the fields available in the Training Set File for now public int essay_id; public int essay_set; public String essay; public int rater1_domain1 = -1; public int rater2_domain1 = -1; public int rater3_domain1 = -1; public int domain1_score = -1; public int rater1_domain2 = -1; public int rater2_domain2 = -1; public int domain2_score = -1; public int rater1_trait1 = -1; public int rater1_trait2 = -1; public int rater1_trait3 = -1; public int rater1_trait4 = -1; public int rater1_trait5 = -1; public int rater1_trait6 = -1; public int rater2_trait1 = -1; public int rater2_trait2 = -1; public int rater2_trait3 = -1; public int rater2_trait4 = -1; public int rater2_trait5 = -1; public int rater2_trait6 = -1; public int rater3_trait1 = -1; public int rater3_trait2 = -1; public int rater3_trait3 = -1; public int rater3_trait4 = -1; public int rater3_trait5 = -1; public int rater3_trait6 = -1; HashMap<String,Double> features; public EssayInstance() { this.features = new HashMap<String,Double>(); } /** * @param featureScores */ public void setFeature(HashMap<String,Double> featureScores) { for (String featureKey : featureScores.keySet()) { if (this.features.containsKey(featureKey)) this.features.put( featureKey.concat("1"), featureScores.get(featureKey)); else this.features.put(featureKey, featureScores.get(featureKey)); } } public HashMap<String,Double> getFeatures() { return this.features; } }
true
b18147fd21afd78ddf83aa0b602a3cc56c9a57a8
Java
lunavictor068/CodeEvalProjects
/src/StringsAndArrows.java
UTF-8
604
3.046875
3
[]
no_license
/** * Created by victorluna on 10/16/15. */ public class StringsAndArrows { public static void main (String[] args){ String arrowString = ""; } public static int findArrows(String arrowString){ int total = 0; int firstIndex = 0; int lastIndex = 3; if (arrowString.length() < 4) total = 0; else for (; firstIndex < arrowString.length(); firstIndex++) { for (int i = 0; i <= 3; i++) { } lastIndex++; } return total; } }
true
dc075182ab57aa29564b7f7c2d533df83df07256
Java
pab993/AcmeFit
/src/main/java/forms/TrainerForm.java
UTF-8
3,861
2.3125
2
[]
no_license
package forms; import javax.persistence.Column; import javax.validation.constraints.Min; import javax.validation.constraints.NotNull; import javax.validation.constraints.Pattern; import javax.validation.constraints.Size; import org.hibernate.validator.constraints.CreditCardNumber; import org.hibernate.validator.constraints.Email; import org.hibernate.validator.constraints.NotBlank; import org.hibernate.validator.constraints.Range; import org.hibernate.validator.constraints.SafeHtml; import org.hibernate.validator.constraints.URL; public class TrainerForm { // Atributes ------------------ private String username; private String password; private String repeatPassword; private String name; private String surname; private String phone; private String email; private String address; private String picture; // CreditCard private String brandName; private String number; private int expirationMonth; private int expirationYear; private int CVV; private String holderName; @SafeHtml @NotBlank public String getHolderName() { return this.holderName; } public void setHolderName(String holderName) { this.holderName = holderName; } @SafeHtml @NotBlank public String getBrandName() { return this.brandName; } public void setBrandName(String brandName) { this.brandName = brandName; } @SafeHtml @NotBlank @CreditCardNumber public String getNumber() { return this.number; } public void setNumber(String number) { this.number = number; } @Range(min = 1, max = 12) public int getExpirationMonth() { return this.expirationMonth; } public void setExpirationMonth(int expirationMonth) { this.expirationMonth = expirationMonth; } @Min(2017) public int getExpirationYear() { return this.expirationYear; } public void setExpirationYear(int expirationYear) { this.expirationYear = expirationYear; } @Range(min = 100, max = 999) public int getCVV() { return this.CVV; } public void setCVV(int CVV) { this.CVV = CVV; } // Aux private boolean check1; private boolean check2; @SafeHtml @Column(unique = true) @Size(min = 5, max = 32) public String getUsername() { return this.username; } public void setUsername(String username) { this.username = username; } @SafeHtml @Size(min = 5, max = 32) public String getPassword() { return this.password; } public void setPassword(String password) { this.password = password; } @SafeHtml @NotNull(message = "Passwords do not match") public String getRepeatPassword() { return this.repeatPassword; } public void setRepeatPassword(String repeatPassword) { this.repeatPassword = repeatPassword; } @SafeHtml @NotBlank public String getName() { return this.name; } public void setName(String name) { this.name = name; } @SafeHtml @NotBlank public String getSurname() { return this.surname; } public void setSurname(String surname) { this.surname = surname; } @SafeHtml @Pattern(regexp = "^[(][+][0-9]{2,3}[)][0-9]{9}$") public String getPhone() { return this.phone; } public void setPhone(String phone) { this.phone = phone; } @SafeHtml @Email @NotBlank @Column(unique = true) public String getEmail() { return this.email; } public void setEmail(String email) { this.email = email; } @SafeHtml @NotBlank public String getAddress() { return this.address; } public void setAddress(String address) { this.address = address; } @SafeHtml @NotBlank @URL public String getPicture() { return this.picture; } public void setPicture(String picture) { this.picture = picture; } public boolean isCheck1() { return this.check1; } public void setCheck1(boolean check1) { this.check1 = check1; } public boolean isCheck2() { return this.check2; } public void setCheck2(boolean check2) { this.check2 = check2; } // CreditCard }
true
e5acb24169eaa3315f418906fd5ff5fd88e984a5
Java
Sashaagapova/CucumberFramework
/src/test/java/runner/JDBCTest.java
UTF-8
2,340
2.90625
3
[]
no_license
package runner; import utilities.Configuration; import utilities.JDBCUtils; import java.io.IOException; import java.sql.*; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class JDBCTest { // Java database Connectivity public static void main(String[] args) throws IOException, SQLException { // connection // statement // ResultSet Connection connection= DriverManager.getConnection( Configuration.getProperties("dbHostname"), Configuration.getProperties("dbUsername"), Configuration.getProperties("dbPassword")); Statement statement= connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); ResultSet resultSet= statement.executeQuery("Select * from employees"); System.out.println(resultSet.getRow()); resultSet.next(); resultSet.next(); resultSet.next(); String myFirstData=resultSet.getString("FIRST_NAME"); System.out.println(myFirstData); resultSet.next(); System.out.println(resultSet.getObject("FIRST_NAME")); resultSet.next(); System.out.println(resultSet.getObject("employee_ID")); System.out.println(resultSet.getRow()); ResultSetMetaData rsMetaData = resultSet.getMetaData(); // resultSet is an object for a data from table System.out.println("-----------"); System.out.println(rsMetaData.getColumnCount()); System.out.println(rsMetaData.getColumnName(5)); System.out.println(rsMetaData.getColumnType(5)); System.out.println(rsMetaData.getColumnClassName(4)); List<Map<String, Object>> listOfMaps= new ArrayList<>(); resultSet.next(); while (resultSet.next()){ Map<String, Object> row = new HashMap<>(); for(int i=1; i<=rsMetaData.getColumnCount();i++) { row.put(rsMetaData.getColumnName(i),resultSet.getObject(rsMetaData.getColumnName(i))); } listOfMaps.add(row); } for(int i=0; i<listOfMaps.size(); i++){ for(String key:listOfMaps.get(i).keySet()){ System.out.println(listOfMaps.get(i).get(key)); } } } }
true
689195cf392108adbfcba52a265137583d31f556
Java
Nebzei/2FA
/src/main/java/com/nebzei/commands/AlertsCMD.java
UTF-8
1,483
2.53125
3
[]
no_license
package com.nebzei.commands; import com.nebzei.TFA; import com.nebzei.utilities.Utils; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; public class AlertsCMD implements CommandExecutor { private TFA plugin; public AlertsCMD(TFA plugin) { this.plugin = plugin; } @Override public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { if (!(sender instanceof Player)) return false; Player player = (Player) sender; if (!player.hasPermission("permissions.toggle-alerts")) { player.sendMessage(Utils.c(plugin.getConfig().getString("messages.no-permission"))); return false; } if (args.length > 0){ player.sendMessage(Utils.c("&8[&c!&8] &eThe proper use for this command is: &f/pinalerts")); return false; } if (plugin.getAlerts().contains(player)){ plugin.getAlerts().remove(player); player.sendMessage(Utils.c(plugin.getConfig().getString("messages.alertsoff_message"))); } else{ plugin.getAlerts().add(player); player.sendMessage(Utils.c(plugin.getConfig().getString("messages.alertson_message"))); } return false; } }
true
d5a69eba07f994548c9d54abd58add588921265a
Java
iris-email-client/iris-java9
/src/iris.persistence.lucene/br/unb/cic/iris/persistence/lucene/internal/FolderDAOLucene.java
UTF-8
3,165
2.359375
2
[ "MIT" ]
permissive
package br.unb.cic.iris.persistence.lucene.internal; import java.util.List; import org.apache.lucene.document.Document; import org.apache.lucene.document.Field.Store; import org.apache.lucene.document.StringField; import org.apache.lucene.index.Term; import org.apache.lucene.search.Query; import org.apache.lucene.search.TermQuery; import br.unb.cic.iris.core.IrisServiceLocator; import br.unb.cic.iris.exception.IrisUncheckedException; import br.unb.cic.iris.model.IrisFolder; import br.unb.cic.iris.persistence.EntityValidator; import br.unb.cic.iris.persistence.FolderDAO; import br.unb.cic.iris.persistence.IrisPersistenceException; import br.unb.cic.iris.persistence.lucene.AbstractDAO; /*** * added by dPersistenceLucene */ public class FolderDAOLucene extends AbstractDAO<IrisFolder> implements FolderDAO { private static FolderDAOLucene instance; private FolderDAOLucene() { this.type = "folder"; } public static FolderDAOLucene instance() { if (instance == null) { instance = new FolderDAOLucene(); try { ensureIsCreated(IrisFolder.INBOX); ensureIsCreated(IrisFolder.OUTBOX); } catch (IrisPersistenceException e) { throw new IrisUncheckedException("Error hwile initializing lucene presistence", e); } } return instance; } private static void ensureIsCreated(String folderName) throws IrisPersistenceException { List<IrisFolder> folders = instance.doFindByName(folderName); if (folders.isEmpty()) { IrisFolder inbox = IrisServiceLocator.instance().getEntityFactory().createIrisFolder(); inbox.setName(folderName); instance.saveOrUpdate(inbox); System.out.println(String.format("%s folder created.", folderName)); } } public IrisFolder findByName(String folderName) throws IrisPersistenceException { List<IrisFolder> result = doFindByName(folderName); // if (result.isEmpty()) { // throw new IrisPersistenceException(String.format("Folder '%s' not found", folderName), null); // } if (! result.isEmpty()) { return result.iterator().next(); } return null; } public List<IrisFolder> doFindByName(String folderName) throws IrisPersistenceException { Query nameQuery = new TermQuery(new Term("name", folderName)); return findByTerms(new Query[] { nameQuery }); } protected IrisFolder fromDocument(Document d) throws IrisPersistenceException { IrisFolder f = IrisServiceLocator.instance().getEntityFactory().createIrisFolder(); f.setId(d.get("id")); f.setName(d.get("name")); return f; } protected Document toDocument(IrisFolder f) throws IrisPersistenceException { Document doc = new Document(); doc.add(new StringField("id", String.valueOf(f.getId()), Store.YES)); doc.add(new StringField("name", f.getName(), Store.YES)); return doc; } @Override public IrisFolder createFolder(String folderName) throws IrisPersistenceException { EntityValidator.checkFolderBeforeCreate(this, folderName); IrisFolder folder = IrisServiceLocator.instance().getEntityFactory().createIrisFolder(folderName); folder = fromDocument(instance.saveOrUpdate(folder)); System.out.println(String.format("%s folder created.", folderName)); return folder; } }
true
5d364af75efef08ad24d39a76ea05d0024b7a4a8
Java
Planeswalker23/Monitor
/monitor-login/src/main/java/cn/fyd/monitorlogin/service/QuartzService.java
UTF-8
1,030
2.140625
2
[]
no_license
package cn.fyd.monitorlogin.service; import cn.fyd.model.Monitor; import org.quartz.SchedulerException; /** * 定时任务服务层 * @author fanyidong * @date Created in 2019-02-12 */ public interface QuartzService { /** * 任务创建与更新 * @param monitor 监控类 * @throws SchedulerException */ void updateQuartz(Monitor monitor) throws SchedulerException; /** * 删除任务 * @param jobName 任务名monitorId * @param jobGroup 任务组userId * @throws SchedulerException */ void deleteQuartz(String jobName, String jobGroup) throws SchedulerException; /** * 恢复任务 * @param jobName 任务名monitorId * @param jobGroup 任务组userId * @throws SchedulerException */ void pauseQuartz(String jobName, String jobGroup) throws SchedulerException; /** * 恢复任务 * @param monitor * @throws SchedulerException */ void resumeQuartz(Monitor monitor) throws SchedulerException; }
true
b3eb0c0d6ae708c12368ca8b7308ebeb2befc766
Java
To-chase/JavaPro
/src/com/day10/Test7/Demo.java
UTF-8
915
3.265625
3
[]
no_license
package com.day10.Test7; import java.util.Arrays; import java.util.Comparator; public class Demo { public static void main(String[] args) { Person[] array={ new Person("amy",12), new Person("amy1",34), new Person("amy2",16), }; // Comparator<Person> comparator=new Comparator<Person>() { // @Override // public int compare(Person o1, Person o2) { // return o1.getAge()-o2.getAge(); // } // }; //// System.out.println(Arrays.toString(array)); // Arrays.sort(array,comparator); // for (Person person:array){ // System.out.println(person); // } Arrays.sort(array,(Person o1,Person o2)->{ return o1.getAge()-o2.getAge(); }); for (Person person:array){ System.out.println(person); } } }
true
f3d9ff044734af0a8c2339a63ef8def3e260b439
Java
rookiesong/online-shopping-mall
/demo/src/main/java/net/suncaper/demo/service/OrdersService.java
UTF-8
492
1.867188
2
[]
no_license
package net.suncaper.demo.service; import net.suncaper.demo.domain.Orders; import java.util.List; public interface OrdersService { public List<Orders> addOrder(String[] cartIds,String userMailAddress,int id); public String deleteOrder(String ordersId); public String editOrder(String ordersId,String newStatus); public Orders findOrder(String ordersId); public List<Orders> showOrder(String userMailAddress); public int countPrice(List<Orders> ordersList); }
true
fd1e578e98629db5b44225c057a877e2332bec2a
Java
ikasarov/multiapps
/multiapps-mta/src/main/java/org/cloudfoundry/multiapps/mta/parsers/v3/ResourceParser.java
UTF-8
3,061
1.890625
2
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
package org.cloudfoundry.multiapps.mta.parsers.v3; import static org.cloudfoundry.multiapps.mta.handlers.v3.Schemas.RESOURCE; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import org.cloudfoundry.multiapps.common.ParsingException; import org.cloudfoundry.multiapps.mta.model.Metadata; import org.cloudfoundry.multiapps.mta.model.RequiredDependency; import org.cloudfoundry.multiapps.mta.model.Resource; import org.cloudfoundry.multiapps.mta.parsers.ListParser; import org.cloudfoundry.multiapps.mta.schema.MapElement; public class ResourceParser extends org.cloudfoundry.multiapps.mta.parsers.v2.ResourceParser { public static final String ACTIVE = "active"; public static final String PROPERTIES_METADATA = "properties-metadata"; public static final String PARAMETERS_METADATA = "parameters-metadata"; public static final String REQUIRES = "requires"; public static final String OPTIONAL = "optional"; public static final String PROCESSED_AFTER = "processed-after"; protected final Set<String> usedRequiredDependencyNames = new HashSet<>(); public ResourceParser(Map<String, Object> source) { super(RESOURCE, source); } protected ResourceParser(MapElement schema, Map<String, Object> source) { super(schema, source); } @Override public Resource parse() throws ParsingException { return super.parse().setActive(getActive()) .setOptional(getOptional()) .setParametersMetadata(getParametersMetadata()) .setPropertiesMetadata(getPropertiesMetadata()) .setRequiredDependencies(getRequiredDependencies()) .setProcessAfter(getProcessedAfter()); } @Override public Resource createEntity() { return Resource.createV3(); } protected Boolean getActive() { return getBooleanElement(ACTIVE); } protected Metadata getPropertiesMetadata() { return getMetadata(PROPERTIES_METADATA, getProperties()); } protected Metadata getParametersMetadata() { return getMetadata(PARAMETERS_METADATA, getParameters()); } protected List<RequiredDependency> getRequiredDependencies() { return getListElement(REQUIRES, new ListParser<RequiredDependency>() { @Override protected RequiredDependency parseItem(Map<String, Object> map) { RequiredDependencyParser parser = getRequiredDependencyParser(map); parser.setUsedValues(usedRequiredDependencyNames); return parser.parse(); } }); } protected Boolean getOptional() { return getBooleanElement(OPTIONAL); } protected RequiredDependencyParser getRequiredDependencyParser(Map<String, Object> source) { return new RequiredDependencyParser(source); } protected List<String> getProcessedAfter() { return getListElement(PROCESSED_AFTER); } }
true
d2f06a57989c597601938252f41e7126d9ab5fbc
Java
kirankbs/dominos
/src/main/java/com/bitwise/dominos/pizza/Crust.java
UTF-8
340
2.921875
3
[]
no_license
package com.bitwise.dominos.pizza; public class Crust { private final String name; private final double price; public Crust(String name, double price) { this.name = name; this.price = price; } public String getName() { return name; } public double getPrice() { return this.price; } }
true
f085c8eb35836c84a7dd0ad58d05350d9ec5f639
Java
XTremEive/Fadin_LD31
/core/src/com/keenao/mygame/entities/items/Item.java
UTF-8
2,659
2.765625
3
[]
no_license
package com.keenao.mygame.entities.items; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.Texture; import com.badlogic.gdx.graphics.g2d.Sprite; import com.badlogic.gdx.graphics.g2d.SpriteBatch; import com.keenao.mygame.entities.Visual; import com.keenao.mygame.managers.InputManager; import com.keenao.mygame.managers.SoundManager; import com.keenao.mygame.managers.TimeManager; import com.keenao.mygame.utils.ColorUtil; public abstract class Item extends Visual { public static final int MOVEMENT_SPEED = 10; private Sprite backgroundSprite; private int velocityX; private int velocityY; private int element; public static Color getElementColor(int element) { return element < 0 ? new Color(Color.WHITE) : ColorUtil.hsvToRgb(element / 360.0f, 0.6f, 0.8f); } protected Item(String asset, String backgroundAsset, String type, int element, int positionX, int positionY, int sizeX, int sizeY) { super(asset, type, positionX, positionY, sizeX, sizeY); this.element = element; // Initialize if (null != backgroundAsset) { this.backgroundSprite = new Sprite(new Texture(backgroundAsset + ".png")); } } public int getVelocityX() { return velocityX; } public void setVelocityX(int velocityX) { this.velocityX = velocityX; } public int getVelocityY() { return velocityY; } public void setVelocityY(int velocityY) { this.velocityY = velocityY; } public void resetElement() { element = -1; } public void setElement(int element) { this.element = element; } public int getElement() { return element; } @Override public void update(InputManager inputManager, TimeManager timeManager, SoundManager soundManager) { // Position setPositionX(getPositionX() + getVelocityX()); setPositionY(getPositionY() + getVelocityY()); // Update aspect setColor(getElementColor(getElement())); } @Override public void draw(SpriteBatch spriteBatch) { if (null != backgroundSprite) { backgroundSprite.setColor(getSprite().getColor()); backgroundSprite.setCenter(backgroundSprite.getWidth() / 2, backgroundSprite.getHeight() / 2); backgroundSprite.setPosition(getPositionX() - backgroundSprite.getWidth() / 2 + getSprite().getWidth() / 2, getPositionY() - backgroundSprite.getHeight() / 2 + getSprite().getWidth() / 2); backgroundSprite.draw(spriteBatch); } // Default super.draw(spriteBatch); } }
true
41c5af7381a939dfc13702d24c3265e45957464b
Java
KatsiarynaZhalabkevich/QuestionnairePortalFinal
/src/main/java/com/github/zhalabkevich/dao/FieldDAO.java
UTF-8
551
2.296875
2
[]
no_license
package com.github.zhalabkevich.dao; import com.github.zhalabkevich.domain.Field; import java.util.List; public interface FieldDAO { void addField(Field field) throws DAOException; boolean isFieldLabelUniq(String label) throws DAOException; Field getFieldByLabel(String label) throws DAOException; Field getFieldById(Long id)throws DAOException; Field updateField(Field field)throws DAOException; List<Field> getFields()throws DAOException; void deleteFieldById(Long id)throws DAOException; }
true
1cdf89c2d6eaf1df14d3fffd4ff2454b60332101
Java
Samsung/Castanets
/build/android/bytecode/java/org/chromium/bytecode/CustomResourcesClassAdapter.java
UTF-8
12,241
1.757813
2
[ "BSD-3-Clause" ]
permissive
// Copyright 2017 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package org.chromium.bytecode; import static org.objectweb.asm.Opcodes.ACC_PUBLIC; import static org.objectweb.asm.Opcodes.ACONST_NULL; import static org.objectweb.asm.Opcodes.ALOAD; import static org.objectweb.asm.Opcodes.ARETURN; import static org.objectweb.asm.Opcodes.ASM5; import static org.objectweb.asm.Opcodes.BIPUSH; import static org.objectweb.asm.Opcodes.GETSTATIC; import static org.objectweb.asm.Opcodes.IFNE; import static org.objectweb.asm.Opcodes.IF_ICMPGE; import static org.objectweb.asm.Opcodes.ILOAD; import static org.objectweb.asm.Opcodes.INVOKESPECIAL; import static org.objectweb.asm.Opcodes.INVOKESTATIC; import static org.objectweb.asm.Opcodes.INVOKEVIRTUAL; import static org.objectweb.asm.Opcodes.RETURN; import static org.chromium.bytecode.TypeUtils.ASSET_MANAGER; import static org.chromium.bytecode.TypeUtils.BOOLEAN; import static org.chromium.bytecode.TypeUtils.BUILD_HOOKS_ANDROID; import static org.chromium.bytecode.TypeUtils.CONFIGURATION; import static org.chromium.bytecode.TypeUtils.CONTEXT; import static org.chromium.bytecode.TypeUtils.CONTEXT_WRAPPER; import static org.chromium.bytecode.TypeUtils.INT; import static org.chromium.bytecode.TypeUtils.RESOURCES; import static org.chromium.bytecode.TypeUtils.STRING; import static org.chromium.bytecode.TypeUtils.THEME; import static org.chromium.bytecode.TypeUtils.VOID; import org.objectweb.asm.ClassVisitor; import org.objectweb.asm.Label; import org.objectweb.asm.MethodVisitor; import org.objectweb.asm.Opcodes; import java.util.Arrays; import java.util.List; /** * A ClassVisitor for providing access to custom resources via BuildHooksAndroid. * * The goal of this class is to provide hooks into all places where android resources * are available so that they can be modified before use. This is done by rewriting the bytecode * for all callable definitions of certain Context methods, specifically: * - getResources * - getAssets * - getTheme * - setTheme * - createConfigurationContext * * Only classes at the framework boundary are rewritten since presumably all other indirect Context * subclasses will end up calling their respective super methods (i.e. we bytecode rewrite * BaseChromiumApplication since it extends Application, but not ContentApplication since it * extends a non-framework subclass. */ class CustomResourcesClassAdapter extends ClassVisitor { private static final String IS_ENABLED_METHOD = "isEnabled"; private static final String IS_ENABLED_DESCRIPTOR = TypeUtils.getMethodDescriptor(BOOLEAN); // Cached since this is used so often. private static final String GET_IDENTIFIER_DESCRIPTOR = TypeUtils.getMethodDescriptor(INT, STRING, STRING, STRING); // Existing methods are more difficult to handle, and not currently needed. private static final List<String> PROHIBITED_METHODS = Arrays.asList( TypeUtils.getMethodSignature("getResources", RESOURCES), TypeUtils.getMethodSignature("getAssets", ASSET_MANAGER), TypeUtils.getMethodSignature("getTheme", THEME), TypeUtils.getMethodSignature("createConfigurationContext", CONTEXT, CONFIGURATION), TypeUtils.getMethodSignature("setTheme", VOID, INT)); private boolean mShouldTransform; private String mClassName; private String mSuperClassName; private ClassLoader mClassLoader; CustomResourcesClassAdapter(ClassVisitor visitor, String className, String superClassName, ClassLoader classLoader) { super(ASM5, visitor); this.mClassName = className; this.mSuperClassName = superClassName; this.mClassLoader = classLoader; } @Override public void visit(int version, int access, String name, String signature, String superName, String[] interfaces) { super.visit(version, access, name, signature, superName, interfaces); mShouldTransform = shouldTransform(); } @Override public MethodVisitor visitMethod(final int access, final String name, String desc, String signature, String[] exceptions) { if (mShouldTransform) { String methodSignature = name + desc; if (requiresModifyingExisting(methodSignature)) { throw new RuntimeException("Rewriting existing methods not supported: " + mClassName + "#" + methodSignature); } } return new RewriteGetIdentifierMethodVisitor( super.visitMethod(access, name, desc, signature, exceptions)); } @Override public void visitEnd() { if (mShouldTransform) { delegateCreateConfigurationContext(); delegateSetTheme(); delegateGet("getAssets", ASSET_MANAGER); delegateGet("getTheme", THEME); delegateGet("getResources", RESOURCES); } super.visitEnd(); } private boolean requiresModifyingExisting(String methodDescriptor) { return PROHIBITED_METHODS.contains(methodDescriptor); } private boolean shouldTransform() { if (!isDescendantOfContext()) { return false; } if (!superClassIsFrameworkClass()) { return false; } return !superClassIsContextWrapper(); } private boolean superClassIsFrameworkClass() { return loadClass(mSuperClassName).getProtectionDomain().toString().contains("android.jar"); } private boolean isDescendantOfContext() { return isSubClass(mClassName, CONTEXT); } private boolean superClassIsContextWrapper() { return mSuperClassName.equals(CONTEXT_WRAPPER); } private boolean isSubClass(String candidate, String other) { Class<?> candidateClazz = loadClass(candidate); Class<?> parentClazz = loadClass(other); return parentClazz.isAssignableFrom(candidateClazz); } private Class<?> loadClass(String className) { try { return mClassLoader.loadClass(className.replace('/', '.')); } catch (ClassNotFoundException e) { throw new RuntimeException(e); } } /** * Remaps Resources.getIdentifier() method calls to use BuildHooksAndroid. * * resourceObj.getIdentifier(String, String, String) becomes: * BuildHooksAndroid.getIdentifier(resourceObj, String, String, String); */ private static final class RewriteGetIdentifierMethodVisitor extends MethodVisitor { RewriteGetIdentifierMethodVisitor(MethodVisitor mv) { super(ASM5, mv); } @Override public void visitMethodInsn( int opcode, String owner, String name, String desc, boolean itf) { String methodName = "getIdentifier"; if (opcode == INVOKEVIRTUAL && owner.equals(RESOURCES) && name.equals(methodName) && desc.equals(GET_IDENTIFIER_DESCRIPTOR)) { super.visitMethodInsn(INVOKESTATIC, BUILD_HOOKS_ANDROID, methodName, TypeUtils.getMethodDescriptor(INT, RESOURCES, STRING, STRING, STRING), itf); } else { super.visitMethodInsn(opcode, owner, name, desc, itf); } } } /** * Generates: * * <pre> * public Context createConfigurationContext(Configuration configuration) { * // createConfigurationContext does not exist before API level 17. * if (Build.VERSION.SDK_INT < 17) return null; * if (!BuildHooksAndroid.isEnabled()) return super.createConfigurationContext(configuration); * return BuildHooksAndroid.createConfigurationContext( * super.createConfigurationContext(configuration)); * } * </pre> * } */ private void delegateCreateConfigurationContext() { String methodName = "createConfigurationContext"; String methodDescriptor = TypeUtils.getMethodDescriptor(CONTEXT, CONFIGURATION); MethodVisitor mv = super.visitMethod(ACC_PUBLIC, methodName, methodDescriptor, null, null); mv.visitCode(); mv.visitFieldInsn(GETSTATIC, "android/os/Build$VERSION", "SDK_INT", INT); mv.visitIntInsn(BIPUSH, 17); Label l0 = new Label(); mv.visitJumpInsn(IF_ICMPGE, l0); mv.visitInsn(ACONST_NULL); mv.visitInsn(ARETURN); mv.visitLabel(l0); mv.visitFrame(Opcodes.F_SAME, 0, null, 0, null); mv.visitMethodInsn( INVOKESTATIC, BUILD_HOOKS_ANDROID, IS_ENABLED_METHOD, IS_ENABLED_DESCRIPTOR, false); Label l1 = new Label(); mv.visitJumpInsn(IFNE, l1); mv.visitVarInsn(ALOAD, 0); mv.visitVarInsn(ALOAD, 1); mv.visitMethodInsn(INVOKESPECIAL, mSuperClassName, methodName, methodDescriptor, false); mv.visitInsn(ARETURN); mv.visitLabel(l1); mv.visitFrame(Opcodes.F_SAME, 0, null, 0, null); mv.visitVarInsn(ALOAD, 0); mv.visitVarInsn(ALOAD, 1); mv.visitMethodInsn(INVOKESPECIAL, mSuperClassName, methodName, methodDescriptor, false); mv.visitMethodInsn(INVOKESTATIC, BUILD_HOOKS_ANDROID, methodName, TypeUtils.getMethodDescriptor(CONTEXT, CONTEXT), false); mv.visitInsn(ARETURN); mv.visitMaxs(2, 2); mv.visitEnd(); } /** * Generates: * * <pre> * public void setTheme(int theme) { * if (!BuildHooksAndroid.isEnabled()) { * super.setTheme(theme); * return; * } * BuildHooksAndroid.setTheme(this, theme); * } * </pre> */ private void delegateSetTheme() { String methodName = "setTheme"; String methodDescriptor = TypeUtils.getMethodDescriptor(VOID, INT); String buildHooksMethodDescriptor = TypeUtils.getMethodDescriptor(VOID, CONTEXT, INT); MethodVisitor mv = super.visitMethod(ACC_PUBLIC, methodName, methodDescriptor, null, null); mv.visitCode(); mv.visitMethodInsn( INVOKESTATIC, BUILD_HOOKS_ANDROID, IS_ENABLED_METHOD, IS_ENABLED_DESCRIPTOR, false); Label l0 = new Label(); mv.visitJumpInsn(IFNE, l0); mv.visitVarInsn(ALOAD, 0); mv.visitVarInsn(ILOAD, 1); mv.visitMethodInsn(INVOKESPECIAL, mSuperClassName, methodName, methodDescriptor, false); mv.visitInsn(RETURN); mv.visitLabel(l0); mv.visitFrame(Opcodes.F_SAME, 0, null, 0, null); mv.visitVarInsn(ALOAD, 0); mv.visitVarInsn(ILOAD, 1); mv.visitMethodInsn( INVOKESTATIC, BUILD_HOOKS_ANDROID, methodName, buildHooksMethodDescriptor, false); mv.visitInsn(RETURN); mv.visitMaxs(2, 2); mv.visitEnd(); } /** * Generates: * * <pre> * public returnType methodName() { * if (!BuildHooksAndroid.isEnabled()) return super.methodName(); * return BuildHooksAndroid.methodName(this); * } * </pre> */ private void delegateGet(String methodName, String returnType) { String getMethodDescriptor = TypeUtils.getMethodDescriptor(returnType); String buildHooksGetMethodDescriptor = TypeUtils.getMethodDescriptor(returnType, CONTEXT); MethodVisitor mv = super.visitMethod(ACC_PUBLIC, methodName, getMethodDescriptor, null, null); mv.visitCode(); mv.visitMethodInsn( INVOKESTATIC, BUILD_HOOKS_ANDROID, IS_ENABLED_METHOD, IS_ENABLED_DESCRIPTOR, false); Label l0 = new Label(); mv.visitJumpInsn(IFNE, l0); mv.visitVarInsn(ALOAD, 0); mv.visitMethodInsn(INVOKESPECIAL, mSuperClassName, methodName, getMethodDescriptor, false); mv.visitInsn(ARETURN); mv.visitLabel(l0); mv.visitFrame(Opcodes.F_SAME, 0, null, 0, null); mv.visitVarInsn(ALOAD, 0); mv.visitMethodInsn(INVOKESTATIC, BUILD_HOOKS_ANDROID, methodName, buildHooksGetMethodDescriptor, false); mv.visitInsn(ARETURN); mv.visitMaxs(1, 1); mv.visitEnd(); } }
true
2f2c480709bdbcd8754f8a064b77527b482992d8
Java
absharma3/Constructs
/Array/src/Equilibrium.java
UTF-8
1,485
3.109375
3
[]
no_license
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; /** * Created by abhimanyus on 1/25/18. */ class Equilibrium { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int N = Integer.parseInt(br.readLine()); int[][] mainArr = new int[N][]; for(int i =0; i< N ; i++){ int arraySize = Integer.parseInt(br.readLine()); int[] array = new int[arraySize]; String[] values = br.readLine().split(" "); for(int j=0; j< arraySize; j++ ){ array[j] = Integer.parseInt(values[j]); } mainArr[i] = array; } for(int i=0; i<N; i++) { System.out.println(findEquilibrium(mainArr[i])); } } private static int findEquilibrium(int[] values) { int N = values.length; if(N ==1) return 1; int [] forwardSum = new int[N]; forwardSum[0] = values[0]; int [] backwardSum = new int[N]; backwardSum[N-1] = values[N-1]; for(int i=1; i<N; i++){ forwardSum[i] = forwardSum[i-1] + values[i]; backwardSum[N-1-i] = backwardSum[N-i] + values[N-1-i]; } for(int i=1; i< N-1; i++){ if(forwardSum[i-1] == backwardSum[i+1]){ return i+1; } } return -1; } }
true
030d06ca6806bf1c9015e566159c2beb739f448f
Java
Belphemur/AdminCmd
/src/main/java/be/Balor/World/AbstractWorldFactory.java
UTF-8
1,689
2.078125
2
[]
no_license
/************************************************************************ * This file is part of AdminCmd. * * AdminCmd 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 3 of the License, or * (at your option) any later version. * * AdminCmd is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with AdminCmd. If not, see <http://www.gnu.org/licenses/>. ************************************************************************/ package be.Balor.World; import org.bukkit.Bukkit; import org.bukkit.World; import be.Balor.Manager.Exceptions.WorldNotLoaded; import be.Balor.Tools.Debug.DebugLog; /** * @author Balor (aka Antoine Aflalo) * */ public abstract class AbstractWorldFactory { public ACWorld createWorld(final String worldName) throws WorldNotLoaded { DebugLog.beginInfo("Loading World " + worldName); try { World w = Bukkit.getServer().getWorld(worldName); if (w == null) { // World isn't loaded by Bukkit or other multi-world plugins so we don't allow unloaded world files to be loaded (possible security issue) throw new WorldNotLoaded(worldName); } return createWorld(w); } finally { DebugLog.endInfo(); } } protected abstract ACWorld createWorld(World world); }
true
6d2dd9c1e3bc075c6bcc7b2149f9fafabbf9752a
Java
domhauton/CM30174-Planetary-Exploration-AI
/rover/rover/src/main/java/rover/mediators/data/update/item/ScannerItem.java
UTF-8
1,663
2.671875
3
[ "Apache-2.0" ]
permissive
package rover.mediators.data.update.item; /** * Created by dominic on 26/10/16. * * Holds a given scanner item */ public class ScannerItem { private final ScannerItemType scannerItemType; private final RelativeCoordinates relativeCoordinates; private final ResourceType resourceType; public ScannerItem(ScannerItemType scannerItemType, RelativeCoordinates relativeCoordinates, ResourceType resourceType) { this.scannerItemType = scannerItemType; this.relativeCoordinates = relativeCoordinates; this.resourceType = resourceType; } public ScannerItemType getScannerItemType() { return scannerItemType; } public RelativeCoordinates getRelativeCoordinates() { return relativeCoordinates; } public ResourceType getResourceType() { return resourceType; } @Override public String toString() { return "ScannerItem{" + "scannerItemType=" + scannerItemType + ", relativeCoordinates=" + relativeCoordinates + '}'; } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof ScannerItem)) return false; ScannerItem that = (ScannerItem) o; if (getScannerItemType() != that.getScannerItemType()) return false; return getRelativeCoordinates() != null ? getRelativeCoordinates().equals(that.getRelativeCoordinates()) : that.getRelativeCoordinates() == null; } @Override public int hashCode() { int result = getScannerItemType() != null ? getScannerItemType().hashCode() : 0; result = 31 * result + (getRelativeCoordinates() != null ? getRelativeCoordinates().hashCode() : 0); return result; } }
true
5227c250506b0b201b709e8c5de747b71e67731e
Java
GeorgeCrochiere/EquationCalculatorJava
/EquationHandler.java
UTF-8
4,746
3.765625
4
[ "MIT" ]
permissive
package MainGraphing; public class EquationHandler { public static String EquationAtPoint(String equation, double x) { String y = ""; int i = 0; int j = 0; int startSearch = 0; int endSearch = 0; //Fixing little problems - Adding Multiplication Signs and Replacing value for X equation = equation.replaceAll(" ", ""); for (int l = 0; l < equation.length()-1; l++) { if ((equation.substring(l, l+1)).equals(")") && (equation.substring(l+1, l+2)).equals("(")) { String frontSection = equation.substring(0,l); String endSection = equation.substring(l); equation = frontSection + "*" + endSection; } if ((equation.substring(l, l+1)).equals("x") && ((equation.substring(l-1,l)).equals("0") || (equation.substring(l-1,l)).equals("1") || (equation.substring(l-1,l)).equals("2") || (equation.substring(l-1,l)).equals("3") || (equation.substring(l-1,l)).equals("4") || (equation.substring(l-1,l)).equals("5") || (equation.substring(l-1,l)).equals("6") || (equation.substring(l-1,l)).equals("7") || (equation.substring(l-1,l)).equals("8") || (equation.substring(l-1,l)).equals("9"))) { String frontSection = equation.substring(0, l); String endSection = equation.substring(l); equation = frontSection + "*" + endSection; } } equation = equation.replaceAll("x", String.valueOf(x)); //Parenthesis for (i = 0; i < equation.length()-1; i++) { if ((equation.substring(i,i+1)).equals("(")) { startSearch = i; int parenthesisCount = 0; for (j = i+1; j < equation.length(); j++) { if ((equation.substring(j, j+1)).equals("(")) { parenthesisCount++; } if ((equation.substring(j, j+1)).equals(")") && parenthesisCount == 0) { endSearch = j+1; break; } if ((equation.substring(j, j+1)).equals(")") && parenthesisCount != 0) { parenthesisCount--; } } String endSection = ""; String simplifiedPart = EquationAtPoint(equation.substring(startSearch+1,endSearch-1), x); String frontSection = equation.substring(0,i); if (equation.length() <= endSearch) { endSection = ""; } else { endSection = equation.substring(j+1); } equation = frontSection + simplifiedPart + endSection; } } //Trigonometry = sin,soc,tan,sec,csc,cot for (int k = 0; k < equation.length()-3; k++) { if ((equation.substring(k, k+3)).equals("sin")) { double sinNumber = EquationHandler.NumberFinder(equation, k+3); String trigAnswer = String.valueOf(Math.sin(sinNumber)); equation = equation.replaceFirst("sin" + String.valueOf(sinNumber), trigAnswer); } if ((equation.substring(k, k+3)).equals("cos")) { double cosNumber = EquationHandler.NumberFinder(equation, k+3); String trigAnswer = String.valueOf(Math.cos(cosNumber)); equation = equation.replaceFirst("sin" + String.valueOf(cosNumber), trigAnswer); } if ((equation.substring(k, k+3)).equals("tan")) { double tanNumber = EquationHandler.NumberFinder(equation, k+3); String trigAnswer = String.valueOf(Math.tan(tanNumber)); equation = equation.replaceFirst("sin" + String.valueOf(tanNumber), trigAnswer); } if ((equation.substring(k, k+3)).equals("csc")) { double cscNumber = EquationHandler.NumberFinder(equation, k+3); String trigAnswer = String.valueOf(Math.asin(cscNumber)); equation = equation.replaceFirst("sin" + String.valueOf(cscNumber), trigAnswer); } if ((equation.substring(k, k+3)).equals("sec")) { double secNumber = EquationHandler.NumberFinder(equation, k+3); String trigAnswer = String.valueOf(Math.acos(secNumber)); equation = equation.replaceFirst("sin" + String.valueOf(secNumber), trigAnswer); } if ((equation.substring(k, k+3)).equals("cot")) { double cotNumber = EquationHandler.NumberFinder(equation, k+3); String trigAnswer = String.valueOf(Math.atan(cotNumber)); equation = equation.replaceFirst("sin" + String.valueOf(cotNumber), trigAnswer); } } //Roots and Exponents for (int l = 0; l < equation.length(); l++) { } return(equation); } public static double NumberFinder(String equation, int startPos) { String tempNumber = ""; for ( int counter = startPos; counter < equation.length(); counter++) { String testNum = equation.substring(counter, counter+1); if (testNum.equals("-") || testNum.equals("1") || testNum.equals("2") || testNum.equals("3") || testNum.equals("4") || testNum.equals("5") || testNum.equals("6") || testNum.equals("7") || testNum.equals("8") || testNum.equals("9") || testNum.equals("0") || testNum.equals(".")) { tempNumber = tempNumber + testNum; } else { break; } } double xvalue = Double.parseDouble(tempNumber); return xvalue; } }
true
9a9f5a76e8378de84d1e378b04f0ec013004d8ed
Java
sceva95/Progetto-Ingegneria-2020
/prova/src/main/java/com/example/prova/model/LibroRepository.java
UTF-8
460
1.820313
2
[]
no_license
package com.example.prova.model; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.repository.CrudRepository; import org.springframework.stereotype.Repository; import java.util.List; @Repository public interface LibroRepository extends JpaRepository<Libro, String> { List<Libro> findByGenereOrderByPosizioneAsc(String genere); List<Libro> findByGenereOrderByVenditeDesc(String genere); }
true
e0581fbb8ca70ff167b98366ca5c5896f36fe7fd
Java
gaia-adm/metrics-gateway-service
/src/main/java/com/hp/gaia/mgs/dto/change/InnerField.java
UTF-8
1,536
2.265625
2
[]
no_license
package com.hp.gaia.mgs.dto.change; import javax.validation.constraints.NotNull; import java.util.HashMap; import java.util.Map; /** * Created by belozovs on 7/16/2015. * Field for IssueChangeEvent */ public class InnerField { @NotNull String name; @NotNull String to; String from; Long ttc; Map<String, String> customFields = new HashMap<>(); public InnerField(String name) { this.name = name; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getTo() { return to; } public void setTo(String to) { this.to = to; } public String getFrom() { return from; } public void setFrom(String from) { this.from = from; } public Long getTtc() { return ttc; } public void setTtc(Long ttc) { this.ttc = ttc; } public Map<String, String> getCustomFields() { return customFields; } public void addCustomField(String name, String value) { if(value!=null) { customFields.put(name, value); } } public Map<String, Object> getMembersAsMap(){ Map<String, Object> map = new HashMap<>(); map.put("name", name); map.put("to", to); if(from!=null){ map.put("from", from); } if(ttc!=null){ map.put("ttc", ttc); } map.putAll(customFields); return map; } }
true
cbd05a01a2871b2a28ef7a063631129188ec15bc
Java
whmbuaa/product-projects
/apps/Demo/src/com/quick/demo/retrofit/RequestResult.java
UTF-8
404
1.875
2
[]
no_license
package com.quick.demo.retrofit; import java.io.Serializable; import java.util.Date; /** * Created by wanghaiming on 2016/1/14. */ public class RequestResult<T> implements Serializable { public static class Status implements Serializable{ public int code; public String message; } public T data; public Status status; public Date systemDate; }
true
df732a81ba09ddc49a9ee9d124b1c1b701b54979
Java
fleigm/TransitRouter
/backend/src/main/java/de/fleigm/transitrouter/presets/PresetRepository.java
UTF-8
1,671
2.296875
2
[]
no_license
package de.fleigm.transitrouter.presets; import com.fasterxml.jackson.databind.ObjectMapper; import de.fleigm.transitrouter.data.Repository; import de.fleigm.transitrouter.feeds.GeneratedFeed; import de.fleigm.transitrouter.feeds.GeneratedFeedRepository; import org.eclipse.microprofile.config.inject.ConfigProperty; import javax.enterprise.context.ApplicationScoped; import javax.inject.Inject; import java.nio.file.Path; import java.util.List; import java.util.UUID; import java.util.stream.Collectors; @ApplicationScoped public class PresetRepository extends Repository<Preset> { private GeneratedFeedRepository generatedFeeds; protected PresetRepository() { } @Inject public PresetRepository(@ConfigProperty(name = "app.storage") Path storageLocation, ObjectMapper objectMapper, GeneratedFeedRepository generatedFeeds) { super(storageLocation.resolve("presets"), objectMapper); this.generatedFeeds = generatedFeeds; } @Override public Class<Preset> entityClass() { return Preset.class; } /** * Find all generated feeds of a given preset. * * @param preset preset. * @return generated feeds of preset. */ public List<GeneratedFeed> generatedFeedsFromPreset(Preset preset) { return generatedFeedsFromPreset(preset.getId()); } /** * @see PresetRepository#generatedFeedsFromPreset(Preset) */ public List<GeneratedFeed> generatedFeedsFromPreset(UUID id) { return generatedFeeds.all() .stream() .filter(GeneratedFeed::hasPreset) .filter(info -> info.getPreset().equals(id)) .collect(Collectors.toList()); } }
true
43ea3391473c515bb08ec07f2979261c0c0dc655
Java
AndreaMendoza1/sistema-escaneo-backend
/src/main/java/sistemas/edu/pe/sistemaescaneo/service/impl/UsuarioService.java
UTF-8
2,692
2.484375
2
[]
no_license
package sistemas.edu.pe.sistemaescaneo.service.impl; import java.util.List; import java.util.stream.Collectors; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.userdetails.User; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import sistemas.edu.pe.sistemaescaneo.dao.IUsuarioDAO; import sistemas.edu.pe.sistemaescaneo.entity.Usuario; import sistemas.edu.pe.sistemaescaneo.service.IUsuarioService; @Service public class UsuarioService implements UserDetailsService, IUsuarioService { private final Logger log = LoggerFactory.getLogger(UsuarioService.class); @Autowired private IUsuarioDAO usuarioDAO; @Autowired private PasswordEncoder passwordEncoder; @Override @Transactional(readOnly=true) public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { Usuario usuario = usuarioDAO.findByUsername(username); if(usuario == null) { log.error("Error en el login: no existe el usuario '"+username+"' en el sistema!"); throw new UsernameNotFoundException("Error en el login: no existe el usuario '"+username+"' en el sistema!"); } List<GrantedAuthority> authorities = usuario.getRoles() .stream() .map(role -> new SimpleGrantedAuthority(role.getNombre())) // convierte los roles a grantedAuthority .peek(authority -> log.info("Role: "+ authority.getAuthority())) // agarra cada rol convertido y lo imprime .collect(Collectors.toList()); // recolecta los datos convertidos y lo guarda en un List return new User(usuario.getUsername(), usuario.getPassword(), usuario.getEnabled(), true, true, true, authorities); } @Override public List<Usuario> findAll() { return (List<Usuario>) usuarioDAO.findAll(); } @Override public Usuario findByUsername(String username) { return usuarioDAO.findByUsername(username); } @Override public Usuario save(Usuario usuario) { String pass = passwordEncoder.encode(usuario.getPassword()); usuario.setPassword(pass); return usuarioDAO.save(usuario); } @Override public void delete(Long id) { usuarioDAO.deleteById(id); } }
true
272929196c68f97ef21a6cade53b88783d4941ab
Java
AlexChanson/BDMA_Hadoop
/src/main/java/com/alexscode/bdma/hadoop/err/StudentNotFoundAdvice.java
UTF-8
992
2.109375
2
[]
no_license
package com.alexscode.bdma.hadoop.err; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import org.springframework.web.context.request.WebRequest; import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler; import java.util.Date; import java.util.HashMap; @ControllerAdvice public class StudentNotFoundAdvice extends ResponseEntityExceptionHandler { @ExceptionHandler(CustomNotFoundException.class) @ResponseBody @ResponseStatus(HttpStatus.NOT_FOUND) public final Object handleUserNotFoundException(CustomNotFoundException ex, WebRequest request) { HashMap<String, Object> error = new HashMap<>(); error.put("Message", ex.getMessage()); error.put("Timestamp", new Date()); error.put("code", "404"); error.put("status", "NOT FOUND"); return new ResponseEntity<>(error, HttpStatus.NOT_FOUND); } }
true
88a5258cdf692db582c937182dddaab09b7d5f4d
Java
knokko/Gui
/src/nl/knokko/gui/component/text/TextArea.java
UTF-8
7,592
2.4375
2
[ "MIT" ]
permissive
/******************************************************************************* * The MIT License * * Copyright (c) 2018 knokko * * 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 nl.knokko.gui.component.text; import java.awt.Graphics2D; import java.awt.image.BufferedImage; import nl.knokko.gui.component.AbstractGuiComponent; import nl.knokko.gui.keycode.KeyCode; import nl.knokko.gui.render.GuiRenderer; import nl.knokko.gui.texture.GuiTexture; import nl.knokko.gui.util.TextBuilder.Properties; public class TextArea extends AbstractGuiComponent { protected Properties properties; protected GuiTexture currentTexture; protected String[] currentLines; protected float[] currentTextHeights; protected int typingX; protected int typingY; public TextArea(Properties properties, String... initialLines) { this.properties = properties; currentLines = initialLines; } /* * Copied from Troll Wars * * public static BufferedImage createDialogueImage(Color backGround, ImageTexture portrait, DialogueText title, DialogueText[] texts, int[] textHeights){ BufferedImage image = new BufferedImage(800, 800, BufferedImage.TYPE_INT_ARGB); Graphics2D g = image.createGraphics(); g.setColor(backGround.toAWTColor()); g.fillRect(0, 500, 800, 300); g.fillRect(34, 466, 766, 34); g.setColor(java.awt.Color.BLACK); g.drawRect(0, 500, 800, 300); g.drawRect(33, 466, 766, 34); g.drawRect(0, 466, 33, 33); g.drawImage(portrait.getImage(), 1, 467, 32, 32, null); g.setFont(title.getFont()); g.setColor(title.getColor().toAWTColor()); g.drawString(title.getText(), 40, 494); int textIndex = 0; int y = 540; for(DialogueText text : texts){ g.setColor(text.getColor().toAWTColor()); g.setFont(text.getFont()); if(textHeights != null) textHeights[textIndex] = y; String textLine = text.getText(); int lineIndex = 0; for(int length = 0; length + lineIndex < textLine.length(); length++){ double width = g.getFontMetrics().getStringBounds(textLine.substring(lineIndex, lineIndex + length), g).getWidth(); if(width > 700){ //dont break words, that's ugly for(int i = length + lineIndex; i > 0; i--){ if(textLine.charAt(i) == ' '){ length = i + 1 - lineIndex; break; } } g.drawString(textLine.substring(lineIndex, lineIndex + length), 50, y); lineIndex += length; length = 0; y += text.getFont().getSize(); } } g.drawString(textLine.substring(lineIndex), 50, y); y += text.getFont().getSize() * 1.4; textIndex++; } g.dispose(); return image; } */ protected void recreateTexture() { int imageWidth = 800; int imageHeight = 800; BufferedImage currentImage = new BufferedImage(imageWidth, imageHeight, BufferedImage.TYPE_INT_RGB); Graphics2D g = currentImage.createGraphics(); g.setColor(properties.backgroundColor); g.fillRect(1, 1, imageWidth - 2, imageHeight - 2); g.setColor(properties.borderColor); g.drawRect(0, 0, imageWidth, imageHeight); int textIndex = 0; int y = 40; g.setColor(properties.textColor); g.setFont(properties.font); currentTextHeights = new float[currentLines.length]; for(String line : currentLines){ currentTextHeights[textIndex] = (float) y / currentImage.getWidth(); int lineIndex = 0; for(int length = 0; length + lineIndex < line.length(); length++){ double width = g.getFontMetrics().getStringBounds(line.substring(lineIndex, lineIndex + length), g).getWidth(); if(width > imageWidth / 8){ //dont break words, that's ugly for(int i = length + lineIndex; i > 0; i--){ if(line.charAt(i) == ' '){ length = i + 1 - lineIndex; break; } } g.drawString(line.substring(lineIndex, lineIndex + length), imageWidth / 16, y); lineIndex += length; length = 0; y += properties.font.getSize(); } } g.drawString(line.substring(lineIndex), imageWidth / 16, y); y += properties.font.getSize() * 1.4; textIndex++; } g.dispose(); currentTexture = state.getWindow().getTextureLoader().loadTexture(currentImage); } protected boolean isTyping() { return typingX != -1; } @Override public void init() { recreateTexture(); typingX = -1; } @Override public void update() {} @Override public void render(GuiRenderer renderer) { renderer.renderTexture(currentTexture, 0, 0, 1, 1); if(isTyping()) { //TODO render the current place to type } } @Override public void click(float x, float y, int button) { // TODO Calculate the new values for typingX and typingY } @Override public void clickOut(int button) { typingX = -1; } @Override public boolean scroll(float amount) { // TODO Enable scrolling return false; } @Override public void keyPressed(int keyCode) { if(isTyping()) { String line = currentLines[typingY]; if(keyCode == KeyCode.KEY_BACKSPACE && typingX > 0) { currentLines[typingY] = line.substring(0, typingX - 1) + line.substring(typingX, line.length()); recreateTexture(); } else if(keyCode == KeyCode.KEY_DELETE && typingX < line.length() - 1) { currentLines[typingY] = line.substring(0, typingX) + line.substring(typingX + 1, line.length()); recreateTexture(); } else if(keyCode == KeyCode.KEY_ENTER) { String[] newLines = new String[currentLines.length + 1]; System.arraycopy(currentLines, 0, newLines, 0, typingY + 1); System.arraycopy(currentLines, typingY + 1, newLines, typingY + 2, currentLines.length - typingY - 1); newLines[typingY + 1] = ""; currentLines = newLines; typingY++; typingX = 0; recreateTexture(); } else if(keyCode == KeyCode.KEY_LEFT && typingX > 0) { typingX--; } else if(keyCode == KeyCode.KEY_RIGHT && typingX < line.length()) { typingX++; } else if(keyCode == KeyCode.KEY_DOWN && typingY < currentLines.length - 1) { typingY++; if(typingX > currentLines[typingY].length()) { typingX = currentLines[typingY].length(); } } else if(keyCode == KeyCode.KEY_UP && typingY > 0) { typingY--; } } } @Override public void keyPressed(char character) { if(isTyping()) { if(typingX == currentLines[typingY].length()) { currentLines[typingY] += character; } else { String line = currentLines[typingY]; currentLines[typingY] = line.substring(0, typingX) + character + line.substring(typingX); } } } @Override public void keyReleased(int keyCode) {} }
true
1f402179721253a2fc0152ef2224261cf88b8d81
Java
AlbusSerpents/the-nimble-sloth-router
/src/main/java/com/nimble/sloth/router/func/apps/AppRecorderRepository.java
UTF-8
153
1.742188
2
[]
no_license
package com.nimble.sloth.router.func.apps; public interface AppRecorderRepository { void recordApp(final String appId, final String appAddress); }
true
6bdc216942996962d2875dd7f61677b5e597dc0e
Java
fangbinbin/AppFramework
/app/src/main/java/com/fangbinbin/appframework/dialog/HookUpAlertDialog.java
UTF-8
2,534
2.5
2
[]
no_license
package com.fangbinbin.appframework.dialog; import android.app.Dialog; import android.content.Context; import android.graphics.Typeface; import android.view.View; import android.widget.Button; import android.widget.TextView; import com.fangbinbin.appframework.R; import com.fangbinbin.appframework.utils.FrameworkApp; /** * HookUpAlertDialog * * Shows alert with buttons options OK and CLOSE, lets user define custom actions for those buttons. */ public class HookUpAlertDialog extends Dialog { private TextView mTvAlertMessage; private Button mBtnDialog; private Context mContext; public HookUpAlertDialog(final Context context) { super(context, R.style.Theme_Transparent); mContext = context; this.setContentView(R.layout.hookup_alert_dialog); mTvAlertMessage = (TextView) this.findViewById(R.id.tvMessage); mTvAlertMessage.setTypeface(FrameworkApp.getTfMyriadPro()); mBtnDialog = (Button) this.findViewById(R.id.btnDialog); mBtnDialog.setTypeface(FrameworkApp.getTfMyriadProBold(), Typeface.BOLD); mBtnDialog.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { HookUpAlertDialog.this.dismiss(); } }); } /** * Sets custom alert message * * @param alertMessage */ public void setMessage(final String alertMessage) { mTvAlertMessage.setText(alertMessage); } public void setButton(ButtonType buttonType) { switch (buttonType) { case OK: mBtnDialog.setText(mContext.getString(R.string.OK)); mBtnDialog.setBackgroundResource(R.drawable.rounded_rect_positive_selector); break; case CLOSE: mBtnDialog.setText(mContext.getString(R.string.CLOSE)); mBtnDialog.setBackgroundResource(R.drawable.rounded_rect_alert_selector); break; default: break; } } /** * Shows dialog with custom alert message * * @param alertMessage */ public void show(String alertMessage) { mTvAlertMessage.setText(alertMessage); HookUpAlertDialog.this.show(); } public void show(String alertMessage, ButtonType buttonType) { setButton(buttonType); mTvAlertMessage.setText(alertMessage); HookUpAlertDialog.this.show(); } public enum ButtonType { OK, CLOSE } }
true
f996953b8dbb4e1102c305bce0d29e16d56f486b
Java
liangfahua/springcloud-parent
/springcloud-zuul/src/main/java/org/springcloud/zuul/ZuulApplication.java
UTF-8
874
1.953125
2
[]
no_license
package org.springcloud.zuul; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.netflix.eureka.EnableEurekaClient; import org.springframework.cloud.netflix.zuul.EnableZuulProxy; /** @EnableZuulProxy 开启zuul的路由功能 @EnableEurekaClient 向服务注册中心注册 @SpringBootApplication 测试地址如下,此应用端口不能配置为6666 http://localhost:7777/api-a/add?token=aaaaa ->此地址跳转到SERVICE-RIBBON中请求 http://localhost:7777/api-b/add?token=aaaaa&a=12&b=23 ->此地址跳转到SERVICE-FEIGN中请求 将请求进行转发 * */ @EnableZuulProxy @EnableEurekaClient @SpringBootApplication public class ZuulApplication { public static void main(String[] args) { SpringApplication.run(ZuulApplication.class, args); } }
true
00baefac38796e0c3c8559ce0fac2866f8ceb443
Java
fanhaibo2020/springboot02
/src/main/java/com/example/designPattern/dynamicProxy/TeacherDao.java
UTF-8
405
2.734375
3
[]
no_license
package com.example.designPattern.dynamicProxy; /** * @ClassName TeacherDao * @Author fhb * @Date 2020/5/8 14:01 * @Version 1.0 **/ public class TeacherDao implements ITeacherDao { @Override public void teach() { System.out.println("老师正在授课中。。。"); } @Override public void sayHello(String name) { System.out.println("sayHello:"+name); } }
true
1f4a887ac952352578a0b02b960063b58d324057
Java
misnearzhang/netty_core_service
/src/main/java/com/syuct/core_service/core/server/ThreadPool.java
UTF-8
3,710
2.5
2
[]
no_license
package com.syuct.core_service.core.server; import com.syuct.core_service.core.define.AbstractParse; import com.syuct.core_service.process.HandMessage; import com.syuct.core_service.process.SendTask; import com.syuct.core_service.protoc.TransMessage; import io.netty.channel.Channel; import java.io.IOException; import java.util.concurrent.*; /** * 线程池 发送线程池 重传线程池 * * @author Misnearzhang */ public class ThreadPool { private Integer corePoolSize;//核心线程池大小 private Integer maxPoolSize;//最大线程池大小 private Integer keepAliveTime;//时间 private Integer blockingQueueSize;//阻塞队列长度 public ThreadPool(Integer corePoolSize, Integer maxPoolSize, Integer keepAliveTime, Integer blockingQueueSize) { this.corePoolSize = corePoolSize; this.maxPoolSize = maxPoolSize; this.keepAliveTime = keepAliveTime; this.blockingQueueSize = blockingQueueSize; } public void init() { queue = new ArrayBlockingQueue(blockingQueueSize); businessExecutor = new ThreadPoolExecutor(corePoolSize, maxPoolSize, keepAliveTime, TimeUnit.SECONDS, queue); ioExecutor= new ScheduledThreadPoolExecutor(5); ioExecutor.setRemoveOnCancelPolicy(true); futures = new ConcurrentHashMap<String, ScheduledFuture>(100); Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { close(); } }); } private void start() throws IOException { } public enum RetransCount { FISRT, SECOND, THIRD } private AbstractParse parse; private BlockingQueue<Runnable> queue; /** * parse线程池,corePoolSize maximumPoolSize keepAliveTime TimeUnit queue */ private ThreadPoolExecutor businessExecutor; /** * 发送线程池 */ private ScheduledThreadPoolExecutor ioExecutor; private ConcurrentHashMap<String, ScheduledFuture> futures; /** * 业务处理类的全限定名 类似 : com.xxx.***.ClassName * * @param clazz * @throws ClassNotFoundException * @throws NoSuchMethodException * @throws IllegalAccessException * @throws InstantiationException */ public void reflectParse(Class clazz) throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InstantiationException { parse = (HandMessage) clazz.newInstance(); } public void parseMessage(TransMessage.Message message, Channel channel) { parse.initData(message, channel,this); businessExecutor.execute(parse); } /** * 立即发送消息 * * @param task * @param uid */ public void sendMessageNow(SendTask task, String uid) { ScheduledFuture future = ioExecutor.schedule(task, 0, TimeUnit.SECONDS); futures.put(uid, future); } /** * 重发消息 * * @param task * @param uid */ public void sendMessage(SendTask task, String uid) { ScheduledFuture future = ioExecutor.schedule(task, 5, TimeUnit.SECONDS); futures.put(uid, future); } /** * 移除重发队列 * @param uid * @return */ public boolean removeFuture(String uid) { if(futures.containsKey(uid)){ ScheduledFuture future = futures.get(uid); future.cancel(false); ioExecutor.purge(); return true; } return true; } public void close(){ System.out.println("shutdown hook revoke!!!!!"); this.ioExecutor.shutdown(); this.businessExecutor.shutdown(); } }
true
b492e364fbf4e00b619176cdc7586833b90d5f65
Java
tppsDev/TimSmithInventorySystem
/src/View_Controller/AddPartController.java
UTF-8
1,951
2.3125
2
[]
no_license
/* * Project written by: Tim Smith * */ package View_Controller; import java.io.IOException; import java.net.URL; import java.util.ResourceBundle; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.fxml.Initializable; import javafx.scene.control.Button; import javafx.scene.control.Label; import javafx.scene.control.RadioButton; import javafx.scene.control.TextField; import javafx.scene.control.ToggleGroup; /** * FXML Controller class * * @author Tim Smith> */ public class AddPartController implements Initializable { // Buttons @FXML private Button saveButton; @FXML private Button cancelButton; // RadioButtons @FXML private RadioButton inhouseRadioButton; @FXML private RadioButton outsourcedRadioButton; @FXML private ToggleGroup partTypeToggleGroup; // Labels @FXML private Label machineOrCompanyLabel; @FXML private Label nameTextFieldErrorLabel; @FXML private Label inStockTextFieldErrorLabel; @FXML private Label priceTextFieldErrorLabel; @FXML private Label minTextFieldErrorLabel; @FXML private Label maxTextFieldErrorLabel; @FXML private Label machineCompanyTextFieldErrorLabel; // TextFields @FXML private TextField partIDTextField; @FXML private TextField nameTextField; @FXML private TextField inStockTextField; @FXML private TextField priceTextField; @FXML private TextField maxTextField; @FXML private TextField minTextField; @FXML private TextField machineCompanyTextField; /** * Initializes the controller class. */ @Override public void initialize(URL url, ResourceBundle rb) { // TODO } public void handleSaveButtonAction(ActionEvent event) throws IOException { } public void handleCancelButtonAction(ActionEvent event) throws IOException { } }
true
145a846ed6cadf9d33d6039e04cddc98897f674e
Java
uPortal-Project/uPortal
/uPortal-content/uPortal-content-portlet/src/main/java/org/apereo/portal/portlet/registry/PortletEntityData.java
UTF-8
4,589
2.046875
2
[ "BSD-3-Clause", "Apache-2.0", "MIT", "CC-BY-3.0", "CDDL-1.0", "LGPL-2.1-only", "CC-BY-SA-3.0", "MPL-1.1", "LicenseRef-scancode-unknown-license-reference", "JSON", "LicenseRef-scancode-proprietary-license", "LicenseRef-scancode-free-unknown", "EPL-1.0", "CPL-1.0", "Classpath-exception-2.0...
permissive
/** * Licensed to Apereo under one or more contributor license agreements. See the NOTICE file * distributed with this work for additional information regarding copyright ownership. Apereo * 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 the * following location: * * <p>http://www.apache.org/licenses/LICENSE-2.0 * * <p>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.apereo.portal.portlet.registry; import java.io.Serializable; import org.apereo.portal.portlet.om.IPortletDefinitionId; import org.apereo.portal.portlet.om.IPortletEntityDescriptor; import org.apereo.portal.portlet.om.IPortletEntityId; /** Session persistent data stored for portlet entities */ class PortletEntityData implements Serializable, IPortletEntityDescriptor { private static final long serialVersionUID = 1L; private final IPortletEntityId portletEntityId; private final IPortletDefinitionId portletDefinitionId; private final String layoutNodeId; private final int userId; public PortletEntityData( IPortletEntityId portletEntityId, IPortletDefinitionId portletDefinitionId, String layoutNodeId, int userId) { this.portletEntityId = portletEntityId; this.portletDefinitionId = portletDefinitionId; this.layoutNodeId = layoutNodeId; this.userId = userId; } /* (non-Javadoc) * @see org.apereo.portal.portlet.registry.IPortletEntityDescriptor#getPortletEntityId() */ @Override public IPortletEntityId getPortletEntityId() { return this.portletEntityId; } /* (non-Javadoc) * @see org.apereo.portal.portlet.registry.IPortletEntityDescriptor#getPortletDefinitionId() */ @Override public IPortletDefinitionId getPortletDefinitionId() { return this.portletDefinitionId; } /* (non-Javadoc) * @see org.apereo.portal.portlet.registry.IPortletEntityDescriptor#getLayoutNodeId() */ @Override public String getLayoutNodeId() { return this.layoutNodeId; } /* (non-Javadoc) * @see org.apereo.portal.portlet.registry.IPortletEntityDescriptor#getUserId() */ @Override public int getUserId() { return this.userId; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((this.layoutNodeId == null) ? 0 : this.layoutNodeId.hashCode()); result = prime * result + ((this.portletDefinitionId == null) ? 0 : this.portletDefinitionId.hashCode()); result = prime * result + ((this.portletEntityId == null) ? 0 : this.portletEntityId.hashCode()); result = prime * result + this.userId; return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; PortletEntityData other = (PortletEntityData) obj; if (this.layoutNodeId == null) { if (other.layoutNodeId != null) return false; } else if (!this.layoutNodeId.equals(other.layoutNodeId)) return false; if (this.portletDefinitionId == null) { if (other.portletDefinitionId != null) return false; } else if (!this.portletDefinitionId.equals(other.portletDefinitionId)) return false; if (this.portletEntityId == null) { if (other.portletEntityId != null) return false; } else if (!this.portletEntityId.equals(other.portletEntityId)) return false; if (this.userId != other.userId) return false; return true; } @Override public String toString() { return "PortletEntityData [portletEntityId=" + this.portletEntityId + ", portletDefinitionId=" + this.portletDefinitionId + ", layoutNodeId=" + this.layoutNodeId + ", userId=" + this.userId + "]"; } }
true
2db22e55f5eaac0d622892f65c7d70d5ca2c8226
Java
marcuspramirez/Feedback-Central
/employee-service/src/test/java/com/company/employeeservice/controller/EmployeeServiceControllerTest.java
UTF-8
6,125
2.375
2
[]
no_license
package com.company.employeeservice.controller; import com.company.employeeservice.dao.EmployeeRepository; import com.company.employeeservice.dto.Employee; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.ImportAutoConfiguration; import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.cloud.autoconfigure.RefreshAutoConfiguration; import org.springframework.http.MediaType; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; import java.util.Arrays; import java.util.List; import static org.mockito.Mockito.when; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; @RunWith(SpringRunner.class) @WebMvcTest(EmployeeServiceController.class) @ImportAutoConfiguration(RefreshAutoConfiguration.class) public class EmployeeServiceControllerTest { @Autowired private MockMvc mockMvc; @MockBean EmployeeRepository employeeRepo; private ObjectMapper mapper = new ObjectMapper(); private String jsonObject; @Before public void setUp() throws Exception { } @Test public void shouldReturnAllEmployees() throws Exception { List<Employee> employeeList = Arrays.asList(new Employee(1,"Alex","Smith", "Sales", null)); jsonObject= mapper.writeValueAsString(employeeList); when(employeeRepo.findAll()).thenReturn(employeeList); // ARRANGE and ACT mockMvc.perform(get("/employee")) // Perform the GET request. .andDo(print()) // Print results to console. .andExpect(status().isOk()) .andExpect(content().json(jsonObject)); } @Test public void shouldGetEmployeeById() throws Exception { Employee outputEmployee = new Employee(); outputEmployee.setId(1); outputEmployee.setFirstName("Alex"); outputEmployee.setLastName("Smith"); outputEmployee.setDepartment("Sales");; // String outputJson = mapper.writeValueAsString(outputEmployee); // ARRANGE and ACT mockMvc.perform(get("/employee/1")) // Perform the GET request. .andDo(print()) // Print results to console. .andExpect(status().isOk()); } @Test public void addEmployee() throws Exception { // ARRANGE Employee inputEmployee = new Employee(); inputEmployee.setId(1); inputEmployee.setFirstName("Justin"); inputEmployee.setLastName("Finley"); inputEmployee.setDepartment("Sales"); // Convert Java Object to JSON. String inputJson = mapper.writeValueAsString(inputEmployee); Employee outputEmployee = new Employee(); outputEmployee.setId(1); outputEmployee.setFirstName("Justin"); outputEmployee.setLastName("Finley"); outputEmployee.setDepartment("Sales"); String outputJson = mapper.writeValueAsString(outputEmployee); // ACT mockMvc.perform( post("/employee") // Perform the POST request. .content(inputJson) // Set the request body. .contentType(MediaType.APPLICATION_JSON) // Tell the server it's in JSON format. ) .andDo(print()) // Print results to console. .andExpect(status().isCreated()) // ASSERT (status code is 201) .andExpect(content().json(outputJson)); // ASSERT that what we're expecting is what we got back. } // // testing DELETE /records/{id} @Test public void shouldDeleteByIdAndReturn204StatusCode() throws Exception { // This method returns nothing, so we're just checking for the correct status code. // In this case, code 204, which indicates No Content. We will test deletes deeper in the future. mockMvc.perform(delete("/employee/1")) .andDo(print()) .andExpect(status().isNoContent()); } @Test public void shouldUpdateEmployee() throws Exception { // ARRANGE Employee inputEmployee = new Employee(); inputEmployee.setFirstName("William"); inputEmployee.setLastName("Joel"); inputEmployee.setDepartment("Engineer"); inputEmployee.setId(2); String inputJson = mapper.writeValueAsString(inputEmployee); // ACT mockMvc.perform( put("/employee/2") .content(inputJson) .contentType(MediaType.APPLICATION_JSON) ) .andDo(print()) .andExpect(status().isNoContent()); // ASSERT that we got back 204 NO CONTENT. // ACT mockMvc.perform( get("/employee/2") .contentType(MediaType.APPLICATION_JSON) ) .andDo(print()); // .andExpect(content().json(inputJson)); // ASSERT that the record was updated successfully. } @Test public void shouldReturn404StatusCodeIfRecordNotFound() throws Exception { mockMvc.perform(get("/employee/-1")) .andDo(print()) .andExpect(status().isNotFound()); } }
true
46dc8fba229dd5b80044df9fbc8904e0e5fc4cda
Java
janamava/nacs_java
/src/javaWeek_9/exercise5/FilmSummariser.java
UTF-8
2,854
3.453125
3
[]
no_license
package javaWeek_9.exercise5; import java.util.Comparator; import java.util.List; import java.util.stream.Collectors; public class FilmSummariser { private List<Film> films = new FilmReader().getFilms(); //three films with the highest rating, sorted by rating public List<Film> getCondition1() { return films.stream() .sorted(Comparator.comparing(Film::getScore).reversed()) .limit(3) .collect(Collectors.toList()); } //three films with the highest rating that are longer than three hours, sorted by rating public List<Film> getCondition2() { return films.stream() .sorted(Comparator.comparing(Film::getScore).reversed()) .filter(e -> e.getRuntime() > 180) .limit(3) .collect(Collectors.toList()); } // four most expensive films, sorted by budget public List<Film> getCondition3() { return films.stream() .sorted((e1, e2) -> e2.getBudget().compareTo(e1.getBudget())) .limit(4) .collect(Collectors.toList()); } // four most expensive films that are shorter than one hour and a half, sorted by budget public List<Film> getCondition4() { return films.stream() .sorted(Comparator.comparing(Film::getBudget).reversed()) .filter(e -> e.getRuntime() < 90) .limit(4) .collect(Collectors.toList()); } // four most rated films with a rating higher than 7 and a budget between 50.000 and 500.000 dollars, // sorted by budget public List<Film> getCondition5() { return films.stream() .filter(e -> e.getScore() > 7.0) .filter(e -> e.getBudget() > 50000 && e.getBudget() < 500000) .sorted(Comparator.comparing(Film::getBudget).reversed()) .limit(4) .collect(Collectors.toList()); } // three shortest movies, that have most votes and highest score public List<Film> getCondition6() { return films.stream() .sorted(Comparator.comparing(Film::getRuntime)) .sorted(Comparator.comparing(Film::getVoteCount).reversed()) .sorted(Comparator.comparing(Film::getScore).reversed()) .limit(3) .collect(Collectors.toList()); } // ten most voted movies with the score more then 8, sorted by highest revenue public List<Film> getCondition7() { return films.stream() .sorted(Comparator.comparing(Film::getVoteCount).reversed()) .filter(e -> e.getScore() > 8) .sorted(Comparator.comparing(Film::getRevenue).reversed()) .limit(10) .collect(Collectors.toList()); } }
true